diff --git a/docs/API.md b/docs/API.md index 617a7a4..1776905 100644 --- a/docs/API.md +++ b/docs/API.md @@ -108,3 +108,23 @@ Rules: one house per person (`409` if you're already in one). Non-members get `4 `Item`: `{ id, name, category, status, priceCents, boughtAt, billId, createdAt, updatedAt, addedBy: User, claimedBy: User|null, boughtBy: User|null }` `bought` lists bought items that are either from the last 14 days or not on a bill yet, newest first. `billable` is what the "Split $14.77 as a bill" button will cover: items you bought and priced that aren't on a bill yet. The button itself comes with the bills feature. + +## Note Board + +| Method | Path | Body / query | Returns | +|---|---|---|---| +| GET | `/houses/:houseId/notes` | – | `{ pinned: Note[], notes: Note[] }` | +| POST | `/houses/:houseId/notes` | `{ body, dueOn?, pinned?, color?, notify? }` | `201 { note }` | +| GET | `/houses/:houseId/notes/:noteId` | – | `{ note }` | +| PATCH | `/houses/:houseId/notes/:noteId` | `{ body?, dueOn?, color? }` | `{ note }` (author only, else `403`) | +| DELETE | `/houses/:houseId/notes/:noteId` | – | `204` (author or house owner, else `403`) | +| POST / DELETE | `/houses/:houseId/notes/:noteId/pin` | – | `{ note }` (pin / unpin, any member) | + +`Note`: `{ id, body, color, dueOn: "YYYY-MM-DD"|null, pinned, pinnedAt, createdAt, updatedAt, author: User }`. `color` is `YELLOW`, `ORANGE`, `BLUE`, `GREEN`, `PINK` or `PURPLE`. + +- `body` is 1–500 characters. `dueOn` is optional, can't be in the past (in the house's time zone), and can be cleared with `null` on PATCH. +- Leave out `color` and the server picks the one used least by the house's recent notes, so the board cycles through all six. The Leave a Note screen has no color picker, so the app normally leaves it out. +- `pinned: true` is the "Pin Note" switch. `notify` is the "Notify Others" switch: it's accepted but does nothing until push notifications exist. +- `pinned` lists pinned notes, most recently pinned first. `notes` lists the rest, newest first. Pinning an already pinned note moves it to the top. +- Notes stay on the board for 14 days after posting, or until their due date if that's later. Pinned notes stay until someone unpins them. A note that's off the board returns `404`. +- A person's notes stay, with their name, after they leave the house. diff --git a/docs/roomie.postman_collection.json b/docs/roomie.postman_collection.json index d1c91d6..e551a26 100644 --- a/docs/roomie.postman_collection.json +++ b/docs/roomie.postman_collection.json @@ -82,11 +82,19 @@ { "key": "weekEnd", "value": "" + }, + { + "key": "noteId", + "value": "" + }, + { + "key": "roommateNoteId", + "value": "" } ], "item": [ { - "name": "0 \u00b7 Start", + "name": "0 · Start", "item": [ { "name": "Health check", @@ -134,7 +142,7 @@ ] }, { - "name": "1 \u00b7 Auth & me", + "name": "1 · Auth & me", "item": [ { "name": "Login (creates account first time)", @@ -282,7 +290,7 @@ ] }, { - "name": "2 \u00b7 Houses", + "name": "2 · Houses", "item": [ { "name": "Create house (+ invite roommate)", @@ -631,7 +639,7 @@ ] }, { - "name": "3 \u00b7 Chores", + "name": "3 · Chores", "item": [ { "name": "Create chore with rotation", @@ -1089,7 +1097,7 @@ ] }, { - "name": "4 \u00b7 Shopping", + "name": "4 · Shopping", "item": [ { "name": "Add item", @@ -1498,7 +1506,381 @@ ] }, { - "name": "5 \u00b7 Leaving", + "name": "5 · Note Board", + "item": [ + { + "name": "Post note", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "pm.collectionVariables.set('noteId', pm.response.json().note.id);" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"body\": \"plumber coming thurs!\",\n \"dueOn\": \"{{today}}\",\n \"notify\": true\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Roommate posts pinned note", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "pm.collectionVariables.set('roommateNoteId', pm.response.json().note.id);", + "pm.test('pinned', () => pm.expect(pm.response.json().note.pinned).to.be.true);" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"body\": \"Rent is due on the 1st\",\n \"pinned\": true\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "dev:{{roommateNetid}}", + "type": "string" + } + ] + } + } + }, + { + "name": "Board", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "pm.test('pinned first', () => pm.expect(pm.response.json().pinned[0].id).to.eql(pm.collectionVariables.get('roommateNoteId')));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes" + ] + } + } + }, + { + "name": "Get note", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{noteId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{noteId}}" + ] + } + } + }, + { + "name": "Edit note (author)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{noteId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{noteId}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"body\": \"plumber coming fri!\",\n \"dueOn\": null\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Edit roommate's note (403)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 403\", () => pm.response.to.have.status(403));" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{roommateNoteId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{roommateNoteId}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"body\": \"nope\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Pin", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "POST", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{noteId}}/pin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{noteId}}", + "pin" + ] + } + } + }, + { + "name": "Unpin", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{noteId}}/pin", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{noteId}}", + "pin" + ] + } + } + }, + { + "name": "Owner deletes roommate's note", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 204\", () => pm.response.to.have.status(204));" + ] + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{roommateNoteId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{roommateNoteId}}" + ] + } + } + }, + { + "name": "Delete note", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 204\", () => pm.response.to.have.status(204));" + ] + } + } + ], + "request": { + "method": "DELETE", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/notes/{{noteId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "notes", + "{{noteId}}" + ] + } + } + } + ] + }, + { + "name": "6 · Leaving", "item": [ { "name": "Roommate leaves house", diff --git a/prisma/migrations/20261111220000_add_notes/migration.sql b/prisma/migrations/20261111220000_add_notes/migration.sql new file mode 100644 index 0000000..2b51a79 --- /dev/null +++ b/prisma/migrations/20261111220000_add_notes/migration.sql @@ -0,0 +1,30 @@ +-- CreateEnum +CREATE TYPE "NoteColor" AS ENUM ('YELLOW', 'ORANGE', 'BLUE', 'GREEN', 'PINK', 'PURPLE'); + +-- CreateTable +CREATE TABLE "Note" ( + "id" SERIAL NOT NULL, + "houseId" INTEGER NOT NULL, + "authorId" INTEGER NOT NULL, + "body" TEXT NOT NULL, + "color" "NoteColor" NOT NULL DEFAULT 'YELLOW', + "dueOn" DATE, + "pinnedAt" TIMESTAMP(3), + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + "updatedAt" TIMESTAMP(3) NOT NULL, + + CONSTRAINT "Note_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE INDEX "Note_houseId_createdAt_idx" ON "Note"("houseId", "createdAt"); + +-- AddForeignKey +ALTER TABLE "Note" ADD CONSTRAINT "Note_houseId_fkey" FOREIGN KEY ("houseId") REFERENCES "House"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- AddForeignKey +ALTER TABLE "Note" ADD CONSTRAINT "Note_authorId_fkey" FOREIGN KEY ("authorId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Keep Supabase's public API out of this table, like the others. The backend connects +-- as the table owner, which RLS doesn't apply to. +ALTER TABLE "Note" ENABLE ROW LEVEL SECURITY; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 0300335..6113612 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -39,6 +39,7 @@ model User { shoppingAdded ShoppingItem[] @relation("ShoppingAddedBy") shoppingClaimed ShoppingItem[] @relation("ShoppingClaimedBy") shoppingBought ShoppingItem[] @relation("ShoppingBoughtBy") + notes Note[] @relation("NoteAuthor") } // ───────────────────────────── Houses ───────────────────────────── @@ -89,6 +90,7 @@ model House { invites HouseInvite[] chores Chore[] shoppingItems ShoppingItem[] + notes Note[] } /// One house per user for the MVP (userId is unique). Drop the unique to allow several. @@ -230,3 +232,36 @@ model ShoppingItem { @@index([houseId, status]) } + +// ───────────────────────────── Note Board ───────────────────────────── + +/// The post-it colors in the Note Board design. +enum NoteColor { + YELLOW + ORANGE + BLUE + GREEN + PINK + PURPLE +} + +/// A post-it on the Note Board. Shown for 14 days after posting (or until its due date, +/// if that's later). Pinned notes stay until someone unpins them. +model Note { + id Int @id @default(autoincrement()) + houseId Int + authorId Int + body String + color NoteColor @default(YELLOW) + /// "Due Date · Optional" on the Leave a Note screen. + dueOn DateTime? @db.Date + /// Set while the note is pinned. Any member can pin or unpin. + pinnedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + house House @relation(fields: [houseId], references: [id], onDelete: Cascade) + author User @relation("NoteAuthor", fields: [authorId], references: [id], onDelete: Cascade) + + @@index([houseId, createdAt]) +} diff --git a/prisma/seed.ts b/prisma/seed.ts index 446ea0c..82f0de0 100644 --- a/prisma/seed.ts +++ b/prisma/seed.ts @@ -116,6 +116,26 @@ const main = async () => { category: 'HOUSEHOLD', }); + const note = ( + body: string, + authorId: number, + color: 'YELLOW' | 'ORANGE' | 'BLUE' | 'GREEN' | 'PINK' | 'PURPLE', + extra: Record = {}, + ) => + prisma.note.create({ + data: { houseId: house.id, body, authorId, color, ...extra }, + }); + await note('Rent is due on the 1st', melissa.id, 'YELLOW', { + pinnedAt: new Date(), + }); + await note('plumber coming thurs!', leah.id, 'ORANGE', { + dueOn: new Date(today.getTime() + 2 * 86_400_000), + }); + await note('good luck with prelims ♡', leah.id, 'BLUE'); + await note('Thanks for cleaning the kitchen!', selena.id, 'GREEN'); + await note('Love living with you all!', melissa.id, 'PINK'); + await note("Movie night Friday? I'll make popcorn", selena.id, 'PURPLE'); + console.log( `Seeded "${house.name}" (id ${house.id}, code ${house.inviteCode}).`, ); diff --git a/src/houses/houseRouter.ts b/src/houses/houseRouter.ts index 4d6757e..6e90c0f 100644 --- a/src/houses/houseRouter.ts +++ b/src/houses/houseRouter.ts @@ -6,6 +6,7 @@ import { requireHouseOwner, } from '../middleware/authentication.js'; import { validateRequest } from '../middleware/validateRequest.js'; +import noteRouter from '../notes/noteRouter.js'; import shoppingRouter from '../shopping/shoppingRouter.js'; import { acceptInvite, @@ -74,5 +75,6 @@ house.delete( // Feature routers mounted under /houses/:houseId house.use('/', choreRouter); house.use('/shopping-items', shoppingRouter); +house.use('/notes', noteRouter); export default router; diff --git a/src/houses/houseService.ts b/src/houses/houseService.ts index 6053a23..9d3f829 100644 --- a/src/houses/houseService.ts +++ b/src/houses/houseService.ts @@ -243,7 +243,7 @@ export const respondToInvite = async ( * - their future, unfinished chore turns are dropped and they leave every rotation * - their "I'll get it" claims on the shopping list are released * - ownership passes to the longest-standing member; the last one out deletes the house - * Done chores and bought items stay in the history. + * Done chores, bought items and their notes stay. */ export const removeMember = async ( houseId: number, diff --git a/src/notes/noteController.ts b/src/notes/noteController.ts new file mode 100644 index 0000000..00065e9 --- /dev/null +++ b/src/notes/noteController.ts @@ -0,0 +1,207 @@ +import type { Request, Response } from 'express'; + +import type { NoteColor, Prisma } from '../generated/prisma/client.js'; +import { valid } from '../middleware/validateRequest.js'; +import { prisma } from '../prisma.js'; +import { + BadRequestError, + ForbiddenError, + NotFoundError, +} from '../utils/AppError.js'; +import { formatDate, parseDate, todayIn } from '../utils/dates.js'; +import { publicUserSelect } from '../utils/selects.js'; +import { + NOTE_COLORS, + createNoteSchema, + listNotesSchema, + noteParamsSchema, + updateNoteSchema, +} from './notes.schema.js'; + +/** "Notes stay on the board for 14 days." */ +export const NOTE_VISIBLE_DAYS = 14; + +const noteInclude = { author: { select: publicUserSelect } } as const; + +type NoteRow = Prisma.NoteGetPayload<{ include: typeof noteInclude }>; + +const serialize = ({ + houseId: _h, + authorId: _a, + dueOn, + pinnedAt, + ...note +}: NoteRow) => ({ + ...note, + dueOn: dueOn && formatDate(dueOn), + pinned: pinnedAt !== null, + pinnedAt, +}); + +const houseToday = async (houseId: number) => { + const house = await prisma.house.findUniqueOrThrow({ + where: { id: houseId }, + select: { timezone: true }, + }); + return todayIn(house.timezone); +}; + +/** Due dates can be today or later, in the house's time zone. */ +const checkDueOn = async ( + houseId: number, + dueOn: string | null | undefined, +) => { + if (!dueOn) return; + if (parseDate(dueOn) < (await houseToday(houseId))) { + throw new BadRequestError('The due date can’t be in the past.'); + } +}; + +/** + * Notes still on the board: pinned, posted in the last 14 days, or due today or later. + * Same visibility everywhere, so an expired note 404s like a deleted one. + */ +const visibleWhere = ( + houseId: number, + today: Date, + now = new Date(), +): Prisma.NoteWhereInput => ({ + houseId, + OR: [ + { pinnedAt: { not: null } }, + { + createdAt: { + gte: new Date(now.getTime() - NOTE_VISIBLE_DAYS * 86_400_000), + }, + }, + { dueOn: { gte: today } }, + ], +}); + +const loadNote = async (houseId: number, noteId: number) => { + const today = await houseToday(houseId); + const note = await prisma.note.findFirst({ + where: { id: noteId, ...visibleWhere(houseId, today) }, + include: noteInclude, + }); + if (!note) throw new NotFoundError('Note not found.'); + return note; +}; + +/** + * Picks the color used least among the house's recent notes, so new notes cycle through + * the palette the way the design shows. Ties go to the earliest color in NOTE_COLORS. + */ +const pickColor = async (houseId: number): Promise => { + const recent = await prisma.note.findMany({ + where: { houseId }, + orderBy: { id: 'desc' }, + take: NOTE_COLORS.length - 1, + select: { color: true }, + }); + const uses = (c: NoteColor) => recent.filter((n) => n.color === c).length; + return NOTE_COLORS.reduce((best, c) => (uses(c) < uses(best) ? c : best)); +}; + +/** + * GET /houses/:houseId/notes + * The Note Board: pinned notes (most recently pinned first), then the rest newest first. + */ +export const listNotes = async (req: Request, res: Response) => { + const { params } = valid(req, listNotesSchema); + const today = await houseToday(params.houseId); + const notes = await prisma.note.findMany({ + where: visibleWhere(params.houseId, today), + orderBy: [{ createdAt: 'desc' }, { id: 'desc' }], + include: noteInclude, + }); + const pinned = notes + .filter((n) => n.pinnedAt !== null) + .sort((a, b) => b.pinnedAt!.getTime() - a.pinnedAt!.getTime()); + res.json({ + pinned: pinned.map(serialize), + notes: notes.filter((n) => n.pinnedAt === null).map(serialize), + }); +}; + +/** POST /houses/:houseId/notes ("Leave a Note"). */ +export const createNote = async (req: Request, res: Response) => { + const { params, body } = valid(req, createNoteSchema); + await checkDueOn(params.houseId, body.dueOn); + const note = await prisma.note.create({ + data: { + houseId: params.houseId, + authorId: req.user!.id, + body: body.body, + color: body.color ?? (await pickColor(params.houseId)), + dueOn: body.dueOn ? parseDate(body.dueOn) : null, + pinnedAt: body.pinned ? new Date() : null, + }, + include: noteInclude, + }); + res.status(201).json({ note: serialize(note) }); +}; + +export const getNote = async (req: Request, res: Response) => { + const { params } = valid(req, noteParamsSchema); + res.json({ note: serialize(await loadNote(params.houseId, params.noteId)) }); +}; + +/** Inline edit: message, due date or color. Only the author can edit. */ +export const updateNote = async (req: Request, res: Response) => { + const { params, body } = valid(req, updateNoteSchema); + const note = await loadNote(params.houseId, params.noteId); + if (note.authorId !== req.user!.id) { + throw new ForbiddenError('You can only edit your own notes.'); + } + await checkDueOn(params.houseId, body.dueOn); + const updated = await prisma.note.update({ + where: { id: note.id }, + data: { + ...(body.body !== undefined && { body: body.body }), + ...(body.color !== undefined && { color: body.color }), + ...(body.dueOn !== undefined && { + dueOn: body.dueOn ? parseDate(body.dueOn) : null, + }), + }, + include: noteInclude, + }); + res.json({ note: serialize(updated) }); +}; + +/** The author can delete their own notes; the house owner can delete any. */ +export const deleteNote = async (req: Request, res: Response) => { + const { params } = valid(req, noteParamsSchema); + const note = await loadNote(params.houseId, params.noteId); + if (note.authorId !== req.user!.id && req.membership!.role !== 'OWNER') { + throw new ForbiddenError( + 'Only the author or the house owner can delete this.', + ); + } + await prisma.note.delete({ where: { id: note.id } }); + res.status(204).end(); +}; + +/** Any member can pin. Pinning an already pinned note moves it to the top. */ +export const pinNote = async (req: Request, res: Response) => { + const { params } = valid(req, noteParamsSchema); + const note = await loadNote(params.houseId, params.noteId); + const updated = await prisma.note.update({ + where: { id: note.id }, + data: { pinnedAt: new Date() }, + include: noteInclude, + }); + res.json({ note: serialize(updated) }); +}; + +/** An unpinned note older than 14 days drops off the board, like any other. */ +export const unpinNote = async (req: Request, res: Response) => { + const { params } = valid(req, noteParamsSchema); + const note = await loadNote(params.houseId, params.noteId); + const updated = await prisma.note.update({ + where: { id: note.id }, + data: { pinnedAt: null }, + include: noteInclude, + }); + res.json({ note: serialize(updated) }); +}; diff --git a/src/notes/noteRouter.ts b/src/notes/noteRouter.ts new file mode 100644 index 0000000..f2ff979 --- /dev/null +++ b/src/notes/noteRouter.ts @@ -0,0 +1,31 @@ +import { Router } from 'express'; + +import { validateRequest } from '../middleware/validateRequest.js'; +import { + createNote, + deleteNote, + getNote, + listNotes, + pinNote, + unpinNote, + updateNote, +} from './noteController.js'; +import { + createNoteSchema, + listNotesSchema, + noteParamsSchema, + updateNoteSchema, +} from './notes.schema.js'; + +/** Mounted at /houses/:houseId/notes (membership already checked). */ +const router = Router({ mergeParams: true }); + +router.get('/', validateRequest(listNotesSchema), listNotes); +router.post('/', validateRequest(createNoteSchema), createNote); +router.get('/:noteId', validateRequest(noteParamsSchema), getNote); +router.patch('/:noteId', validateRequest(updateNoteSchema), updateNote); +router.delete('/:noteId', validateRequest(noteParamsSchema), deleteNote); +router.post('/:noteId/pin', validateRequest(noteParamsSchema), pinNote); +router.delete('/:noteId/pin', validateRequest(noteParamsSchema), unpinNote); + +export default router; diff --git a/src/notes/notes.schema.ts b/src/notes/notes.schema.ts new file mode 100644 index 0000000..384f6a2 --- /dev/null +++ b/src/notes/notes.schema.ts @@ -0,0 +1,41 @@ +import { z } from 'zod'; + +import { houseIdParams, ymd } from '../houses/houses.schema.js'; + +/** The post-it colors in the Note Board design, in the order the server hands them out. */ +export const NOTE_COLORS = [ + 'YELLOW', + 'ORANGE', + 'BLUE', + 'GREEN', + 'PINK', + 'PURPLE', +] as const; + +const color = z.enum(NOTE_COLORS); +const body = z.string().trim().min(1).max(500); + +const noteParams = houseIdParams.extend({ noteId: z.coerce.number().int() }); + +export const listNotesSchema = z.object({ params: houseIdParams }); + +export const createNoteSchema = z.object({ + params: houseIdParams, + body: z.object({ + body, + /** Leave it out and the server picks one, so the board stays colorful. */ + color: color.optional(), + dueOn: ymd.nullable().optional(), + /** The "Pin Note" switch on Leave a Note. */ + pinned: z.boolean().default(false), + /** The "Notify Others" switch. Accepted, but ignored until push notifications exist. */ + notify: z.boolean().optional(), + }), +}); + +export const updateNoteSchema = z.object({ + params: noteParams, + body: z.object({ body, color, dueOn: ymd.nullable() }).partial(), +}); + +export const noteParamsSchema = z.object({ params: noteParams }); diff --git a/test/notes.test.ts b/test/notes.test.ts new file mode 100644 index 0000000..32a4ebe --- /dev/null +++ b/test/notes.test.ts @@ -0,0 +1,222 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { prisma } from '../src/prisma.js'; +import { formatDate, todayIn } from '../src/utils/dates.js'; +import { signUp } from './helpers.js'; + +type Client = Awaited>; +let leah: Client, selena: Client, melissa: Client, base: string; + +const DAY = 86_400_000; +const today = () => todayIn('America/New_York'); +const inDays = (n: number) => formatDate(new Date(today().getTime() + n * DAY)); + +beforeEach(async () => { + leah = await signUp('lk452'); + selena = await signUp('sc2291'); + melissa = await signUp('mv384'); + const house = (await leah.post('/houses', { name: 'The Linden Loft' })).body + .house; + await selena.post('/houses/join', { inviteCode: house.inviteCode }); + await melissa.post('/houses/join', { inviteCode: house.inviteCode }); + base = `/houses/${house.id}/notes`; +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const post = async (as: Client, body: object) => { + const res = await as.post(base, body); + expect(res.status).toBe(201); + return res.body.note; +}; + +/** Moves a note's posting time back, as if it had been on the board that long. */ +const age = (id: number, days: number) => + prisma.note.update({ + where: { id }, + data: { createdAt: new Date(Date.now() - days * DAY) }, + }); + +describe('posting notes', () => { + it('posts a note with the author, an optional due date and a picked color', async () => { + const note = await post(selena, { + body: 'plumber coming thurs!', + dueOn: inDays(2), + notify: true, + }); + expect(note).toMatchObject({ + body: 'plumber coming thurs!', + color: 'YELLOW', + dueOn: inDays(2), + pinned: false, + pinnedAt: null, + author: { netid: 'sc2291' }, + }); + expect(note).not.toHaveProperty('houseId'); + expect(note).not.toHaveProperty('notify'); + }); + + it('cycles colors so recent notes all look different', async () => { + const colors = []; + for (let i = 0; i < 7; i++) { + colors.push((await post(leah, { body: `note ${i}` })).color); + } + expect(colors).toEqual([ + 'YELLOW', + 'ORANGE', + 'BLUE', + 'GREEN', + 'PINK', + 'PURPLE', + 'YELLOW', + ]); + // A color the app chooses is kept. + expect((await post(leah, { body: 'mine', color: 'PINK' })).color).toBe( + 'PINK', + ); + }); + + it('validates the body', async () => { + expect((await leah.post(base, { body: ' ' })).status).toBe(400); + expect((await leah.post(base, { body: 'x'.repeat(501) })).status).toBe(400); + expect((await leah.post(base, { body: 'hi', color: 'RED' })).status).toBe( + 400, + ); + expect((await leah.post(base, { body: 'hi', dueOn: '12/01' })).status).toBe( + 400, + ); + const past = await leah.post(base, { body: 'hi', dueOn: inDays(-1) }); + expect(past.status).toBe(400); + expect(past.body.errorCode).toBe('BAD_REQUEST'); + // Today is fine. + expect( + (await leah.post(base, { body: 'hi', dueOn: inDays(0) })).status, + ).toBe(201); + }); +}); + +describe('the board', () => { + it('shows pinned notes first, then the rest newest first', async () => { + const rent = await post(melissa, { + body: 'Rent is due dec 1', + pinned: true, + }); + await post(leah, { body: 'Mihili, thanks for cleaning!' }); + const movie = await post(selena, { body: 'Movie night Friday?' }); + expect(rent.pinned).toBe(true); + + const board = (await leah.get(base)).body; + expect(board.pinned.map((n: { body: string }) => n.body)).toEqual([ + 'Rent is due dec 1', + ]); + expect(board.notes.map((n: { body: string }) => n.body)).toEqual([ + 'Movie night Friday?', + 'Mihili, thanks for cleaning!', + ]); + expect((await leah.get(`${base}/${movie.id}`)).body.note.body).toBe( + 'Movie night Friday?', + ); + }); + + it('drops notes after 14 days, unless they are pinned or not due yet', async () => { + const old = await post(leah, { body: 'old news' }); + const pinned = await post(leah, { body: 'house rules', pinned: true }); + const due = await post(leah, { body: 'lease renewal', dueOn: inDays(3) }); + const fresh = await post(leah, { body: 'fresh' }); + for (const n of [old, pinned, due]) await age(n.id, 15); + await age(fresh.id, 13); + + const board = (await selena.get(base)).body; + expect(board.pinned.map((n: { id: number }) => n.id)).toEqual([pinned.id]); + expect(board.notes.map((n: { id: number }) => n.id).sort()).toEqual( + [due.id, fresh.id].sort(), + ); + expect((await selena.get(`${base}/${old.id}`)).status).toBe(404); + + // Unpinning an old note takes it off the board. + const unpinned = await selena.delete(`${base}/${pinned.id}/pin`); + expect(unpinned.body.note.pinned).toBe(false); + expect((await selena.get(`${base}/${pinned.id}`)).status).toBe(404); + }); +}); + +describe('editing, deleting and pinning', () => { + it('lets only the author edit the message, due date and color', async () => { + const note = await post(selena, { body: 'plumber coming thurs!' }); + const edited = await selena.patch(`${base}/${note.id}`, { + body: 'plumber coming fri!', + dueOn: inDays(3), + color: 'GREEN', + }); + expect(edited.status).toBe(200); + expect(edited.body.note).toMatchObject({ + body: 'plumber coming fri!', + dueOn: inDays(3), + color: 'GREEN', + }); + const cleared = await selena.patch(`${base}/${note.id}`, { dueOn: null }); + expect(cleared.body.note.dueOn).toBeNull(); + + const other = await melissa.patch(`${base}/${note.id}`, { body: 'nope' }); + expect(other.status).toBe(403); + const past = await selena.patch(`${base}/${note.id}`, { + dueOn: inDays(-2), + }); + expect(past.status).toBe(400); + }); + + it('lets the author or the house owner delete', async () => { + const a = await post(selena, { body: 'a' }); + const b = await post(selena, { body: 'b' }); + expect((await melissa.delete(`${base}/${a.id}`)).status).toBe(403); + expect((await selena.delete(`${base}/${a.id}`)).status).toBe(204); + // Leah created the house, so she owns it. + expect((await leah.delete(`${base}/${b.id}`)).status).toBe(204); + expect((await leah.get(base)).body.notes).toEqual([]); + }); + + it('lets any member pin and unpin; re-pinning moves a note to the top', async () => { + const a = await post(selena, { body: 'a' }); + const b = await post(selena, { body: 'b' }); + await melissa.post(`${base}/${a.id}/pin`); + await new Promise((r) => setTimeout(r, 5)); + await leah.post(`${base}/${b.id}/pin`); + let board = (await leah.get(base)).body; + expect(board.pinned.map((n: { id: number }) => n.id)).toEqual([b.id, a.id]); + + await new Promise((r) => setTimeout(r, 5)); + await leah.post(`${base}/${a.id}/pin`); + board = (await leah.get(base)).body; + expect(board.pinned.map((n: { id: number }) => n.id)).toEqual([a.id, b.id]); + + await melissa.delete(`${base}/${a.id}/pin`); + board = (await leah.get(base)).body; + expect(board.pinned.map((n: { id: number }) => n.id)).toEqual([b.id]); + expect(board.notes.map((n: { id: number }) => n.id)).toEqual([a.id]); + }); +}); + +describe('membership', () => { + it('keeps notes, with their name, after someone moves out', async () => { + await post(melissa, { body: 'Love living with you all!' }); + await melissa.delete(`${base.replace('/notes', '')}/members/me`); + const board = (await leah.get(base)).body; + expect(board.notes[0].author).toMatchObject({ netid: 'mv384' }); + }); + + it("can't see or touch another house's notes", async () => { + const note = await post(selena, { body: 'secret' }); + const outsider = await signUp('xx111'); + const other = (await outsider.post('/houses', { name: 'Elsewhere' })).body + .house; + expect((await outsider.get(base)).status).toBe(404); + expect( + (await outsider.get(`/houses/${other.id}/notes/${note.id}`)).status, + ).toBe(404); + expect( + (await outsider.post(`/houses/${other.id}/notes/${note.id}/pin`)).status, + ).toBe(404); + }); +});