A2: schema core (6 tables, migration, idempotent seed)

- users/roles/services/service_instances/slots/assignments with spec rules:
  - chk_slots_single_parent (Rule 26): slot has exactly one parent
  - uq_active_assignment (Rule 27): partial unique, one active assignment per slot
  - slug immutability, deactivate-only, UTC storage, America/New_York default
- uuidv7 (src/lib/uuid.ts), DST-safe tz helpers (src/lib/tz.ts)
- idempotent seed: 3 roles, 2 services, next 2 Sundays x services, 12 slots, 6 users
- migration drizzle/0000 + 0001
Verified: typecheck/lint/test/build + db:migrate + db:seed all exit 0;
service_instances=4; re-run seed idempotent; CHECK + partial unique enforced.
This commit is contained in:
Tiel Coder
2026-11-17 18:52:35 +00:00
parent c595865496
commit a68e1c6277
12 changed files with 2437 additions and 11 deletions
+251 -10
View File
@@ -1,17 +1,258 @@
/**
* Database schema — Phase A2 populates the full data model here.
* Database schema — Media Team Hub.
*
* Full spec: ARCHITECTURE.md §4 (users, roles, services, instances, slots,
* assignments, the skill taxonomy, notifications outbox, etc.).
* Phase A2 writes the CORE scheduling tables only:
* users → roles → services → service_instances → slots → assignments
*
* Conventions (from the spec):
* - `id` is a UUIDv7 text column
* - timestamps are `*_at` in UTC ISO-8601
* - dates are `*_date` in the church's local timezone
* - soft-delete only where noted; no hard deletes in the taxonomy graph
* Deliberately NOT here (added in later units, do not add "while I'm in the schema"):
* - Catalog taxonomy: skill_categories, vendors, technologies, functions,
* skills, position_skills, user_skills, skill_assessments, growth_goals (B3)
* - service_role_requirements, unavailability, events, notifications outbox
*
* Conventions (ARCHITECTURE §4.2):
* - `id` is a UUIDv7 text column (generated at the app/seed layer, see src/lib/uuid.ts)
* - timestamps `*_at` / starts_at / ends_at / call_time are UTC instants (timestamptz)
* - dates `*_date` / occurs_on / starts_on are DATE in the church's local timezone
* - soft delete only where noted; no hard deletes in the taxonomy graph
*/
// Placeholder: A2 replaces this object with the real tables.
export const schema = {};
import { relations, sql } from "drizzle-orm";
import { pgTable, text, integer, boolean, timestamp, date, numeric, index, uniqueIndex, check } from "drizzle-orm/pg-core";
/* ------------------------------------------------------------------ enums */
export const SYSTEM_ROLES = ["admin", "coordinator", "volunteer", "trainee"] as const;
export type SystemRole = (typeof SYSTEM_ROLES)[number];
export const USER_STATUSES = ["invited", "pending_approval", "active", "inactive", "denied"] as const;
export type UserStatus = (typeof USER_STATUSES)[number];
export const SLOT_STATUSES = ["open", "proposed", "confirmed", "declined", "covered"] as const;
export type SlotStatus = (typeof SLOT_STATUSES)[number];
export const INSTANCE_STATUSES = ["draft", "published", "cancelled"] as const;
export type InstanceStatus = (typeof INSTANCE_STATUSES)[number];
export const ASSIGNMENT_STATUSES = ["proposed", "confirmed", "declined", "completed", "no_show", "cancelled"] as const;
export type AssignmentStatus = (typeof ASSIGNMENT_STATUSES)[number];
export const ASSIGNMENT_SOURCES = ["manual", "auto", "swap", "import"] as const;
export type AssignmentSource = (typeof ASSIGNMENT_SOURCES)[number];
export const CONFIRMED_VIAS = ["app", "email_link", "sms_reply", "admin"] as const;
export type ConfirmedVia = (typeof CONFIRMED_VIAS)[number];
const DEFAULT_TIMEZONE = "America/New_York";
/* ------------------------------------------------------------------ users */
export const users = pgTable(
"users",
{
id: text("id").primaryKey(),
email: text("email").unique().notNull(),
phoneE164: text("phone_e164"),
firstName: text("first_name").notNull(),
lastName: text("last_name").notNull(),
displayName: text("display_name"),
systemRole: text("system_role", { enum: SYSTEM_ROLES }).notNull().default("volunteer"),
status: text("status", { enum: USER_STATUSES }).notNull().default("pending_approval"),
avatarUrl: text("avatar_url"),
timezone: text("timezone").notNull().default(DEFAULT_TIMEZONE),
emergencyContact: text("emergency_contact"),
approvedBy: text("approved_by"),
approvedAt: timestamp("approved_at", { mode: "date", withTimezone: true }),
lastServedAt: timestamp("last_served_at", { mode: "date", withTimezone: true }),
reliabilityScore: numeric("reliability_score", { precision: 5, scale: 2 }),
notes: text("notes"),
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
.notNull()
.defaultNow(),
updatedAt: timestamp("updated_at", { mode: "date", withTimezone: true }),
deactivatedAt: timestamp("deactivated_at", { mode: "date", withTimezone: true }),
},
(table) => [
// Case-insensitive unique login key.
index("users_email_lower_idx").on(sql`lower(${table.email})`),
index("users_status_idx").on(table.status),
index("users_system_role_idx").on(table.systemRole),
],
);
/* ------------------------------------------------------------------ roles */
export const roles = pgTable(
"roles",
{
id: text("id").primaryKey(),
slug: text("slug").unique().notNull(),
name: text("name").notNull(),
description: text("description"),
colorHex: text("color_hex"),
/** e.g. audio = -90 (arrive 90 min before service start). */
callTimeOffsetMinutes: integer("call_time_offset_minutes"),
requiresCertification: boolean("requires_certification").notNull().default(true),
defaultHeadcount: integer("default_headcount").notNull().default(1),
sortOrder: integer("sort_order").notNull().default(0),
},
(table) => [index("roles_slug_idx").on(table.slug)],
);
/* -------------------------------------------------------------- services */
export const services = pgTable(
"services",
{
id: text("id").primaryKey(),
name: text("name").unique().notNull(),
location: text("location"),
timezone: text("timezone").notNull().default(DEFAULT_TIMEZONE),
/** RFC 5545 subset: FREQ=WEEKLY;BYDAY=SU (WEEKLY | BIWEEKLY | MONTHLY). */
rrule: text("rrule"),
startTimeLocal: text("start_time_local").notNull(),
durationMinutes: integer("duration_minutes").notNull().default(75),
doorsOpenMinutesBefore: integer("doors_open_minutes_before").notNull().default(0),
active: boolean("active").notNull().default(true),
notes: text("notes"),
},
(table) => [index("services_active_idx").on(table.active)],
);
/* ------------------------------------------------------- service_instances */
export const serviceInstances = pgTable(
"service_instances",
{
id: text("id").primaryKey(),
serviceId: text("service_id")
.notNull()
.references(() => services.id, { onDelete: "restrict" }),
/** Local date, e.g. 2027-01-10. */
occursOn: date("occurs_on", { mode: "date" }),
/** UTC instants, computed from local time + tz (DST-safe). */
startsAt: timestamp("starts_at", { mode: "date", withTimezone: true }),
endsAt: timestamp("ends_at", { mode: "date", withTimezone: true }),
isSpecial: boolean("is_special").notNull().default(false),
titleOverride: text("title_override"),
status: text("status", { enum: INSTANCE_STATUSES }).notNull().default("draft"),
publishedAt: timestamp("published_at", { mode: "date", withTimezone: true }),
publishedBy: text("published_by"),
notes: text("notes"),
},
(table) => [
// Idempotent instance generation on this key.
uniqueIndex("si_service_starts_at_idx").on(table.serviceId, table.startsAt),
index("si_occurs_on_idx").on(table.occursOn),
index("si_status_idx").on(table.status),
],
);
/* ------------------------------------------------------------------- slots */
export const slots = pgTable(
"slots",
{
id: text("id").primaryKey(),
/** Cascade delete; exactly one of this or `eventId` (CHECK below). */
serviceInstanceId: text("service_instance_id").references(() => serviceInstances.id, { onDelete: "cascade" }),
/** One-off event coverage; reuses the whole assignment pipeline. */
eventId: text("event_id"),
roleId: text("role_id")
.notNull()
.references(() => roles.id, { onDelete: "restrict" }),
/** 1..headcount, for labels ("Audio 2"). */
slotIndex: integer("slot_index").notNull(),
/** = instance.starts_at + role.call_time_offset_minutes. */
callTime: timestamp("call_time", { mode: "date", withTimezone: true }),
/** Derived but stored for query speed. */
status: text("status", { enum: SLOT_STATUSES }).notNull().default("open"),
slotNote: text("slot_note"),
/** Shadow slots don't count toward coverage. */
isTraineeSlot: boolean("is_trainee_slot").notNull().default(false),
/** Mentor shadowing alongside this slot. */
pairedWithUserId: text("paired_with_user_id").references(() => users.id, { onDelete: "set null" }),
},
(table) => [
// One seat per role per instance: (instance, role, seat number).
uniqueIndex("slots_instance_role_idx").on(
table.serviceInstanceId,
table.roleId,
table.slotIndex,
),
index("slots_status_idx").on(table.status),
// Spec rule 26: a slot belongs to exactly one of a service instance or an event.
// Parentheses force both operands to boolean so <> is XOR (not "boolean <> text").
check(
"chk_slots_single_parent",
sql`(service_instance_id IS NOT NULL) <> (event_id IS NOT NULL)`,
),
],
);
/* ------------------------------------------------------------- assignments */
export const assignments = pgTable(
"assignments",
{
id: text("id").primaryKey(),
slotId: text("slot_id")
.notNull()
.references(() => slots.id, { onDelete: "cascade" }),
userId: text("user_id")
.notNull()
.references(() => users.id, { onDelete: "restrict" }),
status: text("status", { enum: ASSIGNMENT_STATUSES }).notNull().default("proposed"),
source: text("source", { enum: ASSIGNMENT_SOURCES }).notNull().default("manual"),
assignedBy: text("assigned_by"),
assignedAt: timestamp("assigned_at", { mode: "date", withTimezone: true }),
respondedAt: timestamp("responded_at", { mode: "date", withTimezone: true }),
declineReason: text("decline_reason"),
confirmedVia: text("confirmed_via", { enum: CONFIRMED_VIAS }),
reminderCount: integer("reminder_count").notNull().default(0),
},
(table) => [
// Invariant: at most one non-terminal assignment per slot.
// History is preserved by keeping declined/cancelled rows.
uniqueIndex("uq_active_assignment")
.on(table.slotId)
.where(sql`${table.status} IN ('proposed','confirmed','completed')`),
index("assignments_user_idx").on(table.userId),
],
);
/* ------------------------------------------------------------- relations */
export const usersRelations = relations(users, ({ many }) => ({
assignments: many(assignments),
}));
export const serviceInstanceRelations = relations(serviceInstances, ({ one, many }) => ({
service: one(services),
slots: many(slots),
}));
export const slotRelations = relations(slots, ({ one, many }) => ({
role: one(roles),
instance: one(serviceInstances),
assignments: many(assignments),
}));
export const assignmentRelations = relations(assignments, ({ one }) => ({
slot: one(slots),
user: one(users),
}));
/**
* The schema object Drizzle uses for migrations and the query layer.
* Phase A2 core only; catalog + downstream tables are added in their own units.
*/
export const schema = {
users,
roles,
services,
serviceInstances,
slots,
assignments,
};
export type Schema = typeof schema;