diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..617a7a4 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,110 @@ +# Roomie API (MVP) + +Base URL (local): `http://localhost:8000`. JSON in and out. + +Every route except `/health` and `/auth/login` needs `Authorization: Bearer `. Locally you can use `Bearer dev:`. + +**Errors** always look like this: + +```json +{ "status": "fail", "statusCode": 400, "message": "Request validation failed", + "errorCode": "VALIDATION_ERROR", "data": { "body.name": "Too small: expected string to have >=1 characters" } } +``` + +`errorCode` is one of `VALIDATION_ERROR`, `BAD_REQUEST`, `UNAUTHORIZED` (missing or expired token: refresh and retry), `FORBIDDEN`, `NOT_FOUND`, `CONFLICT` or `TOO_MANY_REQUESTS`. + +**Types used below:** `User` = `{ id, netid, name, avatarUrl, presence: "HOME"|"AWAY" }`. Dates are `"YYYY-MM-DD"`, timestamps are ISO 8601, and money is whole cents. + +--- + +## Auth and me + +| Method | Path | Body | Returns | +|---|---|---|---| +| POST | `/auth/login` | – | `201` first time / `200` after: `{ isNewUser, user, house, pendingInvites }` | +| GET | `/users/me` | – | `{ user, house, pendingInvites }` | +| PATCH | `/users/me` | `{ name?, major?, presence? }` | same as GET | + +`house` is `{ id, name, color, role }` or `null`. `pendingInvites` are `[{ id, createdAt, house: { id, name, color, members: User[] }, invitedBy: User }]`. + +**Which screen to open:** `house` set → Home. Otherwise, `pendingInvites` not empty → "Join The Linden Loft?". Otherwise → onboarding. + +## Houses (onboarding and settings) + +| Method | Path | Body | Returns | +|---|---|---|---| +| POST | `/houses` | `{ name, color?, livingType?, address?, unit?, leaseEndsOn?, timezone?, features?, inviteNetids? }` | `201 { house }` | +| POST | `/houses/join` | `{ inviteCode }` (case-insensitive) | `{ house }` | +| POST | `/invites/:inviteId/accept` | – | `{ house }` | +| POST | `/invites/:inviteId/decline` | – | `204` | +| GET | `/houses/:houseId` | – | `{ house }` | +| PATCH | `/houses/:houseId` | any field from create except `inviteNetids` | `{ house }` | +| POST | `/houses/:houseId/invites` | `{ netids: ["sc2291"] }` | `201 { house }` | +| DELETE | `/houses/:houseId/invites/:inviteId` | – | `204` | +| POST | `/houses/:houseId/invite-code` | – (owner only) | `{ house }` with a new code | +| DELETE | `/houses/:houseId/members/me` | – | `204` (leave) | +| DELETE | `/houses/:houseId/members/:userId` | – (owner only) | `204` | + +`house`: + +```json +{ "id": 1, "name": "The Linden Loft", "color": "#8B5A34", "inviteCode": "LOFT-4827", + "livingType": "OFF_CAMPUS", "address": "112 Linden Ave", "unit": "Apt 3B", + "leaseEndsOn": "2027-05-31", "timezone": "America/New_York", + "features": ["BILLS","CHORES","SHOPPING","CALENDAR","STORAGE","MOODBOARD"], + "members": [{ "id": 1, "netid": "lk452", "name": "Leah Kim", "avatarUrl": null, "presence": "HOME", "role": "OWNER", "joinedAt": "…" }], + "pendingInvites": [{ "id": 3, "netid": "mv384", "createdAt": "…" }] } +``` + +Rules: one house per person (`409` if you're already in one). Non-members get `404` for anything under `/houses/:houseId`. If the owner leaves, the longest-standing member becomes owner, and the last person to leave deletes the house. + +## Chores + +| Method | Path | Body / query | Returns | +|---|---|---|---| +| GET | `/houses/:houseId/chores` | – | `{ chores: Chore[] }` | +| POST | `/houses/:houseId/chores` | `{ title, frequency, startsOn, rotation: userId[], allowSwaps?, reminderHour? }` | `201 { chore }` | +| GET | `/houses/:houseId/chores/:choreId` | – | `{ chore }` | +| PATCH | `/houses/:houseId/chores/:choreId` | any create field | `{ chore }` | +| DELETE | `/houses/:houseId/chores/:choreId` | – | `204` | +| GET | `/houses/:houseId/chore-assignments` | `?from=&to=&assignee=me\|&includeOverdue=true` | `{ assignments: Turn[] }` | +| POST | `/houses/:houseId/chore-assignments/:id/complete` | – | `{ assignment }` | +| DELETE | `/houses/:houseId/chore-assignments/:id/complete` | – | `{ assignment }` (undo) | +| POST | `/houses/:houseId/chore-assignments/:id/swap` | `{ withAssignmentId }` | `{ assignments: [Turn, Turn] }` | +| GET | `/houses/:houseId/chores/stats` | `?month=YYYY-MM` (default: this month) | `{ month, members: [{ user, done }] }` | + +- `frequency` is one of `DAILY`, `EVERY_OTHER_DAY`, `WEEKLY`, `BIWEEKLY` or `MONTHLY`. +- `rotation` is the turn order, and the first person takes the first turn. +- `reminderHour` (0–23, default 18) means "remind the day before at this hour". It's stored, but reminders aren't sent yet. + +`Chore`: `{ id, title, frequency, startsOn, allowSwaps, reminderHour, rotation: User[], comingUp: Turn[] }` (`comingUp` holds the next 3 turns). + +`Turn`: `{ id, chore: { id, title, frequency }, dueOn, status, assignee: User, completedAt, completedBy: User|null, canSwap }`. `status` is one of `DONE`, `OVERDUE`, `DUE_TODAY` or `UPCOMING`, computed in the house's time zone. + +**Calls each screen makes:** +- **Home, "Your chores today":** `GET /chore-assignments?from=&to=&assignee=me&includeOverdue=true` +- **Chores week view:** `GET /chore-assignments?from=&to=&includeOverdue=true`. Split the results into "Yours" and "Everyone else" by `assignee.id`. +- **Done this month bars:** `GET /chores/stats` + +**How edits work:** +- Changing the rotation makes the new first person go next. +- Changing the frequency or start date starts a new schedule; `startsOn` must be today or later. +- Finished and overdue turns are never rewritten. +- When someone moves out, the person after them in the rotation takes their turn. +- Anyone in the house can mark a turn done (covering for someone counts toward the person who did it). Only upcoming, unfinished turns of the same chore can be swapped, and you must hold one of them. + +## Shopping list + +| Method | Path | Body / query | Returns | +|---|---|---|---| +| GET | `/houses/:houseId/shopping-items` | `?category=GROCERIES\|HOUSEHOLD\|OTHER&status=NEEDED\|BOUGHT` | `{ needed: Item[], bought: Item[], billable: { itemIds, totalCents } }` | +| POST | `/houses/:houseId/shopping-items` | `{ name, category? }` | `201 { item }` | +| PATCH | `/houses/:houseId/shopping-items/:itemId` | `{ name?, category?, priceCents? }` | `{ item }` | +| DELETE | `/houses/:houseId/shopping-items/:itemId` | – | `204` | +| POST / DELETE | `/houses/:houseId/shopping-items/:itemId/claim` | – | `{ item }` ("I'll get it" / undo) | +| POST | `/houses/:houseId/shopping-items/:itemId/buy` | `{ priceCents? }` | `{ item }` | +| DELETE | `/houses/:houseId/shopping-items/:itemId/buy` | – | `{ item }` (undo) | + +`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. diff --git a/docs/roomie.postman_collection.json b/docs/roomie.postman_collection.json index 7a20188..d1c91d6 100644 --- a/docs/roomie.postman_collection.json +++ b/docs/roomie.postman_collection.json @@ -54,6 +54,34 @@ { "key": "extraInviteId", "value": "" + }, + { + "key": "choreId", + "value": "" + }, + { + "key": "assignmentId", + "value": "" + }, + { + "key": "otherAssignmentId", + "value": "" + }, + { + "key": "itemId", + "value": "" + }, + { + "key": "roommateItemId", + "value": "" + }, + { + "key": "today", + "value": "" + }, + { + "key": "weekEnd", + "value": "" } ], "item": [ @@ -603,7 +631,874 @@ ] }, { - "name": "3 \u00b7 Leaving", + "name": "3 \u00b7 Chores", + "item": [ + { + "name": "Create chore with rotation", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "", + "const { chore } = pm.response.json();", + "pm.collectionVariables.set('choreId', chore.id);", + "pm.test(\"coming up has 3 turns\", () => pm.expect(chore.comingUp).to.have.lengthOf(3));" + ] + } + }, + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "// Today and a week from today, in local time (YYYY-MM-DD)", + "const fmt = (d) => d.toLocaleDateString('en-CA');", + "const today = new Date();", + "pm.collectionVariables.set('today', fmt(today));", + "pm.collectionVariables.set('weekEnd', fmt(new Date(today.getTime() + 6 * 86400000)));" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chores", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"title\": \"Take out trash & recycling\",\n \"frequency\": \"EVERY_OTHER_DAY\",\n \"startsOn\": \"{{today}}\",\n \"rotation\": [\n {{myId}},\n {{roommateId}}\n ],\n \"allowSwaps\": true,\n \"reminderHour\": 18\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "List chores", + "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}}/chores", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores" + ] + } + } + }, + { + "name": "Get chore", + "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}}/chores/{{choreId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores", + "{{choreId}}" + ] + } + } + }, + { + "name": "This week's turns (everyone)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "", + "const a = pm.response.json().assignments;", + "pm.test(\"has turns\", () => pm.expect(a.length).to.be.above(1));", + "pm.collectionVariables.set('assignmentId', a[0].id);", + "pm.collectionVariables.set('otherAssignmentId', a[1].id);" + ] + } + }, + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "// Today and a week from today, in local time (YYYY-MM-DD)", + "const fmt = (d) => d.toLocaleDateString('en-CA');", + "const today = new Date();", + "pm.collectionVariables.set('today', fmt(today));", + "pm.collectionVariables.set('weekEnd', fmt(new Date(today.getTime() + 6 * 86400000)));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chore-assignments?from={{today}}&to={{weekEnd}}&includeOverdue=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chore-assignments" + ], + "query": [ + { + "key": "from", + "value": "{{today}}" + }, + { + "key": "to", + "value": "{{weekEnd}}" + }, + { + "key": "includeOverdue", + "value": "true" + } + ] + } + } + }, + { + "name": "My chores today (Home)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + }, + { + "listen": "prerequest", + "script": { + "type": "text/javascript", + "exec": [ + "// Today and a week from today, in local time (YYYY-MM-DD)", + "const fmt = (d) => d.toLocaleDateString('en-CA');", + "const today = new Date();", + "pm.collectionVariables.set('today', fmt(today));", + "pm.collectionVariables.set('weekEnd', fmt(new Date(today.getTime() + 6 * 86400000)));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chore-assignments?from={{today}}&to={{today}}&assignee=me&includeOverdue=true", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chore-assignments" + ], + "query": [ + { + "key": "from", + "value": "{{today}}" + }, + { + "key": "to", + "value": "{{today}}" + }, + { + "key": "assignee", + "value": "me" + }, + { + "key": "includeOverdue", + "value": "true" + } + ] + } + } + }, + { + "name": "Swap two turns", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chore-assignments/{{assignmentId}}/swap", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chore-assignments", + "{{assignmentId}}", + "swap" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"withAssignmentId\": {{otherAssignmentId}}\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Mark turn done", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "pm.test(\"status DONE\", () => pm.expect(pm.response.json().assignment.status).to.eql('DONE'));" + ] + } + } + ], + "request": { + "method": "POST", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chore-assignments/{{assignmentId}}/complete", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chore-assignments", + "{{assignmentId}}", + "complete" + ] + } + } + }, + { + "name": "Undo done", + "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}}/chore-assignments/{{assignmentId}}/complete", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chore-assignments", + "{{assignmentId}}", + "complete" + ] + } + } + }, + { + "name": "Done this month", + "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}}/chores/stats", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores", + "stats" + ] + } + } + }, + { + "name": "Reorder rotation", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "pm.test(\"roommate goes next\", () => pm.expect(pm.response.json().chore.comingUp[0].assignee.id).to.eql(Number(pm.collectionVariables.get('roommateId'))));" + ] + } + } + ], + "request": { + "method": "PATCH", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/chores/{{choreId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores", + "{{choreId}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"rotation\": [\n {{roommateId}},\n {{myId}}\n ]\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Delete chore", + "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}}/chores/{{choreId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "chores", + "{{choreId}}" + ] + } + } + } + ] + }, + { + "name": "4 \u00b7 Shopping", + "item": [ + { + "name": "Add item", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "pm.collectionVariables.set('itemId', pm.response.json().item.id);" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/shopping-items", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Eggs (dozen)\",\n \"category\": \"GROCERIES\"\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Roommate adds item", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 201\", () => pm.response.to.have.status(201));", + "pm.collectionVariables.set('roommateItemId', pm.response.json().item.id);" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/shopping-items", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"name\": \"Dish soap\",\n \"category\": \"HOUSEHOLD\"\n}", + "options": { + "raw": { + "language": "json" + } + } + }, + "auth": { + "type": "bearer", + "bearer": [ + { + "key": "token", + "value": "dev:{{roommateNetid}}", + "type": "string" + } + ] + } + } + }, + { + "name": "List", + "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}}/shopping-items", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items" + ] + } + } + }, + { + "name": "List household only", + "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}}/shopping-items?category=HOUSEHOLD", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items" + ], + "query": [ + { + "key": "category", + "value": "HOUSEHOLD" + } + ] + } + } + }, + { + "name": "I'll get it (claim)", + "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}}/shopping-items/{{roommateItemId}}/claim", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{roommateItemId}}", + "claim" + ] + } + } + }, + { + "name": "Unclaim", + "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}}/shopping-items/{{roommateItemId}}/claim", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{roommateItemId}}", + "claim" + ] + } + } + }, + { + "name": "Mark bought ($4.29)", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));" + ] + } + } + ], + "request": { + "method": "POST", + "header": [ + { + "key": "Content-Type", + "value": "application/json" + } + ], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/shopping-items/{{itemId}}/buy", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{itemId}}", + "buy" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"priceCents\": 429\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "List shows billable total", + "event": [ + { + "listen": "test", + "script": { + "type": "text/javascript", + "exec": [ + "pm.test(\"status is 200\", () => pm.response.to.have.status(200));", + "pm.test(\"billable is $4.29\", () => pm.expect(pm.response.json().billable.totalCents).to.eql(429));" + ] + } + } + ], + "request": { + "method": "GET", + "header": [], + "url": { + "raw": "{{baseUrl}}/houses/{{houseId}}/shopping-items", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items" + ] + } + } + }, + { + "name": "Edit item (rename / price)", + "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}}/shopping-items/{{itemId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{itemId}}" + ] + }, + "body": { + "mode": "raw", + "raw": "{\n \"priceCents\": 499\n}", + "options": { + "raw": { + "language": "json" + } + } + } + } + }, + { + "name": "Undo bought", + "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}}/shopping-items/{{itemId}}/buy", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{itemId}}", + "buy" + ] + } + } + }, + { + "name": "Delete item", + "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}}/shopping-items/{{itemId}}", + "host": [ + "{{baseUrl}}" + ], + "path": [ + "houses", + "{{houseId}}", + "shopping-items", + "{{itemId}}" + ] + } + } + } + ] + }, + { + "name": "5 \u00b7 Leaving", "item": [ { "name": "Roommate leaves house", @@ -678,4 +1573,4 @@ ] } ] -} \ No newline at end of file +} diff --git a/package.json b/package.json index 6803bca..ec94b4c 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "format": "prettier --write '{src,test,prisma}/**/*.ts'", "db:migrate": "prisma migrate dev && prisma generate", "db:deploy": "prisma migrate deploy", + "db:seed": "tsx prisma/seed.ts", "studio": "prisma studio", "generate": "prisma generate" }, diff --git a/prisma.config.ts b/prisma.config.ts index 921e7b4..60357ad 100644 --- a/prisma.config.ts +++ b/prisma.config.ts @@ -5,6 +5,7 @@ export default defineConfig({ schema: 'prisma/schema.prisma', migrations: { path: 'prisma/migrations', + seed: 'tsx prisma/seed.ts', }, datasource: { url: env('DATABASE_URL'), diff --git a/prisma/seed.ts b/prisma/seed.ts new file mode 100644 index 0000000..446ea0c --- /dev/null +++ b/prisma/seed.ts @@ -0,0 +1,130 @@ +/** + * Demo data matching the Figma designs: The Linden Loft with Leah, Selena and Melissa. + * Run with `npm run db:seed` (wipes the database first, so never point it at prod). + * Then sign in locally as `Bearer dev:lk452`, `dev:sc2291` or `dev:mv384`. + */ +import 'dotenv/config'; + +import { prisma } from '../src/prisma.js'; +import { todayIn } from '../src/utils/dates.js'; + +const TZ = 'America/New_York'; + +const main = async () => { + if (process.env.NODE_ENV === 'production') { + throw new Error('Refusing to seed in production.'); + } + + await prisma.$executeRawUnsafe( + 'TRUNCATE "User", "House" RESTART IDENTITY CASCADE', + ); + + const person = (netid: string, name: string, major: string) => + prisma.user.create({ + data: { + firebaseUid: `dev-${netid}`, + netid, + email: `${netid}@cornell.edu`, + name, + major, + }, + }); + const leah = await person('lk452', 'Leah Kim', 'Info Science'); + const selena = await person('sc2291', 'Selena Chen', 'Info Science'); + const melissa = await person( + 'mv384', + 'Melissa Velasquez', + 'Computer Science', + ); + await prisma.user.update({ + where: { id: melissa.id }, + data: { presence: 'AWAY' }, + }); + + const house = await prisma.house.create({ + data: { + name: 'The Linden Loft', + color: '#8B5A34', + inviteCode: 'LOFT-4827', + address: '112 Linden Ave', + unit: 'Apt 3B', + leaseEndsOn: new Date('2027-05-31T00:00:00Z'), + timezone: TZ, + createdById: leah.id, + members: { + create: [ + { userId: leah.id, role: 'OWNER' }, + { userId: selena.id }, + { userId: melissa.id }, + ], + }, + }, + }); + + const today = todayIn(TZ); + const chore = ( + title: string, + frequency: 'DAILY' | 'EVERY_OTHER_DAY' | 'WEEKLY', + rotation: number[], + ) => + prisma.chore.create({ + data: { + houseId: house.id, + title, + frequency, + startsOn: today, + createdById: leah.id, + rotation: { + create: rotation.map((userId, position) => ({ userId, position })), + }, + }, + }); + await chore('Take out trash & recycling', 'WEEKLY', [ + leah.id, + selena.id, + melissa.id, + ]); + await chore('Wipe kitchen counters', 'EVERY_OTHER_DAY', [leah.id, selena.id]); + await chore('Vacuum living room', 'WEEKLY', [selena.id, melissa.id, leah.id]); + await chore('Clean bathroom', 'WEEKLY', [melissa.id, leah.id, selena.id]); + + const item = ( + name: string, + addedById: number, + extra: Record = {}, + ) => + prisma.shoppingItem.create({ + data: { houseId: house.id, name, addedById, ...extra }, + }); + await item('Eggs (dozen)', melissa.id); + await item('Oat milk', leah.id, { claimedById: selena.id }); + await item('Dish soap', selena.id, { category: 'HOUSEHOLD' }); + await item('Trash bags', leah.id, { + category: 'HOUSEHOLD', + claimedById: leah.id, + }); + const bought = { + status: 'BOUGHT' as const, + boughtById: leah.id, + boughtAt: new Date(), + }; + await item('Apples', leah.id, { ...bought, priceCents: 429 }); + await item('Whole milk', leah.id, { ...bought, priceCents: 399 }); + await item('Paper towels', leah.id, { + ...bought, + priceCents: 649, + category: 'HOUSEHOLD', + }); + + console.log( + `Seeded "${house.name}" (id ${house.id}, code ${house.inviteCode}).`, + ); + console.log('Sign in with Bearer dev:lk452 / dev:sc2291 / dev:mv384'); +}; + +main() + .catch((e) => { + console.error(e); + process.exit(1); + }) + .finally(() => prisma.$disconnect()); diff --git a/src/app.ts b/src/app.ts index 6a3abc5..83e44e2 100644 --- a/src/app.ts +++ b/src/app.ts @@ -47,7 +47,6 @@ export const createApp = () => { router.use('/users', userRouter); router.use('/houses', houseRouter); router.use('/invites', inviteRouter); - // Feature routers (chores, shopping) get mounted here. app.use(router); diff --git a/src/houses/houseRouter.ts b/src/houses/houseRouter.ts index 0105c2f..4d6757e 100644 --- a/src/houses/houseRouter.ts +++ b/src/houses/houseRouter.ts @@ -1,11 +1,12 @@ import { Router } from 'express'; -import choreRouter from '../chores/choreRouter.js'; +import choreRouter from '../chores/choreRouter.js'; import { requireHouseMember, requireHouseOwner, } from '../middleware/authentication.js'; import { validateRequest } from '../middleware/validateRequest.js'; +import shoppingRouter from '../shopping/shoppingRouter.js'; import { acceptInvite, createHouse, @@ -72,4 +73,6 @@ house.delete( // Feature routers mounted under /houses/:houseId house.use('/', choreRouter); +house.use('/shopping-items', shoppingRouter); + export default router; diff --git a/src/houses/houseService.ts b/src/houses/houseService.ts index 22ce733..6053a23 100644 --- a/src/houses/houseService.ts +++ b/src/houses/houseService.ts @@ -240,9 +240,10 @@ export const respondToInvite = async ( /** * Leaving (or being removed): + * - 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 - * - features hook their own cleanup in below (e.g. chores drop the person from - * rotations, shopping releases their "I'll get it" claims) + * Done chores and bought items stay in the history. */ export const removeMember = async ( houseId: number, @@ -271,6 +272,11 @@ export const removeMember = async ( targetUserId, todayIn(house.timezone), ); + await tx.shoppingItem.updateMany({ + where: { houseId, claimedById: targetUserId, status: 'NEEDED' }, + data: { claimedById: null }, + }); + await tx.houseMember.delete({ where: { userId: targetUserId } }); const others = await tx.houseMember.findMany({ diff --git a/src/shopping/shopping.schema.ts b/src/shopping/shopping.schema.ts new file mode 100644 index 0000000..d9c3ff9 --- /dev/null +++ b/src/shopping/shopping.schema.ts @@ -0,0 +1,43 @@ +import { z } from 'zod'; + +import { houseIdParams } from '../houses/houses.schema.js'; + +const category = z.enum(['GROCERIES', 'HOUSEHOLD', 'OTHER']); +/** Money is always whole cents: $4.29 → 429. */ +const cents = z.number().int().min(0).max(10_000_000); + +const itemParams = houseIdParams.extend({ itemId: z.coerce.number().int() }); + +export const listItemsSchema = z.object({ + params: houseIdParams, + query: z.object({ + category: category.optional(), + status: z.enum(['NEEDED', 'BOUGHT']).optional(), + }), +}); + +export const createItemSchema = z.object({ + params: houseIdParams, + body: z.object({ + name: z.string().trim().min(1).max(80), + category: category.default('GROCERIES'), + }), +}); + +export const updateItemSchema = z.object({ + params: itemParams, + body: z + .object({ + name: z.string().trim().min(1).max(80), + category, + priceCents: cents.nullable(), + }) + .partial(), +}); + +export const itemParamsSchema = z.object({ params: itemParams }); + +export const buyItemSchema = z.object({ + params: itemParams, + body: z.object({ priceCents: cents.optional() }), +}); diff --git a/src/shopping/shoppingController.ts b/src/shopping/shoppingController.ts new file mode 100644 index 0000000..adf555b --- /dev/null +++ b/src/shopping/shoppingController.ts @@ -0,0 +1,181 @@ +import type { Request, Response } from 'express'; + +import type { Prisma } from '../generated/prisma/client.js'; +import { valid } from '../middleware/validateRequest.js'; +import { prisma } from '../prisma.js'; +import { BadRequestError, NotFoundError } from '../utils/AppError.js'; +import { publicUserSelect } from '../utils/selects.js'; +import { + buyItemSchema, + createItemSchema, + itemParamsSchema, + listItemsSchema, + updateItemSchema, +} from './shopping.schema.js'; + +/** Bought items drop off the list after this long unless they're still waiting to be billed. */ +const BOUGHT_VISIBLE_DAYS = 14; + +const itemInclude = { + addedBy: { select: publicUserSelect }, + claimedBy: { select: publicUserSelect }, + boughtBy: { select: publicUserSelect }, +} as const; + +type ItemRow = Prisma.ShoppingItemGetPayload<{ include: typeof itemInclude }>; + +const serialize = ({ + houseId: _h, + addedById: _a, + claimedById: _c, + boughtById: _b, + ...item +}: ItemRow) => item; + +const loadItem = async (houseId: number, itemId: number) => { + const item = await prisma.shoppingItem.findFirst({ + where: { id: itemId, houseId }, + include: itemInclude, + }); + if (!item) throw new NotFoundError('Item not found.'); + return item; +}; + +const updateAndReturn = async ( + houseId: number, + itemId: number, + data: Prisma.ShoppingItemUncheckedUpdateInput, +) => { + await loadItem(houseId, itemId); + await prisma.shoppingItem.update({ where: { id: itemId }, data }); + return serialize(await loadItem(houseId, itemId)); +}; + +/** + * GET /houses/:houseId/shopping-items + * Returns the two sections of the Shopping screen plus what "Split $X as a bill" + * would cover (bought by you, priced, not billed yet). + */ +export const listItems = async (req: Request, res: Response) => { + const { params, query } = valid(req, listItemsSchema); + const since = new Date(Date.now() - BOUGHT_VISIBLE_DAYS * 86_400_000); + + const items = await prisma.shoppingItem.findMany({ + where: { + houseId: params.houseId, + ...(query.category && { category: query.category }), + ...(query.status && { status: query.status }), + OR: [ + { status: 'NEEDED' }, + { status: 'BOUGHT', billId: null }, + { status: 'BOUGHT', boughtAt: { gte: since } }, + ], + }, + orderBy: [{ createdAt: 'asc' }], + include: itemInclude, + }); + + const needed = items.filter((i) => i.status === 'NEEDED'); + const bought = items + .filter((i) => i.status === 'BOUGHT') + .sort((a, b) => b.boughtAt!.getTime() - a.boughtAt!.getTime()); + const billable = bought.filter( + (i) => + i.boughtById === req.user!.id && + i.billId === null && + i.priceCents !== null, + ); + + res.json({ + needed: needed.map(serialize), + bought: bought.map(serialize), + billable: { + itemIds: billable.map((i) => i.id), + totalCents: billable.reduce((sum, i) => sum + i.priceCents!, 0), + }, + }); +}; + +export const createItem = async (req: Request, res: Response) => { + const { params, body } = valid(req, createItemSchema); + const item = await prisma.shoppingItem.create({ + data: { ...body, houseId: params.houseId, addedById: req.user!.id }, + include: itemInclude, + }); + res.status(201).json({ item: serialize(item) }); +}; + +export const updateItem = async (req: Request, res: Response) => { + const { params, body } = valid(req, updateItemSchema); + const existing = await loadItem(params.houseId, params.itemId); + if (existing.billId !== null && body.priceCents !== undefined) { + throw new BadRequestError('This item is already on a bill.'); + } + res.json({ + item: await updateAndReturn(params.houseId, params.itemId, body), + }); +}; + +export const deleteItem = async (req: Request, res: Response) => { + const { params } = valid(req, itemParamsSchema); + const item = await loadItem(params.houseId, params.itemId); + if (item.billId !== null) { + throw new BadRequestError('This item is on a bill and can’t be deleted.'); + } + await prisma.shoppingItem.delete({ where: { id: item.id } }); + res.status(204).end(); +}; + +/** "I'll get it" */ +export const claimItem = async (req: Request, res: Response) => { + const { params } = valid(req, itemParamsSchema); + const item = await loadItem(params.houseId, params.itemId); + if (item.status !== 'NEEDED') throw new BadRequestError('Already bought.'); + res.json({ + item: await updateAndReturn(params.houseId, params.itemId, { + claimedById: req.user!.id, + }), + }); +}; + +export const unclaimItem = async (req: Request, res: Response) => { + const { params } = valid(req, itemParamsSchema); + res.json({ + item: await updateAndReturn(params.houseId, params.itemId, { + claimedById: null, + }), + }); +}; + +/** Tick the checkbox. Price is optional now and can be added later with PATCH. */ +export const buyItem = async (req: Request, res: Response) => { + const { params, body } = valid(req, buyItemSchema); + const item = await loadItem(params.houseId, params.itemId); + if (item.status === 'BOUGHT') throw new BadRequestError('Already bought.'); + res.json({ + item: await updateAndReturn(params.houseId, params.itemId, { + status: 'BOUGHT', + boughtById: req.user!.id, + boughtAt: new Date(), + claimedById: null, + ...(body.priceCents !== undefined && { priceCents: body.priceCents }), + }), + }); +}; + +/** Undo a mis-tap. */ +export const unbuyItem = async (req: Request, res: Response) => { + const { params } = valid(req, itemParamsSchema); + const item = await loadItem(params.houseId, params.itemId); + if (item.billId !== null) { + throw new BadRequestError('This item is already on a bill.'); + } + res.json({ + item: await updateAndReturn(params.houseId, params.itemId, { + status: 'NEEDED', + boughtById: null, + boughtAt: null, + priceCents: null, + }), + }); +}; diff --git a/src/shopping/shoppingRouter.ts b/src/shopping/shoppingRouter.ts new file mode 100644 index 0000000..e10d154 --- /dev/null +++ b/src/shopping/shoppingRouter.ts @@ -0,0 +1,34 @@ +import { Router } from 'express'; + +import { validateRequest } from '../middleware/validateRequest.js'; +import { + buyItemSchema, + createItemSchema, + itemParamsSchema, + listItemsSchema, + updateItemSchema, +} from './shopping.schema.js'; +import { + buyItem, + claimItem, + createItem, + deleteItem, + listItems, + unbuyItem, + unclaimItem, + updateItem, +} from './shoppingController.js'; + +/** Mounted at /houses/:houseId/shopping-items (membership already checked). */ +const router = Router({ mergeParams: true }); + +router.get('/', validateRequest(listItemsSchema), listItems); +router.post('/', validateRequest(createItemSchema), createItem); +router.patch('/:itemId', validateRequest(updateItemSchema), updateItem); +router.delete('/:itemId', validateRequest(itemParamsSchema), deleteItem); +router.post('/:itemId/claim', validateRequest(itemParamsSchema), claimItem); +router.delete('/:itemId/claim', validateRequest(itemParamsSchema), unclaimItem); +router.post('/:itemId/buy', validateRequest(buyItemSchema), buyItem); +router.delete('/:itemId/buy', validateRequest(itemParamsSchema), unbuyItem); + +export default router; diff --git a/test/shopping.test.ts b/test/shopping.test.ts new file mode 100644 index 0000000..5ae1525 --- /dev/null +++ b/test/shopping.test.ts @@ -0,0 +1,135 @@ +import { beforeEach, describe, expect, it } from 'vitest'; + +import { signUp } from './helpers.js'; + +type Client = Awaited>; +let leah: Client, selena: Client, melissa: Client, base: string; + +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}/shopping-items`; +}); + +const add = async (as: Client, name: string, category?: string) => { + const res = await as.post(base, { name, ...(category && { category }) }); + expect(res.status).toBe(201); + return res.body.item; +}; + +describe('shopping list', () => { + it('adds items and shows who added them', async () => { + const eggs = await add(melissa, 'Eggs (dozen)'); + expect(eggs).toMatchObject({ + name: 'Eggs (dozen)', + category: 'GROCERIES', + status: 'NEEDED', + addedBy: { netid: 'mv384' }, + claimedBy: null, + }); + expect(eggs).not.toHaveProperty('houseId'); + + await add(selena, 'Dish soap', 'HOUSEHOLD'); + const list = await leah.get(base); + expect(list.body.needed.map((i: { name: string }) => i.name)).toEqual([ + 'Eggs (dozen)', + 'Dish soap', + ]); + + const household = await leah.get(`${base}?category=HOUSEHOLD`); + expect(household.body.needed).toHaveLength(1); + }); + + it('"I\'ll get it" claims and unclaims', async () => { + const soap = await add(selena, 'Dish soap', 'HOUSEHOLD'); + const claimed = await leah.post(`${base}/${soap.id}/claim`); + expect(claimed.body.item.claimedBy).toMatchObject({ netid: 'lk452' }); + const unclaimed = await leah.delete(`${base}/${soap.id}/claim`); + expect(unclaimed.body.item.claimedBy).toBeNull(); + }); + + it('buying moves items to "Bought" and totals what you can split', async () => { + const apples = await add(leah, 'Apples'); + const milk = await add(leah, 'Whole milk'); + const towels = await add(leah, 'Paper towels', 'HOUSEHOLD'); + const eggs = await add(melissa, 'Eggs'); + + await leah.post(`${base}/${apples.id}/buy`, { priceCents: 429 }); + await leah.post(`${base}/${milk.id}/buy`, { priceCents: 399 }); + await leah.post(`${base}/${towels.id}/buy`); // price added later + await leah.patch(`${base}/${towels.id}`, { priceCents: 649 }); + await selena.post(`${base}/${eggs.id}/buy`, { priceCents: 500 }); + + const list = (await leah.get(base)).body; + expect(list.needed).toEqual([]); + expect(list.bought).toHaveLength(4); + expect(list.bought[0]).toMatchObject({ + status: 'BOUGHT', + boughtBy: expect.any(Object), + }); + // The design's "Split $14.77 as a bill": only Leah's priced purchases. + expect(list.billable).toEqual({ + itemIds: expect.arrayContaining([apples.id, milk.id, towels.id]), + totalCents: 1477, + }); + expect(list.billable.itemIds).toHaveLength(3); + }); + + it('buying clears the claim, and can be undone', async () => { + const soap = await add(selena, 'Dish soap'); + await leah.post(`${base}/${soap.id}/claim`); + const bought = await leah.post(`${base}/${soap.id}/buy`, { + priceCents: 300, + }); + expect(bought.body.item).toMatchObject({ + claimedBy: null, + boughtBy: { netid: 'lk452' }, + }); + expect((await leah.post(`${base}/${soap.id}/buy`)).status).toBe(400); + + const undone = await leah.delete(`${base}/${soap.id}/buy`); + expect(undone.body.item).toMatchObject({ + status: 'NEEDED', + boughtBy: null, + priceCents: null, + }); + }); + + it('validates prices as whole cents', async () => { + const soap = await add(selena, 'Dish soap'); + const res = await leah.post(`${base}/${soap.id}/buy`, { priceCents: 3.5 }); + expect(res.status).toBe(400); + }); + + it('deletes items', async () => { + const soap = await add(selena, 'Dish soap'); + expect((await leah.delete(`${base}/${soap.id}`)).status).toBe(204); + expect((await leah.get(base)).body.needed).toEqual([]); + }); + + it('releases claims when someone moves out', async () => { + const soap = await add(selena, 'Dish soap'); + await melissa.post(`${base}/${soap.id}/claim`); + const houseId = base.split('/')[2]; + await melissa.delete(`/houses/${houseId}/members/me`); + const list = (await leah.get(base)).body; + expect(list.needed[0].claimedBy).toBeNull(); + }); + + it("can't touch another house's list", async () => { + const soap = await add(selena, 'Dish soap'); + const outsider = await signUp('xx111'); + const other = (await outsider.post('/houses', { name: 'Elsewhere' })).body + .house; + const res = await outsider.post( + `/houses/${other.id}/shopping-items/${soap.id}/buy`, + ); + expect(res.status).toBe(404); + expect((await outsider.get(base)).status).toBe(404); + }); +});