f7a0c8618f
CI / build (push) Has been cancelled
Event photos and videos are now stored only on the NFS/local share named in Settings -> Media storage. Uploads, photo editing, video processing and the per-event filing step refuse to run until that share is configured and writable, so nothing is silently written inside the container. Video originals, renditions, posters and sidecars share one folder on the share. Also adds volunteer growth goals with a mentor queue, an admin retention and storage sweep with a cron entry point, cached gallery thumbnails with per-folder ZIP downloads, a server-rendered booth-sheet PDF, and in-app confirm/release for every upcoming assignment. Service reminders now ignore the one-off event reminder rule, which had been queueing an extra bogus reminder for each published service. Generated with Codebuff 🤖 Co-Authored-By: Codebuff <noreply@codebuff.com>
1471 lines
55 KiB
TypeScript
1471 lines
55 KiB
TypeScript
/**
|
|
* 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 (C2), skill_assessments (C3), growth_goals (C6),
|
|
* skill_equivalencies (later)
|
|
* - service_role_requirements, 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, bigint, 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];
|
|
|
|
// Added in D4 (blackout CRUD + isUnavailable). ARCHITECTURE §"unavailability — blackout dates".
|
|
export const UNAVAILABILITY_KINDS = ["blackout", "vacation", "recurring", "preference"] as const;
|
|
export type UnavailabilityKind = (typeof UNAVAILABILITY_KINDS)[number];
|
|
|
|
export const UNAVAILABILITY_STATUSES = ["active", "cancelled"] as const;
|
|
export type UnavailabilityStatus = (typeof UNAVAILABILITY_STATUSES)[number];
|
|
|
|
export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const;
|
|
export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
|
|
|
|
// Added in E1 (outbox). ARCHITECTURE §6.1 / §4 outbox table.
|
|
export const NOTIFICATION_CHANNELS = ["email", "sms"] as const;
|
|
export type NotificationChannel = (typeof NOTIFICATION_CHANNELS)[number];
|
|
|
|
// Added in E7 (reminder rules). ARCHITECTURE §6.2.
|
|
export const NOTIFICATION_RULE_EVENTS = [
|
|
"assignment.created",
|
|
"assignment.unconfirmed",
|
|
"slot.unfilled",
|
|
/** One-off coverage events (photo shoots: the lead time before `startsAt`). */
|
|
"event.reminder",
|
|
] as const;
|
|
export type NotificationRuleEvent = (typeof NOTIFICATION_RULE_EVENTS)[number];
|
|
|
|
/** Outbox status ladder; the domain ladder is drift-guarded against this. */
|
|
export const NOTIFICATION_STATUSES = [
|
|
"queued",
|
|
"sending",
|
|
"sent",
|
|
"failed",
|
|
"suppressed",
|
|
"cancelled",
|
|
] as const;
|
|
export type NotificationStatus = (typeof NOTIFICATION_STATUSES)[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];
|
|
|
|
/** Who produced an assessment row — durable evidence for the audit trail. */
|
|
export const ASSESSMENT_KINDS = ["self", "mentor", "admin", "quiz"] as const;
|
|
export type AssessmentKind = (typeof ASSESSMENT_KINDS)[number];
|
|
|
|
/** Growth-goal lifecycle (ARCHITECTURE §5.8.6). */
|
|
export const GOAL_STATUSES = [
|
|
"requested",
|
|
"mentor_assigned",
|
|
"in_progress",
|
|
"achieved",
|
|
"paused",
|
|
"declined",
|
|
] as const;
|
|
export type GoalStatus = (typeof GOAL_STATUSES)[number];
|
|
|
|
const DEFAULT_TIMEZONE = "America/New_York";
|
|
|
|
/* ------------------------------------------------------------------ users */
|
|
|
|
export const users = pgTable(
|
|
"users",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
email: text("email").unique().notNull(),
|
|
/** Login handle. Existing accounts backfill to their email address. */
|
|
username: text("username").notNull(),
|
|
/** Null until the person sets a password after their first magic link. */
|
|
passwordHash: text("password_hash"),
|
|
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),
|
|
/** Secret token for the personal read-only ICS calendar feed. */
|
|
calendarFeedToken: text("calendar_feed_token"),
|
|
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. Enforced in the database as well as
|
|
// the app so a second insertion path cannot create a case-variant duplicate.
|
|
uniqueIndex("users_email_lower_key").on(sql`lower(${table.email})`),
|
|
uniqueIndex("users_username_lower_key").on(sql`lower(${table.username})`),
|
|
uniqueIndex("users_calendar_feed_token_key").on(table.calendarFeedToken),
|
|
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)`,
|
|
),
|
|
// A shadow/trainee slot only exists alongside a mentor in the same instance
|
|
// (ARCHITECTURE §5.8.5). The pure validation in src/domain/shadows.ts is the
|
|
// first line; this CHECK is the data-layer backstop.
|
|
check(
|
|
"chk_shadow_paired",
|
|
sql`not is_trainee_slot or paired_with_user_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),
|
|
],
|
|
);
|
|
|
|
/* ----------------------------------------------------------- audit log (D8) */
|
|
|
|
/**
|
|
* Append-only audit trail (ARCHITECTURE §638, BUILD-SPEC §7 rule 12).
|
|
* Every admin mutation writes one row here; the app never updates or deletes
|
|
* a row. `before_json` / `after_json` capture the before/after of the change
|
|
* (empty string when there is none); `created_at` is a UTC instant.
|
|
*/
|
|
export const auditLog = pgTable("audit_log", {
|
|
id: text("id").primaryKey(),
|
|
actorId: text("actor_id").notNull(),
|
|
actorIpHash: text("actor_ip_hash"),
|
|
action: text("action").notNull(),
|
|
entityType: text("entity_type").notNull(),
|
|
entityId: text("entity_id"),
|
|
beforeJson: text("before_json").notNull().default(""),
|
|
afterJson: text("after_json").notNull().default(""),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [index("audit_log_created_idx").on(table.createdAt)],
|
|
);
|
|
|
|
/* ------------------------------------------------- unavailability (D4) */
|
|
|
|
/**
|
|
* Blackout / unavailability rows (ARCHITECTURE §\"unavailability — blackout
|
|
* dates\"). A volunteer publishes blackout dates; `isUnavailable` (D4) reads
|
|
* them to exclude the volunteer from the assign picker and auto-fill.
|
|
*
|
|
* `starts_on` / `ends_on` are inclusive local dates (same day = one day).
|
|
* CHECK constraints enforce `ends_on >= starts_on` and a <= 365 day span.
|
|
*/
|
|
export const unavailability = pgTable(
|
|
"unavailability",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
userId: text("user_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "cascade" }),
|
|
kind: text("kind", { enum: UNAVAILABILITY_KINDS })
|
|
.notNull()
|
|
.default("blackout"),
|
|
/** Inclusive local-date range; same day = one day. Stored as YYYY-MM-DD. */
|
|
startsOn: date("starts_on", { mode: "string" }).notNull(),
|
|
endsOn: date("ends_on", { mode: "string" }).notNull(),
|
|
allDay: boolean("all_day").notNull().default(true),
|
|
/** Private by default; admin-visible only. */
|
|
reason: text("reason"),
|
|
/** Recurring pattern (RFC 5545 subset), e.g. every other week. */
|
|
rrule: text("rrule"),
|
|
status: text("status", { enum: UNAVAILABILITY_STATUSES })
|
|
.notNull()
|
|
.default("active"),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.defaultNow(),
|
|
createdBy: text("created_by"),
|
|
},
|
|
(table) => [
|
|
// One active record per (user, range); recurring records carry an rrule.
|
|
uniqueIndex("uq_unavailability_range")
|
|
.on(table.userId, table.startsOn, table.endsOn)
|
|
.where(sql`${table.status} = 'active'`),
|
|
index("unavailability_user_idx").on(table.userId),
|
|
// Inclusive range: ends_on must not precede starts_on.
|
|
check("chk_unavailability_span", sql`${table.endsOn} >= ${table.startsOn}`),
|
|
// Max span 365 days (date - date is an integer number of days in PG).
|
|
check(
|
|
"chk_unavailability_max_span",
|
|
sql`${table.endsOn} - ${table.startsOn} <= 365`,
|
|
),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------------------------- 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),
|
|
/**
|
|
* Admin sign-off on the mentor designation (C5). `isMentorReady` requires
|
|
* it alongside the verified level and the volunteer's opt-in; the column
|
|
* exists so the flag is persisted rather than inferred from the level.
|
|
*/
|
|
mentorApprovedAt: timestamp("mentor_approved_at", {
|
|
mode: "date",
|
|
withTimezone: true,
|
|
}),
|
|
mentorApprovedBy: text("mentor_approved_by"),
|
|
/** 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),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------- skill_assessments (C3) */
|
|
|
|
/**
|
|
* Append-only progression history (ARCHITECTURE §4.3). Every movement of a
|
|
* volunteer's verified level — up or down — writes exactly one row here, and
|
|
* there is deliberately no update or delete path: this table is the audit trail
|
|
* that answers "why was this person cleared?". `comfort_at_time` snapshots the
|
|
* volunteer's self-reported comfort at the moment of the decision, so a later
|
|
* slider move cannot rewrite the context the assessor saw.
|
|
*/
|
|
export const skillAssessments = pgTable(
|
|
"skill_assessments",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
userId: text("user_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "cascade" }),
|
|
skillId: text("skill_id")
|
|
.notNull()
|
|
.references(() => skills.id, { onDelete: "cascade" }),
|
|
/** Mentor/admin who signed off; null for self or quiz assessments. */
|
|
assessorId: text("assessor_id").references(() => users.id, { onDelete: "set null" }),
|
|
kind: text("kind", { enum: ASSESSMENT_KINDS }).notNull().default("admin"),
|
|
/** The verified level before this assessment (server-owned, never client-set). */
|
|
levelFrom: text("level_from", { enum: SKILL_LEVELS }).notNull(),
|
|
levelTo: text("level_to", { enum: SKILL_LEVELS }).notNull(),
|
|
/** Snapshot of `user_skills.self_comfort` when the assessment was recorded. */
|
|
comfortAtTime: integer("comfort_at_time"),
|
|
notes: text("notes"),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
index("skill_assessments_user_created_idx").on(table.userId, table.createdAt),
|
|
index("skill_assessments_skill_idx").on(table.skillId),
|
|
],
|
|
);
|
|
|
|
/* --------------------------------------------- growth_goals (C6) */
|
|
|
|
/**
|
|
* "I want to skill up" (ARCHITECTURE §4.3, §5.8.6). One active goal per
|
|
* (user_id, skill_id) — a volunteer can hold many skills at different levels but
|
|
* only one open goal per skill. Drives the mentor queue and the growth report.
|
|
*/
|
|
export const growthGoals = pgTable(
|
|
"growth_goals",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
userId: text("user_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "cascade" }),
|
|
skillId: text("skill_id")
|
|
.notNull()
|
|
.references(() => skills.id, { onDelete: "cascade" }),
|
|
targetLevel: text("target_level", { enum: SKILL_LEVELS }).notNull(),
|
|
targetDate: date("target_date", { mode: "date" }),
|
|
status: text("status", { enum: GOAL_STATUSES }).notNull().default("requested"),
|
|
mentorUserId: text("mentor_user_id").references(() => users.id, { onDelete: "set null" }),
|
|
shadowCount: integer("shadow_count").notNull().default(0),
|
|
createdBy: text("created_by"),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
// One active goal per (user, skill).
|
|
uniqueIndex("growth_goals_user_skill_idx").on(table.userId, table.skillId),
|
|
index("growth_goals_status_idx").on(table.status),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------- notifications outbox (E1) */
|
|
|
|
/**
|
|
* The notification outbox — the queue is a table (ARCHITECTURE §4 / §6.1).
|
|
*
|
|
* Enqueue is idempotent on `dedupe_key` (`template:ref:channel`), so publishing
|
|
* twice or re-running a rule cannot double-send. `payload_json` is fully merged
|
|
* at enqueue time (subject/html/text/links), making every row auditable and
|
|
* replayable. The dispatcher (E2) drains it; the admin log reads from it.
|
|
*/
|
|
export const notifications = pgTable(
|
|
"notifications",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
userId: text("user_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "cascade" }),
|
|
channel: text("channel", { enum: NOTIFICATION_CHANNELS })
|
|
.notNull()
|
|
.default("email"),
|
|
templateKey: text("template_key").notNull(),
|
|
ruleKey: text("rule_key"),
|
|
assignmentId: text("assignment_id").references(() => assignments.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
slotId: text("slot_id").references(() => slots.id, { onDelete: "set null" }),
|
|
/** Resolved destination at enqueue time (email address; E5 adds phone). */
|
|
toAddress: text("to_address").notNull(),
|
|
/** Fully merged message payload — exactly what will be sent. */
|
|
payloadJson: text("payload_json").notNull().default(""),
|
|
/** Unique per (template, reference, channel): the dedupe guarantee. */
|
|
dedupeKey: text("dedupe_key").unique().notNull(),
|
|
scheduledFor: timestamp("scheduled_for", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
status: text("status", { enum: NOTIFICATION_STATUSES })
|
|
.notNull()
|
|
.default("queued"),
|
|
attempts: integer("attempts").notNull().default(0),
|
|
providerId: text("provider_id"),
|
|
providerStatus: text("provider_status"),
|
|
error: text("error"),
|
|
sentAt: timestamp("sent_at", { mode: "date", withTimezone: true }),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
|
},
|
|
(table) => [
|
|
// The dispatcher's only hot query: due rows in status order.
|
|
index("notifications_status_scheduled_idx").on(table.status, table.scheduledFor),
|
|
index("notifications_user_idx").on(table.userId),
|
|
index("notifications_assignment_idx").on(table.assignmentId),
|
|
],
|
|
);
|
|
|
|
/**
|
|
* Single-use record for magic-link sign-in tokens. The signed token carries a
|
|
* `jti`; `/api/dev/complete` inserts it here before establishing a session, so
|
|
* a replayed link is rejected. Rows are independent of assignments and are
|
|
* safe to prune after the token expiry window (10 minutes).
|
|
*/
|
|
export const usedMagicTokens = pgTable("used_magic_tokens", {
|
|
jti: text("jti").primaryKey(),
|
|
email: text("email").notNull(),
|
|
usedAt: timestamp("used_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
});
|
|
|
|
/**
|
|
* Single-use record for respond links (ARCHITECTURE §5.6). The signed token
|
|
* carries a `jti`; the first POST consumes it here, and a second POST with the
|
|
* same token is rejected. Rows cascade with their assignment (history cleanup).
|
|
*/
|
|
export const usedTokens = pgTable("used_tokens", {
|
|
jti: text("jti").primaryKey(),
|
|
assignmentId: text("assignment_id")
|
|
.notNull()
|
|
.references(() => assignments.id, { onDelete: "cascade" }),
|
|
action: text("action").notNull(),
|
|
usedAt: timestamp("used_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
});
|
|
|
|
/* ------------------------------------------- notification rules (E7) */
|
|
|
|
/**
|
|
* Offset-based reminder rules (ARCHITECTURE §6.2). "Friday before" is
|
|
* `offset_days = -2` at 18:00 local — a row, not code, so the church can move
|
|
* it to Thursday 20:00 without a deploy. `channel_set` is `email`, `sms` or
|
|
* `email+sms`; SMS rows are suppressed until E5.
|
|
*/
|
|
export const notificationRules = pgTable(
|
|
"notification_rules",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
key: text("key").unique().notNull(),
|
|
event: text("event", { enum: NOTIFICATION_RULE_EVENTS })
|
|
.notNull()
|
|
.default("assignment.created"),
|
|
/** Days from the instance start; -2 is the Friday-before-Sunday reminder. */
|
|
offsetDays: integer("offset_days").notNull(),
|
|
sendAtLocalTime: text("send_at_local_time").notNull().default("09:00"),
|
|
channelSet: text("channel_set").notNull().default("email"),
|
|
/** null = every service. */
|
|
appliesToServiceId: text("applies_to_service_id").references(
|
|
() => services.id,
|
|
{ onDelete: "set null" },
|
|
),
|
|
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("notification_rules_active_idx").on(table.active),
|
|
check(
|
|
"chk_notification_rules_channel",
|
|
sql`${table.channelSet} IN ('email','sms','email+sms')`,
|
|
),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------- app settings (runtime admin) */
|
|
|
|
/**
|
|
* Small key/value store for settings an admin edits at runtime — currently the
|
|
* email sender identity and where admin test/failure mail goes. Kept out of
|
|
* the seed reset: these are deployment choices, not demo data.
|
|
*/
|
|
export const appSettings = pgTable("app_settings", {
|
|
key: text("key").primaryKey(),
|
|
value: text("value").notNull(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
});
|
|
|
|
/* --------------------------------------------------- training (lessons) */
|
|
|
|
/**
|
|
* Training content authored in the app (F2). Lessons are ordered, can be
|
|
* published/unpublished, and carry plain-text/Markdown-ish bodies. Attachments
|
|
* live in `training_resources` (bytes on disk, metadata here).
|
|
*/
|
|
export const trainingLessons = pgTable(
|
|
"training_lessons",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
title: text("title").notNull(),
|
|
summary: text("summary"),
|
|
body: text("body").notNull().default(""),
|
|
published: boolean("published").notNull().default(false),
|
|
sortOrder: integer("sort_order").notNull().default(0),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
|
},
|
|
(table) => [index("training_lessons_published_idx").on(table.published)],
|
|
);
|
|
|
|
/** Attachment metadata; the file itself is stored under `UPLOAD_DIR`. */
|
|
export const trainingResources = pgTable(
|
|
"training_resources",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
lessonId: text("lesson_id")
|
|
.notNull()
|
|
.references(() => trainingLessons.id, { onDelete: "cascade" }),
|
|
filename: text("filename").notNull(),
|
|
mimeType: text("mime_type").notNull(),
|
|
sizeBytes: integer("size_bytes").notNull(),
|
|
/** Random on-disk name; never derived from user input. */
|
|
storedName: text("stored_name").notNull(),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [index("training_resources_lesson_idx").on(table.lessonId)],
|
|
);
|
|
|
|
/* ------------------------------------------------ events & photo folders */
|
|
|
|
/** How an assigned person takes part in an event. */
|
|
export const EVENT_PHOTOGRAPHER_ROLES = [
|
|
"photographer",
|
|
"second_shooter",
|
|
"editor",
|
|
] as const;
|
|
export type EventPhotographerRole =
|
|
(typeof EVENT_PHOTOGRAPHER_ROLES)[number];
|
|
|
|
/** What a folder is for; `mixed` is the honest default for ad-hoc uploads. */
|
|
export const EVENT_FOLDER_KINDS = ["originals", "edited", "mixed"] as const;
|
|
export type EventFolderKind = (typeof EVENT_FOLDER_KINDS)[number];
|
|
|
|
/** `raw` = camera original; `image` = browser-renderable JPEG/PNG/WebP/etc. */
|
|
export const EVENT_PHOTO_KINDS = ["raw", "image"] as const;
|
|
export type EventPhotoKind = (typeof EVENT_PHOTO_KINDS)[number];
|
|
|
|
/**
|
|
* A one-off coverage event (wedding, portrait session, outreach night). This is
|
|
* deliberately a lighter table than the full J-phase event model: it exists so
|
|
* photographers can be assigned and share deliverables, and does not yet create
|
|
* scheduling slots or go through the publish/confirm pipeline.
|
|
*/
|
|
export const events = pgTable(
|
|
"events",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
title: text("title").notNull(),
|
|
/** Free-form: wedding, portrait, service, outreach… */
|
|
eventType: text("event_type").notNull().default("photoshoot"),
|
|
startsAt: timestamp("starts_at", { mode: "date", withTimezone: true }).notNull(),
|
|
endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }),
|
|
location: text("location"),
|
|
/** Shot brief / what to capture, shown on the event page. */
|
|
description: text("description"),
|
|
createdBy: text("created_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
|
},
|
|
(table) => [
|
|
index("events_starts_at_idx").on(table.startsAt),
|
|
index("events_created_by_idx").on(table.createdBy),
|
|
],
|
|
);
|
|
|
|
/**
|
|
* Who may see and contribute to an event. The UNIQUE (event, user) key means a
|
|
* person holds one role per event; re-assigning updates the role rather than
|
|
* creating a duplicate.
|
|
*/
|
|
export const eventPhotographers = pgTable(
|
|
"event_photographers",
|
|
{
|
|
eventId: text("event_id")
|
|
.notNull()
|
|
.references(() => events.id, { onDelete: "cascade" }),
|
|
userId: text("user_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "cascade" }),
|
|
role: text("role", { enum: EVENT_PHOTOGRAPHER_ROLES })
|
|
.notNull()
|
|
.default("photographer"),
|
|
assignedBy: text("assigned_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
assignedAt: timestamp("assigned_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
primaryKey({ name: "event_photographers_pk", columns: [table.eventId, table.userId] }),
|
|
index("event_photographers_user_idx").on(table.userId),
|
|
],
|
|
);
|
|
|
|
/** A named folder inside an event: "Originals", "Edited selects", … */
|
|
export const eventFolders = pgTable(
|
|
"event_folders",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
eventId: text("event_id")
|
|
.notNull()
|
|
.references(() => events.id, { onDelete: "cascade" }),
|
|
name: text("name").notNull(),
|
|
kind: text("kind", { enum: EVENT_FOLDER_KINDS })
|
|
.notNull()
|
|
.default("originals"),
|
|
createdBy: text("created_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
uniqueIndex("event_folders_event_name_idx").on(table.eventId, table.name),
|
|
index("event_folders_event_idx").on(table.eventId),
|
|
],
|
|
);
|
|
|
|
/**
|
|
* Photo metadata. Bytes live under `<archive root>/events/<eventId>/` on the
|
|
* configured NFS/local share; only this row is in Postgres. `checksum` is the SHA-256 of the bytes and is unique per
|
|
* folder, so re-uploading the same frame is a no-op instead of a duplicate.
|
|
* `storedName` is a generated relative path, never user input.
|
|
*/
|
|
export const eventPhotos = pgTable(
|
|
"event_photos",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
folderId: text("folder_id")
|
|
.notNull()
|
|
.references(() => eventFolders.id, { onDelete: "cascade" }),
|
|
uploaderId: text("uploader_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "restrict" }),
|
|
filename: text("filename").notNull(),
|
|
mimeType: text("mime_type").notNull(),
|
|
sizeBytes: integer("size_bytes").notNull(),
|
|
storedName: text("stored_name").unique().notNull(),
|
|
checksumSha256: text("checksum_sha256").notNull(),
|
|
kind: text("kind", { enum: EVENT_PHOTO_KINDS }).notNull(),
|
|
/** Last saved adjustment recipe (JSON); the original is never overwritten. */
|
|
editJson: text("edit_json"),
|
|
/** Generated full-resolution JPEG. Null until the first edit is saved. */
|
|
editedStoredName: text("edited_stored_name"),
|
|
editedSizeBytes: integer("edited_size_bytes"),
|
|
editedAt: timestamp("edited_at", { mode: "date", withTimezone: true }),
|
|
editedBy: text("edited_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
uniqueIndex("event_photos_folder_checksum_idx").on(
|
|
table.folderId,
|
|
table.checksumSha256,
|
|
),
|
|
index("event_photos_folder_idx").on(table.folderId, table.createdAt),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------------------- event videos */
|
|
|
|
/** Processing state for an uploaded event video. */
|
|
export const EVENT_VIDEO_STATUSES = [
|
|
"processing",
|
|
"ready",
|
|
"failed",
|
|
] as const;
|
|
export type EventVideoStatus = (typeof EVENT_VIDEO_STATUSES)[number];
|
|
|
|
/** `team` is private; `unlisted` is link-only; `public` can be discovered. */
|
|
export const EVENT_VIDEO_VISIBILITIES = [
|
|
"team",
|
|
"unlisted",
|
|
"public",
|
|
] as const;
|
|
export type EventVideoVisibility =
|
|
(typeof EVENT_VIDEO_VISIBILITIES)[number];
|
|
|
|
/**
|
|
* Event video metadata. The camera original, browser derivatives and poster
|
|
* all live in one folder on the configured NFS/local media storage share.
|
|
* `trim_start_ms` / `trim_end_ms` are a non-destructive recipe applied when
|
|
* the web MP4 is rendered, so the original is never changed.
|
|
*/
|
|
export const eventVideos = pgTable(
|
|
"event_videos",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
eventId: text("event_id")
|
|
.notNull()
|
|
.references(() => events.id, { onDelete: "cascade" }),
|
|
uploaderId: text("uploader_id")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "restrict" }),
|
|
title: text("title").notNull(),
|
|
description: text("description"),
|
|
filename: text("filename").notNull(),
|
|
mimeType: text("mime_type").notNull(),
|
|
/** bigint: a 4 GB camera video does not fit a signed 32-bit integer. */
|
|
sizeBytes: bigint("size_bytes", { mode: "number" }).notNull(),
|
|
checksumSha256: text("checksum_sha256").notNull(),
|
|
/** Path relative to `<archivePath>/<archiveFolder>`, e.g. videos/…/original.mp4. */
|
|
originalStoredName: text("original_stored_name").unique().notNull(),
|
|
/** The archive folder in use at upload time, so a later settings change cannot orphan it. */
|
|
archiveFolder: text("archive_folder").notNull(),
|
|
durationMs: integer("duration_ms"),
|
|
width: integer("width"),
|
|
height: integer("height"),
|
|
trimStartMs: integer("trim_start_ms").notNull().default(0),
|
|
trimEndMs: integer("trim_end_ms"),
|
|
webStoredName: text("web_stored_name"),
|
|
posterStoredName: text("poster_stored_name"),
|
|
status: text("status", { enum: EVENT_VIDEO_STATUSES })
|
|
.notNull()
|
|
.default("processing"),
|
|
visibility: text("visibility", { enum: EVENT_VIDEO_VISIBILITIES })
|
|
.notNull()
|
|
.default("team"),
|
|
errorMessage: text("error_message"),
|
|
processedAt: timestamp("processed_at", { mode: "date", withTimezone: true }),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
uniqueIndex("event_videos_event_checksum_idx").on(
|
|
table.eventId,
|
|
table.checksumSha256,
|
|
),
|
|
index("event_videos_event_created_idx").on(
|
|
table.eventId,
|
|
table.createdAt,
|
|
),
|
|
index("event_videos_status_idx").on(table.status),
|
|
],
|
|
);
|
|
|
|
/* ---------------------------------------------------- announcements */
|
|
|
|
/**
|
|
* Team announcements authored by admins/coordinators (`content.author`).
|
|
* Plain text for now (the rich-text editor is F1); drafts are hidden from
|
|
* volunteers and can be published/unpublished at any time.
|
|
*/
|
|
export const announcements = pgTable(
|
|
"announcements",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
title: text("title").notNull(),
|
|
body: text("body").notNull().default(""),
|
|
published: boolean("published").notNull().default(false),
|
|
createdBy: text("created_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
|
},
|
|
(table) => [
|
|
index("announcements_published_created_idx").on(
|
|
table.published,
|
|
table.createdAt,
|
|
),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------ coverage (swap) requests */
|
|
|
|
export const COVERAGE_REQUEST_STATUSES = [
|
|
"pending",
|
|
"approved",
|
|
"declined",
|
|
"cancelled",
|
|
] as const;
|
|
export type CoverageRequestStatus =
|
|
(typeof COVERAGE_REQUEST_STATUSES)[number];
|
|
|
|
/**
|
|
* A volunteer asking for their seat to be released, with an optional
|
|
* replacement chosen by a coordinator. The assignment stays live until the
|
|
* request is approved, so a pending request never silently opens a hole.
|
|
*
|
|
* At most one pending request per assignment; resolved rows remain as history.
|
|
*/
|
|
export const coverageRequests = pgTable(
|
|
"coverage_requests",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
assignmentId: text("assignment_id")
|
|
.notNull()
|
|
.references(() => assignments.id, { onDelete: "cascade" }),
|
|
requestedBy: text("requested_by")
|
|
.notNull()
|
|
.references(() => users.id, { onDelete: "restrict" }),
|
|
reason: text("reason"),
|
|
status: text("status", { enum: COVERAGE_REQUEST_STATUSES })
|
|
.notNull()
|
|
.default("pending"),
|
|
replacementUserId: text("replacement_user_id").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
resolvedBy: text("resolved_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
resolvedAt: timestamp("resolved_at", { mode: "date", withTimezone: true }),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
uniqueIndex("coverage_requests_pending_assignment_idx")
|
|
.on(table.assignmentId)
|
|
.where(sql`${table.status} = 'pending'`),
|
|
index("coverage_requests_status_idx").on(table.status, table.createdAt),
|
|
index("coverage_requests_requester_idx").on(table.requestedBy),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------------------------ run sheet */
|
|
|
|
/**
|
|
* One run sheet per service instance (PK = instance). Holds the service-wide
|
|
* header: speaker, message title, stream/slides links, and free notes. Items
|
|
* live in `run_sheet_items`; checklists in `service_checklist_items`.
|
|
*/
|
|
export const serviceRunSheets = pgTable("service_run_sheets", {
|
|
serviceInstanceId: text("service_instance_id")
|
|
.primaryKey()
|
|
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
|
speaker: text("speaker"),
|
|
sermonTitle: text("sermon_title"),
|
|
streamUrl: text("stream_url"),
|
|
slidesUrl: text("slides_url"),
|
|
notes: text("notes"),
|
|
updatedBy: text("updated_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
|
|
});
|
|
|
|
/**
|
|
* An ordered cue in the service. `timeLabel` is free text ("10:58") so a
|
|
* coordinator can write the booth sheet exactly as the service runs.
|
|
*/
|
|
export const runSheetItems = pgTable(
|
|
"run_sheet_items",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
serviceInstanceId: text("service_instance_id")
|
|
.notNull()
|
|
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
|
sortOrder: integer("sort_order").notNull().default(0),
|
|
timeLabel: text("time_label"),
|
|
title: text("title").notNull(),
|
|
owner: text("owner"),
|
|
notes: text("notes"),
|
|
},
|
|
(table) => [
|
|
index("run_sheet_items_instance_idx").on(
|
|
table.serviceInstanceId,
|
|
table.sortOrder,
|
|
),
|
|
],
|
|
);
|
|
|
|
/** Checklist phase: before the service starts, or after it ends. */
|
|
export const CHECKLIST_PHASES = ["pre", "post"] as const;
|
|
export type ChecklistPhase = (typeof CHECKLIST_PHASES)[number];
|
|
|
|
/**
|
|
* Per-instance checklist. Rows are copied from a default template the first
|
|
* time the run sheet is opened, then owned by the instance so a coordinator can
|
|
* add or remove steps for a special service without editing a global template.
|
|
*/
|
|
export const serviceChecklistItems = pgTable(
|
|
"service_checklist_items",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
serviceInstanceId: text("service_instance_id")
|
|
.notNull()
|
|
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
|
phase: text("phase", { enum: CHECKLIST_PHASES }).notNull().default("pre"),
|
|
sortOrder: integer("sort_order").notNull().default(0),
|
|
label: text("label").notNull(),
|
|
doneAt: timestamp("done_at", { mode: "date", withTimezone: true }),
|
|
doneBy: text("done_by").references(() => users.id, { onDelete: "set null" }),
|
|
},
|
|
(table) => [
|
|
uniqueIndex("service_checklist_instance_label_idx").on(
|
|
table.serviceInstanceId,
|
|
table.phase,
|
|
table.label,
|
|
),
|
|
index("service_checklist_instance_idx").on(
|
|
table.serviceInstanceId,
|
|
table.phase,
|
|
table.sortOrder,
|
|
),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------------ coverage intake form */
|
|
|
|
export const COVERAGE_INTAKE_STATUSES = [
|
|
"new",
|
|
"scheduled",
|
|
"declined",
|
|
] as const;
|
|
export type CoverageIntakeStatus =
|
|
(typeof COVERAGE_INTAKE_STATUSES)[number];
|
|
|
|
/**
|
|
* A media-coverage request from a ministry leader or member of the church.
|
|
* Submitted from the public `/request-coverage` form, reviewed by a
|
|
* coordinator, and converted into an event (which already carries the
|
|
* photographer assignment and file-sharing workflow).
|
|
*/
|
|
export const coverageIntakes = pgTable(
|
|
"coverage_intakes",
|
|
{
|
|
id: text("id").primaryKey(),
|
|
requesterName: text("requester_name").notNull(),
|
|
requesterEmail: text("requester_email").notNull(),
|
|
requesterPhone: text("requester_phone"),
|
|
ministry: text("ministry"),
|
|
title: text("title").notNull(),
|
|
eventType: text("event_type").notNull().default("coverage"),
|
|
startsAt: timestamp("starts_at", { mode: "date", withTimezone: true })
|
|
.notNull(),
|
|
endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }),
|
|
location: text("location"),
|
|
description: text("description"),
|
|
status: text("status", { enum: COVERAGE_INTAKE_STATUSES })
|
|
.notNull()
|
|
.default("new"),
|
|
createdEventId: text("created_event_id").references(() => events.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
reviewedBy: text("reviewed_by").references(() => users.id, {
|
|
onDelete: "set null",
|
|
}),
|
|
reviewedAt: timestamp("reviewed_at", { mode: "date", withTimezone: true }),
|
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
|
.notNull()
|
|
.defaultNow(),
|
|
},
|
|
(table) => [
|
|
index("coverage_intakes_status_idx").on(table.status, table.createdAt),
|
|
index("coverage_intakes_starts_idx").on(table.startsAt),
|
|
],
|
|
);
|
|
|
|
/* ------------------------------------------------------------- relations */
|
|
|
|
/**
|
|
* Skills compose from the four catalog tables (B3). `skills`,
|
|
* `position_skills`, `user_skills` and `skill_assessments` 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,
|
|
auditLog,
|
|
unavailability,
|
|
skillCategories,
|
|
vendors,
|
|
technologies,
|
|
functions,
|
|
skills,
|
|
positionSkills,
|
|
userSkills,
|
|
skillAssessments,
|
|
growthGoals,
|
|
notifications,
|
|
usedTokens,
|
|
usedMagicTokens,
|
|
notificationRules,
|
|
appSettings,
|
|
trainingLessons,
|
|
trainingResources,
|
|
events,
|
|
eventPhotographers,
|
|
eventFolders,
|
|
eventPhotos,
|
|
eventVideos,
|
|
announcements,
|
|
coverageRequests,
|
|
serviceRunSheets,
|
|
runSheetItems,
|
|
serviceChecklistItems,
|
|
coverageIntakes,
|
|
};
|
|
|
|
export type Schema = typeof schema;
|