diff --git a/docs/superpowers/specs/2026-11-15-event-lifecycle-and-polish.md b/docs/superpowers/specs/2026-11-15-event-lifecycle-and-polish.md new file mode 100644 index 0000000..96ee03c --- /dev/null +++ b/docs/superpowers/specs/2026-11-15-event-lifecycle-and-polish.md @@ -0,0 +1,60 @@ +# Event lifecycle and polish: 10 features + +Date: 2026-11-15. Status: approved by the host (user said "I like all of em"); decisions below are Opus's defaults. + +## Shared ground rules + +- **Schema is fixed.** Migration `0005` (written by the orchestrator, already committed) adds five nullable columns to `events`: + `deleted_at`, `cancelled_at`, `details_changed_at` (timestamptz), `cover_emoji`, `cover_color` (text). + Children MUST NOT edit `src/db/schema.ts` or anything in `drizzle/`. +- **Event state precedence** (derive with one helper, `eventState(event, now)` in `src/lib/event-state.ts`): + `deleted` (deletedAt set) > `cancelled` (cancelledAt set) > `past` (startsAt < now − 12h) > `upcoming`. + Past is derived from `startsAt`; there is no archived column. +- Server actions take bound ids that are NOT trusted: every service re-checks host ownership (pattern: `and(eq(events.id, id), eq(events.hostId, hostId))`). +- Children run targeted tests + `npx tsc --noEmit` + `npm run lint`; CI runs the full suite (the machine is heavily loaded; PGlite hooks time out under load, use `--testTimeout=30000 --hookTimeout=60000`). + +## Wave 1: lifecycle (one child, sequential) + +### 1. Undo instead of confirm (soft delete) +- `deleteEvent` sets `deletedAt = now()` instead of deleting. New `restoreEvent(db, hostId, eventId)` clears it (NotFoundError if not the host's or not deleted). +- **Every read and write path must exclude deleted events.** Grep every query touching `events` (services/*, server/host-event.ts, e/[code] pages + actions, g/[token] page, listHostEvents, headcountForEvents, menu/shopping/split/guestAdmin services, dev actions) and list them in the report. Host pages for a deleted event → notFound(). Add a test per service path that a deleted event is invisible / its writes rejected. +- Purge: lazy and host-scoped. On dashboard load, hard-delete that host's events with `deletedAt < now − 30 days` (`purgeDeletedEvents(db, hostId)`), cascade handles children. +- UI: the danger-zone confirm step goes away. "Delete event" submits immediately (still a POST form, pending state). Redirect to `/host?deleted=`. Dashboard looks up that id (host-scoped, deleted only) and shows `Deleted "". [Undo]` where Undo is a form posting `restoreEventAction(eventId)` → redirect to the event page. Plus a Dismiss link. If the id doesn't resolve, show nothing. +- Copy on the danger zone: "You can undo this from your events list for 30 days." + +### 2. Past events auto-archive +- Dashboard splits into Upcoming (soonest first) and Past (most recent first). Past is a `<details>` collapsed by default, summary "Past events (N)". Cancelled events sort into their date bucket but show a "Cancelled" badge. + +### 4. Guest page for a deleted or cancelled event +- `/e/[code]` and `/e/[code]/g/[token]`: deleted → a friendly "This event is no longer available" page (not the 404), with the host's name. Cancelled → page renders with a prominent "Cancelled by <host>" banner, RSVP form hidden; existing reply shown read-only. +- RSVP server actions reject deleted and cancelled events server-side (ValidationError with a friendly message). Tested. + +### 5. Cancel without deleting +- `cancelEvent` / `uncancelEvent` services (host-scoped) set/clear `cancelledAt`. Actions on the edit page, above the danger zone: "Cancel event" (POST) / "Reinstate event". +- When cancelled, the host event layout shows a "Cancelled" banner, and a `CopyReminderButton`-style "Copy cancellation message" button with text: `Sorry everyone, <title> on <when> is cancelled. <optional reason-free closing>`. Reuse existing copy-button component and format helpers. + +## Wave 2: new surfaces (parallel with wave 1, new files only) + +### 3. Duplicate an event ("Plan this again") +- `duplicateEvent(db, hostId, eventId)` in a transaction: new id, new share code (reuse the generator createEvent uses), same title + " (again)", location, timezone, maybePercent, venmoUsername, hostCoverCents, menu dishes (servingsPerPerson), invitees (names of the old guest list AND old invitees, deduped case-insensitively). `startsAt` = same weekday/time one week after the later of (original startsAt, now). Do NOT copy guests, plus-ones, shopping state, extra costs, cover columns, cancelled/deleted/detailsChanged. +- Button "Plan this again" on the event page header (host layout) → redirect to the new event's edit page. + +### 8. Add to calendar +- Route handler `src/app/e/[code]/calendar.ics/route.ts`: `text/calendar; charset=utf-8`, `Content-Disposition: attachment; filename="<slug>.ics"`. VEVENT with UID `<eventId>@spread`, DTSTAMP, DTSTART in UTC (`YYYYMMDDTHHMMSSZ`), DTEND = start + 3h, SUMMARY, LOCATION, URL (share URL), DESCRIPTION "Hosted by <host> · RSVP: <url>". CRLF line endings, RFC 5545 text escaping (`\\`, `;`, `,`, newlines), fold lines > 75 octets. Pure builder in `src/lib/ics.ts` with unit tests. Deleted event → 404; cancelled → include `STATUS:CANCELLED`. +- On the guest page: "Add to calendar" link to the .ics plus a Google Calendar link (`https://calendar.google.com/calendar/render?action=TEMPLATE&text=..&dates=START/END&location=..&details=..`). Builder in the same lib, tested. + +### 10. Day-of view ("Today" tab) +- There is no per-recipe timing data, so do not invent cook times. New host tab `/host/events/[id]/today` (add to EventTabs): a checklist built from existing data — unticked shopping items (from the shopping service), prep sheet dishes/quantities (buildPrepSheet), and fixed milestones relative to startsAt: "Shopping done" (morning), "Start prep" (startsAt − 3h), "Set up" (startsAt − 1h), "Guests arrive" (startsAt), shown in the event timezone. Check state stored in localStorage keyed by event id (no schema). Shows headcount at top. Pure builder in `src/lib/today-plan.ts` with tests. + +## Wave 3: after wave 1 merges + +### 6. Change alerts +- `updateEvent` sets `detailsChangedAt = now()` only when startsAt, timezone or location actually changes (compare before/after); title-only edits don't count. Test both. +- Guest pages: if `detailsChangedAt` is set and later than the guest's `createdAt` (or for anonymous visitors, within the last 14 days), show "Updated <relative date>: now <when> at <location>". +- After saving a change to time/location, the host lands on the event page with a copyable "Heads up: <title> is now <when> at <location>" message (via `?changed=1`). + +### 7. Dashboard at a glance +- Each upcoming card shows countdown ("today", "tomorrow", "in 6 days"), yes/maybe/no counts, and "N haven't replied" (invitees with no matching guest, same rule as `noReplyNames`). Batch all counts in one or two queries for all events (pattern: `headcountForEvents`); no per-event queries. Tested. + +### 9. Event cover +- Edit and new-event forms get a cover picker: 8 preset emoji (🎉 🍔 🎂 🍕 🌮 🥂 🎃 🎄) and 6 preset colors mapped to existing palette tokens in globals.css. Validate against the preset lists server-side (zod). Shown on dashboard cards, event layout header and guest page header. Defaults: 🎉 + mustard when null. diff --git a/drizzle/0005_event_lifecycle.sql b/drizzle/0005_event_lifecycle.sql new file mode 100644 index 0000000..cb24a8c --- /dev/null +++ b/drizzle/0005_event_lifecycle.sql @@ -0,0 +1,5 @@ +ALTER TABLE "events" ADD COLUMN "deleted_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "events" ADD COLUMN "cancelled_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "events" ADD COLUMN "details_changed_at" timestamp with time zone;--> statement-breakpoint +ALTER TABLE "events" ADD COLUMN "cover_emoji" text;--> statement-breakpoint +ALTER TABLE "events" ADD COLUMN "cover_color" text; \ No newline at end of file diff --git a/drizzle/meta/0005_snapshot.json b/drizzle/meta/0005_snapshot.json new file mode 100644 index 0000000..852037d --- /dev/null +++ b/drizzle/meta/0005_snapshot.json @@ -0,0 +1,1054 @@ +{ + "id": "c6419cad-27e8-4cec-a86f-6043ad3194d1", + "prevId": "caeec9a4-90b5-4e1d-bd52-81550e3998b8", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.event_dishes": { + "name": "event_dishes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "servings_per_person": { + "name": "servings_per_person", + "type": "double precision", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "event_dishes_event_recipe_unique": { + "name": "event_dishes_event_recipe_unique", + "columns": [ + { + "expression": "event_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "recipe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "event_dishes_event_id_events_id_fk": { + "name": "event_dishes_event_id_events_id_fk", + "tableFrom": "event_dishes", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "event_dishes_recipe_id_recipes_id_fk": { + "name": "event_dishes_recipe_id_recipes_id_fk", + "tableFrom": "event_dishes", + "tableTo": "recipes", + "columnsFrom": [ + "recipe_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.events": { + "name": "events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "host_id": { + "name": "host_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "host_name": { + "name": "host_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'UTC'" + }, + "share_code": { + "name": "share_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "maybe_percent": { + "name": "maybe_percent", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 50 + }, + "venmo_username": { + "name": "venmo_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "host_cover_cents": { + "name": "host_cover_cents", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "details_changed_at": { + "name": "details_changed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cover_emoji": { + "name": "cover_emoji", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cover_color": { + "name": "cover_color", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "events_share_code_unique": { + "name": "events_share_code_unique", + "nullsNotDistinct": false, + "columns": [ + "share_code" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.extra_costs": { + "name": "extra_costs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "extra_costs_event_id_events_id_fk": { + "name": "extra_costs_event_id_events_id_fk", + "tableFrom": "extra_costs", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.guests": { + "name": "guests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "guest_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true + }, + "food_notes": { + "name": "food_notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "edit_token": { + "name": "edit_token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attended": { + "name": "attended", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "excluded": { + "name": "excluded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paid": { + "name": "paid", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "link_sent_at": { + "name": "link_sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "link_sent_amount_cents": { + "name": "link_sent_amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "guests_event_id_events_id_fk": { + "name": "guests_event_id_events_id_fk", + "tableFrom": "guests", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "guests_edit_token_unique": { + "name": "guests_edit_token_unique", + "nullsNotDistinct": false, + "columns": [ + "edit_token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitees": { + "name": "invitees", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "invitees_event_id_events_id_fk": { + "name": "invitees_event_id_events_id_fk", + "tableFrom": "invitees", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.plus_ones": { + "name": "plus_ones", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "guest_id": { + "name": "guest_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "plus_ones_guest_id_guests_id_fk": { + "name": "plus_ones_guest_id_guests_id_fk", + "tableFrom": "plus_ones", + "tableTo": "guests", + "columnsFrom": [ + "guest_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.recipe_items": { + "name": "recipe_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "recipe_id": { + "name": "recipe_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "per_serving": { + "name": "per_serving", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "unit": { + "name": "unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "buy_unit": { + "name": "buy_unit", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "units_per_buy": { + "name": "units_per_buy", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": {}, + "foreignKeys": { + "recipe_items_recipe_id_recipes_id_fk": { + "name": "recipe_items_recipe_id_recipes_id_fk", + "tableFrom": "recipe_items", + "tableTo": "recipes", + "columnsFrom": [ + "recipe_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.recipes": { + "name": "recipes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "owner_id": { + "name": "owner_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "emoji": { + "name": "emoji", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "default_servings_per_person": { + "name": "default_servings_per_person", + "type": "double precision", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "session_userId_idx": { + "name": "session_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.shopping_state": { + "name": "shopping_state", + "schema": "", + "columns": { + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipe_item_id": { + "name": "recipe_item_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "checked": { + "name": "checked", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "checked_qty": { + "name": "checked_qty", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "actual_cents": { + "name": "actual_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "shopping_state_event_id_events_id_fk": { + "name": "shopping_state_event_id_events_id_fk", + "tableFrom": "shopping_state", + "tableTo": "events", + "columnsFrom": [ + "event_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "shopping_state_recipe_item_id_recipe_items_id_fk": { + "name": "shopping_state_recipe_item_id_recipe_items_id_fk", + "tableFrom": "shopping_state", + "tableTo": "recipe_items", + "columnsFrom": [ + "recipe_item_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "shopping_state_event_item_unique": { + "name": "shopping_state_event_item_unique", + "nullsNotDistinct": false, + "columns": [ + "event_id", + "recipe_item_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": { + "public.guest_status": { + "name": "guest_status", + "schema": "public", + "values": [ + "yes", + "maybe", + "no" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 494d3a8..1c0c244 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -36,6 +36,13 @@ "when": 1794372497075, "tag": "0004_cold_black_bolt", "breakpoints": true + }, + { + "idx": 5, + "version": "7", + "when": 1794797697309, + "tag": "0005_event_lifecycle", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/app/e/[code]/calendar.ics/route.test.ts b/src/app/e/[code]/calendar.ics/route.test.ts new file mode 100644 index 0000000..fca1ecc --- /dev/null +++ b/src/app/e/[code]/calendar.ics/route.test.ts @@ -0,0 +1,75 @@ +// @vitest-environment node +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { Db } from "@/db/client"; +import { events } from "@/db/schema"; +import { createTestDb } from "@/db/test-db"; +import { createEvent } from "@/services/events"; + +const state = vi.hoisted(() => ({ db: null as unknown })); +vi.mock("@/db/client", () => ({ getDb: async () => state.db })); + +import { GET } from "./route"; + +let db: Db; + +beforeEach(async () => { + db = await createTestDb(); + state.db = db; +}); + +const params = (code: string) => ({ params: Promise.resolve({ code }) }); +const request = () => + new Request("https://spread.example/e/code/calendar.ics", { + headers: { host: "spread.example", "x-forwarded-proto": "https" }, + }); + +async function makeEvent(title = "Fourth of July") { + return createEvent(db, "host-1", { + title, + startsAt: new Date("2026-11-15T01:00:00Z"), + location: "Backyard", + hostName: "Will", + timezone: "America/Chicago", + }); +} + +describe("GET /e/[code]/calendar.ics", () => { + it("returns a downloadable calendar file for the event", async () => { + const { shareCode } = await makeEvent(); + const response = await GET(request(), params(shareCode)); + + expect(response.status).toBe(200); + expect(response.headers.get("content-type")).toBe("text/calendar; charset=utf-8"); + expect(response.headers.get("content-disposition")).toBe( + 'attachment; filename="fourth-of-july.ics"', + ); + const body = await response.text(); + expect(body).toContain("BEGIN:VEVENT"); + expect(body).toContain("DTSTART:20261115T010000Z"); + expect(body).toContain("URL:https://spread.example/e/" + shareCode); + expect(body).not.toContain("STATUS:CANCELLED"); + }); + + it("marks a cancelled event as cancelled", async () => { + const { id, shareCode } = await makeEvent(); + await db.update(events).set({ cancelledAt: new Date() }).where(eq(events.id, id)); + + const response = await GET(request(), params(shareCode)); + expect(response.status).toBe(200); + expect(await response.text()).toContain("STATUS:CANCELLED"); + }); + + it("returns 404 for an unknown share code", async () => { + const response = await GET(request(), params("nosuchcode")); + expect(response.status).toBe(404); + }); + + it("returns 404 for a deleted event", async () => { + const { id, shareCode } = await makeEvent(); + await db.update(events).set({ deletedAt: new Date() }).where(eq(events.id, id)); + + const response = await GET(request(), params(shareCode)); + expect(response.status).toBe(404); + }); +}); diff --git a/src/app/e/[code]/calendar.ics/route.ts b/src/app/e/[code]/calendar.ics/route.ts new file mode 100644 index 0000000..dc14a54 --- /dev/null +++ b/src/app/e/[code]/calendar.ics/route.ts @@ -0,0 +1,53 @@ +import { getDb } from "@/db/client"; +import { buildIcs, icsFilename } from "@/lib/ics"; +import { baseUrlFrom, shareUrl } from "@/server/base-url"; +import { getCalendarEvent } from "@/services/calendar"; +import { NotFoundError } from "@/services/errors"; + +// Reads the database, so it must never be prerendered or cached. +export const dynamic = "force-dynamic"; + +/** + * `/e/[code]/calendar.ics` downloads the event as an iCalendar file. + * Unknown and deleted events are a plain 404; cancelled events download with + * STATUS:CANCELLED. + */ +export async function GET( + request: Request, + context: RouteContext<"/e/[code]/calendar.ics">, +): Promise<Response> { + const { code } = await context.params; + const db = await getDb(); + + let event; + try { + event = await getCalendarEvent(db, code); + } catch (error) { + if (error instanceof NotFoundError) { + return new Response("Event not found", { status: 404 }); + } + throw error; + } + + const url = shareUrl( + baseUrlFrom(new Headers(request.headers), process.env.BETTER_AUTH_URL), + event.shareCode, + ); + const ics = buildIcs({ + id: event.id, + title: event.title, + startsAt: event.startsAt, + location: event.location, + hostName: event.hostName, + url, + cancelled: event.cancelled, + }); + + return new Response(ics, { + status: 200, + headers: { + "Content-Type": "text/calendar; charset=utf-8", + "Content-Disposition": `attachment; filename="${icsFilename(event.title)}"`, + }, + }); +} diff --git a/src/app/e/[code]/page.tsx b/src/app/e/[code]/page.tsx index 11a2a67..b9cfaa0 100644 --- a/src/app/e/[code]/page.tsx +++ b/src/app/e/[code]/page.tsx @@ -6,6 +6,8 @@ import { getDb } from "@/db/client"; import { formatWhen } from "@/lib/format"; import { guestCookieName } from "@/lib/guest-cookie"; import { eventPreview, wantsBlankForm } from "@/lib/guest-page"; +import { calendarDetails, googleCalendarUrl } from "@/lib/ics"; +import { getBaseUrl, shareUrl } from "@/server/base-url"; import { NotFoundError } from "@/services/errors"; import { getGuestByToken, getPublicEvent } from "@/services/rsvp"; import { submitGuestRsvp } from "./actions"; @@ -51,6 +53,14 @@ export default async function GuestPage({ params, searchParams }: PageProps<"/e/ if (known) redirect(`/e/${encodeURIComponent(code)}/g/${encodeURIComponent(token)}`); } + const guestUrl = shareUrl(await getBaseUrl(), code); + const googleUrl = googleCalendarUrl({ + title: event.title, + startsAt: event.startsAt, + location: event.location, + details: calendarDetails(event.hostName, guestUrl), + }); + return ( <main> <RsvpForm @@ -62,6 +72,28 @@ export default async function GuestPage({ params, searchParams }: PageProps<"/e/ }} action={submitGuestRsvp.bind(null, code)} /> + + <aside className="mx-auto -mt-6 w-full max-w-lg px-3 pb-14 sm:px-5"> + <div className="ticket-surface rounded-2xl border border-divider bg-paper p-4"> + <h2 className="text-base font-bold text-ink">Add to calendar</h2> + <p className="mt-1 text-sm leading-relaxed text-ink/80"> + Save the time now. Come back to this link if plans change. + </p> + <div className="mt-3 flex flex-wrap gap-x-5 gap-y-2"> + <a href={`/e/${encodeURIComponent(code)}/calendar.ics`} className="quiet-link"> + Download .ics + </a> + <a + href={googleUrl} + target="_blank" + rel="noreferrer" + className="quiet-link" + > + Google Calendar + </a> + </div> + </div> + </aside> </main> ); } diff --git a/src/app/host/events/[id]/duplicate-action.ts b/src/app/host/events/[id]/duplicate-action.ts new file mode 100644 index 0000000..3a608f2 --- /dev/null +++ b/src/app/host/events/[id]/duplicate-action.ts @@ -0,0 +1,25 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { notFound, redirect } from "next/navigation"; +import { getDb } from "@/db/client"; +import { requireHost } from "@/server/auth"; +import { NotFoundError } from "@/services/errors"; +import { duplicateEvent } from "@/services/duplicate"; + +// The host comes from the session. The event id arrives through `bind`, which the +// browser can alter, so duplicateEvent re-checks that the event belongs to the host. + +/** "Plan this again": copies the event's plan and opens the copy's edit page. */ +export async function duplicateEventAction(eventId: string): Promise<void> { + const host = await requireHost(); + let id: string; + try { + ({ id } = await duplicateEvent(await getDb(), host.id, eventId)); + } catch (error) { + if (error instanceof NotFoundError) notFound(); + throw error; + } + revalidatePath("/host"); + redirect(`/host/events/${encodeURIComponent(id)}/edit`); +} diff --git a/src/app/host/events/[id]/layout.tsx b/src/app/host/events/[id]/layout.tsx index 888bb0a..7795d26 100644 --- a/src/app/host/events/[id]/layout.tsx +++ b/src/app/host/events/[id]/layout.tsx @@ -6,6 +6,7 @@ import { Wordmark } from "@/components/ui/Wordmark"; import { formatWhen } from "@/lib/format"; import { getBaseUrl, shareUrl } from "@/server/base-url"; import { loadHostEvent } from "@/server/host-event"; +import { duplicateEventAction } from "./duplicate-action"; // Reads the session and the database, so it must never be prerendered. export const dynamic = "force-dynamic"; @@ -42,12 +43,19 @@ export default async function EventLayout({ <p className="event-meta"> {formatWhen(event.startsAt, event.location, event.timezone)} </p> - <Link - href={`/host/events/${encodeURIComponent(event.id)}/edit`} - className="quiet-link mt-2" - > - Edit details - </Link> + <div className="mt-2 flex flex-wrap items-center gap-x-5"> + <Link + href={`/host/events/${encodeURIComponent(event.id)}/edit`} + className="quiet-link" + > + Edit details + </Link> + <form action={duplicateEventAction.bind(null, event.id)}> + <button type="submit" className="quiet-link"> + Plan this again + </button> + </form> + </div> </div> <div className="ticket-count"> <p> diff --git a/src/app/host/events/[id]/today/page.tsx b/src/app/host/events/[id]/today/page.tsx new file mode 100644 index 0000000..0263b46 --- /dev/null +++ b/src/app/host/events/[id]/today/page.tsx @@ -0,0 +1,50 @@ +import { TodayChecklist } from "@/components/today/TodayChecklist"; +import { getDb } from "@/db/client"; +import { buildPrepSheet } from "@/lib/prep-sheet"; +import { buildTodayPlan } from "@/lib/today-plan"; +import { requireHost } from "@/server/auth"; +import { loadHostEvent } from "@/server/host-event"; +import { getGuestsOverview } from "@/services/guestsOverview"; +import { getMenu } from "@/services/menu"; +import { getShoppingPlan } from "@/services/shopping"; + +// Reads the session and the database, so it must never be prerendered. +export const dynamic = "force-dynamic"; + +export default async function TodayTab({ params }: PageProps<"/host/events/[id]/today">) { + // Layouts and pages are authorised independently: check ownership here too. + const { event } = await loadHostEvent((await params).id); + const host = await requireHost(); + const db = await getDb(); + const [shopping, menu, overview] = await Promise.all([ + getShoppingPlan(db, host.id, event.id), + getMenu(db, host.id, event.id), + getGuestsOverview(db, host.id, event.id), + ]); + + const sheet = buildPrepSheet({ + event: { + id: event.id, + title: event.title, + startsAt: event.startsAt, + location: event.location, + timezone: event.timezone, + }, + dishes: menu.dishes, + headcount: overview.headcount, + guests: overview.guests, + }); + + const plan = buildTodayPlan({ + event: { + id: event.id, + title: event.title, + startsAt: event.startsAt, + timezone: event.timezone, + }, + shopping: shopping.lines, + prepSheet: sheet, + }); + + return <TodayChecklist plan={plan} />; +} diff --git a/src/components/EventTabs.test.tsx b/src/components/EventTabs.test.tsx index 83ec358..7e69d33 100644 --- a/src/components/EventTabs.test.tsx +++ b/src/components/EventTabs.test.tsx @@ -11,7 +11,7 @@ function current() { } describe("EventTabs", () => { - it("links the four tabs under the event", () => { + it("links the five tabs under the event", () => { usePathname.mockReturnValue("/host/events/ev1"); render(<EventTabs eventId="ev1" />); const links = screen.getAllByRole("link"); @@ -20,6 +20,7 @@ describe("EventTabs", () => { ["Menu", "/host/events/ev1/menu"], ["Shopping", "/host/events/ev1/shopping"], ["Split", "/host/events/ev1/split"], + ["Today", "/host/events/ev1/today"], ]); }); @@ -33,6 +34,7 @@ describe("EventTabs", () => { ["/host/events/ev1/menu", "Menu"], ["/host/events/ev1/shopping", "Shopping"], ["/host/events/ev1/split", "Split"], + ["/host/events/ev1/today", "Today"], ["/host/events/ev1/menu/", "Menu"], ["/host/events/ev1/prep", "Menu"], ["/host/events/ev1/prep/", "Menu"], diff --git a/src/components/EventTabs.tsx b/src/components/EventTabs.tsx index bf8d7e3..e41766b 100644 --- a/src/components/EventTabs.tsx +++ b/src/components/EventTabs.tsx @@ -22,6 +22,7 @@ export function EventTabs({ eventId }: { eventId: string }) { { label: "Menu", href: `${base}/menu` }, { label: "Shopping", href: `${base}/shopping` }, { label: "Split", href: `${base}/split` }, + { label: "Today", href: `${base}/today` }, ]; const tabPath = pathname.replace(/\/+$/, "") === `${base}/prep` ? `${base}/menu` : pathname; return <TabBar tabs={tabs} activeHref={activeTabHref(tabs, tabPath)} />; diff --git a/src/components/today/TodayChecklist.test.tsx b/src/components/today/TodayChecklist.test.tsx new file mode 100644 index 0000000..95a2d87 --- /dev/null +++ b/src/components/today/TodayChecklist.test.tsx @@ -0,0 +1,55 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { TodayPlan } from "@/lib/today-plan"; +import { TodayChecklist } from "./TodayChecklist"; + +const plan: TodayPlan = { + eventId: "evt-1", + title: "Party", + when: "Sat, Nov 14 · 7pm · Backyard", + planFor: 8, + headcountLine: "6 confirmed + ~2 from maybes · range 6–10", + milestones: [ + { id: "shopping-done", label: "Shopping done", timeLabel: "9:00 AM" }, + { id: "start-prep", label: "Start prep", timeLabel: "4:00 PM" }, + { id: "set-up", label: "Set up", timeLabel: "6:00 PM" }, + { id: "guests-arrive", label: "Guests arrive", timeLabel: "7:00 PM" }, + ], + shopping: [{ id: "shop:i1", label: "Ground beef", detail: "4 lb to buy" }], + prep: [{ id: "prep:d1", label: "Burgers", detail: "make 12 burgers" }], +}; + +describe("TodayChecklist", () => { + beforeEach(() => window.localStorage.clear()); + + it("shows the headcount, milestone times and both checklists", () => { + render(<TodayChecklist plan={plan} />); + expect(screen.getByText("6 confirmed + ~2 from maybes · range 6–10")).toBeInTheDocument(); + expect(screen.getByText(/Planning for ~8 people/)).toBeInTheDocument(); + expect(screen.getByText("4:00 PM")).toBeInTheDocument(); + expect(screen.getByText("4 lb to buy")).toBeInTheDocument(); + expect(screen.getByText("make 12 burgers")).toBeInTheDocument(); + expect(screen.getAllByRole("checkbox")).toHaveLength(6); + }); + + it("remembers ticks in localStorage per event", () => { + const { unmount } = render(<TodayChecklist plan={plan} />); + fireEvent.click(screen.getByRole("checkbox", { name: /Burgers/ })); + + expect(window.localStorage.getItem("spread:today:evt-1")).toContain("prep:d1"); + expect(screen.getByText("1 of 6 done")).toBeInTheDocument(); + + unmount(); + render(<TodayChecklist plan={plan} />); + expect(screen.getByRole("checkbox", { name: /Burgers/ })).toBeChecked(); + }); + + it("clears the ticks again", () => { + render(<TodayChecklist plan={plan} />); + fireEvent.click(screen.getByRole("checkbox", { name: /Shopping done/ })); + fireEvent.click(screen.getByRole("button", { name: "Clear ticks" })); + + expect(window.localStorage.getItem("spread:today:evt-1")).toBeNull(); + expect(screen.getByRole("checkbox", { name: /Shopping done/ })).not.toBeChecked(); + }); +}); diff --git a/src/components/today/TodayChecklist.tsx b/src/components/today/TodayChecklist.tsx new file mode 100644 index 0000000..6f622c8 --- /dev/null +++ b/src/components/today/TodayChecklist.tsx @@ -0,0 +1,244 @@ +"use client"; + +import { useMemo, useSyncExternalStore } from "react"; +import { Button } from "@/components/ui/Button"; +import { Card } from "@/components/ui/Card"; +import type { TodayChecklistItem, TodayPlan } from "@/lib/today-plan"; + +// Day-of ticks are a local convenience, not event data: no schema, no server round trip. +const STORAGE_PREFIX = "spread:today:"; + +type Ticks = Record<string, boolean>; +const NO_TICKS: Ticks = {}; + +function parseTicks(raw: string | null): Ticks { + if (!raw) return NO_TICKS; + try { + const parsed: unknown = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return NO_TICKS; + const ticks: Ticks = {}; + for (const [id, value] of Object.entries(parsed)) { + if (value === true) ticks[id] = true; + } + return ticks; + } catch { + return NO_TICKS; + } +} + +/** + * One checklist's ticks in localStorage, read through useSyncExternalStore so the + * server renders unticked and the browser hydrates straight to the saved ticks. + */ +function createTicksStore(storageKey: string) { + let cachedRaw: string | null = null; + let cached: Ticks = NO_TICKS; + const listeners = new Set<() => void>(); + const notify = () => { + for (const listener of listeners) listener(); + }; + + return { + subscribe(listener: () => void) { + listeners.add(listener); + // Another tab changing this checklist (or clearing site data) refreshes this one. + const onStorage = (event: StorageEvent) => { + if (event.key === null || event.key === storageKey) { + cachedRaw = null; + listener(); + } + }; + window.addEventListener("storage", onStorage); + return () => { + listeners.delete(listener); + window.removeEventListener("storage", onStorage); + }; + }, + getSnapshot(): Ticks { + let raw: string | null = null; + try { + raw = window.localStorage.getItem(storageKey); + } catch { + raw = null; + } + if (raw !== cachedRaw) { + cachedRaw = raw; + cached = parseTicks(raw); + } + return cached; + }, + getServerSnapshot(): Ticks { + return NO_TICKS; + }, + write(next: Ticks) { + cached = next; + try { + const raw = JSON.stringify(next); + window.localStorage.setItem(storageKey, raw); + cachedRaw = raw; + } catch { + // A blocked store keeps the ticks in memory for this visit. + cachedRaw = null; + } + notify(); + }, + clear() { + cached = NO_TICKS; + cachedRaw = null; + try { + window.localStorage.removeItem(storageKey); + } catch { + // Nothing else to clear. + } + notify(); + }, + }; +} + +function ChecklistRow({ + item, + checked, + onToggle, +}: { + item: TodayChecklistItem; + checked: boolean; + onToggle: () => void; +}) { + return ( + <label className="flex min-h-11 cursor-pointer items-start gap-3 border-t border-dashed border-divider py-3 first:border-t-0"> + <input + type="checkbox" + checked={checked} + onChange={onToggle} + className="mt-1 size-5 shrink-0 accent-ketchup" + /> + <span className="min-w-0"> + <span + className={ + checked + ? "font-semibold text-ink-muted line-through decoration-1" + : "font-semibold text-ink" + } + > + {item.label} + </span> + {item.detail ? ( + <span className="block text-sm leading-relaxed text-ink-muted">{item.detail}</span> + ) : null} + </span> + </label> + ); +} + +/** The Today tab checklist: fixed times, outstanding shopping, and dish prep. */ +export function TodayChecklist({ plan }: { plan: TodayPlan }) { + const storageKey = `${STORAGE_PREFIX}${plan.eventId}`; + const store = useMemo(() => createTicksStore(storageKey), [storageKey]); + const done = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot); + + function toggle(id: string) { + store.write({ ...done, [id]: !done[id] }); + } + + function reset() { + store.clear(); + } + + const items: TodayChecklistItem[] = [ + ...plan.milestones.map((milestone) => ({ + id: `milestone:${milestone.id}`, + label: milestone.label, + detail: milestone.timeLabel, + })), + ...plan.shopping, + ...plan.prep, + ]; + const doneCount = items.filter((item) => done[item.id]).length; + + return ( + <div className="flex flex-col gap-4"> + <Card className="flex flex-wrap items-baseline justify-between gap-x-4 gap-y-1"> + <div> + <p className="text-lg font-bold">{plan.headcountLine}</p> + <p className="text-sm text-ink/80"> + Planning for ~{plan.planFor} {plan.planFor === 1 ? "person" : "people"} · {plan.when} + </p> + </div> + <p className="text-sm font-bold text-ink-muted"> + {doneCount} of {items.length} done + </p> + </Card> + + <div className="grid gap-4 lg:grid-cols-3 lg:items-start"> + <Card> + <h2 className="text-lg font-bold">Timeline</h2> + <p className="mt-1 text-sm leading-relaxed text-ink-muted"> + Times use the event's own time zone. + </p> + <div className="mt-2"> + {plan.milestones.map((milestone) => ( + <ChecklistRow + key={milestone.id} + item={{ + id: `milestone:${milestone.id}`, + label: milestone.label, + detail: milestone.timeLabel, + }} + checked={Boolean(done[`milestone:${milestone.id}`])} + onToggle={() => toggle(`milestone:${milestone.id}`)} + /> + ))} + </div> + </Card> + + <Card> + <h2 className="text-lg font-bold">Still to buy</h2> + {plan.shopping.length === 0 ? ( + <p className="mt-2 text-sm leading-relaxed text-ink/80"> + Every shopping item is ticked. Nice. + </p> + ) : ( + <div className="mt-2"> + {plan.shopping.map((item) => ( + <ChecklistRow + key={item.id} + item={item} + checked={Boolean(done[item.id])} + onToggle={() => toggle(item.id)} + /> + ))} + </div> + )} + </Card> + + <Card> + <h2 className="text-lg font-bold">Make</h2> + {plan.prep.length === 0 ? ( + <p className="mt-2 text-sm leading-relaxed text-ink/80"> + No dishes saved yet. Add them on the Menu tab. + </p> + ) : ( + <div className="mt-2"> + {plan.prep.map((item) => ( + <ChecklistRow + key={item.id} + item={item} + checked={Boolean(done[item.id])} + onToggle={() => toggle(item.id)} + /> + ))} + </div> + )} + </Card> + </div> + + {doneCount > 0 ? ( + <div> + <Button variant="outline" onClick={reset} className="min-h-11 py-2 text-sm"> + Clear ticks + </Button> + </div> + ) : null} + </div> + ); +} diff --git a/src/db/schema.ts b/src/db/schema.ts index d3220d5..6bd72ad 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -33,6 +33,15 @@ export const events = pgTable("events", { maybePercent: integer("maybe_percent").notNull().default(50), venmoUsername: text("venmo_username"), hostCoverCents: integer("host_cover_cents").notNull().default(0), + // Soft delete: hidden everywhere, restorable for 30 days, then purged. + deletedAt: timestamp("deleted_at", { withTimezone: true }), + // Cancelled events stay visible (with a banner) but take no RSVPs. + cancelledAt: timestamp("cancelled_at", { withTimezone: true }), + // Last time the time, timezone or location changed; drives guest "Updated" notices. + detailsChangedAt: timestamp("details_changed_at", { withTimezone: true }), + // Cover: one of the preset emoji / palette keys; null means the default. + coverEmoji: text("cover_emoji"), + coverColor: text("cover_color"), }); export const recipes = pgTable("recipes", { diff --git a/src/lib/ics.test.ts b/src/lib/ics.test.ts new file mode 100644 index 0000000..7be5cfa --- /dev/null +++ b/src/lib/ics.test.ts @@ -0,0 +1,129 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + buildIcs, + calendarDetails, + escapeIcsText, + foldIcsLine, + googleCalendarUrl, + icsFilename, + utcStamp, +} from "./ics"; + +const event = { + id: "evt-1", + title: "Fourth of July", + startsAt: new Date("2026-11-15T01:00:00Z"), // 7pm on Nov 14 in Chicago + location: "Will's backyard", + hostName: "Will", + url: "https://spread.example/e/abc1234567", + stamp: new Date("2026-11-01T12:34:56Z"), +}; + +const lines = (ics: string) => ics.split("\r\n"); + +describe("buildIcs", () => { + it("writes one UTC VEVENT three hours long with CRLF endings", () => { + const ics = buildIcs(event); + expect(ics.endsWith("\r\n")).toBe(true); + expect(ics.replace(/\r\n/g, "")).not.toMatch(/[\r\n]/); + expect(lines(ics)).toEqual( + expect.arrayContaining([ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "BEGIN:VEVENT", + "UID:evt-1@spread", + "DTSTAMP:20261101T123456Z", + "DTSTART:20261115T010000Z", + "DTEND:20261115T040000Z", + "SUMMARY:Fourth of July", + "LOCATION:Will's backyard", + "DESCRIPTION:Hosted by Will · RSVP: https://spread.example/e/abc1234567", + "URL:https://spread.example/e/abc1234567", + "END:VEVENT", + "END:VCALENDAR", + ]), + ); + }); + + it("leaves STATUS off a normal event and marks a cancelled one", () => { + expect(buildIcs(event)).not.toContain("STATUS:"); + expect(buildIcs({ ...event, cancelled: true })).toContain("STATUS:CANCELLED\r\n"); + }); + + it("escapes backslashes, semicolons, commas and newlines in text fields", () => { + const ics = buildIcs({ + ...event, + title: 'Burgers, dogs; "fixins" \\ late\nnight', + location: "Patio; side, door", + }); + expect(ics).toContain('SUMMARY:Burgers\\, dogs\\; "fixins" \\\\ late\\nnight\r\n'); + expect(ics).toContain("LOCATION:Patio\\; side\\, door\r\n"); + }); + + it("folds lines over 75 octets and unfolds back to the same value", () => { + const title = "A".repeat(100); + const ics = buildIcs({ ...event, title }); + const encoder = new TextEncoder(); + for (const line of lines(ics)) { + expect(encoder.encode(line).length).toBeLessThanOrEqual(75); + } + const unfolded = ics.replace(/\r\n /g, ""); + expect(lines(unfolded)).toContain(`SUMMARY:${title}`); + }); + + it("folds without splitting a multi-byte character", () => { + const title = "é".repeat(80); + const ics = buildIcs({ ...event, title }); + const encoder = new TextEncoder(); + for (const line of lines(ics)) { + expect(encoder.encode(line).length).toBeLessThanOrEqual(75); + } + expect(lines(ics.replace(/\r\n /g, ""))).toContain(`SUMMARY:${title}`); + }); +}); + +describe("calendar helpers", () => { + it("formats UTC timestamps compactly", () => { + expect(utcStamp(new Date("2026-01-02T03:04:05Z"))).toBe("20260102T030405Z"); + }); + + it("escapes text in the RFC 5545 order", () => { + expect(escapeIcsText("a\\b;c,d\r\ne")).toBe("a\\\\b\\;c\\,d\\ne"); + }); + + it("folds to 75 octets including the continuation space", () => { + const folded = foldIcsLine("x".repeat(200)); + const parts = folded.split("\r\n"); + expect(parts[0]).toHaveLength(75); + expect(parts[1].startsWith(" ")).toBe(true); + expect(parts.every((p) => p.length <= 75)).toBe(true); + expect(folded.replace(/\r\n /g, "")).toHaveLength(200); + }); + + it("builds a Google Calendar link with UTC dates, text, location and details", () => { + const url = new URL( + googleCalendarUrl({ + title: "Fourth of July", + startsAt: event.startsAt, + location: "Will's backyard", + details: calendarDetails("Will", event.url), + }), + ); + expect(url.origin + url.pathname).toBe( + "https://calendar.google.com/calendar/render", + ); + expect(url.searchParams.get("action")).toBe("TEMPLATE"); + expect(url.searchParams.get("text")).toBe("Fourth of July"); + expect(url.searchParams.get("dates")).toBe("20261115T010000Z/20261115T040000Z"); + expect(url.searchParams.get("location")).toBe("Will's backyard"); + expect(url.searchParams.get("details")).toBe( + "Hosted by Will · RSVP: https://spread.example/e/abc1234567", + ); + }); + + it("slugs the attachment filename", () => { + expect(icsFilename("Will's 4th of July!")).toBe("will-s-4th-of-july.ics"); + expect(icsFilename("🎉")).toBe("event.ics"); + }); +}); diff --git a/src/lib/ics.ts b/src/lib/ics.ts new file mode 100644 index 0000000..1985122 --- /dev/null +++ b/src/lib/ics.ts @@ -0,0 +1,131 @@ +// RFC 5545 (iCalendar) text building for the "Add to calendar" links. +// Everything here is pure so the format can be pinned by unit tests. + +const END_MS = 3 * 60 * 60 * 1000; + +export interface IcsEvent { + id: string; + title: string; + startsAt: Date; + location: string; + hostName: string; + /** The public guest link for this event. */ + url: string; + /** Cancelled events keep their calendar entry but mark it cancelled. */ + cancelled?: boolean; + /** DTSTAMP; defaults to now (injectable so tests are stable). */ + stamp?: Date; +} + +export interface GoogleCalendarEvent { + title: string; + startsAt: Date; + location: string; + details: string; +} + +/** "20261114T190000Z": the UTC form both iCalendar and Google Calendar expect. */ +export function utcStamp(date: Date): string { + return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z"); +} + +/** RFC 5545 TEXT escaping: backslash first, then the delimiters and newlines. */ +export function escapeIcsText(value: string): string { + return value + .replace(/\\/g, "\\\\") + .replace(/;/g, "\\;") + .replace(/,/g, "\\,") + .replace(/\r\n|\r|\n/g, "\\n"); +} + +/** + * Folds one content line to at most 75 octets, continuation lines starting with a + * space (which counts toward the limit). Iterates code points so a multi-byte + * character is never split across lines. + */ +export function foldIcsLine(line: string): string { + const encoder = new TextEncoder(); + if (encoder.encode(line).length <= 75) return line; + + const parts: string[] = []; + let current = ""; + let bytes = 0; + // Continuation lines lose one octet to the leading space. + let limit = 75; + for (const char of line) { + const size = encoder.encode(char).length; + if (bytes + size > limit) { + parts.push(current); + current = ""; + bytes = 0; + limit = 74; + } + current += char; + bytes += size; + } + if (current) parts.push(current); + return parts.map((part, index) => (index === 0 ? part : ` ${part}`)).join("\r\n"); +} + +/** "Hosted by Will · RSVP: https://…" for both calendar flavours. */ +export function calendarDetails(hostName: string, url: string): string { + return `Hosted by ${hostName} · RSVP: ${url}`; +} + +/** + * A complete VCALENDAR with one VEVENT: three hours long, in UTC, CRLF line + * endings, escaped text and folded long lines. Cancelled events carry + * `STATUS:CANCELLED`. The UID is stable so a re-download updates the same entry. + */ +export function buildIcs(event: IcsEvent): string { + const end = new Date(event.startsAt.getTime() + END_MS); + const lines = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//Spread//Spread//EN", + "CALSCALE:GREGORIAN", + "METHOD:PUBLISH", + "BEGIN:VEVENT", + `UID:${event.id}@spread`, + `DTSTAMP:${utcStamp(event.stamp ?? new Date())}`, + `DTSTART:${utcStamp(event.startsAt)}`, + `DTEND:${utcStamp(end)}`, + `SUMMARY:${escapeIcsText(event.title)}`, + `LOCATION:${escapeIcsText(event.location)}`, + `DESCRIPTION:${escapeIcsText(calendarDetails(event.hostName, event.url))}`, + `URL:${event.url}`, + ...(event.cancelled ? ["STATUS:CANCELLED"] : []), + "END:VEVENT", + "END:VCALENDAR", + ]; + return `${lines.map(foldIcsLine).join("\r\n")}\r\n`; +} + +/** + * A Google Calendar "create event" link. Google takes the same compact UTC + * timestamps as iCalendar (`dates=START/END`) and URL-decodes the rest itself. + */ +export function googleCalendarUrl(event: GoogleCalendarEvent): string { + const end = new Date(event.startsAt.getTime() + END_MS); + const params = new URLSearchParams({ + action: "TEMPLATE", + text: event.title, + dates: `${utcStamp(event.startsAt)}/${utcStamp(end)}`, + location: event.location, + details: event.details, + }); + return `https://calendar.google.com/calendar/render?${params.toString()}`; +} + +/** A safe ASCII attachment name: "fourth-of-july-again.ics". */ +export function icsFilename(title: string): string { + const slug = title + .normalize("NFKD") + .replace(/[\u0300-\u036f]/g, "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 60) + .replace(/-+$/g, ""); + return `${slug || "event"}.ics`; +} diff --git a/src/lib/today-plan.test.ts b/src/lib/today-plan.test.ts new file mode 100644 index 0000000..ff42ff8 --- /dev/null +++ b/src/lib/today-plan.test.ts @@ -0,0 +1,126 @@ +// @vitest-environment node +import { afterEach, describe, expect, it } from "vitest"; +import { computeHeadcount } from "@/domain/headcount"; +import { buildTodayPlan, type TodayShoppingLine } from "./today-plan"; +import { zonedLocalToDate } from "./zoned-time"; + +const startsAt = zonedLocalToDate("2026-11-14T19:00", "America/Chicago"); + +const prepSheet = { + when: "Sat, Nov 14 · 7pm · Backyard", + headcount: computeHeadcount([ + { status: "yes", plusOnes: 1 }, + { status: "maybe", plusOnes: 1 }, + ]), + headcountLine: "2 confirmed + ~1 from maybes · range 2–4", + dishes: [ + { + dishId: "dish-1", + name: "Burgers", + emoji: "🍔", + servings: 12, + servingsPerPerson: 1.5, + servingsLabel: "12 burgers", + ingredients: [], + }, + { + dishId: "dish-2", + name: "Slaw", + emoji: "🥗", + servings: 6, + servingsPerPerson: 0.75, + servingsLabel: "6 bowls", + ingredients: [], + }, + ], +}; + +const shopping: TodayShoppingLine[] = [ + { itemId: "i1", name: "Ground beef", buyQty: 4, buyUnit: "lb", checked: false, needsReview: false }, + { itemId: "i2", name: "Buns", buyQty: 2, buyUnit: "pack", checked: true, needsReview: false }, + { itemId: "i3", name: "Cheese", buyQty: 1, buyUnit: "pack", checked: false, needsReview: true }, + { itemId: "i4", name: "Ice", buyQty: 0, buyUnit: "bag", checked: false, needsReview: false }, +]; + +const build = () => + buildTodayPlan({ + event: { id: "evt-1", title: "Party", startsAt, timezone: "America/Chicago" }, + shopping, + prepSheet, + }); + +describe("buildTodayPlan", () => { + const originalTz = process.env.TZ; + + // Restore the process time zone so other tests are unaffected. + afterEach(() => { + if (originalTz === undefined) delete process.env.TZ; + else process.env.TZ = originalTz; + }); + + it("shows milestone times on the event's own clock", () => { + const plan = build(); + expect(plan.milestones).toEqual([ + { id: "shopping-done", label: "Shopping done", timeLabel: "9:00 AM" }, + { id: "start-prep", label: "Start prep", timeLabel: "4:00 PM" }, + { id: "set-up", label: "Set up", timeLabel: "6:00 PM" }, + { id: "guests-arrive", label: "Guests arrive", timeLabel: "7:00 PM" }, + ]); + }); + + it("keeps the same labels whatever the server's own time zone", () => { + for (const tz of ["UTC", "Asia/Tokyo", "America/Los_Angeles"]) { + process.env.TZ = tz; + expect(build().milestones.map((m) => m.timeLabel)).toEqual([ + "9:00 AM", + "4:00 PM", + "6:00 PM", + "7:00 PM", + ]); + } + }); + + it("pulls shopping earlier for an event that starts before 1pm", () => { + const morning = zonedLocalToDate("2026-11-14T11:00", "America/Chicago"); + const plan = buildTodayPlan({ + event: { id: "evt-1", title: "Brunch", startsAt: morning, timezone: "America/Chicago" }, + shopping, + prepSheet, + }); + expect(plan.milestones.map((m) => m.timeLabel)).toEqual([ + "7:00 AM", + "8:00 AM", + "10:00 AM", + "11:00 AM", + ]); + }); + + it("lists only unticked shopping that needs buying", () => { + const plan = build(); + expect(plan.shopping.map((item) => item.id)).toEqual(["shop:i1", "shop:i3"]); + expect(plan.shopping[0]).toEqual({ + id: "shop:i1", + label: "Ground beef", + detail: "4 lb to buy", + }); + expect(plan.shopping[1].detail).toContain("recheck the amount"); + }); + + it("makes one prep row per dish with the servings to make", () => { + const plan = build(); + expect(plan.prep).toEqual([ + { id: "prep:dish-1", label: "Burgers", detail: "make 12 burgers" }, + { id: "prep:dish-2", label: "Slaw", detail: "make 6 bowls" }, + ]); + }); + + it("carries the event identity, when line and planning headcount", () => { + expect(build()).toMatchObject({ + eventId: "evt-1", + title: "Party", + when: "Sat, Nov 14 · 7pm · Backyard", + planFor: 3, + headcountLine: "2 confirmed + ~1 from maybes · range 2–4", + }); + }); +}); diff --git a/src/lib/today-plan.ts b/src/lib/today-plan.ts new file mode 100644 index 0000000..9f45f7c --- /dev/null +++ b/src/lib/today-plan.ts @@ -0,0 +1,131 @@ +import type { PrepSheet } from "./prep-sheet"; +import { formatBuyQty } from "./shopping-text"; +import { dateToZonedLocal, zonedLocalToDate } from "./zoned-time"; + +const HOUR_MS = 60 * 60 * 1000; + +export interface TodayPlanEvent { + id: string; + title: string; + startsAt: Date; + /** IANA zone the event's times belong to. */ + timezone: string; +} + +/** The shopping fields the day-of list reads (see getShoppingPlan's lines). */ +export interface TodayShoppingLine { + itemId: string; + name: string; + buyQty: number; + buyUnit: string; + /** The effective tick: false while a tick needs rechecking counts as not done. */ + checked: boolean; + needsReview: boolean; +} + +export interface TodayChecklistItem { + id: string; + label: string; + /** Secondary line: a quantity, or why the item needs a second look. */ + detail?: string; +} + +export interface TodayMilestone { + id: string; + label: string; + /** Wall-clock time in the event's zone, e.g. "4:00 PM". */ + timeLabel: string; +} + +export interface TodayPlan { + eventId: string; + title: string; + /** Event date, time and place in the event's own zone. */ + when: string; + planFor: number; + headcountLine: string; + milestones: TodayMilestone[]; + /** Unticked shopping items that actually need buying. */ + shopping: TodayChecklistItem[]; + /** One checklist row per dish, with the servings to make. */ + prep: TodayChecklistItem[]; +} + +export interface BuildTodayPlanInput { + event: TodayPlanEvent; + shopping: TodayShoppingLine[]; + prepSheet: Pick<PrepSheet, "when" | "headcount" | "headcountLine" | "dishes">; +} + +function timeLabel(date: Date, timeZone: string): string { + return date.toLocaleTimeString("en-US", { + hour: "numeric", + minute: "2-digit", + timeZone, + }); +} + +/** + * "Shopping done" is 9am on the event's own morning, pulled earlier for events + * that start before 1pm so it always lands before prep begins. + */ +function shoppingDoneAt(startsAt: Date, timeZone: string): Date { + const localDate = dateToZonedLocal(startsAt, timeZone).slice(0, 10); + const nineAm = zonedLocalToDate(`${localDate}T09:00`, timeZone); + const cutoff = new Date(startsAt.getTime() - 4 * HOUR_MS); + return nineAm.getTime() <= cutoff.getTime() ? nineAm : cutoff; +} + +/** + * The day-of checklist from data Spread already has: fixed milestones around the + * start time, the shopping still outstanding, and what each dish makes. There is + * no cooking-time data, so nothing here claims a cook time. + */ +export function buildTodayPlan({ event, shopping, prepSheet }: BuildTodayPlanInput): TodayPlan { + const shoppingDone = shoppingDoneAt(event.startsAt, event.timezone); + const milestones: TodayMilestone[] = [ + { id: "shopping-done", label: "Shopping done", timeLabel: timeLabel(shoppingDone, event.timezone) }, + { + id: "start-prep", + label: "Start prep", + timeLabel: timeLabel(new Date(event.startsAt.getTime() - 3 * HOUR_MS), event.timezone), + }, + { + id: "set-up", + label: "Set up", + timeLabel: timeLabel(new Date(event.startsAt.getTime() - HOUR_MS), event.timezone), + }, + { + id: "guests-arrive", + label: "Guests arrive", + timeLabel: timeLabel(event.startsAt, event.timezone), + }, + ]; + + const outstanding: TodayChecklistItem[] = shopping + .filter((line) => !line.checked && line.buyQty > 0) + .map((line) => ({ + id: `shop:${line.itemId}`, + label: line.name, + detail: line.needsReview + ? `${formatBuyQty(line.buyQty, line.buyUnit)} to buy · recheck the amount` + : `${formatBuyQty(line.buyQty, line.buyUnit)} to buy`, + })); + + const prep: TodayChecklistItem[] = prepSheet.dishes.map((dish) => ({ + id: `prep:${dish.dishId}`, + label: dish.name, + detail: `make ${dish.servingsLabel}`, + })); + + return { + eventId: event.id, + title: event.title, + when: prepSheet.when, + planFor: prepSheet.headcount.planFor, + headcountLine: prepSheet.headcountLine, + milestones, + shopping: outstanding, + prep, + }; +} diff --git a/src/services/calendar.ts b/src/services/calendar.ts new file mode 100644 index 0000000..1466b1d --- /dev/null +++ b/src/services/calendar.ts @@ -0,0 +1,36 @@ +import { and, eq, isNull } from "drizzle-orm"; +import type { Db } from "@/db/client"; +import { events } from "@/db/schema"; +import { NotFoundError } from "./errors"; + +/** The public fields a calendar file needs. Deleted events never resolve. */ +export interface CalendarEvent { + id: string; + shareCode: string; + title: string; + startsAt: Date; + location: string; + hostName: string; + cancelled: boolean; +} + +/** + * The event behind a share code, with the cancelled flag folded in. + * A soft-deleted event is a NotFoundError: its calendar link must 404. + */ +export async function getCalendarEvent(db: Db, shareCode: string): Promise<CalendarEvent> { + const [event] = await db + .select() + .from(events) + .where(and(eq(events.shareCode, shareCode), isNull(events.deletedAt))); + if (!event) throw new NotFoundError("Event not found"); + return { + id: event.id, + shareCode: event.shareCode, + title: event.title, + startsAt: event.startsAt, + location: event.location, + hostName: event.hostName, + cancelled: event.cancelledAt !== null, + }; +} diff --git a/src/services/duplicate.test.ts b/src/services/duplicate.test.ts new file mode 100644 index 0000000..644d325 --- /dev/null +++ b/src/services/duplicate.test.ts @@ -0,0 +1,191 @@ +// @vitest-environment node +import { eq } from "drizzle-orm"; +import { beforeEach, describe, expect, it } from "vitest"; +import type { Db } from "@/db/client"; +import { + eventDishes, + events, + extraCosts, + guests, + invitees, + plusOnes, + shoppingState, +} from "@/db/schema"; +import { seedStarterRecipes } from "@/db/seed"; +import { createTestDb } from "@/db/test-db"; +import { NotFoundError } from "./errors"; +import { duplicateEvent } from "./duplicate"; +import { addInvitees, createEvent, getHostEvent } from "./events"; +import { addDishToEvent } from "./menu"; +import { submitRsvp } from "./rsvp"; +import { setChecked } from "./shopping"; + +let db: Db; + +beforeEach(async () => { + db = await createTestDb(); + await seedStarterRecipes(db); +}); + +const input = { + title: "Fourth of July", + startsAt: new Date("2026-07-04T18:00:00Z"), + location: "Backyard", + hostName: "Will", + timezone: "America/Chicago", +}; + +async function makeSource() { + const { id, shareCode } = await createEvent(db, "host-1", input); + await db + .update(events) + .set({ + maybePercent: 80, + venmoUsername: "will-cooks", + hostCoverCents: 1500, + coverEmoji: "🎉", + coverColor: "mustard", + detailsChangedAt: new Date("2026-07-01T12:00:00Z"), + }) + .where(eq(events.id, id)); + return { id, shareCode }; +} + +describe("duplicateEvent", () => { + it("copies the plan fields into a new event with ' (again)' in the title", async () => { + const { id, shareCode } = await makeSource(); + const copy = await duplicateEvent(db, "host-1", id, { now: new Date("2026-06-01T00:00:00Z") }); + + expect(copy.id).not.toBe(id); + const event = await getHostEvent(db, "host-1", copy.id); + expect(event).toMatchObject({ + hostId: "host-1", + hostName: "Will", + title: "Fourth of July (again)", + location: "Backyard", + timezone: "America/Chicago", + shareCode: copy.shareCode, + maybePercent: 80, + venmoUsername: "will-cooks", + hostCoverCents: 1500, + cancelledAt: null, + deletedAt: null, + detailsChangedAt: null, + coverEmoji: null, + coverColor: null, + }); + expect(event.startsAt.toISOString()).toBe("2026-07-11T18:00:00.000Z"); + expect(copy.shareCode).not.toBe(shareCode); + }); + + it("does not stack ' (again)' when duplicating a copy", async () => { + const { id } = await makeSource(); + const copy = await duplicateEvent(db, "host-1", id); + const copyOfCopy = await duplicateEvent(db, "host-1", copy.id); + const event = await getHostEvent(db, "host-1", copyOfCopy.id); + expect(event.title).toBe("Fourth of July (again)"); + }); + + it("gives the copy a fresh share code with the same shape as createEvent's", async () => { + const { id } = await makeSource(); + const copy = await duplicateEvent(db, "host-1", id); + expect(copy.shareCode).toMatch(/^[A-Za-z0-9_-]{8,}$/); + const codes = await db.select({ shareCode: events.shareCode }).from(events); + expect(new Set(codes.map((c) => c.shareCode)).size).toBe(codes.length); + }); + + it("retries with a new code when the generator collides", async () => { + const { id } = await makeSource(); + // Take a code that another event already uses, then a fresh one. + await db.update(events).set({ shareCode: "collision1" }).where(eq(events.id, id)); + const queue = ["collision1", "freshcode2"]; + const copy = await duplicateEvent(db, "host-1", id, { + newShareCode: () => queue.shift() as string, + }); + expect(copy.shareCode).toBe("freshcode2"); + }); + + it("moves a future event one week later, same weekday and time", async () => { + const { id } = await makeSource(); + const copy = await duplicateEvent(db, "host-1", id, { + now: new Date("2026-06-01T09:30:00Z"), + }); + const event = await getHostEvent(db, "host-1", copy.id); + expect(event.startsAt.toISOString()).toBe("2026-07-11T18:00:00.000Z"); + }); + + it("moves a past event to one week after now", async () => { + const { id } = await makeSource(); + const now = new Date("2026-08-20T12:00:00Z"); + const copy = await duplicateEvent(db, "host-1", id, { now }); + const event = await getHostEvent(db, "host-1", copy.id); + expect(event.startsAt.toISOString()).toBe("2026-08-27T12:00:00.000Z"); + }); + + it("keeps the same wall-clock time across a daylight-saving change", async () => { + // 7pm on Oct 25 (CDT); DST ends on Nov 1, so next week is 7pm CST, not 6pm. + const { id } = await createEvent(db, "host-1", { + ...input, + startsAt: new Date("2026-10-26T00:00:00Z"), + }); + const copy = await duplicateEvent(db, "host-1", id, { + now: new Date("2026-10-01T00:00:00Z"), + }); + const event = await getHostEvent(db, "host-1", copy.id); + expect(event.startsAt.toISOString()).toBe("2026-11-02T01:00:00.000Z"); + }); + + it("carries the menu and invitees, deduping the old guest list case-insensitively", async () => { + const { id, shareCode } = await makeSource(); + await addDishToEvent(db, "host-1", id, "starter-burgers"); + await addInvitees(db, "host-1", id, ["Alex", "SAM"]); + await submitRsvp(db, { shareCode, name: " alex ", status: "yes", plusOneNames: ["Jo"] }); + await submitRsvp(db, { shareCode, name: "Bea", status: "maybe", plusOneNames: [] }); + + const copy = await duplicateEvent(db, "host-1", id, { now: new Date("2026-06-01T00:00:00Z") }); + + const dishes = await db.select().from(eventDishes).where(eq(eventDishes.eventId, copy.id)); + expect(dishes).toHaveLength(1); + expect(dishes[0].recipeId).toBe("starter-burgers"); + + const copied = await db + .select({ name: invitees.name }) + .from(invitees) + .where(eq(invitees.eventId, copy.id)); + expect(copied.map((r) => r.name).sort()).toEqual(["Alex", "Bea", "SAM"]); + }); + + it("does not copy RSVPs, plus-ones, shopping state or extra costs", async () => { + const { id, shareCode } = await makeSource(); + await addDishToEvent(db, "host-1", id, "starter-burgers"); + await submitRsvp(db, { shareCode, name: "Pat", status: "yes", plusOneNames: ["Sam"] }); + await setChecked(db, "host-1", id, "starter-burgers-beef", true); + await db.insert(extraCosts).values({ eventId: id, label: "Ice", amountCents: 400 }); + + const copy = await duplicateEvent(db, "host-1", id, { now: new Date("2026-06-01T00:00:00Z") }); + + expect(await db.select().from(guests).where(eq(guests.eventId, copy.id))).toHaveLength(0); + expect(await db.select().from(plusOnes)).toHaveLength(1); // only the source guest's + expect( + await db.select().from(shoppingState).where(eq(shoppingState.eventId, copy.id)), + ).toHaveLength(0); + expect( + await db.select().from(extraCosts).where(eq(extraCosts.eventId, copy.id)), + ).toHaveLength(0); + }); + + it("rejects another host's event and creates nothing", async () => { + const { id } = await makeSource(); + await expect(duplicateEvent(db, "host-2", id)).rejects.toBeInstanceOf(NotFoundError); + expect(await db.select().from(events)).toHaveLength(1); + }); + + it("rejects an unknown id and a deleted event", async () => { + await expect(duplicateEvent(db, "host-1", "missing")).rejects.toBeInstanceOf(NotFoundError); + + const { id } = await makeSource(); + await db.update(events).set({ deletedAt: new Date() }).where(eq(events.id, id)); + await expect(duplicateEvent(db, "host-1", id)).rejects.toBeInstanceOf(NotFoundError); + expect(await db.select().from(events)).toHaveLength(1); + }); +}); diff --git a/src/services/duplicate.ts b/src/services/duplicate.ts new file mode 100644 index 0000000..0cd73ca --- /dev/null +++ b/src/services/duplicate.ts @@ -0,0 +1,132 @@ +import { and, eq, isNull } from "drizzle-orm"; +import type { Db } from "@/db/client"; +import { eventDishes, events, guests, invitees } from "@/db/schema"; +import { dateToZonedLocal, zonedLocalToDate } from "@/lib/zoned-time"; +import { NotFoundError } from "./errors"; +import { generateShareCode } from "./events"; + +const SHARE_CODE_ATTEMPTS = 5; + +export interface DuplicateEventOptions { + /** Injectable "now" so the start-date rule is testable. */ + now?: Date; + /** Injectable share-code generator, like createEvent's. */ + newShareCode?: () => string; +} + +const nameKey = (name: string) => name.trim().toLowerCase(); + +/** Adds whole days to a "YYYY-MM-DD" date without a time zone getting in the way. */ +function addDays(date: string, days: number): string { + const [year, month, day] = date.split("-").map(Number); + return new Date(Date.UTC(year, month - 1, day + days)).toISOString().slice(0, 10); +} + +/** + * The same weekday and wall-clock time one week after `later`, read in the event's + * own zone so a DST change in the middle doesn't shift the party by an hour. + */ +function oneWeekLater(later: Date, timezone: string): Date { + const local = dateToZonedLocal(later, timezone); + const date = local.slice(0, 10); + const time = local.slice(11); + return zonedLocalToDate(`${addDays(date, 7)}T${time}`, timezone); +} + +/** + * Copies an event's plan into a fresh one ("Plan this again"), in a transaction. + * + * Copied: title + " (again)", location, timezone, maybe percent, Venmo username, + * host cover, menu dishes (with their portions) and invitees (the old invitee list + * plus everyone on the old guest list, deduped case-insensitively). + * + * Not copied: RSVPs, plus-ones, shopping ticks and prices, extra costs, cover + * columns, and the cancelled/deleted/updated markers. + * + * The new start is the same weekday and time one week after the later of the old + * start and now, so a past party lands in the coming week rather than in the past. + * The event id is bound on the client and cannot be trusted, so the source is + * looked up by host id too; a deleted or foreign event is a NotFoundError. + */ +export async function duplicateEvent( + db: Db, + hostId: string, + eventId: string, + options: DuplicateEventOptions = {}, +): Promise<{ id: string; shareCode: string }> { + const now = options.now ?? new Date(); + const newShareCode = options.newShareCode ?? generateShareCode; + + const [source] = await db + .select() + .from(events) + .where(and(eq(events.id, eventId), eq(events.hostId, hostId), isNull(events.deletedAt))); + if (!source) throw new NotFoundError("Event not found"); + + const [sourceInvitees, sourceGuests, sourceDishes] = await Promise.all([ + db.select({ name: invitees.name }).from(invitees).where(eq(invitees.eventId, eventId)), + db.select({ name: guests.name }).from(guests).where(eq(guests.eventId, eventId)), + db + .select({ + recipeId: eventDishes.recipeId, + servingsPerPerson: eventDishes.servingsPerPerson, + }) + .from(eventDishes) + .where(eq(eventDishes.eventId, eventId)), + ]); + + // The old guest list may already contain someone who was also an invitee; keep + // the first spelling and one row per person. + const seen = new Set<string>(); + const names: string[] = []; + for (const name of [ + ...sourceInvitees.map((row) => row.name), + ...sourceGuests.map((row) => row.name), + ]) { + const key = nameKey(name); + if (!key || seen.has(key)) continue; + seen.add(key); + names.push(name.trim()); + } + + const later = source.startsAt.getTime() > now.getTime() ? source.startsAt : now; + const startsAt = oneWeekLater(later, source.timezone); + + return db.transaction(async (tx) => { + for (let attempt = 0; attempt < SHARE_CODE_ATTEMPTS; attempt++) { + const shareCode = newShareCode(); + const [row] = await tx + .insert(events) + .values({ + hostId, + hostName: source.hostName, + title: `${source.title.replace(/ \(again\)$/, "")} (again)`, + startsAt, + location: source.location, + timezone: source.timezone, + shareCode, + maybePercent: source.maybePercent, + venmoUsername: source.venmoUsername, + hostCoverCents: source.hostCoverCents, + }) + .onConflictDoNothing({ target: events.shareCode }) + .returning({ id: events.id }); + if (!row) continue; + + if (sourceDishes.length > 0) { + await tx.insert(eventDishes).values( + sourceDishes.map((dish) => ({ + eventId: row.id, + recipeId: dish.recipeId, + servingsPerPerson: dish.servingsPerPerson, + })), + ); + } + if (names.length > 0) { + await tx.insert(invitees).values(names.map((name) => ({ eventId: row.id, name }))); + } + return { id: row.id, shareCode }; + } + throw new Error("Could not generate a unique share code"); + }); +} diff --git a/src/services/events.ts b/src/services/events.ts index 24587d4..459614e 100644 --- a/src/services/events.ts +++ b/src/services/events.ts @@ -49,7 +49,7 @@ const createSchema = z.object({ }); /** 10 URL-safe characters (~60 bits): unguessable and short enough to paste. */ -function generateShareCode(): string { +export function generateShareCode(): string { return randomBytes(8).toString("base64url").slice(0, 10); }