/** * Database schema — Media Team Hub. * * Phase A2 writes the CORE scheduling tables only: * users → roles → services → service_instances → slots → assignments * * Deliberately NOT here (added in later units, do not add "while I'm in the schema"): * - notification_templates/rules/outbox (later) * - skills, position_skills, user_skills, skill_assessments, growth_goals (C1-C6) * - 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 */ 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]; /** TCPA consent source recorded on SMS opt-in (ARCHITECTURE §4.76). */ export const SMS_CONSENT_SOURCES = ["web_signup", "paper_form", "admin_import"] as const; export type SmsConsentSource = (typeof SMS_CONSENT_SOURCES)[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), ], ); /* -------------------------------------------------- notification prefs */ /** * Per-user notification preferences (ARCHITECTURE §4.76). One row per user * (PK = user_id). SMS consent fields are TCPA evidence: an explicit opt-in * records the timestamp, source, and IP. Consent is bound to a phone number, * so changing the number clears it (see src/db/profile.ts). */ export const notificationPreferences = pgTable( "notification_preferences", { userId: text("user_id") .primaryKey() .references(() => users.id, { onDelete: "cascade" }), emailEnabled: boolean("email_enabled").notNull().default(true), smsEnabled: boolean("sms_enabled").notNull().default(false), smsConsentAt: timestamp("sms_consent_at", { mode: "date", withTimezone: true }), smsConsentSource: text("sms_consent_source", { enum: SMS_CONSENT_SOURCES }), smsConsentIp: text("sms_consent_ip"), reminderLeadDays: integer("reminder_lead_days").notNull().default(7), quietHoursStart: text("quiet_hours_start").notNull().default("21:00"), quietHoursEnd: text("quiet_hours_end").notNull().default("08:00"), digestOnly: boolean("digest_only").notNull().default(false), }, () => [], ); /* ------------------------------------------------------------------ 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), ], ); /* ------------------------------------------------------------- catalog */ /** * Skill taxonomy — five admin-defined tables with zero hardcoded lists * (ARCHITECTURE §4.3). B3 writes the four leaf tables; `skills` (composed from * them) arrives in C1. Integrity rules enforced here: deactivate-only (no hard * delete — `ON DELETE RESTRICT` on every FK), slugs frozen after creation. */ export const skillCategories = pgTable( "skill_categories", { id: text("id").primaryKey(), slug: text("slug").unique().notNull(), /** Editable — the display name an admin renames. */ name: text("name").notNull(), description: text("description"), colorHex: text("color_hex"), icon: text("icon"), sortOrder: integer("sort_order").notNull().default(0), active: boolean("active").notNull().default(true), createdAt: timestamp("created_at", { mode: "date", withTimezone: true }) .notNull() .defaultNow(), updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), }, (table) => [ index("skill_categories_slug_idx").on(table.slug), index("skill_categories_active_idx").on(table.active), ], ); export const vendors = pgTable( "vendors", { id: text("id").primaryKey(), slug: text("slug").unique().notNull(), name: text("name").notNull(), supportUrl: text("support_url"), supportPhone: text("support_phone"), notes: text("notes"), sortOrder: integer("sort_order").notNull().default(0), active: boolean("active").notNull().default(true), createdAt: timestamp("created_at", { mode: "date", withTimezone: true }) .notNull() .defaultNow(), updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), }, (table) => [ index("vendors_slug_idx").on(table.slug), index("vendors_active_idx").on(table.active), ], ); export const technologies = pgTable( "technologies", { id: text("id").primaryKey(), slug: text("slug").unique().notNull(), name: text("name").notNull(), vendorId: text("vendor_id") .notNull() .references(() => vendors.id, { onDelete: "restrict" }), categoryId: text("category_id") .notNull() .references(() => skillCategories.id, { onDelete: "restrict" }), modelNumber: text("model_number"), versionLabel: text("version_label"), docsUrl: text("docs_url"), /** Local-date asset tracking, stored as "YYYY-MM-DD" (string mode). */ purchasedOn: date("purchased_on", { mode: "string" }), serialNumber: text("serial_number"), retiredAt: timestamp("retired_at", { mode: "date", withTimezone: true }), /** "ATEM Mini Pro → ATEM SDI Pro ISO" migration hint. Plain text (no * self-FK): the pointer is a soft hint validated at the app layer, so a * self-referential FK does not create a circular schema type. */ successorTechnologyId: text("successor_technology_id"), sortOrder: integer("sort_order").notNull().default(0), active: boolean("active").notNull().default(true), createdAt: timestamp("created_at", { mode: "date", withTimezone: true }) .notNull() .defaultNow(), updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), }, (table) => [ index("technologies_slug_idx").on(table.slug), index("technologies_active_idx").on(table.active), index("technologies_vendor_idx").on(table.vendorId), index("technologies_category_idx").on(table.categoryId), ], ); export const functions = pgTable( "functions", { id: text("id").primaryKey(), slug: text("slug").unique().notNull(), name: text("name").notNull(), /** Functions are grouped, not enumerated — one category each. */ categoryId: text("category_id") .notNull() .references(() => skillCategories.id, { onDelete: "restrict" }), description: text("description"), sortOrder: integer("sort_order").notNull().default(0), active: boolean("active").notNull().default(true), createdAt: timestamp("created_at", { mode: "date", withTimezone: true }) .notNull() .defaultNow(), updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), }, (table) => [ index("functions_slug_idx").on(table.slug), index("functions_active_idx").on(table.active), index("functions_category_idx").on(table.categoryId), ], ); /* ------------------------------------------------------------- relations */ export const usersRelations = relations(users, ({ many }) => ({ assignments: many(assignments), })); export const notificationPreferencesRelations = relations( notificationPreferences, () => ({}), ); 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), })); export const skillCategoriesRelations = relations( skillCategories, ({ many }) => ({ technologies: many(technologies), functions: many(functions), }), ); export const vendorsRelations = relations(vendors, ({ many }) => ({ technologies: many(technologies), })); export const technologiesRelations = relations( technologies, ({ one }) => ({ vendor: one(vendors, { fields: [technologies.vendorId], references: [vendors.id] }), category: one( skillCategories, { fields: [technologies.categoryId], references: [skillCategories.id] }, ), }), ); export const functionsRelations = relations( functions, ({ one }) => ({ category: one( skillCategories, { fields: [functions.categoryId], references: [skillCategories.id] }, ), }), ); /** * 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, notificationPreferences, roles, services, serviceInstances, slots, assignments, skillCategories, vendors, technologies, functions, }; export type Schema = typeof schema;