From 281c1a45731cda5a54846caed58e74e7bc5c087a Mon Sep 17 00:00:00 2001 From: Mihili Herath Date: Mon, 9 Nov 2026 21:06:49 -0500 Subject: [PATCH] Add chores --- src/chores/choreController.ts | 118 +++++++++ src/chores/choreRouter.ts | 68 +++++ src/chores/choreService.ts | 482 ++++++++++++++++++++++++++++++++++ src/chores/chores.schema.ts | 84 ++++++ src/chores/schedule.ts | 69 +++++ src/houses/houseRouter.ts | 3 +- src/houses/houseService.ts | 14 +- test/chores.test.ts | 376 ++++++++++++++++++++++++++ test/schedule.test.ts | 63 +++++ 9 files changed, 1273 insertions(+), 4 deletions(-) create mode 100644 src/chores/choreController.ts create mode 100644 src/chores/choreRouter.ts create mode 100644 src/chores/choreService.ts create mode 100644 src/chores/chores.schema.ts create mode 100644 src/chores/schedule.ts create mode 100644 test/chores.test.ts create mode 100644 test/schedule.test.ts diff --git a/src/chores/choreController.ts b/src/chores/choreController.ts new file mode 100644 index 0000000..fb9f2e8 --- /dev/null +++ b/src/chores/choreController.ts @@ -0,0 +1,118 @@ +import type { Request, Response } from 'express'; + +import { valid } from '../middleware/validateRequest.js'; +import { prisma } from '../prisma.js'; +import { todayIn } from '../utils/dates.js'; +import * as choreService from './choreService.js'; +import { + assignmentParamsSchema, + choreParamsSchema, + createChoreSchema, + listAssignmentsSchema, + listChoresSchema, + statsSchema, + swapSchema, + updateChoreSchema, +} from './chores.schema.js'; + +/** "Today" depends on where the house is, not the server. */ +const houseToday = async (houseId: number) => { + const { timezone } = await prisma.house.findUniqueOrThrow({ + where: { id: houseId }, + select: { timezone: true }, + }); + return todayIn(timezone); +}; + +export const listChores = async (req: Request, res: Response) => { + const { params } = valid(req, listChoresSchema); + const today = await houseToday(params.houseId); + res.json({ chores: await choreService.listChores(params.houseId, today) }); +}; + +export const getChore = async (req: Request, res: Response) => { + const { params } = valid(req, choreParamsSchema); + const today = await houseToday(params.houseId); + res.json({ + chore: await choreService.getChore(params.houseId, params.choreId, today), + }); +}; + +export const createChore = async (req: Request, res: Response) => { + const { params, body } = valid(req, createChoreSchema); + const today = await houseToday(params.houseId); + const chore = await choreService.createChore( + params.houseId, + req.user!.id, + body, + today, + ); + res.status(201).json({ chore }); +}; + +export const updateChore = async (req: Request, res: Response) => { + const { params, body } = valid(req, updateChoreSchema); + const today = await houseToday(params.houseId); + const chore = await choreService.updateChore( + params.houseId, + params.choreId, + body, + today, + ); + res.json({ chore }); +}; + +export const archiveChore = async (req: Request, res: Response) => { + const { params } = valid(req, choreParamsSchema); + const today = await houseToday(params.houseId); + await choreService.archiveChore(params.houseId, params.choreId, today); + res.status(204).end(); +}; + +export const listAssignments = async (req: Request, res: Response) => { + const { params, query } = valid(req, listAssignmentsSchema); + const today = await houseToday(params.houseId); + const assignments = await choreService.listAssignments( + params.houseId, + req.user!.id, + query, + today, + ); + res.json({ assignments }); +}; + +const setCompleted = + (completed: boolean) => async (req: Request, res: Response) => { + const { params } = valid(req, assignmentParamsSchema); + const today = await houseToday(params.houseId); + const assignment = await choreService.setCompleted( + params.houseId, + params.assignmentId, + req.user!.id, + completed, + today, + ); + res.json({ assignment }); + }; +export const completeAssignment = setCompleted(true); +export const uncompleteAssignment = setCompleted(false); + +export const swapAssignment = async (req: Request, res: Response) => { + const { params, body } = valid(req, swapSchema); + const today = await houseToday(params.houseId); + const assignments = await choreService.swapTurns( + params.houseId, + params.assignmentId, + body.withAssignmentId, + req.user!.id, + today, + ); + res.json({ assignments }); +}; + +export const stats = async (req: Request, res: Response) => { + const { params, query } = valid(req, statsSchema); + const month = + query.month ?? (await houseToday(params.houseId)).toISOString().slice(0, 7); + res.json(await choreService.monthlyStats(params.houseId, month)); +}; diff --git a/src/chores/choreRouter.ts b/src/chores/choreRouter.ts new file mode 100644 index 0000000..761325d --- /dev/null +++ b/src/chores/choreRouter.ts @@ -0,0 +1,68 @@ +import { Router } from 'express'; + +import { validateRequest } from '../middleware/validateRequest.js'; +import { + archiveChore, + completeAssignment, + createChore, + getChore, + listAssignments, + listChores, + stats, + swapAssignment, + uncompleteAssignment, + updateChore, +} from './choreController.js'; +import { + assignmentParamsSchema, + choreParamsSchema, + createChoreSchema, + listAssignmentsSchema, + listChoresSchema, + statsSchema, + swapSchema, + updateChoreSchema, +} from './chores.schema.js'; + +/** Mounted under /houses/:houseId (membership already checked). */ +const router = Router({ mergeParams: true }); + +// Chore definitions + rotations ("New chore" screen) +router.get('/chores', validateRequest(listChoresSchema), listChores); +router.post('/chores', validateRequest(createChoreSchema), createChore); +router.get('/chores/stats', validateRequest(statsSchema), stats); +router.get('/chores/:choreId', validateRequest(choreParamsSchema), getChore); +router.patch( + '/chores/:choreId', + validateRequest(updateChoreSchema), + updateChore, +); +router.delete( + '/chores/:choreId', + validateRequest(choreParamsSchema), + archiveChore, +); + +// Individual turns ("Chores" week view, "Your chores today" on Home) +router.get( + '/chore-assignments', + validateRequest(listAssignmentsSchema), + listAssignments, +); +router.post( + '/chore-assignments/:assignmentId/complete', + validateRequest(assignmentParamsSchema), + completeAssignment, +); +router.delete( + '/chore-assignments/:assignmentId/complete', + validateRequest(assignmentParamsSchema), + uncompleteAssignment, +); +router.post( + '/chore-assignments/:assignmentId/swap', + validateRequest(swapSchema), + swapAssignment, +); + +export default router; diff --git a/src/chores/choreService.ts b/src/chores/choreService.ts new file mode 100644 index 0000000..f43dada --- /dev/null +++ b/src/chores/choreService.ts @@ -0,0 +1,482 @@ +import type { + Chore, + ChoreFrequency, + ChoreRotation, + Prisma, +} from '../generated/prisma/client.js'; +import { prisma } from '../prisma.js'; +import { + BadRequestError, + ForbiddenError, + NotFoundError, +} from '../utils/AppError.js'; +import { addDays, formatDate, parseDate } from '../utils/dates.js'; +import { publicUserSelect } from '../utils/selects.js'; +import { + assigneeFor, + dueDateOf, + firstTurnOnOrAfter, + turnsInRange, +} from './schedule.js'; + +type Db = Prisma.TransactionClient | typeof prisma; +type ChoreWithRotation = Chore & { rotation: ChoreRotation[] }; + +const OVERDUE_LOOKBACK_DAYS = 30; +const COMING_UP_COUNT = 3; + +const rotationOrder = (chore: ChoreWithRotation) => + [...chore.rotation] + .sort((a, b) => a.position - b.position) + .map((r) => r.userId); + +const loadChore = async (db: Db, houseId: number, choreId: number) => { + const chore = await db.chore.findFirst({ + where: { id: choreId, houseId, archivedAt: null }, + include: { rotation: true }, + }); + if (!chore) throw new NotFoundError('Chore not found.'); + return chore; +}; + +const assertMembers = async (db: Db, houseId: number, userIds: number[]) => { + const count = await db.houseMember.count({ + where: { houseId, userId: { in: userIds } }, + }); + if (count !== new Set(userIds).size) { + throw new BadRequestError( + 'Everyone in the rotation must live in the house.', + ); + } +}; + +/** + * Turns are stored lazily: whenever a date range is read, any turn in it that + * hasn't been stored yet is created from the rotation. After that the stored row + * wins, so completions and swaps stick even if the rotation changes later. + */ +const ensureAssignments = async ( + db: Db, + chores: ChoreWithRotation[], + from: Date, + to: Date, +) => { + const rows: Prisma.ChoreAssignmentCreateManyInput[] = []; + for (const chore of chores) { + const order = rotationOrder(chore); + for (const { k, dueOn } of turnsInRange(chore, from, to)) { + const occurrence = chore.occurrenceBase + k; + const assigneeId = assigneeFor(chore, order, occurrence); + if (assigneeId !== null) { + rows.push({ choreId: chore.id, occurrence, dueOn, assigneeId }); + } + } + } + if (rows.length > 0) { + await db.choreAssignment.createMany({ data: rows, skipDuplicates: true }); + } +}; + +/** Drops unfinished turns due today or later so they're regenerated from the new setup. */ +const clearFutureTurns = (db: Db, choreId: number, today: Date) => + db.choreAssignment.deleteMany({ + where: { choreId, completedAt: null, dueOn: { gte: today } }, + }); + +const writeRotation = async (db: Db, choreId: number, userIds: number[]) => { + await db.choreRotation.deleteMany({ where: { choreId } }); + await db.choreRotation.createMany({ + data: userIds.map((userId, position) => ({ choreId, userId, position })), + }); +}; + +const assignmentInclude = { + chore: { + select: { id: true, title: true, frequency: true, allowSwaps: true }, + }, + assignee: { select: publicUserSelect }, + completedBy: { select: publicUserSelect }, +} as const; + +type AssignmentRow = Prisma.ChoreAssignmentGetPayload<{ + include: typeof assignmentInclude; +}>; + +const serializeAssignment = (a: AssignmentRow, today: Date) => ({ + id: a.id, + chore: { id: a.chore.id, title: a.chore.title, frequency: a.chore.frequency }, + dueOn: formatDate(a.dueOn), + status: a.completedAt + ? 'DONE' + : a.dueOn < today + ? 'OVERDUE' + : a.dueOn.getTime() === today.getTime() + ? 'DUE_TODAY' + : 'UPCOMING', + assignee: a.assignee, + completedAt: a.completedAt, + completedBy: a.completedBy, + canSwap: a.chore.allowSwaps && !a.completedAt && a.dueOn >= today, +}); + +// ─────────────────────────── Chore definitions ─────────────────────────── + +const serializeChore = async (chore: ChoreWithRotation, today: Date) => { + // "Coming up": make sure the next few turns exist, then read them back. + const k = firstTurnOnOrAfter(chore, today); + await ensureAssignments( + prisma, + [chore], + today, + dueDateOf(chore, k + COMING_UP_COUNT - 1), + ); + const comingUp = await prisma.choreAssignment.findMany({ + where: { choreId: chore.id, dueOn: { gte: today } }, + orderBy: { dueOn: 'asc' }, + take: COMING_UP_COUNT, + include: assignmentInclude, + }); + const users = await prisma.user.findMany({ + where: { id: { in: chore.rotation.map((r) => r.userId) } }, + select: publicUserSelect, + }); + const byId = new Map(users.map((u) => [u.id, u])); + + return { + id: chore.id, + title: chore.title, + frequency: chore.frequency, + startsOn: formatDate(chore.startsOn), + allowSwaps: chore.allowSwaps, + reminderHour: chore.reminderHour, + rotation: rotationOrder(chore).map((id) => byId.get(id)!), + comingUp: comingUp.map((a) => serializeAssignment(a, today)), + }; +}; + +export const listChores = async (houseId: number, today: Date) => { + const chores = await prisma.chore.findMany({ + where: { houseId, archivedAt: null }, + include: { rotation: true }, + orderBy: { createdAt: 'asc' }, + }); + return Promise.all(chores.map((c) => serializeChore(c, today))); +}; + +export const getChore = async (houseId: number, choreId: number, today: Date) => + serializeChore(await loadChore(prisma, houseId, choreId), today); + +export interface ChoreInput { + title?: string; + frequency?: ChoreFrequency; + startsOn?: string; + rotation?: number[]; + allowSwaps?: boolean; + reminderHour?: number | null; +} + +export const createChore = async ( + houseId: number, + createdById: number, + input: Required< + Pick + > & + ChoreInput, + today: Date, +) => { + const id = await prisma.$transaction(async (tx) => { + await assertMembers(tx, houseId, input.rotation); + const chore = await tx.chore.create({ + data: { + houseId, + createdById, + title: input.title, + frequency: input.frequency, + startsOn: parseDate(input.startsOn), + allowSwaps: input.allowSwaps, + reminderHour: input.reminderHour, + }, + }); + await writeRotation(tx, chore.id, input.rotation); + return chore.id; + }); + return getChore(houseId, id, today); +}; + +/** + * Editing a chore never rewrites history: finished turns and overdue ones stay. + * - schedule change (frequency / start date): new turns start at startsOn + * (defaults to the next turn under the old schedule) with rotation position 0. + * - rotation change only: rotation position 0 takes the next turn. + */ +export const updateChore = async ( + houseId: number, + choreId: number, + input: ChoreInput, + today: Date, +) => { + await prisma.$transaction(async (tx) => { + const chore = await loadChore(tx, houseId, choreId); + const data: Prisma.ChoreUpdateInput = { + title: input.title, + allowSwaps: input.allowSwaps, + reminderHour: input.reminderHour, + }; + + const scheduleChanged = + (input.frequency !== undefined && input.frequency !== chore.frequency) || + (input.startsOn !== undefined && + input.startsOn !== formatDate(chore.startsOn)); + + if (input.rotation) { + await assertMembers(tx, houseId, input.rotation); + } + + if (scheduleChanged || input.rotation) { + await clearFutureTurns(tx, choreId, today); + } + + if (scheduleChanged) { + const startsOn = input.startsOn + ? parseDate(input.startsOn) + : dueDateOf(chore, firstTurnOnOrAfter(chore, today)); + if (startsOn < today) { + throw new BadRequestError( + 'A new schedule has to start today or later.', + ); + } + const last = await tx.choreAssignment.aggregate({ + where: { choreId }, + _max: { occurrence: true }, + }); + const base = Math.max( + chore.occurrenceBase + firstTurnOnOrAfter(chore, today), + (last._max.occurrence ?? -1) + 1, + ); + Object.assign(data, { + frequency: input.frequency ?? chore.frequency, + startsOn, + occurrenceBase: base, + rotationAnchor: base, + }); + } else if (input.rotation) { + data.rotationAnchor = + chore.occurrenceBase + firstTurnOnOrAfter(chore, today); + } + + if (input.rotation) { + await writeRotation(tx, choreId, input.rotation); + } + await tx.chore.update({ where: { id: choreId }, data }); + }); + return getChore(houseId, choreId, today); +}; + +export const archiveChore = async ( + houseId: number, + choreId: number, + today: Date, +) => { + await prisma.$transaction(async (tx) => { + await loadChore(tx, houseId, choreId); + await clearFutureTurns(tx, choreId, today); + await tx.chore.update({ + where: { id: choreId }, + data: { archivedAt: new Date() }, + }); + }); +}; + +/** + * Called when someone leaves the house. They drop out of every rotation, their + * unfinished turns go away, and the rotation carries on with whoever was next. + */ +export const removeFromRotations = async ( + tx: Prisma.TransactionClient, + houseId: number, + userId: number, + today: Date, +) => { + const chores = await tx.chore.findMany({ + where: { houseId, rotation: { some: { userId } } }, + include: { rotation: true }, + }); + + for (const chore of chores) { + const oldOrder = rotationOrder(chore); + const newOrder = oldOrder.filter((id) => id !== userId); + const nextK = firstTurnOnOrAfter(chore, today); + const nextOccurrence = chore.occurrenceBase + nextK; + + // Who would have gone next? If that's the leaver, the person after them. + let nextUser = assigneeFor(chore, oldOrder, nextOccurrence); + if (nextUser === userId && newOrder.length > 0) { + nextUser = oldOrder[(oldOrder.indexOf(userId) + 1) % oldOrder.length]!; + } + + await tx.choreAssignment.deleteMany({ + where: { + choreId: chore.id, + completedAt: null, + OR: [{ dueOn: { gte: today } }, { assigneeId: userId }], + }, + }); + await writeRotation(tx, chore.id, newOrder); + if (newOrder.length > 0 && nextUser !== null) { + await tx.chore.update({ + where: { id: chore.id }, + data: { rotationAnchor: nextOccurrence - newOrder.indexOf(nextUser) }, + }); + } + } +}; + +// ─────────────────────────── Turns (assignments) ─────────────────────────── + +export const listAssignments = async ( + houseId: number, + meId: number, + q: { + from: string; + to: string; + assignee?: 'me' | number; + includeOverdue: boolean; + }, + today: Date, +) => { + const from = parseDate(q.from); + const to = parseDate(q.to); + const lookbackFrom = q.includeOverdue + ? addDays(from, -OVERDUE_LOOKBACK_DAYS) + : from; + + const chores = await prisma.chore.findMany({ + where: { houseId, archivedAt: null }, + include: { rotation: true }, + }); + await ensureAssignments(prisma, chores, lookbackFrom, to); + + const assigneeId = q.assignee === 'me' ? meId : q.assignee; + const rows = await prisma.choreAssignment.findMany({ + where: { + chore: { houseId, archivedAt: null }, + ...(assigneeId !== undefined && { assigneeId }), + OR: [ + { dueOn: { gte: from, lte: to } }, + ...(q.includeOverdue + ? [{ dueOn: { gte: lookbackFrom, lt: from }, completedAt: null }] + : []), + ], + }, + orderBy: [{ dueOn: 'asc' }, { id: 'asc' }], + include: assignmentInclude, + }); + return rows.map((a) => serializeAssignment(a, today)); +}; + +const loadAssignment = async (houseId: number, assignmentId: number) => { + const a = await prisma.choreAssignment.findFirst({ + where: { id: assignmentId, chore: { houseId } }, + include: assignmentInclude, + }); + if (!a) throw new NotFoundError('Chore turn not found.'); + return a; +}; + +/** Anyone in the house can tick a turn off (covering for someone counts). */ +export const setCompleted = async ( + houseId: number, + assignmentId: number, + userId: number, + completed: boolean, + today: Date, +) => { + await loadAssignment(houseId, assignmentId); + await prisma.choreAssignment.update({ + where: { id: assignmentId }, + data: completed + ? { completedAt: new Date(), completedById: userId } + : { completedAt: null, completedById: null }, + }); + return serializeAssignment( + await loadAssignment(houseId, assignmentId), + today, + ); +}; + +/** + * Trade turns of the same chore. MVP: takes effect immediately if you hold one + * of the two turns. (Later: ask the other person to accept first.) + */ +export const swapTurns = async ( + houseId: number, + assignmentId: number, + withAssignmentId: number, + userId: number, + today: Date, +) => { + const [a, b] = await Promise.all([ + loadAssignment(houseId, assignmentId), + loadAssignment(houseId, withAssignmentId), + ]); + if (a.chore.id !== b.chore.id) { + throw new BadRequestError('You can only swap turns of the same chore.'); + } + if (!a.chore.allowSwaps) { + throw new ForbiddenError('Swaps are turned off for this chore.'); + } + if (a.completedAt || b.completedAt || a.dueOn < today || b.dueOn < today) { + throw new BadRequestError( + 'Only upcoming, unfinished turns can be swapped.', + ); + } + if (a.assignee.id !== userId && b.assignee.id !== userId) { + throw new ForbiddenError('You can only swap one of your own turns.'); + } + await prisma.$transaction([ + prisma.choreAssignment.update({ + where: { id: a.id }, + data: { assigneeId: b.assignee.id }, + }), + prisma.choreAssignment.update({ + where: { id: b.id }, + data: { assigneeId: a.assignee.id }, + }), + ]); + return Promise.all([ + loadAssignment(houseId, a.id).then((x) => serializeAssignment(x, today)), + loadAssignment(houseId, b.id).then((x) => serializeAssignment(x, today)), + ]); +}; + +/** "Done this month": turns each roommate finished in the given month. */ +export const monthlyStats = async (houseId: number, month: string) => { + const start = parseDate(`${month}-01`); + const end = new Date( + Date.UTC(start.getUTCFullYear(), start.getUTCMonth() + 1, 1), + ); + const [members, counts] = await Promise.all([ + prisma.houseMember.findMany({ + where: { houseId }, + orderBy: { joinedAt: 'asc' }, + select: { user: { select: publicUserSelect } }, + }), + prisma.choreAssignment.groupBy({ + by: ['completedById'], + where: { + chore: { houseId }, + completedAt: { not: null }, + dueOn: { gte: start, lt: end }, + }, + _count: { _all: true }, + }), + ]); + const byUser = new Map(counts.map((c) => [c.completedById, c._count._all])); + return { + month, + members: members.map(({ user }) => ({ + user, + done: byUser.get(user.id) ?? 0, + })), + }; +}; diff --git a/src/chores/chores.schema.ts b/src/chores/chores.schema.ts new file mode 100644 index 0000000..4ca0d75 --- /dev/null +++ b/src/chores/chores.schema.ts @@ -0,0 +1,84 @@ +import { z } from 'zod'; + +import { houseIdParams, ymd } from '../houses/houses.schema.js'; + +const frequency = z.enum([ + 'DAILY', + 'EVERY_OTHER_DAY', + 'WEEKLY', + 'BIWEEKLY', + 'MONTHLY', +]); + +const rotation = z + .array(z.number().int()) + .min(1, 'Pick at least one person') + .refine((ids) => new Set(ids).size === ids.length, 'No duplicates'); + +const choreFields = z.object({ + title: z.string().trim().min(1).max(80), + frequency, + startsOn: ymd, + /** User IDs in turn order; the first person takes the next turn. */ + rotation, + allowSwaps: z.boolean(), + /** Hour (0–23) the day before to remind the assignee; null for no reminder. */ + reminderHour: z.number().int().min(0).max(23).nullable(), +}); + +const choreParams = houseIdParams.extend({ choreId: z.coerce.number().int() }); +const assignmentParams = houseIdParams.extend({ + assignmentId: z.coerce.number().int(), +}); + +export const listChoresSchema = z.object({ params: houseIdParams }); + +export const createChoreSchema = z.object({ + params: houseIdParams, + body: choreFields.partial({ allowSwaps: true, reminderHour: true }), +}); + +export const choreParamsSchema = z.object({ params: choreParams }); + +export const updateChoreSchema = z.object({ + params: choreParams, + body: choreFields.partial(), +}); + +export const listAssignmentsSchema = z.object({ + params: houseIdParams, + query: z + .object({ + from: ymd, + to: ymd, + /** "me" or a user ID */ + assignee: z.union([z.literal('me'), z.coerce.number().int()]).optional(), + /** Also return unfinished turns from the 30 days before `from`. */ + includeOverdue: z + .enum(['true', 'false']) + .default('false') + .transform((v) => v === 'true'), + }) + .refine((q) => q.from <= q.to, 'from must be on or before to') + .refine( + (q) => (Date.parse(q.to) - Date.parse(q.from)) / 86_400_000 <= 62, + 'Range can be at most 62 days', + ), +}); + +export const assignmentParamsSchema = z.object({ params: assignmentParams }); + +export const swapSchema = z.object({ + params: assignmentParams, + body: z.object({ withAssignmentId: z.number().int() }), +}); + +export const statsSchema = z.object({ + params: houseIdParams, + query: z.object({ + month: z + .string() + .regex(/^\d{4}-(0[1-9]|1[0-2])$/, 'Use YYYY-MM') + .optional(), + }), +}); diff --git a/src/chores/schedule.ts b/src/chores/schedule.ts new file mode 100644 index 0000000..4eda774 --- /dev/null +++ b/src/chores/schedule.ts @@ -0,0 +1,69 @@ +import type { ChoreFrequency } from '../generated/prisma/client.js'; +import { addDays, addMonths, daysBetween } from '../utils/dates.js'; + +/** + * How chore turns are numbered + * ──────────────────────────── + * Each turn of a chore has an occurrence number. Turn k of the current schedule + * is due on `startsOn + k × frequency` and has occurrence `occurrenceBase + k`. + * When the schedule changes, occurrenceBase moves past every number already used, + * so stored turns (completed ones especially) never collide with new ones. + * + * Whose turn it is: rotation[(occurrence − rotationAnchor) mod rotation.length]. + * Moving the anchor to the next upcoming occurrence makes rotation position 0 + * take the next turn. + */ +export interface ChoreSchedule { + frequency: ChoreFrequency; + startsOn: Date; + occurrenceBase: number; + rotationAnchor: number; +} + +const STEP_DAYS: Record, number> = { + DAILY: 1, + EVERY_OTHER_DAY: 2, + WEEKLY: 7, + BIWEEKLY: 14, +}; + +/** Due date of local turn k (k = 0 is startsOn). */ +export const dueDateOf = (s: ChoreSchedule, k: number): Date => + s.frequency === 'MONTHLY' + ? addMonths(s.startsOn, k) + : addDays(s.startsOn, k * STEP_DAYS[s.frequency]); + +/** Smallest local k whose due date is on or after `date`. */ +export const firstTurnOnOrAfter = (s: ChoreSchedule, date: Date): number => { + if (date <= s.startsOn) return 0; + if (s.frequency === 'MONTHLY') { + const months = + (date.getUTCFullYear() - s.startsOn.getUTCFullYear()) * 12 + + (date.getUTCMonth() - s.startsOn.getUTCMonth()); + let k = Math.max(0, months - 1); + while (dueDateOf(s, k) < date) k++; + return k; + } + return Math.ceil(daysBetween(s.startsOn, date) / STEP_DAYS[s.frequency]); +}; + +/** Local turn numbers due within [from, to] (inclusive). */ +export const turnsInRange = (s: ChoreSchedule, from: Date, to: Date) => { + const turns: { k: number; dueOn: Date }[] = []; + for (let k = firstTurnOnOrAfter(s, from); ; k++) { + const dueOn = dueDateOf(s, k); + if (dueOn > to) break; + turns.push({ k, dueOn }); + } + return turns; +}; + +export const assigneeFor = ( + s: ChoreSchedule, + rotation: number[], + occurrence: number, +): number | null => { + if (rotation.length === 0) return null; + const n = rotation.length; + return rotation[(((occurrence - s.rotationAnchor) % n) + n) % n]!; +}; diff --git a/src/houses/houseRouter.ts b/src/houses/houseRouter.ts index 0dc84ca..0105c2f 100644 --- a/src/houses/houseRouter.ts +++ b/src/houses/houseRouter.ts @@ -1,4 +1,5 @@ import { Router } from 'express'; +import choreRouter from '../chores/choreRouter.js'; import { requireHouseMember, @@ -70,5 +71,5 @@ house.delete( ); // Feature routers mounted under /houses/:houseId - +house.use('/', choreRouter); export default router; diff --git a/src/houses/houseService.ts b/src/houses/houseService.ts index 346d04d..22ce733 100644 --- a/src/houses/houseService.ts +++ b/src/houses/houseService.ts @@ -1,3 +1,4 @@ +import { removeFromRotations } from '../chores/choreService.js'; import { Prisma } from '../generated/prisma/client.js'; import type { HouseFeature, LivingType } from '../generated/prisma/client.js'; import { prisma } from '../prisma.js'; @@ -6,7 +7,7 @@ import { ConflictError, NotFoundError, } from '../utils/AppError.js'; -import { parseDate } from '../utils/dates.js'; +import { parseDate, todayIn } from '../utils/dates.js'; import { makeInviteCode, normalizeInviteCode } from '../utils/inviteCode.js'; import { publicUserSelect } from '../utils/selects.js'; @@ -261,8 +262,15 @@ export const removeMember = async ( throw new NotFoundError('Member not found.'); } - // Feature cleanup on leave goes here (chore rotations, shopping claims). - + const house = await tx.house.findUniqueOrThrow({ + where: { id: houseId }, + }); + await removeFromRotations( + tx, + houseId, + targetUserId, + todayIn(house.timezone), + ); await tx.houseMember.delete({ where: { userId: targetUserId } }); const others = await tx.houseMember.findMany({ diff --git a/test/chores.test.ts b/test/chores.test.ts new file mode 100644 index 0000000..6596f78 --- /dev/null +++ b/test/chores.test.ts @@ -0,0 +1,376 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { signUp } from './helpers.js'; + +type Client = Awaited>; +type Turn = { + id: number; + dueOn: string; + status: string; + assignee: { netid: string }; +}; + +/** Monday, Nov 9 2026, 10am in Ithaca: the week shown in the Chores design. */ +const NOW = new Date('2026-11-09T15:00:00Z'); + +let leah: Client, selena: Client, melissa: Client, houseId: number; + +beforeEach(async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + vi.setSystemTime(NOW); + + leah = await signUp('lk452'); + selena = await signUp('sc2291'); + melissa = await signUp('mv384'); + const house = (await leah.post('/houses', { name: 'The Linden Loft' })).body + .house; + houseId = house.id; + await selena.post('/houses/join', { inviteCode: house.inviteCode }); + await melissa.post('/houses/join', { inviteCode: house.inviteCode }); +}); + +afterEach(() => { + vi.useRealTimers(); +}); + +const createChore = async (body: object, as: Client = leah) => { + const res = await as.post(`/houses/${houseId}/chores`, body); + expect(res.status).toBe(201); + return res.body.chore; +}; + +const turns = async (as: Client, query: string): Promise => { + const res = await as.get(`/houses/${houseId}/chore-assignments?${query}`); + expect(res.status).toBe(200); + return res.body.assignments; +}; + +const who = (ts: Turn[]) => ts.map((t) => `${t.dueOn} ${t.assignee.netid}`); + +describe('creating chores', () => { + it('matches the "Coming up" preview in the design', async () => { + const chore = await createChore({ + title: 'Clean bathroom', + frequency: 'WEEKLY', + startsOn: '2026-11-15', + rotation: [melissa.id, leah.id, selena.id], + }); + expect(chore).toMatchObject({ + title: 'Clean bathroom', + allowSwaps: true, + reminderHour: 18, + rotation: [{ netid: 'mv384' }, { netid: 'lk452' }, { netid: 'sc2291' }], + }); + expect(who(chore.comingUp)).toEqual([ + '2026-11-15 mv384', + '2026-11-22 lk452', + '2026-11-29 sc2291', + ]); + }); + + it('only rotates people who live in the house', async () => { + const stranger = await signUp('xx111'); + const res = await leah.post(`/houses/${houseId}/chores`, { + title: 'Dishes', + frequency: 'DAILY', + startsOn: '2026-11-09', + rotation: [leah.id, stranger.id], + }); + expect(res.status).toBe(400); + }); + + it('validates the body', async () => { + const res = await leah.post(`/houses/${houseId}/chores`, { + title: '', + frequency: 'HOURLY', + startsOn: 'tomorrow', + rotation: [leah.id, leah.id], + }); + expect(res.status).toBe(400); + expect(Object.keys(res.body.data).sort()).toEqual([ + 'body.frequency', + 'body.rotation', + 'body.startsOn', + 'body.title', + ]); + }); +}); + +describe('the week view', () => { + it('shows everyone’s turns, with status, and filters to "me"', async () => { + await createChore({ + title: 'Wipe kitchen counters', + frequency: 'EVERY_OTHER_DAY', + startsOn: '2026-11-09', + rotation: [leah.id, selena.id], + }); + await createChore({ + title: 'Take out trash & recycling', + frequency: 'WEEKLY', + startsOn: '2026-11-12', + rotation: [leah.id, selena.id, melissa.id], + }); + + const week = await turns(leah, 'from=2026-11-09&to=2026-11-15'); + expect(who(week)).toEqual([ + '2026-11-09 lk452', + '2026-11-11 sc2291', + '2026-11-12 lk452', + '2026-11-13 lk452', + '2026-11-15 sc2291', + ]); + expect(week[0]!.status).toBe('DUE_TODAY'); + expect(week[1]!.status).toBe('UPCOMING'); + + const mine = await turns(leah, 'from=2026-11-09&to=2026-11-15&assignee=me'); + expect(mine.every((t) => t.assignee.netid === 'lk452')).toBe(true); + + // Reading the same range again doesn't duplicate anything. + expect(await turns(leah, 'from=2026-11-09&to=2026-11-15')).toHaveLength(5); + }); + + it('includes overdue turns when asked', async () => { + await createChore({ + title: 'Clean bathroom', + frequency: 'DAILY', + startsOn: '2026-11-07', + rotation: [melissa.id], + }); + const today = await turns( + melissa, + 'from=2026-11-09&to=2026-11-09&includeOverdue=true', + ); + expect(today.map((t) => `${t.dueOn} ${t.status}`)).toEqual([ + '2026-11-07 OVERDUE', + '2026-11-08 OVERDUE', + '2026-11-09 DUE_TODAY', + ]); + }); + + it('rejects huge or backwards ranges', async () => { + const res1 = await leah.get( + `/houses/${houseId}/chore-assignments?from=2026-01-01&to=2026-12-31`, + ); + const res2 = await leah.get( + `/houses/${houseId}/chore-assignments?from=2026-11-15&to=2026-11-09`, + ); + expect([res1.status, res2.status]).toEqual([400, 400]); + }); +}); + +describe('completing, swapping, stats', () => { + it('ticks a turn off, undoes it, and counts it in "Done this month"', async () => { + await createChore({ + title: 'Trash', + frequency: 'DAILY', + startsOn: '2026-11-09', + rotation: [leah.id, selena.id], + }); + const [first] = await turns(leah, 'from=2026-11-09&to=2026-11-09'); + + const done = await leah.post( + `/houses/${houseId}/chore-assignments/${first!.id}/complete`, + ); + expect(done.body.assignment).toMatchObject({ + status: 'DONE', + completedBy: { netid: 'lk452' }, + canSwap: false, + }); + + // Melissa covers Selena's turn tomorrow; it counts for Melissa. + const [second] = await turns(leah, 'from=2026-11-10&to=2026-11-10'); + await melissa.post( + `/houses/${houseId}/chore-assignments/${second!.id}/complete`, + ); + + const stats = await leah.get(`/houses/${houseId}/chores/stats`); + expect(stats.body.month).toBe('2026-11'); + expect( + stats.body.members.map((m: { user: { netid: string }; done: number }) => [ + m.user.netid, + m.done, + ]), + ).toEqual([ + ['lk452', 1], + ['sc2291', 0], + ['mv384', 1], + ]); + + const undone = await leah.delete( + `/houses/${houseId}/chore-assignments/${first!.id}/complete`, + ); + expect(undone.body.assignment.status).toBe('DUE_TODAY'); + }); + + it('swaps turns of the same chore', async () => { + await createChore({ + title: 'Vacuum', + frequency: 'WEEKLY', + startsOn: '2026-11-12', + rotation: [leah.id, selena.id], + }); + const [a, b] = await turns(leah, 'from=2026-11-09&to=2026-11-22'); + expect(who([a!, b!])).toEqual(['2026-11-12 lk452', '2026-11-19 sc2291']); + + // Melissa holds neither turn. + const nope = await melissa.post( + `/houses/${houseId}/chore-assignments/${a!.id}/swap`, + { + withAssignmentId: b!.id, + }, + ); + expect(nope.status).toBe(403); + + const res = await leah.post( + `/houses/${houseId}/chore-assignments/${a!.id}/swap`, + { + withAssignmentId: b!.id, + }, + ); + expect(res.status).toBe(200); + expect(who(await turns(leah, 'from=2026-11-09&to=2026-11-22'))).toEqual([ + '2026-11-12 sc2291', + '2026-11-19 lk452', + ]); + }); + + it('respects "Allow swaps" being off', async () => { + await createChore({ + title: 'Vacuum', + frequency: 'WEEKLY', + startsOn: '2026-11-12', + rotation: [leah.id, selena.id], + allowSwaps: false, + }); + const [a, b] = await turns(leah, 'from=2026-11-09&to=2026-11-22'); + const res = await leah.post( + `/houses/${houseId}/chore-assignments/${a!.id}/swap`, + { + withAssignmentId: b!.id, + }, + ); + expect(res.status).toBe(403); + }); +}); + +describe('editing chores', () => { + it('reordering the rotation makes the new first person go next', async () => { + const chore = await createChore({ + title: 'Bathroom', + frequency: 'WEEKLY', + startsOn: '2026-11-15', + rotation: [melissa.id, leah.id, selena.id], + }); + const res = await leah.patch(`/houses/${houseId}/chores/${chore.id}`, { + rotation: [selena.id, melissa.id], + }); + expect(who(res.body.chore.comingUp)).toEqual([ + '2026-11-15 sc2291', + '2026-11-22 mv384', + '2026-11-29 sc2291', + ]); + }); + + it('changing the schedule keeps finished turns', async () => { + const chore = await createChore({ + title: 'Counters', + frequency: 'DAILY', + startsOn: '2026-11-07', + rotation: [leah.id, selena.id], + }); + const past = await turns(leah, 'from=2026-11-07&to=2026-11-08'); + await leah.post( + `/houses/${houseId}/chore-assignments/${past[0]!.id}/complete`, + ); + + const res = await leah.patch(`/houses/${houseId}/chores/${chore.id}`, { + frequency: 'WEEKLY', + startsOn: '2026-11-10', + }); + expect(res.status).toBe(200); + expect(who(res.body.chore.comingUp)).toEqual([ + '2026-11-10 lk452', + '2026-11-17 sc2291', + '2026-11-24 lk452', + ]); + + const history = await turns(leah, 'from=2026-11-07&to=2026-11-17'); + expect(history.map((t) => `${t.dueOn} ${t.status}`)).toEqual([ + '2026-11-07 DONE', + '2026-11-08 OVERDUE', + '2026-11-10 UPCOMING', + '2026-11-17 UPCOMING', + ]); + }); + + it('a new schedule cannot start in the past', async () => { + const chore = await createChore({ + title: 'Counters', + frequency: 'DAILY', + startsOn: '2026-11-09', + rotation: [leah.id], + }); + const res = await leah.patch(`/houses/${houseId}/chores/${chore.id}`, { + frequency: 'WEEKLY', + startsOn: '2026-11-01', + }); + expect(res.status).toBe(400); + }); + + it('deleting a chore removes it and its upcoming turns', async () => { + const chore = await createChore({ + title: 'Counters', + frequency: 'DAILY', + startsOn: '2026-11-09', + rotation: [leah.id], + }); + expect( + (await leah.delete(`/houses/${houseId}/chores/${chore.id}`)).status, + ).toBe(204); + expect((await leah.get(`/houses/${houseId}/chores`)).body.chores).toEqual( + [], + ); + expect(await turns(leah, 'from=2026-11-09&to=2026-11-15')).toEqual([]); + }); +}); + +describe('when someone leaves', () => { + it('drops them from the rotation and carries on with whoever was next', async () => { + await createChore({ + title: 'Bathroom', + frequency: 'WEEKLY', + startsOn: '2026-11-15', + rotation: [melissa.id, leah.id, selena.id], + }); + // Melissa was up first; she moves out. + await melissa.delete(`/houses/${houseId}/members/me`); + + const res = await leah.get(`/houses/${houseId}/chores`); + const [chore] = res.body.chores; + expect(chore.rotation.map((u: { netid: string }) => u.netid)).toEqual([ + 'lk452', + 'sc2291', + ]); + expect(who(chore.comingUp)).toEqual([ + '2026-11-15 lk452', + '2026-11-22 sc2291', + '2026-11-29 lk452', + ]); + }); +}); + +describe('access', () => { + it('hides other houses’ chores', async () => { + const chore = await createChore({ + title: 'Bathroom', + frequency: 'WEEKLY', + startsOn: '2026-11-15', + rotation: [leah.id], + }); + const outsider = await signUp('xx111'); + await outsider.post('/houses', { name: 'Elsewhere' }); + expect( + (await outsider.get(`/houses/${houseId}/chores/${chore.id}`)).status, + ).toBe(404); + }); +}); diff --git a/test/schedule.test.ts b/test/schedule.test.ts new file mode 100644 index 0000000..0aea2d4 --- /dev/null +++ b/test/schedule.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from 'vitest'; + +import { + assigneeFor, + dueDateOf, + firstTurnOnOrAfter, + turnsInRange, +} from '../src/chores/schedule.js'; +import { formatDate, parseDate, todayIn } from '../src/utils/dates.js'; + +const sched = (frequency: string, startsOn: string, anchor = 0) => ({ + frequency: frequency as 'WEEKLY', + startsOn: parseDate(startsOn), + occurrenceBase: 0, + rotationAnchor: anchor, +}); + +describe('chore schedule math', () => { + it('steps weekly and every other day', () => { + expect(formatDate(dueDateOf(sched('WEEKLY', '2026-11-15'), 2))).toBe( + '2026-11-29', + ); + expect( + formatDate(dueDateOf(sched('EVERY_OTHER_DAY', '2026-11-09'), 3)), + ).toBe('2026-11-15'); + }); + + it('clamps monthly chores to the end of short months', () => { + const s = sched('MONTHLY', '2027-01-31'); + expect([1, 2, 3].map((k) => formatDate(dueDateOf(s, k)))).toEqual([ + '2027-02-28', + '2027-03-31', + '2027-04-30', + ]); + expect(firstTurnOnOrAfter(s, parseDate('2027-03-01'))).toBe(2); + }); + + it('lists turns in a range', () => { + const s = sched('EVERY_OTHER_DAY', '2026-11-01'); + expect( + turnsInRange(s, parseDate('2026-11-09'), parseDate('2026-11-15')).map( + (t) => formatDate(t.dueOn), + ), + ).toEqual(['2026-11-09', '2026-11-11', '2026-11-13', '2026-11-15']); + }); + + it('rotates from the anchor', () => { + const s = sched('WEEKLY', '2026-11-01', 4); + expect([4, 5, 6, 7].map((o) => assigneeFor(s, [10, 20, 30], o))).toEqual([ + 10, 20, 30, 10, + ]); + expect(assigneeFor(s, [10, 20, 30], 3)).toBe(30); + expect(assigneeFor(s, [], 3)).toBeNull(); + }); + + it("computes today in the house's time zone", () => { + const lateNightUtc = new Date('2026-11-10T03:30:00Z'); // 10:30pm Nov 9 in Ithaca + expect(formatDate(todayIn('America/New_York', lateNightUtc))).toBe( + '2026-11-09', + ); + expect(formatDate(todayIn('UTC', lateNightUtc))).toBe('2026-11-10'); + }); +});