/** * 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) * - user_skills, skill_assessments, growth_goals, skill_equivalencies (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, primaryKey } 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]; /** * Verified-level ladder (ARCHITECTURE §5.8). `verified_level` on a user's * competency record and `required_level` on a position's core skills both live * here — the gate vocabulary is shared, never a local string. */ export const SKILL_LEVELS = ["none", "observer", "assisted", "qualified", "expert"] as const; export type SkillLevel = (typeof SKILL_LEVELS)[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), /** Soft-delete flag; deactivated roles drop out of pickers (B4). */ active: boolean("active").notNull().default(true), updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }), }, (table) => [ index("roles_slug_idx").on(table.slug), index("roles_active_idx").on(table.active), ], ); /* -------------------------------------------------------------- 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) and `position_skills` arrive in B4. 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), ], ); /* -------------------------------------------------- skills (B4) */ /** * The rated unit — what a volunteer has a level in (ARCHITECTURE §4.3). * Composed from the four catalog tables: category (required) + optional * technology + optional function. `dedupe_key` = `category|technology|function` * so the SQL unique constraint treats NULLs as distinct. Slug freezes after * creation; the composed display name is freely editable. B4 creates these as a * prerequisite of `position_skills`; the name-composition UI is C1. */ export const skills = pgTable( "skills", { id: text("id").primaryKey(), slug: text("slug").unique().notNull(), name: text("name").notNull(), categoryId: text("category_id") .notNull() .references(() => skillCategories.id, { onDelete: "restrict" }), technologyId: text("technology_id") .references(() => technologies.id, { onDelete: "restrict" }), functionId: text("function_id") .references(() => functions.id, { onDelete: "restrict" }), /** category|technology|function — unique even with NULLs (encoded ""). */ dedupeKey: text("dedupe_key").unique().notNull(), description: text("description"), mentorMinLevel: text("mentor_min_level", { enum: SKILL_LEVELS }) .notNull() .default("expert"), staleAfterDays: integer("stale_after_days").notNull().default(120), recertRequired: boolean("recert_required").notNull().default(false), 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("skills_slug_idx").on(table.slug), index("skills_active_idx").on(table.active), index("skills_category_idx").on(table.categoryId), ], ); /* ------------------------------------------- position_skills (B4) */ /** * What a schedulable position demands (ARCHITECTURE §4.3). The join that turns * "who is an audio person" into "who can run audio this Sunday". `is_core` * skills gate a position's publishability (a position with no core skill cannot * be published); non-core skills only rank. `weight` feeds the readiness score. */ export const positionSkills = pgTable( "position_skills", { positionId: text("position_id") .notNull() .references(() => roles.id, { onDelete: "restrict" }), skillId: text("skill_id") .notNull() .references(() => skills.id, { onDelete: "restrict" }), /** 1..5 — weight in the readiness score. */ weight: integer("weight").notNull().default(1), /** Minimum verified level to run this position solo (nullable). */ requiredLevel: text("required_level", { enum: SKILL_LEVELS }), /** Core skills gate hard; non-core only rank. */ isCore: boolean("is_core").notNull().default(false), }, (table) => [ // One skill per position: the composite key is the PK. primaryKey({ name: "position_skills_pk", columns: [table.positionId, table.skillId] }), index("position_skills_skill_idx").on(table.skillId), ], ); /* ------------------------------------------------- user_skills (C2) */ /** * A volunteer's competency record for one skill (ARCHITECTURE §4.3). The two * numbers that matter — `self_comfort` (the volunteer's own 0-100 rating, the * signal) and `verified_level` (the mentor/admin gate) — are independent: a * volunteer rating their comfort never moves the verified level. C2 owns the * self_comfort path; C3 owns verified_level (skill_assessments). */ export const userSkills = pgTable( "user_skills", { id: text("id").primaryKey(), userId: text("user_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), skillId: text("skill_id") .notNull() .references(() => skills.id, { onDelete: "cascade" }), /** 0..100 — the volunteer's own rating; null until they rate it. */ selfComfort: integer("self_comfort"), /** When they last rated their own comfort. */ selfRatedAt: timestamp("self_rated_at", { mode: "date", withTimezone: true }), /** Verified level — the gate. Set by a mentor/admin, never by self-report. */ verifiedLevel: text("verified_level", { enum: SKILL_LEVELS }) .notNull() .default("none"), /** Mentor/admin who signed off. */ verifiedBy: text("verified_by"), verifiedAt: timestamp("verified_at", { mode: "date", withTimezone: true }), /** Volunteer agrees to teach this skill (C5 mentor designation). */ mentorOptIn: boolean("mentor_opt_in").notNull().default(false), /** Maintained by the system on assignment completion — never entered by hand. */ lastServedOn: date("last_served_on"), notes: text("notes"), }, (table) => [ // Unique (user_id, skill_id) — one competency record per user per skill. uniqueIndex("user_skills_user_skill_idx").on(table.userId, table.skillId), index("user_skills_skill_idx").on(table.skillId), ], ); /* ------------------------------------------------------------- relations */ /** * Skills compose from the four catalog tables (B3). `skills`, * `position_skills` and `user_skills` are intentionally excluded from `relations`: * their FK columns are themselves part of composite/unique keys, which trips * Drizzle 0.45.4's `one()` typing (see the B2 note). Queried directly until a * working eager-load pattern exists — the grid render in I2 pre-resolves the joins. */ 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, skills, positionSkills, userSkills, }; export type Schema = typeof schema;