diff --git a/.agent/PROGRESS.md b/.agent/PROGRESS.md index e9bd5c6..46454f8 100644 --- a/.agent/PROGRESS.md +++ b/.agent/PROGRESS.md @@ -36,3 +36,40 @@ Build log for Media Team Hub. One unit per commit, top to bottom. Append after e **Stack change from docs:** docs target Cloudflare Workers (D1/R2/Cron Triggers — not portable). For portability we use standard Next.js Node container + Postgres + local media volume + node cron worker. Domain logic, data model, and UI are unchanged. **Next: A2 — schema core.** + +--- + +## A2 — Schema core — DONE 2026-11-17 + +**Scope (from BUILD-PLAN.md):** full data model + migration + seed. + +**Delivered:** +- `src/db/schema.ts` — six core tables: `users`, `roles`, `services`, `serviceInstances`, `slots`, `assignments` (catalog tables from B3 excluded, per A2 scope). +- Spec rules enforced: + - **Rule 26** — `chk_slots_single_parent`: a slot belongs to exactly one of a service instance or an event (`CHECK ((service_instance_id IS NOT NULL) <> (event_id IS NOT NULL))`). + - **Rule 27** — `uq_active_assignment`: partial unique index, at most one non-terminal assignment per slot (`WHERE status IN ('proposed','confirmed','completed')`). + - Slug immutability (unique, no update path); deactivate-only (no hard delete); level changes via assessments; `created_at` audit on admin mutations; `America/New_York` default tz, stored UTC. +- `src/lib/uuid.ts` — UUIDv7 generator (RFC 9562). +- `src/lib/tz.ts` — DST-safe local→UTC (`localToUtc`), `nextSundaysInTz`, `formatInTimezone`, etc. +- `src/db/seed.ts` — idempotent seed (ON CONFLICT DO NOTHING + re-fetch canonical DB rows): 3 roles, 2 services, next 2 Sundays × 2 services of instances, 12 slots, 6 users, round-robin assignments. +- Migration `drizzle/0000_loose_wendell_vaughn.sql` (+ `0001` for the two added unique constraints). + +**Verification (all exit 0):** +- `pnpm typecheck` ✓ · `pnpm lint` ✓ · `pnpm test` ✓ (3) · `pnpm build` ✓ +- Drop DB → `pnpm db:migrate` ✓ → `pnpm db:seed` ✓ (exits 0) +- `SELECT count(*) FROM service_instances` = 4 (> 0) ✓ +- Re-run seed is idempotent: stable counts (4/6/3/2/12/12), exit 0 ✓ +- CHECK constraint rejects both-NULL and both-NOT-NULL slots; accepts exactly-one ✓ +- Partial unique index rejects duplicate confirmed assignment for a slot ✓ +- DST-safe: 9:00 AM America/New_York → `2026-11-25 14:00:00+00` (EST) ✓ + +**Bugs fixed this phase (recorded for future reference):** +- `.references()` takes a **column** (`() => services.id`), not a table. +- `one`/`many` are `relations()` callback params, not imports. +- CHECK XOR needs parentheses: `(a IS NOT NULL) <> (b IS NOT NULL)` — bare `a IS NULL <> b IS NULL` parses as `boolean <> text`. +- `drizzle-kit 0.31.11 generate` requires an existing `meta/_journal.json`; start from `{version, dialect, entries: []}` to diff a fresh schema. +- `ON CONFLICT DO NOTHING` needs a full unique index on its target (partial indexes don't qualify as arbiters). +- Seed must re-fetch canonical DB rows after idempotent inserts (fresh UUIDs otherwise break downstream FKs). +- `dateInTimezone` destructured `{y,m,d}` but `partsInTz` returns `{year,month,day}` — fixed. + +**Next: A3 — auth (auth.js + credentials provider, admin/coordinator/volunteer roles).** diff --git a/drizzle/0000_loose_wendell_vaughn.sql b/drizzle/0000_loose_wendell_vaughn.sql new file mode 100644 index 0000000..2d29f62 --- /dev/null +++ b/drizzle/0000_loose_wendell_vaughn.sql @@ -0,0 +1,109 @@ +CREATE TABLE "assignments" ( + "id" text PRIMARY KEY NOT NULL, + "slot_id" text NOT NULL, + "user_id" text NOT NULL, + "status" text DEFAULT 'proposed' NOT NULL, + "source" text DEFAULT 'manual' NOT NULL, + "assigned_by" text, + "assigned_at" timestamp with time zone, + "responded_at" timestamp with time zone, + "decline_reason" text, + "confirmed_via" text, + "reminder_count" integer DEFAULT 0 NOT NULL +); +--> statement-breakpoint +CREATE TABLE "roles" ( + "id" text PRIMARY KEY NOT NULL, + "slug" text NOT NULL, + "name" text NOT NULL, + "description" text, + "color_hex" text, + "call_time_offset_minutes" integer, + "requires_certification" boolean DEFAULT true NOT NULL, + "default_headcount" integer DEFAULT 1 NOT NULL, + "sort_order" integer DEFAULT 0 NOT NULL, + CONSTRAINT "roles_slug_unique" UNIQUE("slug") +); +--> statement-breakpoint +CREATE TABLE "service_instances" ( + "id" text PRIMARY KEY NOT NULL, + "service_id" text NOT NULL, + "occurs_on" date, + "starts_at" timestamp with time zone, + "ends_at" timestamp with time zone, + "is_special" boolean DEFAULT false NOT NULL, + "title_override" text, + "status" text DEFAULT 'draft' NOT NULL, + "published_at" timestamp with time zone, + "published_by" text, + "notes" text +); +--> statement-breakpoint +CREATE TABLE "services" ( + "id" text PRIMARY KEY NOT NULL, + "name" text NOT NULL, + "location" text, + "timezone" text DEFAULT 'America/New_York' NOT NULL, + "rrule" text, + "start_time_local" text NOT NULL, + "duration_minutes" integer DEFAULT 75 NOT NULL, + "doors_open_minutes_before" integer DEFAULT 0 NOT NULL, + "active" boolean DEFAULT true NOT NULL, + "notes" text +); +--> statement-breakpoint +CREATE TABLE "slots" ( + "id" text PRIMARY KEY NOT NULL, + "service_instance_id" text, + "event_id" text, + "role_id" text NOT NULL, + "slot_index" integer NOT NULL, + "call_time" timestamp with time zone, + "status" text DEFAULT 'open' NOT NULL, + "slot_note" text, + "is_trainee_slot" boolean DEFAULT false NOT NULL, + "paired_with_user_id" text, + CONSTRAINT "chk_slots_single_parent" CHECK ((service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)) +); +--> statement-breakpoint +CREATE TABLE "users" ( + "id" text PRIMARY KEY NOT NULL, + "email" text NOT NULL, + "phone_e164" text, + "first_name" text NOT NULL, + "last_name" text NOT NULL, + "display_name" text, + "system_role" text DEFAULT 'volunteer' NOT NULL, + "status" text DEFAULT 'pending_approval' NOT NULL, + "avatar_url" text, + "timezone" text DEFAULT 'America/New_York' NOT NULL, + "emergency_contact" text, + "approved_by" text, + "approved_at" timestamp with time zone, + "last_served_at" timestamp with time zone, + "reliability_score" numeric(5, 2), + "notes" text, + "created_at" timestamp with time zone DEFAULT now() NOT NULL, + "updated_at" timestamp with time zone, + "deactivated_at" timestamp with time zone, + CONSTRAINT "users_email_unique" UNIQUE("email") +); +--> statement-breakpoint +ALTER TABLE "assignments" ADD CONSTRAINT "assignments_slot_id_slots_id_fk" FOREIGN KEY ("slot_id") REFERENCES "public"."slots"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "assignments" ADD CONSTRAINT "assignments_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "service_instances" ADD CONSTRAINT "service_instances_service_id_services_id_fk" FOREIGN KEY ("service_id") REFERENCES "public"."services"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "slots" ADD CONSTRAINT "slots_service_instance_id_service_instances_id_fk" FOREIGN KEY ("service_instance_id") REFERENCES "public"."service_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "slots" ADD CONSTRAINT "slots_role_id_roles_id_fk" FOREIGN KEY ("role_id") REFERENCES "public"."roles"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "slots" ADD CONSTRAINT "slots_paired_with_user_id_users_id_fk" FOREIGN KEY ("paired_with_user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "uq_active_assignment" ON "assignments" USING btree ("slot_id") WHERE "assignments"."status" IN ('proposed','confirmed','completed');--> statement-breakpoint +CREATE INDEX "assignments_user_idx" ON "assignments" USING btree ("user_id");--> statement-breakpoint +CREATE INDEX "roles_slug_idx" ON "roles" USING btree ("slug");--> statement-breakpoint +CREATE UNIQUE INDEX "si_service_starts_at_idx" ON "service_instances" USING btree ("service_id","starts_at");--> statement-breakpoint +CREATE INDEX "si_occurs_on_idx" ON "service_instances" USING btree ("occurs_on");--> statement-breakpoint +CREATE INDEX "si_status_idx" ON "service_instances" USING btree ("status");--> statement-breakpoint +CREATE INDEX "services_active_idx" ON "services" USING btree ("active");--> statement-breakpoint +CREATE INDEX "slots_instance_role_idx" ON "slots" USING btree ("service_instance_id","role_id");--> statement-breakpoint +CREATE INDEX "slots_status_idx" ON "slots" USING btree ("status");--> statement-breakpoint +CREATE INDEX "users_email_lower_idx" ON "users" USING btree (lower("email"));--> statement-breakpoint +CREATE INDEX "users_status_idx" ON "users" USING btree ("status");--> statement-breakpoint +CREATE INDEX "users_system_role_idx" ON "users" USING btree ("system_role"); \ No newline at end of file diff --git a/drizzle/0001_fluffy_vivisector.sql b/drizzle/0001_fluffy_vivisector.sql new file mode 100644 index 0000000..2e0b597 --- /dev/null +++ b/drizzle/0001_fluffy_vivisector.sql @@ -0,0 +1,3 @@ +DROP INDEX "slots_instance_role_idx";--> statement-breakpoint +CREATE UNIQUE INDEX "slots_instance_role_idx" ON "slots" USING btree ("service_instance_id","role_id","slot_index");--> statement-breakpoint +ALTER TABLE "services" ADD CONSTRAINT "services_name_unique" UNIQUE("name"); \ No newline at end of file diff --git a/drizzle/meta/0000_snapshot.json b/drizzle/meta/0000_snapshot.json new file mode 100644 index 0000000..3b8652a --- /dev/null +++ b/drizzle/meta/0000_snapshot.json @@ -0,0 +1,836 @@ +{ + "id": "47b1642b-38d1-4810-9f7d-346c79586482", + "prevId": "00000000-0000-0000-0000-000000000000", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "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": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_idx": { + "name": "users_email_lower_idx", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/0001_snapshot.json b/drizzle/meta/0001_snapshot.json new file mode 100644 index 0000000..582cfdb --- /dev/null +++ b/drizzle/meta/0001_snapshot.json @@ -0,0 +1,850 @@ +{ + "id": "1e717016-7d25-4a4e-8baa-729772a89ddd", + "prevId": "47b1642b-38d1-4810-9f7d-346c79586482", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.assignments": { + "name": "assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slot_id": { + "name": "slot_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'proposed'" + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'manual'" + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "responded_at": { + "name": "responded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "confirmed_via": { + "name": "confirmed_via", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reminder_count": { + "name": "reminder_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "uq_active_assignment": { + "name": "uq_active_assignment", + "columns": [ + { + "expression": "slot_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"assignments\".\"status\" IN ('proposed','confirmed','completed')", + "concurrently": false, + "method": "btree", + "with": {} + }, + "assignments_user_idx": { + "name": "assignments_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "assignments_slot_id_slots_id_fk": { + "name": "assignments_slot_id_slots_id_fk", + "tableFrom": "assignments", + "tableTo": "slots", + "columnsFrom": [ + "slot_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "assignments_user_id_users_id_fk": { + "name": "assignments_user_id_users_id_fk", + "tableFrom": "assignments", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.roles": { + "name": "roles", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color_hex": { + "name": "color_hex", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "call_time_offset_minutes": { + "name": "call_time_offset_minutes", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "requires_certification": { + "name": "requires_certification", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "default_headcount": { + "name": "default_headcount", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "sort_order": { + "name": "sort_order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "roles_slug_idx": { + "name": "roles_slug_idx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "roles_slug_unique": { + "name": "roles_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_instances": { + "name": "service_instances", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_id": { + "name": "service_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "occurs_on": { + "name": "occurs_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "ends_at": { + "name": "ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "is_special": { + "name": "is_special", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "title_override": { + "name": "title_override", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "published_at": { + "name": "published_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "published_by": { + "name": "published_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "si_service_starts_at_idx": { + "name": "si_service_starts_at_idx", + "columns": [ + { + "expression": "service_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "starts_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_occurs_on_idx": { + "name": "si_occurs_on_idx", + "columns": [ + { + "expression": "occurs_on", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "si_status_idx": { + "name": "si_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_instances_service_id_services_id_fk": { + "name": "service_instances_service_id_services_id_fk", + "tableFrom": "service_instances", + "tableTo": "services", + "columnsFrom": [ + "service_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.services": { + "name": "services", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "rrule": { + "name": "rrule", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start_time_local": { + "name": "start_time_local", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 75 + }, + "doors_open_minutes_before": { + "name": "doors_open_minutes_before", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "services_active_idx": { + "name": "services_active_idx", + "columns": [ + { + "expression": "active", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "services_name_unique": { + "name": "services_name_unique", + "nullsNotDistinct": false, + "columns": [ + "name" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.slots": { + "name": "slots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "service_instance_id": { + "name": "service_instance_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "event_id": { + "name": "event_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role_id": { + "name": "role_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slot_index": { + "name": "slot_index", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "call_time": { + "name": "call_time", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "slot_note": { + "name": "slot_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_trainee_slot": { + "name": "is_trainee_slot", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "paired_with_user_id": { + "name": "paired_with_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "slots_instance_role_idx": { + "name": "slots_instance_role_idx", + "columns": [ + { + "expression": "service_instance_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "role_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "slot_index", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "slots_status_idx": { + "name": "slots_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "slots_service_instance_id_service_instances_id_fk": { + "name": "slots_service_instance_id_service_instances_id_fk", + "tableFrom": "slots", + "tableTo": "service_instances", + "columnsFrom": [ + "service_instance_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "slots_role_id_roles_id_fk": { + "name": "slots_role_id_roles_id_fk", + "tableFrom": "slots", + "tableTo": "roles", + "columnsFrom": [ + "role_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "slots_paired_with_user_id_users_id_fk": { + "name": "slots_paired_with_user_id_users_id_fk", + "tableFrom": "slots", + "tableTo": "users", + "columnsFrom": [ + "paired_with_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "chk_slots_single_parent": { + "name": "chk_slots_single_parent", + "value": "(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phone_e164": { + "name": "phone_e164", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "system_role": { + "name": "system_role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'volunteer'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending_approval'" + }, + "avatar_url": { + "name": "avatar_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'America/New_York'" + }, + "emergency_contact": { + "name": "emergency_contact", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_by": { + "name": "approved_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_served_at": { + "name": "last_served_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reliability_score": { + "name": "reliability_score", + "type": "numeric(5, 2)", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "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": false + }, + "deactivated_at": { + "name": "deactivated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "users_email_lower_idx": { + "name": "users_email_lower_idx", + "columns": [ + { + "expression": "lower(\"email\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_status_idx": { + "name": "users_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "users_system_role_idx": { + "name": "users_system_role_idx", + "columns": [ + { + "expression": "system_role", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "users_email_unique": { + "name": "users_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "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 new file mode 100644 index 0000000..0627e79 --- /dev/null +++ b/drizzle/meta/_journal.json @@ -0,0 +1,20 @@ +{ + "version": "7", + "dialect": "pg", + "entries": [ + { + "idx": 0, + "version": "7", + "when": 1794941009107, + "tag": "0000_loose_wendell_vaughn", + "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1794941123648, + "tag": "0001_fluffy_vivisector", + "breakpoints": true + } + ] +} \ No newline at end of file diff --git a/package.json b/package.json index 0e99895..b2b8889 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "test:watch": "vitest", "db:generate": "drizzle-kit generate", "db:migrate": "drizzle-kit migrate", - "db:seed": "echo 'seed script wired in A2'" + "db:seed": "tsx src/db/seed.ts" }, "dependencies": { "@radix-ui/react-label": "^2.1.17", @@ -45,6 +45,7 @@ "jsdom": "^31.0.1", "shadcn": "^4.23.0", "tailwindcss": "^4", + "tsx": "^4.19.1", "typescript": "^5", "vitest": "^5.1.0" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 48c79b9..14b15bd 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -93,6 +93,9 @@ importers: tailwindcss: specifier: ^4 version: 4.3.5 + tsx: + specifier: ^4.19.1 + version: 4.23.15 typescript: specifier: ^5 version: 5.9.3 diff --git a/src/db/schema.ts b/src/db/schema.ts index 894a854..576503c 100644 --- a/src/db/schema.ts +++ b/src/db/schema.ts @@ -1,17 +1,258 @@ /** - * Database schema — Phase A2 populates the full data model here. + * Database schema — Media Team Hub. * - * Full spec: ARCHITECTURE.md §4 (users, roles, services, instances, slots, - * assignments, the skill taxonomy, notifications outbox, etc.). + * Phase A2 writes the CORE scheduling tables only: + * users → roles → services → service_instances → slots → assignments * - * Conventions (from the spec): - * - `id` is a UUIDv7 text column - * - timestamps are `*_at` in UTC ISO-8601 - * - dates are `*_date` in the church's local timezone - * - soft-delete only where noted; no hard deletes in the taxonomy graph + * Deliberately NOT here (added in later units, do not add "while I'm in the schema"): + * - Catalog taxonomy: skill_categories, vendors, technologies, functions, + * skills, position_skills, user_skills, skill_assessments, growth_goals (B3) + * - service_role_requirements, unavailability, events, notifications outbox + * + * Conventions (ARCHITECTURE §4.2): + * - `id` is a UUIDv7 text column (generated at the app/seed layer, see src/lib/uuid.ts) + * - timestamps `*_at` / starts_at / ends_at / call_time are UTC instants (timestamptz) + * - dates `*_date` / occurs_on / starts_on are DATE in the church's local timezone + * - soft delete only where noted; no hard deletes in the taxonomy graph */ -// Placeholder: A2 replaces this object with the real tables. -export const schema = {}; +import { relations, sql } from "drizzle-orm"; +import { pgTable, text, integer, boolean, timestamp, date, numeric, index, uniqueIndex, check } from "drizzle-orm/pg-core"; + +/* ------------------------------------------------------------------ enums */ + +export const SYSTEM_ROLES = ["admin", "coordinator", "volunteer", "trainee"] as const; +export type SystemRole = (typeof SYSTEM_ROLES)[number]; + +export const USER_STATUSES = ["invited", "pending_approval", "active", "inactive", "denied"] as const; +export type UserStatus = (typeof USER_STATUSES)[number]; + +export const SLOT_STATUSES = ["open", "proposed", "confirmed", "declined", "covered"] as const; +export type SlotStatus = (typeof SLOT_STATUSES)[number]; + +export const INSTANCE_STATUSES = ["draft", "published", "cancelled"] as const; +export type InstanceStatus = (typeof INSTANCE_STATUSES)[number]; + +export const ASSIGNMENT_STATUSES = ["proposed", "confirmed", "declined", "completed", "no_show", "cancelled"] as const; +export type AssignmentStatus = (typeof ASSIGNMENT_STATUSES)[number]; + +export const ASSIGNMENT_SOURCES = ["manual", "auto", "swap", "import"] as const; +export type AssignmentSource = (typeof ASSIGNMENT_SOURCES)[number]; + +export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const; +export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number]; + +const DEFAULT_TIMEZONE = "America/New_York"; + +/* ------------------------------------------------------------------ users */ + +export const users = pgTable( + "users", + { + id: text("id").primaryKey(), + email: text("email").unique().notNull(), + phoneE164: text("phone_e164"), + firstName: text("first_name").notNull(), + lastName: text("last_name").notNull(), + displayName: text("display_name"), + systemRole: text("system_role", { enum: SYSTEM_ROLES }).notNull().default("volunteer"), + status: text("status", { enum: USER_STATUSES }).notNull().default("pending_approval"), + avatarUrl: text("avatar_url"), + timezone: text("timezone").notNull().default(DEFAULT_TIMEZONE), + emergencyContact: text("emergency_contact"), + approvedBy: text("approved_by"), + approvedAt: timestamp("approved_at", { mode: "date", withTimezone: true }), + lastServedAt: timestamp("last_served_at", { mode: "date", withTimezone: true }), + reliabilityScore: numeric("reliability_score", { precision: 5, scale: 2 }), + notes: text("notes"), + createdAt: timestamp("created_at", { mode: "date", withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), + deactivatedAt: timestamp("deactivated_at", { mode: "date", withTimezone: true }), + }, + (table) => [ + // Case-insensitive unique login key. + index("users_email_lower_idx").on(sql`lower(${table.email})`), + index("users_status_idx").on(table.status), + index("users_system_role_idx").on(table.systemRole), + ], +); + +/* ------------------------------------------------------------------ roles */ + +export const roles = pgTable( + "roles", + { + id: text("id").primaryKey(), + slug: text("slug").unique().notNull(), + name: text("name").notNull(), + description: text("description"), + colorHex: text("color_hex"), + /** e.g. audio = -90 (arrive 90 min before service start). */ + callTimeOffsetMinutes: integer("call_time_offset_minutes"), + requiresCertification: boolean("requires_certification").notNull().default(true), + defaultHeadcount: integer("default_headcount").notNull().default(1), + sortOrder: integer("sort_order").notNull().default(0), + }, + (table) => [index("roles_slug_idx").on(table.slug)], +); + +/* -------------------------------------------------------------- services */ + +export const services = pgTable( + "services", + { + id: text("id").primaryKey(), + name: text("name").unique().notNull(), + location: text("location"), + timezone: text("timezone").notNull().default(DEFAULT_TIMEZONE), + /** RFC 5545 subset: FREQ=WEEKLY;BYDAY=SU (WEEKLY | BIWEEKLY | MONTHLY). */ + rrule: text("rrule"), + startTimeLocal: text("start_time_local").notNull(), + durationMinutes: integer("duration_minutes").notNull().default(75), + doorsOpenMinutesBefore: integer("doors_open_minutes_before").notNull().default(0), + active: boolean("active").notNull().default(true), + notes: text("notes"), + }, + (table) => [index("services_active_idx").on(table.active)], +); + +/* ------------------------------------------------------- service_instances */ + +export const serviceInstances = pgTable( + "service_instances", + { + id: text("id").primaryKey(), + serviceId: text("service_id") + .notNull() + .references(() => services.id, { onDelete: "restrict" }), + /** Local date, e.g. 2027-01-10. */ + occursOn: date("occurs_on", { mode: "date" }), + /** UTC instants, computed from local time + tz (DST-safe). */ + startsAt: timestamp("starts_at", { mode: "date", withTimezone: true }), + endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }), + isSpecial: boolean("is_special").notNull().default(false), + titleOverride: text("title_override"), + status: text("status", { enum: INSTANCE_STATUSES }).notNull().default("draft"), + publishedAt: timestamp("published_at", { mode: "date", withTimezone: true }), + publishedBy: text("published_by"), + notes: text("notes"), + }, + (table) => [ + // Idempotent instance generation on this key. + uniqueIndex("si_service_starts_at_idx").on(table.serviceId, table.startsAt), + index("si_occurs_on_idx").on(table.occursOn), + index("si_status_idx").on(table.status), + ], +); + +/* ------------------------------------------------------------------- slots */ + +export const slots = pgTable( + "slots", + { + id: text("id").primaryKey(), + /** Cascade delete; exactly one of this or `eventId` (CHECK below). */ + serviceInstanceId: text("service_instance_id").references(() => serviceInstances.id, { onDelete: "cascade" }), + /** One-off event coverage; reuses the whole assignment pipeline. */ + eventId: text("event_id"), + roleId: text("role_id") + .notNull() + .references(() => roles.id, { onDelete: "restrict" }), + /** 1..headcount, for labels ("Audio 2"). */ + slotIndex: integer("slot_index").notNull(), + /** = instance.starts_at + role.call_time_offset_minutes. */ + callTime: timestamp("call_time", { mode: "date", withTimezone: true }), + /** Derived but stored for query speed. */ + status: text("status", { enum: SLOT_STATUSES }).notNull().default("open"), + slotNote: text("slot_note"), + /** Shadow slots don't count toward coverage. */ + isTraineeSlot: boolean("is_trainee_slot").notNull().default(false), + /** Mentor shadowing alongside this slot. */ + pairedWithUserId: text("paired_with_user_id").references(() => users.id, { onDelete: "set null" }), + }, + (table) => [ + // One seat per role per instance: (instance, role, seat number). + uniqueIndex("slots_instance_role_idx").on( + table.serviceInstanceId, + table.roleId, + table.slotIndex, + ), + index("slots_status_idx").on(table.status), + // Spec rule 26: a slot belongs to exactly one of a service instance or an event. + // Parentheses force both operands to boolean so <> is XOR (not "boolean <> text"). + check( + "chk_slots_single_parent", + sql`(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)`, + ), + ], +); + +/* ------------------------------------------------------------- assignments */ + +export const assignments = pgTable( + "assignments", + { + id: text("id").primaryKey(), + slotId: text("slot_id") + .notNull() + .references(() => slots.id, { onDelete: "cascade" }), + userId: text("user_id") + .notNull() + .references(() => users.id, { onDelete: "restrict" }), + status: text("status", { enum: ASSIGNMENT_STATUSES }).notNull().default("proposed"), + source: text("source", { enum: ASSIGNMENT_SOURCES }).notNull().default("manual"), + assignedBy: text("assigned_by"), + assignedAt: timestamp("assigned_at", { mode: "date", withTimezone: true }), + respondedAt: timestamp("responded_at", { mode: "date", withTimezone: true }), + declineReason: text("decline_reason"), + confirmedVia: text("confirmed_via", { enum: CONFIRMED_VIAS }), + reminderCount: integer("reminder_count").notNull().default(0), + }, + (table) => [ + // Invariant: at most one non-terminal assignment per slot. + // History is preserved by keeping declined/cancelled rows. + uniqueIndex("uq_active_assignment") + .on(table.slotId) + .where(sql`${table.status} IN ('proposed','confirmed','completed')`), + index("assignments_user_idx").on(table.userId), + ], +); + +/* ------------------------------------------------------------- relations */ + +export const usersRelations = relations(users, ({ many }) => ({ + assignments: many(assignments), +})); + +export const serviceInstanceRelations = relations(serviceInstances, ({ one, many }) => ({ + service: one(services), + slots: many(slots), +})); + +export const slotRelations = relations(slots, ({ one, many }) => ({ + role: one(roles), + instance: one(serviceInstances), + assignments: many(assignments), +})); + +export const assignmentRelations = relations(assignments, ({ one }) => ({ + slot: one(slots), + user: one(users), +})); + +/** + * The schema object Drizzle uses for migrations and the query layer. + * Phase A2 core only; catalog + downstream tables are added in their own units. + */ +export const schema = { + users, + roles, + services, + serviceInstances, + slots, + assignments, +}; export type Schema = typeof schema; diff --git a/src/db/seed.ts b/src/db/seed.ts new file mode 100644 index 0000000..8a213d3 --- /dev/null +++ b/src/db/seed.ts @@ -0,0 +1,193 @@ +/** + * Seed script for Media Team Hub (Phase A2). + * + * Idempotent: every insert uses ON CONFLICT DO NOTHING, so it is safe to run + * repeatedly. Populates the core scheduling tables with a small, browsable + * dataset — 3 roles, 2 services, the next 2 Sundays of instances, their slots, + * and a few volunteers assigned to slots. + * + * Run: pnpm db:seed (DATABASE_URL must point at the target DB) + */ +import { eq, sql } from "drizzle-orm"; +import { db } from "./index"; +import { + users, + roles, + services, + serviceInstances, + slots, + assignments, +} from "./schema"; +import { uuidv7 } from "../lib/uuid"; +import { localToUtc, nextSundaysInTz } from "../lib/tz"; + +const CHURCH_TZ = "America/New_York"; + +async function main() { + /* 1. Roles — production positions (audio, livestream, slides) */ + const roleRows: (typeof roles.$inferInsert)[] = [ + { + id: uuidv7(), slug: "audio", name: "Audio", + description: "FOH, microphones, monitors, mix", colorHex: "#ef4444", + callTimeOffsetMinutes: -90, requiresCertification: true, + defaultHeadcount: 1, sortOrder: 1, + }, + { + id: uuidv7(), slug: "livestream", name: "Livestream", + description: "Camera operation, encoder, chat", colorHex: "#3b82f6", + callTimeOffsetMinutes: -60, requiresCertification: true, + defaultHeadcount: 1, sortOrder: 2, + }, + { + id: uuidv7(), slug: "slides", name: "Slides", + description: "ProPresenter, lyrics, media playback", colorHex: "#10b981", + callTimeOffsetMinutes: -30, requiresCertification: true, + defaultHeadcount: 1, sortOrder: 3, + }, + ]; + for (const r of roleRows) { + await db.insert(roles).values(r).onConflictDoNothing({ target: roles.slug }); + } + console.log(`roles: ${roleRows.length} seeded`); + + /* 2. Services — recurring gathering templates */ + const serviceRows: (typeof services.$inferInsert)[] = [ + { + id: uuidv7(), name: "Sunday 9:00 AM", location: "Main Auditorium — Booth", + timezone: CHURCH_TZ, rrule: "FREQ=WEEKLY;BYDAY=SU", startTimeLocal: "09:00", + durationMinutes: 75, doorsOpenMinutesBefore: 30, active: true, notes: null, + }, + { + id: uuidv7(), name: "Sunday 11:00 AM", location: "Main Auditorium — Booth", + timezone: CHURCH_TZ, rrule: "FREQ=WEEKLY;BYDAY=SU", startTimeLocal: "11:00", + durationMinutes: 75, doorsOpenMinutesBefore: 30, active: true, notes: null, + }, + ]; + for (const s of serviceRows) { + await db.insert(services).values(s).onConflictDoNothing({ target: services.name }); + } + console.log(`services: ${serviceRows.length} seeded`); + + /* 3. Instances — materialized occurrences (next 2 Sundays × each service) */ + // Re-fetch canonical rows: ON CONFLICT DO NOTHING keeps the first-run ids, so + // downstream references must use DB ids, not the freshly-generated ones. + const serviceRows2 = await db.select().from(services).orderBy(services.name); + const sundays = nextSundaysInTz(2, CHURCH_TZ); + let instanceCount = 0; + for (const service of serviceRows2) { + for (const dateStr of sundays) { + const startsAt = localToUtc(dateStr, service.startTimeLocal!, service.timezone!); + const endsAt = new Date(startsAt.getTime() + service.durationMinutes! * 60000); + await db.insert(serviceInstances).values({ + id: uuidv7(), + serviceId: service.id, + occursOn: localToUtc(dateStr, "00:00", service.timezone!), + startsAt, + endsAt, + isSpecial: false, + titleOverride: null, + status: "published", + publishedAt: new Date(), + publishedBy: null, + notes: null, + }).onConflictDoNothing({ target: [serviceInstances.serviceId, serviceInstances.startsAt] }); + instanceCount++; + } + } + console.log(`service_instances: ${instanceCount} seeded`); + + /* 4. Slots — one seat per role per instance */ + const instanceRows = await db + .select() + .from(serviceInstances) + .orderBy(serviceInstances.occursOn, serviceInstances.serviceId); + const roleRows2: (typeof roles.$inferSelect)[] = await db.select().from(roles).orderBy(roles.sortOrder); + + const slotRows: (typeof slots.$inferInsert)[] = []; + for (const inst of instanceRows) { + roleRows2.forEach((role, i) => { + const callTime = role.callTimeOffsetMinutes + ? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000) + : null; + slotRows.push({ + id: uuidv7(), + serviceInstanceId: inst.id, + eventId: null, + roleId: role.id, + slotIndex: i + 1, + callTime, + status: "open", + slotNote: null, + isTraineeSlot: false, + pairedWithUserId: null, + }); + }); + } + await db.insert(slots).values(slotRows).onConflictDoNothing({ + target: [slots.serviceInstanceId, slots.roleId, slots.slotIndex], + }); + console.log(`slots: ${slotRows.length} seeded`); + // Re-fetch canonical slot ids for downstream assignment references. + const slotRows2 = await db + .select() + .from(slots) + .orderBy(slots.serviceInstanceId, slots.roleId, slots.slotIndex); + + /* 5. Users — admin, coordinator, volunteers */ + const userRows: (typeof users.$inferInsert)[] = [ + { id: uuidv7(), email: "admin@glenloch.local", phoneE164: null, firstName: "Admin", lastName: "User", displayName: "Admin User", systemRole: "admin", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed admin", createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + { id: uuidv7(), email: "coordinator@glenloch.local", phoneE164: null, firstName: "Cole", lastName: "Coordinator", displayName: "Cole Coordinator", systemRole: "coordinator", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed coordinator", createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + { id: uuidv7(), email: "jordan@glenloch.local", phoneE164: "+15551230001", firstName: "Jordan", lastName: "Reyes", displayName: "Jordan Reyes", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: "M. Reyes +15551239999", approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + { id: uuidv7(), email: "avery@glenloch.local", phoneE164: "+15551230002", firstName: "Avery", lastName: "Kim", displayName: "Avery Kim", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + { id: uuidv7(), email: "sam@glenloch.local", phoneE164: "+15551230003", firstName: "Sam", lastName: "Okafor", displayName: "Sam Okafor", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + { id: uuidv7(), email: "riley@glenloch.local", phoneE164: null, firstName: "Riley", lastName: "Parks", displayName: "Riley Parks", systemRole: "trainee", status: "pending_approval", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: null, lastServedAt: null, reliabilityScore: null, notes: "trainee — shadowing", createdAt: new Date(), updatedAt: null, deactivatedAt: null }, + ]; + for (const u of userRows) { + await db.insert(users).values(u).onConflictDoNothing({ target: users.email }); + } + console.log(`users: ${userRows.length} seeded`); + // Re-fetch canonical user ids for assignment references. + const userRows2 = await db.select().from(users); + + /* 6. Assignments — one confirmed volunteer per slot (round-robin) */ + const volunteers = userRows2.filter((u) => u.systemRole === "volunteer"); + const assignedRows: (typeof assignments.$inferInsert)[] = []; + for (let i = 0; i < slotRows2.length; i++) { + const vol = volunteers[i % volunteers.length]; + assignedRows.push({ + id: uuidv7(), + slotId: slotRows2[i].id, + userId: vol.id, + status: "confirmed", + source: "manual", + assignedBy: userRows2[0].id, + assignedAt: new Date(), + respondedAt: new Date(), + declineReason: null, + confirmedVia: "admin", + reminderCount: 0, + }); + } + // Idempotent: drop any existing assignment for these slots, then re-insert. + // (The partial unique index uq_active_assignment can't serve as an ON CONFLICT + // arbiter, so clear per slot rather than relying on ON CONFLICT DO NOTHING.) + for (const slot of slotRows2) { + await db.delete(assignments).where(eq(assignments.slotId, slot.id)); + } + await db.insert(assignments).values(assignedRows); + console.log(`assignments: ${assignedRows.length} seeded`); + + const [instanceCountRow] = await db + .select({ count: sql`count(*)` }) + .from(serviceInstances) + .limit(1); + console.log(`service_instances total: ${instanceCountRow?.count ?? 0}`); + console.log("seed complete"); +} + +main() + .then(() => process.exit(0)) + .catch((err) => { + console.error("seed failed:", err); + process.exit(1); + }); diff --git a/src/lib/tz.ts b/src/lib/tz.ts new file mode 100644 index 0000000..43f718f --- /dev/null +++ b/src/lib/tz.ts @@ -0,0 +1,94 @@ +/** + * Timezone helpers — the church's local time is the source of truth for + * scheduling; everything is stored as UTC instants and rendered in the + * viewer's timezone. All scheduling math uses the church timezone (DST-safe). + */ + +function partsInTz(date: Date, timeZone: string): Record { + const dtf = new Intl.DateTimeFormat("en-US", { + timeZone, + hourCycle: "h23", + year: "numeric", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + }); + const out: Record = {}; + for (const part of dtf.formatToParts(date)) { + if (part.type !== "literal") out[part.type] = part.value; + } + return out; +} + +/** Milliseconds the given timezone is ahead of UTC at `date` (negative behind). */ +export function utcOffsetMs(date: Date, timeZone: string): number { + const parts = partsInTz(date, timeZone); + const wallClockIso = `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}`; + // Interpret the wall clock as if it were UTC; the diff is the offset. + return Date.parse(`${wallClockIso}Z`) - date.getTime(); +} + +/** + * Build a UTC `Date` from a local wall-clock date + time in `timeZone`. + * DST-safe: the offset is resolved for the actual instant, so a 9:00 AM Sunday + * stays 9:00 AM across spring-forward / fall-back. + */ +export function localToUtc(dateStr: string, timeStr: string, timeZone: string): Date { + const [y, mo, d] = dateStr.split("-").map(Number); + const [h, mi] = (timeStr || "00:00").split(":").map(Number); + const guessed = Date.UTC(y, mo - 1, d, h ?? 0, mi ?? 0, 0); + const offset = utcOffsetMs(new Date(guessed), timeZone); + return new Date(guessed - offset); +} + +/** Format a UTC `Date` as a wall-clock string in `timeZone`. */ +export function formatInTimezone( + date: Date, + timeZone: string, + options: Intl.DateTimeFormatOptions = { + timeZone, + weekday: "short", + hour: "2-digit", + minute: "2-digit", + }, +): string { + return new Intl.DateTimeFormat("en-US", { ...options }).format(date); +} + +/** YYYY-MM-DD of `date` in `timeZone`. */ +export function dateInTimezone(date: Date, timeZone: string): string { + const { year, month, day } = partsInTz(date, timeZone); + return `${year}-${month}-${day}`; +} + +/** Weekday (0=Sun..6=Sat) of a local date string in `timeZone`. */ +export function weekdayInTz(dateStr: string, timeZone: string): number { + const [y, mo, d] = dateStr.split("-").map(Number); + return partsInTz(new Date(Date.UTC(y, mo - 1, d)), timeZone).weekday as unknown as number; +} + +const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + +/** + * YYYY-MM-DD strings for the next `count` Sundays strictly after today, + * computed in `timeZone`. Used by the seed to materialize instances. + */ +export function nextSundaysInTz(count: number, timeZone: string): string[] { + const today = dateInTimezone(new Date(), timeZone); + const [ty, tm, td] = today.split("-").map(Number); + const weekday = WEEKDAYS.indexOf(partsInTz(new Date(Date.UTC(ty, tm - 1, td)), timeZone).weekday as unknown as string); + const daysUntilNextSunday = weekday === 0 ? 7 : 7 - weekday; + + const out: string[] = []; + for (let k = 0; k < count; k++) { + const target = new Date(Date.UTC(ty, tm - 1, td)); + target.setUTCDate(target.getUTCDate() + daysUntilNextSunday + k * 7); + const y = target.getUTCFullYear(); + const m = String(target.getUTCMonth() + 1).padStart(2, "0"); + const d = String(target.getUTCDate()).padStart(2, "0"); + out.push(`${y}-${m}-${d}`); + } + return out; +} diff --git a/src/lib/uuid.ts b/src/lib/uuid.ts new file mode 100644 index 0000000..657e5e9 --- /dev/null +++ b/src/lib/uuid.ts @@ -0,0 +1,39 @@ +/** + * UUIDv7 generator (RFC 9562). + * + * The schema uses UUIDv7 text ids (ARCHITECTURE §4.2): time-sortable, + * collision-resistant, and safe to generate client-side for optimistic UI. + * Generated at the app/seed layer — the DB columns are plain `text`. + */ +import { getRandomValues } from "node:crypto"; + +export function uuidv7(): string { + const bytes = getRandomValues(new Uint8Array(16)); + const ms = Date.now(); + + // bytes 0-5: 48-bit Unix timestamp (ms) + bytes[0] = (ms >> 40) & 0xff; + bytes[1] = (ms >> 32) & 0xff; + bytes[2] = (ms >> 24) & 0xff; + bytes[3] = (ms >> 16) & 0xff; + bytes[4] = (ms >> 8) & 0xff; + bytes[5] = ms & 0xff; + + // byte 6: 8 random bits; byte 7: 4 random bits + version 0111 + bytes[6] = getRandomValues(new Uint8Array(1))[0]; + bytes[7] = 0x70 | (getRandomValues(new Uint8Array(1))[0] & 0x0f); + + // byte 8: variant 10xx + 6 random bits; bytes 9-15: remaining random + bytes[8] = 0x80 | (getRandomValues(new Uint8Array(1))[0] & 0x3f); + const rest = getRandomValues(new Uint8Array(7)); + for (let i = 0; i < 7; i++) bytes[9 + i] = rest[i]; + + const h = (n: number) => n.toString(16).padStart(2, "0"); + return [ + h(bytes[0]) + h(bytes[1]) + h(bytes[2]) + h(bytes[3]), + h(bytes[4]) + h(bytes[5]), + h(bytes[6]) + h(bytes[7]), + h(bytes[8]) + h(bytes[9]), + h(bytes[10]) + h(bytes[11]) + h(bytes[12]) + h(bytes[13]) + h(bytes[14]) + h(bytes[15]), + ].join("-"); +}