4 Commits

Author SHA1 Message Date
bhursey b42700a943 fix(seed): one seat per role per instance
CI / build (push) Has been cancelled
The seed numbered seats by role position, so Livestream became seat 2 and
Slides seat 3. Existing instances number every role's first seat 1, so the
insert did not match them and added a duplicate Livestream and Slides seat to
every Sunday. Always use seat 1.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-22 22:11:21 +00:00
bhursey f71952f838 fix(seed): never run the demo seed as part of a deploy
CI / build (push) Has been cancelled
The migrate task chained db:seed, so every production deploy inserted demo
users, duplicate Sunday templates and 45 fake assignments, and its unconditional
assignment delete wiped real schedule data. Migrations now run alone, and the
seed aborts when the database already holds non-seed users unless SEED_FORCE=1
is set for a throwaway database.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-22 21:34:02 +00:00
bhursey ade21425d4 fix(schedule): use the instance title on every schedule surface
CI / build (push) Has been cancelled
One-off services hang off a shared parent template, so anything that printed the
template name showed "Special services (one-off)" instead of the real service.
Grid, coverage, run sheet, reminders, outbox mail, candidates and exports now
prefer the instance title override, which already existed but was ignored.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-22 18:21:09 +00:00
bhursey aaa3fd9ed1 feat(schedule): add one-off services with chosen positions
CI / build (push) Has been cancelled
Special services were impossible to schedule: every instance came from a
recurring template and opened seats for all three roles. Coordinators can now
add a dated one-off service that materializes only the positions it needs, and
optionally pick a photographer at the same time, which creates the matching
media event with them already assigned.

🤖 Generated with Codebuff
Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-11-22 18:08:59 +00:00
17 changed files with 620 additions and 26 deletions
+1 -1
View File
@@ -29,7 +29,7 @@ RUN pnpm build
# ---------------------------------------------------------------------------
FROM builder AS tools
ENV NODE_ENV=development
CMD ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
CMD ["pnpm", "db:migrate"]
FROM base AS runner
WORKDIR /app
+5 -2
View File
@@ -159,14 +159,17 @@ services:
retries: 10
restart: unless-stopped
# One-shot migrations + seed. Run on demand:
# One-shot migrations. Run on demand:
# docker compose --profile tools run --rm migrate
# Seed is intentionally separate: it inserts demo users/services and rewrites
# assignments, so it must never run as part of a production deploy. On a
# fresh install run: docker compose --profile tools run --rm migrate pnpm db:seed
migrate:
build:
context: .
dockerfile: Dockerfile
target: tools
command: ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
command: ["pnpm", "db:migrate"]
environment:
DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media}
depends_on:
+5 -1
View File
@@ -6,6 +6,7 @@ import { listUsersForAdmin } from "@/db/users";
import { listSkillsMatrix } from "@/db/assessments";
import { getPositionSkills, listPositions, listSkills } from "@/db/positions";
import { listServices } from "@/db/services";
import { SPECIAL_SERVICE_NAME } from "@/db/specials";
import { listNotifications } from "@/db/outbox";
import { listRules } from "@/db/reminders";
import { getEmailSettings } from "@/db/settings";
@@ -270,7 +271,10 @@ export default async function AdminPage() {
</CardHeader>
<CardContent>
<ServicesPanel
services={services.map((service) => ({
services={services
// The one-off parent is plumbing, not a template to manage.
.filter((service) => service.name !== SPECIAL_SERVICE_NAME)
.map((service) => ({
id: service.id,
name: service.name,
startTimeLocal: service.startTimeLocal,
+16 -1
View File
@@ -5,6 +5,8 @@ import { WeekNav } from "@/components/app/week-nav";
import { ScheduleAdminBar } from "@/components/app/schedule-admin-bar";
import { ScheduleGrid } from "@/components/app/schedule-grid";
import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor";
import { SpecialServiceForm } from "@/components/app/special-service-form";
import { listPositions } from "@/db/positions";
import {
MonthNav,
ScheduleViewToggle,
@@ -119,12 +121,25 @@ export default async function SchedulePage({
}
const week = await gridForWeek(weekStart);
const [roles, volunteers] = canEdit
? await Promise.all([listPositions({ active: true }), activeVolunteers(db)])
: [[], []];
return (
<div className="space-y-4">
{header}
{toggle}
<WeekNav weekStart={weekStart} />
{canEdit && (
<SpecialServiceForm
roles={roles.map((role) => ({ id: role.id, name: role.name }))}
volunteers={volunteers.map((person) => ({
id: person.id,
displayName: person.displayName,
}))}
defaultDate={weekStart}
/>
)}
{canEdit && (
<ScheduleAdminBar
instances={week.instances.map((inst) => ({
@@ -135,7 +150,7 @@ export default async function SchedulePage({
/>
)}
{canEdit ? (
<ScheduleGridEditor week={week} volunteers={await activeVolunteers(db)} />
<ScheduleGridEditor week={week} volunteers={volunteers} />
) : (
<ScheduleGrid week={week} />
)}
+61
View File
@@ -0,0 +1,61 @@
import { NextRequest } from "next/server";
import { z } from "zod";
import { gateOrUser } from "@/auth/api";
import {
createSpecialService,
SpecialServiceError,
} from "@/db/specials";
import { errorResponse, jsonResponse } from "@/lib/http";
const schema = z.object({
title: z.string().trim().min(1).max(140),
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "choose a valid date"),
startTimeLocal: z
.string()
.regex(/^\d{2}:\d{2}$/, "choose a valid start time"),
durationMinutes: z.number().int().min(5).max(600).default(60),
location: z.string().trim().max(200).nullable().optional(),
notes: z.string().trim().max(2000).nullable().optional(),
roleIds: z.array(z.string().min(1)).max(12).default([]),
photographerId: z.string().min(1).nullable().optional(),
});
/**
* POST /api/dev/schedule/special
*
* Adds a one-off dated service to the schedule with only the positions the
* scheduler selected. Picking a photographer also creates their media event.
* Coordinators and admins only (`schedule.publish`).
*/
export const POST = async (req: NextRequest) => {
const gate = await gateOrUser("schedule.publish");
if (gate instanceof Response) return gate;
const parsed = schema.safeParse(await req.json().catch(() => null));
if (!parsed.success) {
return errorResponse(
400,
parsed.error.issues[0]?.message ?? "invalid special service",
);
}
try {
const result = await createSpecialService({
...parsed.data,
createdBy: gate.id,
});
return jsonResponse(result, 201);
} catch (error) {
if (error instanceof SpecialServiceError) {
return errorResponse(error.status, error.message);
}
if ((error as { code?: string }).code === "23505") {
return errorResponse(
409,
"a special service already exists at that date and time",
);
}
console.error("[special-service] create failed:", error);
return errorResponse(500, "failed to add the special service");
}
};
+252
View File
@@ -0,0 +1,252 @@
"use client";
import { useState } from "react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
export interface SpecialServiceRole {
id: string;
name: string;
}
export interface SpecialServicePerson {
id: string;
displayName: string;
}
/**
* Adds a one-off service to the week on screen. Unlike a recurring template it
* has no rrule: just a date, a time, and the positions this occurrence actually
* needs — a Wednesday prayer meeting can run with Audio alone.
*
* Picking a photographer creates their media event for the same date/time, so
* the shoot lands in their Events list with them already assigned.
*/
export function SpecialServiceForm({
roles,
volunteers,
defaultDate,
}: {
roles: SpecialServiceRole[];
volunteers: SpecialServicePerson[];
defaultDate: string;
}) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [title, setTitle] = useState("");
const [date, setDate] = useState(defaultDate);
const [startTime, setStartTime] = useState("10:00");
const [duration, setDuration] = useState("60");
const [location, setLocation] = useState("");
const [roleIds, setRoleIds] = useState<string[]>([]);
const [photographerId, setPhotographerId] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [message, setMessage] = useState<string | null>(null);
const [eventId, setEventId] = useState<string | null>(null);
function toggleRole(id: string) {
setRoleIds((current) =>
current.includes(id)
? current.filter((value) => value !== id)
: [...current, id],
);
}
async function submit(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
setMessage(null);
setEventId(null);
try {
const res = await fetch("/api/dev/schedule/special", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
title,
date,
startTimeLocal: startTime,
durationMinutes: Number(duration) || 60,
location: location || null,
roleIds,
photographerId: photographerId || null,
}),
});
const data = (await res.json().catch(() => ({}))) as {
error?: string;
eventId?: string | null;
seats?: number;
};
if (!res.ok) {
setError(data.error ?? "Could not add the special service.");
return;
}
setMessage(
`Added with ${data.seats ?? 0} position seat${(data.seats ?? 0) === 1 ? "" : "s"}${
data.eventId ? " and a media event for the photographer" : ""
}.`,
);
setEventId(data.eventId ?? null);
setTitle("");
setLocation("");
setRoleIds([]);
setPhotographerId("");
router.refresh();
} catch {
setError("Network error.");
} finally {
setBusy(false);
}
}
return (
<div className="rounded-md border border-border">
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/30 px-3 py-2">
<div>
<p className="text-sm font-semibold text-foreground">Special service</p>
<p className="text-xs text-muted-foreground">
A one-off dated service with only the positions it needs.
</p>
</div>
<Button
size="sm"
variant="outline"
onClick={() => setOpen((value) => !value)}
>
{open ? "Close" : "Add a special service"}
</Button>
</div>
{open && (
<form onSubmit={submit} className="space-y-4 p-3">
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
<div className="flex flex-col gap-2 sm:col-span-2">
<Label htmlFor="special-title">Title</Label>
<Input
id="special-title"
required
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Good Friday service"
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="special-date">Date</Label>
<Input
id="special-date"
type="date"
required
value={date}
onChange={(e) => setDate(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="special-time">Start time</Label>
<Input
id="special-time"
type="time"
required
value={startTime}
onChange={(e) => setStartTime(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="special-duration">Minutes</Label>
<Input
id="special-duration"
type="number"
min={5}
max={600}
value={duration}
onChange={(e) => setDuration(e.target.value)}
/>
</div>
<div className="flex flex-col gap-2 sm:col-span-2 lg:col-span-3">
<Label htmlFor="special-location">Location</Label>
<Input
id="special-location"
value={location}
onChange={(e) => setLocation(e.target.value)}
placeholder="Main Auditorium"
/>
</div>
</div>
<fieldset className="space-y-2">
<legend className="text-sm font-medium text-foreground">
Positions needed
</legend>
<p className="text-xs text-muted-foreground">
Only the selected positions get seats. Leave all unchecked if the
service needs no media team.
</p>
<div className="flex flex-wrap gap-4">
{roles.map((role) => (
<label
key={role.id}
className="flex items-center gap-2 text-sm text-foreground"
>
<input
type="checkbox"
className="h-4 w-4 accent-primary"
checked={roleIds.includes(role.id)}
onChange={() => toggleRole(role.id)}
/>
{role.name}
</label>
))}
</div>
</fieldset>
<div className="flex flex-col gap-2 sm:max-w-sm">
<Label htmlFor="special-photographer">Photographer (optional)</Label>
<select
id="special-photographer"
className="h-9 rounded-md border border-input bg-background px-3 text-sm"
value={photographerId}
onChange={(e) => setPhotographerId(e.target.value)}
>
<option value="">No photographer</option>
{volunteers.map((person) => (
<option key={person.id} value={person.id}>
{person.displayName}
</option>
))}
</select>
<p className="text-xs text-muted-foreground">
Creates a media event for this service and assigns them to it.
</p>
</div>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" disabled={busy}>
{busy ? "Adding…" : "Add special service"}
</Button>
{message && (
<p role="status" className="text-sm text-foreground">
{message}
{eventId && (
<>
{" "}
<Link className="underline" href={`/events/${eventId}`}>
Open the event
</Link>
</>
)}
</p>
)}
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
</div>
</form>
)}
</div>
);
}
+2 -2
View File
@@ -105,7 +105,7 @@ export async function listPendingCoverageRequests(): Promise<
assignmentId: coverageRequests.assignmentId,
slotId: slots.id,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
startsAt: serviceInstances.startsAt,
callTime: slots.callTime,
location: services.location,
@@ -386,7 +386,7 @@ export async function listPendingAlternativeProposals(): Promise<
requesterName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
requesterEmail: users.email,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
currentStartsAt: serviceInstances.startsAt,
proposedStartsAt: proposedInstance.startsAt,
note: assignmentProposals.note,
+2 -2
View File
@@ -37,7 +37,7 @@ export async function scheduleExportRows(
return db
.select({
occursOn: serviceInstances.occursOn,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
startsAt: serviceInstances.startsAt,
callTime: slots.callTime,
roleName: roles.name,
@@ -103,7 +103,7 @@ export async function servingHistoryCsv(userId?: string): Promise<string> {
const rows = await db
.select({
occursOn: serviceInstances.occursOn,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
roleName: roles.name,
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
email: users.email,
+1 -1
View File
@@ -162,7 +162,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
instance = {
id: row.instanceId,
serviceId: row.serviceId,
serviceName: row.serviceName,
serviceName: row.titleOverride ?? row.serviceName,
occursOn: occursOnISO(row.occursOn),
startsAt: row.startsAt ?? new Date(0),
titleOverride: row.titleOverride ?? null,
+2 -2
View File
@@ -66,7 +66,7 @@ export async function enqueuePublishNotifications(
displayName: users.displayName,
timeZone: users.timezone,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
startsAt: serviceInstances.startsAt,
callTime: slots.callTime,
@@ -242,7 +242,7 @@ export async function enqueueAssignmentProposed(
firstName: users.firstName,
timeZone: users.timezone,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
startsAt: serviceInstances.startsAt,
callTime: slots.callTime,
+1 -1
View File
@@ -73,7 +73,7 @@ export async function rankedCandidatesForSlot(
roleName: roles.name,
isTraineeSlot: slots.isTraineeSlot,
serviceInstanceId: slots.serviceInstanceId,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
startsAt: serviceInstances.startsAt,
occursOn: serviceInstances.occursOn,
+2 -2
View File
@@ -10,7 +10,7 @@
* so republishing or a retry cannot double-book a reminder.
*/
import { and, eq, inArray } from "drizzle-orm";
import { and, eq, inArray, sql } from "drizzle-orm";
import { db } from "@/db";
import {
assignments,
@@ -158,7 +158,7 @@ export async function enqueueRemindersForInstance(
firstName: users.firstName,
timeZone: users.timezone,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
callTime: slots.callTime,
})
+2 -2
View File
@@ -8,7 +8,7 @@
* and writes the audit row — all in one transaction.
*/
import { and, asc, eq, gt, ne } from "drizzle-orm";
import { and, asc, eq, gt, ne, sql } from "drizzle-orm";
import { db } from "@/db";
import {
assignments,
@@ -73,7 +73,7 @@ export async function getRespondAssignment(
displayName: users.displayName,
timeZone: users.timezone,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
startsAt: serviceInstances.startsAt,
callTime: slots.callTime,
+1 -1
View File
@@ -154,7 +154,7 @@ export async function getRunSheet(
const [instance] = await db
.select({
id: serviceInstances.id,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
location: services.location,
startsAt: serviceInstances.startsAt,
endsAt: serviceInstances.endsAt,
+34 -6
View File
@@ -1,10 +1,15 @@
/**
* 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.
* 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.
*
* NOT safe on a populated database: step 6 deletes every assignment before
* inserting the demo ones, and the demo services collide with real Sunday
* templates. It therefore refuses to run when non-seed users already exist
* unless SEED_FORCE=1 is set. The dev reset route truncates first, so it is
* unaffected.
*
* Run: pnpm db:seed (DATABASE_URL must point at the target DB)
*/
@@ -31,6 +36,16 @@ import { localToUtc, nextSundaysInTz } from "../lib/tz";
const CHURCH_TZ = "America/New_York";
/** Accounts this script owns; anything else means the DB has real data. */
const SEED_EMAILS = new Set([
"admin@glenloch.local",
"coordinator@glenloch.local",
"jordan@glenloch.local",
"avery@glenloch.local",
"sam@glenloch.local",
"riley@glenloch.local",
]);
// Tables the seed owns. Truncating these (and cascading) gives a clean slate
// for E2E resets without touching schema/migration tables.
const RESET_TABLES = [
@@ -60,6 +75,16 @@ const RESET_TABLES = [
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
export async function seed() {
const existingUsers = await db.select({ email: users.email }).from(users);
const foreignUsers = existingUsers.filter((u) => !SEED_EMAILS.has(u.email));
if (foreignUsers.length > 0 && process.env.SEED_FORCE !== "1") {
throw new Error(
`seed: refusing to run on a database with ${foreignUsers.length} non-seed user(s) ` +
`(${foreignUsers.map((u) => u.email).join(", ")}). ` +
"This script rewrites demo services and assignments; set SEED_FORCE=1 only on a throwaway database.",
);
}
/* 1. Roles — production positions (audio, livestream, slides) */
const roleRows: (typeof roles.$inferInsert)[] = [
{
@@ -144,7 +169,7 @@ export async function seed() {
const slotRows: (typeof slots.$inferInsert)[] = [];
for (const inst of instanceRows) {
roleRows2.forEach((role, i) => {
roleRows2.forEach((role) => {
const callTime = role.callTimeOffsetMinutes
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
: null;
@@ -153,7 +178,10 @@ export async function seed() {
serviceInstanceId: inst.id,
eventId: null,
roleId: role.id,
slotIndex: i + 1,
// One seat per role per instance; the app also numbers every role's
// first seat 1, so a different index would insert duplicate seats on
// instances that already exist.
slotIndex: 1,
callTime,
status: "open",
slotNote: null,
+231
View File
@@ -0,0 +1,231 @@
/**
* One-off ("special") services, scheduled from the week view.
*
* A special service is a dated service instance with no recurrence. It reuses
* the normal instance + slot pipeline so assignments, coverage and publishing
* work unchanged, but only the positions the scheduler picked are materialized
* — a Wednesday prayer meeting may need Audio alone, not all three seats.
*
* `service_instances.service_id` is required, so the instances hang off one
* inactive parent template. It never generates instances (it has no rrule) and
* stays out of the active template list; it exists only to satisfy the FK and
* to group one-off services in queries.
*
* When a photographer is picked at scheduling time, a media event for the same
* date and time is created and assigned to them immediately, so the shoot shows
* up in their Events list without a second trip through the Events page.
*/
import { and, eq, inArray } from "drizzle-orm";
import { db } from "@/db";
import {
eventPhotographers,
events,
roles,
serviceInstances,
services,
slots,
users,
} from "@/db/schema";
import { planSlots, type RolePlanInput } from "@/domain/slots";
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
import { uuidv7 } from "@/lib/uuid";
/** Shared parent template for one-off instances; hidden from active services. */
export const SPECIAL_SERVICE_NAME = "Special services (one-off)";
export class SpecialServiceError extends Error {
constructor(
message: string,
readonly status = 400,
) {
super(message);
this.name = "SpecialServiceError";
}
}
export interface SpecialServiceInput {
title: string;
/** Local date, YYYY-MM-DD. */
date: string;
/** Local wall-clock start, HH:MM. */
startTimeLocal: string;
durationMinutes: number;
location?: string | null;
notes?: string | null;
/** Positions (roles) this occurrence needs; may be empty. */
roleIds: string[];
/** Pick a photographer up front to create their media event. */
photographerId?: string | null;
createdBy: string;
}
export interface SpecialServiceResult {
instanceId: string;
eventId: string | null;
seats: number;
}
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
async function getSpecialTemplateId(tx: Tx): Promise<string> {
const [existing] = await tx
.select({ id: services.id })
.from(services)
.where(eq(services.name, SPECIAL_SERVICE_NAME))
.limit(1);
if (existing) return existing.id;
try {
const [row] = await tx
.insert(services)
.values({
id: uuidv7(),
name: SPECIAL_SERVICE_NAME,
timezone: CHURCH_TIMEZONE,
startTimeLocal: "00:00",
durationMinutes: 60,
active: false,
notes:
"Parent for one-off services added from the Schedule. Not a recurring template.",
})
.returning({ id: services.id });
return row!.id;
} catch (error) {
// Another scheduler created the parent in the same instant.
if ((error as { code?: string }).code === "23505") {
const [raced] = await tx
.select({ id: services.id })
.from(services)
.where(eq(services.name, SPECIAL_SERVICE_NAME))
.limit(1);
if (raced) return raced.id;
}
throw error;
}
}
export async function createSpecialService(
input: SpecialServiceInput,
): Promise<SpecialServiceResult> {
if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date)) {
throw new SpecialServiceError("choose a valid date");
}
if (!/^\d{2}:\d{2}$/.test(input.startTimeLocal)) {
throw new SpecialServiceError("choose a valid start time");
}
const startsAt = localToUtc(input.date, input.startTimeLocal, CHURCH_TIMEZONE);
if (Number.isNaN(startsAt.getTime())) {
throw new SpecialServiceError("choose a valid date and time");
}
const endsAt = new Date(
startsAt.getTime() + Math.max(1, input.durationMinutes) * 60_000,
);
const uniqueRoleIds = [...new Set(input.roleIds)];
const roleRows = uniqueRoleIds.length
? await db
.select()
.from(roles)
.where(and(inArray(roles.id, uniqueRoleIds), eq(roles.active, true)))
.orderBy(roles.sortOrder, roles.name)
: [];
if (roleRows.length !== uniqueRoleIds.length) {
throw new SpecialServiceError("one of the selected positions is not active");
}
return db.transaction(async (tx) => {
const serviceId = await getSpecialTemplateId(tx);
const [duplicate] = await tx
.select({ id: serviceInstances.id })
.from(serviceInstances)
.where(
and(
eq(serviceInstances.serviceId, serviceId),
eq(serviceInstances.startsAt, startsAt),
),
)
.limit(1);
if (duplicate) {
throw new SpecialServiceError(
"a special service already exists at that date and time",
409,
);
}
const instanceId = uuidv7();
await tx.insert(serviceInstances).values({
id: instanceId,
serviceId,
occursOn: localToUtc(input.date, "00:00", CHURCH_TIMEZONE),
startsAt,
endsAt,
isSpecial: true,
titleOverride: input.title,
status: "draft",
notes: input.notes ?? null,
});
const plan: RolePlanInput[] = roleRows.map((role) => ({
id: role.id,
callTimeOffsetMinutes: role.callTimeOffsetMinutes,
defaultHeadcount: role.defaultHeadcount,
}));
let seats = 0;
for (const seat of planSlots(startsAt, plan)) {
await tx.insert(slots).values({
id: uuidv7(),
serviceInstanceId: instanceId,
eventId: null,
roleId: seat.roleId,
slotIndex: seat.slotIndex,
callTime: seat.callTime,
status: "open",
});
seats++;
}
let eventId: string | null = null;
if (input.photographerId) {
const [person] = await tx
.select({ id: users.id })
.from(users)
.where(
and(
eq(users.id, input.photographerId),
eq(users.status, "active"),
),
)
.limit(1);
if (!person) {
throw new SpecialServiceError(
"that photographer is not an active team member",
);
}
eventId = uuidv7();
await tx.insert(events).values({
id: eventId,
title: input.title,
eventType: "special service",
startsAt,
endsAt,
location: input.location ?? null,
description: "Photo coverage for this special service.",
createdBy: input.createdBy,
createdAt: new Date(),
});
await tx.insert(eventPhotographers).values({
eventId,
userId: input.photographerId,
role: "photographer",
assignedBy: input.createdBy,
assignedAt: new Date(),
});
}
return { instanceId, eventId, seats };
});
}
+2 -2
View File
@@ -55,7 +55,7 @@ function serveSelect() {
slotId: slots.id,
instanceId: serviceInstances.id,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
status: assignments.status,
occursOn: serviceInstances.occursOn,
startsAt: serviceInstances.startsAt,
@@ -248,7 +248,7 @@ export async function calendarFeedForUser(
.select({
id: assignments.id,
roleName: roles.name,
serviceName: services.name,
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
startsAt: serviceInstances.startsAt,
endsAt: serviceInstances.endsAt,
callTime: slots.callTime,