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:
+251
-10
@@ -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;
|
||||
|
||||
+193
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* Seed script for Media Team Hub (Phase A2).
|
||||
*
|
||||
* Idempotent: every insert uses ON CONFLICT DO NOTHING, so it is safe to run
|
||||
* repeatedly. Populates the core scheduling tables with a small, browsable
|
||||
* dataset — 3 roles, 2 services, the next 2 Sundays of instances, their slots,
|
||||
* and a few volunteers assigned to slots.
|
||||
*
|
||||
* Run: pnpm db:seed (DATABASE_URL must point at the target DB)
|
||||
*/
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { db } from "./index";
|
||||
import {
|
||||
users,
|
||||
roles,
|
||||
services,
|
||||
serviceInstances,
|
||||
slots,
|
||||
assignments,
|
||||
} from "./schema";
|
||||
import { uuidv7 } from "../lib/uuid";
|
||||
import { localToUtc, nextSundaysInTz } from "../lib/tz";
|
||||
|
||||
const CHURCH_TZ = "America/New_York";
|
||||
|
||||
async function main() {
|
||||
/* 1. Roles — production positions (audio, livestream, slides) */
|
||||
const roleRows: (typeof roles.$inferInsert)[] = [
|
||||
{
|
||||
id: uuidv7(), slug: "audio", name: "Audio",
|
||||
description: "FOH, microphones, monitors, mix", colorHex: "#ef4444",
|
||||
callTimeOffsetMinutes: -90, requiresCertification: true,
|
||||
defaultHeadcount: 1, sortOrder: 1,
|
||||
},
|
||||
{
|
||||
id: uuidv7(), slug: "livestream", name: "Livestream",
|
||||
description: "Camera operation, encoder, chat", colorHex: "#3b82f6",
|
||||
callTimeOffsetMinutes: -60, requiresCertification: true,
|
||||
defaultHeadcount: 1, sortOrder: 2,
|
||||
},
|
||||
{
|
||||
id: uuidv7(), slug: "slides", name: "Slides",
|
||||
description: "ProPresenter, lyrics, media playback", colorHex: "#10b981",
|
||||
callTimeOffsetMinutes: -30, requiresCertification: true,
|
||||
defaultHeadcount: 1, sortOrder: 3,
|
||||
},
|
||||
];
|
||||
for (const r of roleRows) {
|
||||
await db.insert(roles).values(r).onConflictDoNothing({ target: roles.slug });
|
||||
}
|
||||
console.log(`roles: ${roleRows.length} seeded`);
|
||||
|
||||
/* 2. Services — recurring gathering templates */
|
||||
const serviceRows: (typeof services.$inferInsert)[] = [
|
||||
{
|
||||
id: uuidv7(), name: "Sunday 9:00 AM", location: "Main Auditorium — Booth",
|
||||
timezone: CHURCH_TZ, rrule: "FREQ=WEEKLY;BYDAY=SU", startTimeLocal: "09:00",
|
||||
durationMinutes: 75, doorsOpenMinutesBefore: 30, active: true, notes: null,
|
||||
},
|
||||
{
|
||||
id: uuidv7(), name: "Sunday 11:00 AM", location: "Main Auditorium — Booth",
|
||||
timezone: CHURCH_TZ, rrule: "FREQ=WEEKLY;BYDAY=SU", startTimeLocal: "11:00",
|
||||
durationMinutes: 75, doorsOpenMinutesBefore: 30, active: true, notes: null,
|
||||
},
|
||||
];
|
||||
for (const s of serviceRows) {
|
||||
await db.insert(services).values(s).onConflictDoNothing({ target: services.name });
|
||||
}
|
||||
console.log(`services: ${serviceRows.length} seeded`);
|
||||
|
||||
/* 3. Instances — materialized occurrences (next 2 Sundays × each service) */
|
||||
// Re-fetch canonical rows: ON CONFLICT DO NOTHING keeps the first-run ids, so
|
||||
// downstream references must use DB ids, not the freshly-generated ones.
|
||||
const serviceRows2 = await db.select().from(services).orderBy(services.name);
|
||||
const sundays = nextSundaysInTz(2, CHURCH_TZ);
|
||||
let instanceCount = 0;
|
||||
for (const service of serviceRows2) {
|
||||
for (const dateStr of sundays) {
|
||||
const startsAt = localToUtc(dateStr, service.startTimeLocal!, service.timezone!);
|
||||
const endsAt = new Date(startsAt.getTime() + service.durationMinutes! * 60000);
|
||||
await db.insert(serviceInstances).values({
|
||||
id: uuidv7(),
|
||||
serviceId: service.id,
|
||||
occursOn: localToUtc(dateStr, "00:00", service.timezone!),
|
||||
startsAt,
|
||||
endsAt,
|
||||
isSpecial: false,
|
||||
titleOverride: null,
|
||||
status: "published",
|
||||
publishedAt: new Date(),
|
||||
publishedBy: null,
|
||||
notes: null,
|
||||
}).onConflictDoNothing({ target: [serviceInstances.serviceId, serviceInstances.startsAt] });
|
||||
instanceCount++;
|
||||
}
|
||||
}
|
||||
console.log(`service_instances: ${instanceCount} seeded`);
|
||||
|
||||
/* 4. Slots — one seat per role per instance */
|
||||
const instanceRows = await db
|
||||
.select()
|
||||
.from(serviceInstances)
|
||||
.orderBy(serviceInstances.occursOn, serviceInstances.serviceId);
|
||||
const roleRows2: (typeof roles.$inferSelect)[] = await db.select().from(roles).orderBy(roles.sortOrder);
|
||||
|
||||
const slotRows: (typeof slots.$inferInsert)[] = [];
|
||||
for (const inst of instanceRows) {
|
||||
roleRows2.forEach((role, i) => {
|
||||
const callTime = role.callTimeOffsetMinutes
|
||||
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
|
||||
: null;
|
||||
slotRows.push({
|
||||
id: uuidv7(),
|
||||
serviceInstanceId: inst.id,
|
||||
eventId: null,
|
||||
roleId: role.id,
|
||||
slotIndex: i + 1,
|
||||
callTime,
|
||||
status: "open",
|
||||
slotNote: null,
|
||||
isTraineeSlot: false,
|
||||
pairedWithUserId: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
await db.insert(slots).values(slotRows).onConflictDoNothing({
|
||||
target: [slots.serviceInstanceId, slots.roleId, slots.slotIndex],
|
||||
});
|
||||
console.log(`slots: ${slotRows.length} seeded`);
|
||||
// Re-fetch canonical slot ids for downstream assignment references.
|
||||
const slotRows2 = await db
|
||||
.select()
|
||||
.from(slots)
|
||||
.orderBy(slots.serviceInstanceId, slots.roleId, slots.slotIndex);
|
||||
|
||||
/* 5. Users — admin, coordinator, volunteers */
|
||||
const userRows: (typeof users.$inferInsert)[] = [
|
||||
{ id: uuidv7(), email: "admin@glenloch.local", phoneE164: null, firstName: "Admin", lastName: "User", displayName: "Admin User", systemRole: "admin", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed admin", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "coordinator@glenloch.local", phoneE164: null, firstName: "Cole", lastName: "Coordinator", displayName: "Cole Coordinator", systemRole: "coordinator", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: "seed coordinator", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "jordan@glenloch.local", phoneE164: "+15551230001", firstName: "Jordan", lastName: "Reyes", displayName: "Jordan Reyes", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: "M. Reyes +15551239999", approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "avery@glenloch.local", phoneE164: "+15551230002", firstName: "Avery", lastName: "Kim", displayName: "Avery Kim", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "sam@glenloch.local", phoneE164: "+15551230003", firstName: "Sam", lastName: "Okafor", displayName: "Sam Okafor", systemRole: "volunteer", status: "active", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: new Date(), lastServedAt: null, reliabilityScore: null, notes: null, createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
{ id: uuidv7(), email: "riley@glenloch.local", phoneE164: null, firstName: "Riley", lastName: "Parks", displayName: "Riley Parks", systemRole: "trainee", status: "pending_approval", avatarUrl: null, timezone: CHURCH_TZ, emergencyContact: null, approvedBy: null, approvedAt: null, lastServedAt: null, reliabilityScore: null, notes: "trainee — shadowing", createdAt: new Date(), updatedAt: null, deactivatedAt: null },
|
||||
];
|
||||
for (const u of userRows) {
|
||||
await db.insert(users).values(u).onConflictDoNothing({ target: users.email });
|
||||
}
|
||||
console.log(`users: ${userRows.length} seeded`);
|
||||
// Re-fetch canonical user ids for assignment references.
|
||||
const userRows2 = await db.select().from(users);
|
||||
|
||||
/* 6. Assignments — one confirmed volunteer per slot (round-robin) */
|
||||
const volunteers = userRows2.filter((u) => u.systemRole === "volunteer");
|
||||
const assignedRows: (typeof assignments.$inferInsert)[] = [];
|
||||
for (let i = 0; i < slotRows2.length; i++) {
|
||||
const vol = volunteers[i % volunteers.length];
|
||||
assignedRows.push({
|
||||
id: uuidv7(),
|
||||
slotId: slotRows2[i].id,
|
||||
userId: vol.id,
|
||||
status: "confirmed",
|
||||
source: "manual",
|
||||
assignedBy: userRows2[0].id,
|
||||
assignedAt: new Date(),
|
||||
respondedAt: new Date(),
|
||||
declineReason: null,
|
||||
confirmedVia: "admin",
|
||||
reminderCount: 0,
|
||||
});
|
||||
}
|
||||
// Idempotent: drop any existing assignment for these slots, then re-insert.
|
||||
// (The partial unique index uq_active_assignment can't serve as an ON CONFLICT
|
||||
// arbiter, so clear per slot rather than relying on ON CONFLICT DO NOTHING.)
|
||||
for (const slot of slotRows2) {
|
||||
await db.delete(assignments).where(eq(assignments.slotId, slot.id));
|
||||
}
|
||||
await db.insert(assignments).values(assignedRows);
|
||||
console.log(`assignments: ${assignedRows.length} seeded`);
|
||||
|
||||
const [instanceCountRow] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(serviceInstances)
|
||||
.limit(1);
|
||||
console.log(`service_instances total: ${instanceCountRow?.count ?? 0}`);
|
||||
console.log("seed complete");
|
||||
}
|
||||
|
||||
main()
|
||||
.then(() => process.exit(0))
|
||||
.catch((err) => {
|
||||
console.error("seed failed:", err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Timezone helpers — the church's local time is the source of truth for
|
||||
* scheduling; everything is stored as UTC instants and rendered in the
|
||||
* viewer's timezone. All scheduling math uses the church timezone (DST-safe).
|
||||
*/
|
||||
|
||||
function partsInTz(date: Date, timeZone: string): Record<string, string> {
|
||||
const dtf = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
hourCycle: "h23",
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
second: "2-digit",
|
||||
});
|
||||
const out: Record<string, string> = {};
|
||||
for (const part of dtf.formatToParts(date)) {
|
||||
if (part.type !== "literal") out[part.type] = part.value;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Milliseconds the given timezone is ahead of UTC at `date` (negative behind). */
|
||||
export function utcOffsetMs(date: Date, timeZone: string): number {
|
||||
const parts = partsInTz(date, timeZone);
|
||||
const wallClockIso = `${parts.year}-${parts.month}-${parts.day}T${parts.hour}:${parts.minute}:${parts.second}`;
|
||||
// Interpret the wall clock as if it were UTC; the diff is the offset.
|
||||
return Date.parse(`${wallClockIso}Z`) - date.getTime();
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a UTC `Date` from a local wall-clock date + time in `timeZone`.
|
||||
* DST-safe: the offset is resolved for the actual instant, so a 9:00 AM Sunday
|
||||
* stays 9:00 AM across spring-forward / fall-back.
|
||||
*/
|
||||
export function localToUtc(dateStr: string, timeStr: string, timeZone: string): Date {
|
||||
const [y, mo, d] = dateStr.split("-").map(Number);
|
||||
const [h, mi] = (timeStr || "00:00").split(":").map(Number);
|
||||
const guessed = Date.UTC(y, mo - 1, d, h ?? 0, mi ?? 0, 0);
|
||||
const offset = utcOffsetMs(new Date(guessed), timeZone);
|
||||
return new Date(guessed - offset);
|
||||
}
|
||||
|
||||
/** Format a UTC `Date` as a wall-clock string in `timeZone`. */
|
||||
export function formatInTimezone(
|
||||
date: Date,
|
||||
timeZone: string,
|
||||
options: Intl.DateTimeFormatOptions = {
|
||||
timeZone,
|
||||
weekday: "short",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
},
|
||||
): string {
|
||||
return new Intl.DateTimeFormat("en-US", { ...options }).format(date);
|
||||
}
|
||||
|
||||
/** YYYY-MM-DD of `date` in `timeZone`. */
|
||||
export function dateInTimezone(date: Date, timeZone: string): string {
|
||||
const { year, month, day } = partsInTz(date, timeZone);
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
/** Weekday (0=Sun..6=Sat) of a local date string in `timeZone`. */
|
||||
export function weekdayInTz(dateStr: string, timeZone: string): number {
|
||||
const [y, mo, d] = dateStr.split("-").map(Number);
|
||||
return partsInTz(new Date(Date.UTC(y, mo - 1, d)), timeZone).weekday as unknown as number;
|
||||
}
|
||||
|
||||
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
|
||||
/**
|
||||
* YYYY-MM-DD strings for the next `count` Sundays strictly after today,
|
||||
* computed in `timeZone`. Used by the seed to materialize instances.
|
||||
*/
|
||||
export function nextSundaysInTz(count: number, timeZone: string): string[] {
|
||||
const today = dateInTimezone(new Date(), timeZone);
|
||||
const [ty, tm, td] = today.split("-").map(Number);
|
||||
const weekday = WEEKDAYS.indexOf(partsInTz(new Date(Date.UTC(ty, tm - 1, td)), timeZone).weekday as unknown as string);
|
||||
const daysUntilNextSunday = weekday === 0 ? 7 : 7 - weekday;
|
||||
|
||||
const out: string[] = [];
|
||||
for (let k = 0; k < count; k++) {
|
||||
const target = new Date(Date.UTC(ty, tm - 1, td));
|
||||
target.setUTCDate(target.getUTCDate() + daysUntilNextSunday + k * 7);
|
||||
const y = target.getUTCFullYear();
|
||||
const m = String(target.getUTCMonth() + 1).padStart(2, "0");
|
||||
const d = String(target.getUTCDate()).padStart(2, "0");
|
||||
out.push(`${y}-${m}-${d}`);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/**
|
||||
* UUIDv7 generator (RFC 9562).
|
||||
*
|
||||
* The schema uses UUIDv7 text ids (ARCHITECTURE §4.2): time-sortable,
|
||||
* collision-resistant, and safe to generate client-side for optimistic UI.
|
||||
* Generated at the app/seed layer — the DB columns are plain `text`.
|
||||
*/
|
||||
import { getRandomValues } from "node:crypto";
|
||||
|
||||
export function uuidv7(): string {
|
||||
const bytes = getRandomValues(new Uint8Array(16));
|
||||
const ms = Date.now();
|
||||
|
||||
// bytes 0-5: 48-bit Unix timestamp (ms)
|
||||
bytes[0] = (ms >> 40) & 0xff;
|
||||
bytes[1] = (ms >> 32) & 0xff;
|
||||
bytes[2] = (ms >> 24) & 0xff;
|
||||
bytes[3] = (ms >> 16) & 0xff;
|
||||
bytes[4] = (ms >> 8) & 0xff;
|
||||
bytes[5] = ms & 0xff;
|
||||
|
||||
// byte 6: 8 random bits; byte 7: 4 random bits + version 0111
|
||||
bytes[6] = getRandomValues(new Uint8Array(1))[0];
|
||||
bytes[7] = 0x70 | (getRandomValues(new Uint8Array(1))[0] & 0x0f);
|
||||
|
||||
// byte 8: variant 10xx + 6 random bits; bytes 9-15: remaining random
|
||||
bytes[8] = 0x80 | (getRandomValues(new Uint8Array(1))[0] & 0x3f);
|
||||
const rest = getRandomValues(new Uint8Array(7));
|
||||
for (let i = 0; i < 7; i++) bytes[9 + i] = rest[i];
|
||||
|
||||
const h = (n: number) => n.toString(16).padStart(2, "0");
|
||||
return [
|
||||
h(bytes[0]) + h(bytes[1]) + h(bytes[2]) + h(bytes[3]),
|
||||
h(bytes[4]) + h(bytes[5]),
|
||||
h(bytes[6]) + h(bytes[7]),
|
||||
h(bytes[8]) + h(bytes[9]),
|
||||
h(bytes[10]) + h(bytes[11]) + h(bytes[12]) + h(bytes[13]) + h(bytes[14]) + h(bytes[15]),
|
||||
].join("-");
|
||||
}
|
||||
Reference in New Issue
Block a user