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>
This commit is contained in:
2026-11-22 18:08:59 +00:00
parent 7bad1e8293
commit aaa3fd9ed1
5 changed files with 565 additions and 2 deletions
+5 -1
View File
@@ -6,6 +6,7 @@ import { listUsersForAdmin } from "@/db/users";
import { listSkillsMatrix } from "@/db/assessments"; import { listSkillsMatrix } from "@/db/assessments";
import { getPositionSkills, listPositions, listSkills } from "@/db/positions"; import { getPositionSkills, listPositions, listSkills } from "@/db/positions";
import { listServices } from "@/db/services"; import { listServices } from "@/db/services";
import { SPECIAL_SERVICE_NAME } from "@/db/specials";
import { listNotifications } from "@/db/outbox"; import { listNotifications } from "@/db/outbox";
import { listRules } from "@/db/reminders"; import { listRules } from "@/db/reminders";
import { getEmailSettings } from "@/db/settings"; import { getEmailSettings } from "@/db/settings";
@@ -270,7 +271,10 @@ export default async function AdminPage() {
</CardHeader> </CardHeader>
<CardContent> <CardContent>
<ServicesPanel <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, id: service.id,
name: service.name, name: service.name,
startTimeLocal: service.startTimeLocal, 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 { ScheduleAdminBar } from "@/components/app/schedule-admin-bar";
import { ScheduleGrid } from "@/components/app/schedule-grid"; import { ScheduleGrid } from "@/components/app/schedule-grid";
import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor"; import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor";
import { SpecialServiceForm } from "@/components/app/special-service-form";
import { listPositions } from "@/db/positions";
import { import {
MonthNav, MonthNav,
ScheduleViewToggle, ScheduleViewToggle,
@@ -119,12 +121,25 @@ export default async function SchedulePage({
} }
const week = await gridForWeek(weekStart); const week = await gridForWeek(weekStart);
const [roles, volunteers] = canEdit
? await Promise.all([listPositions({ active: true }), activeVolunteers(db)])
: [[], []];
return ( return (
<div className="space-y-4"> <div className="space-y-4">
{header} {header}
{toggle} {toggle}
<WeekNav weekStart={weekStart} /> <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 && ( {canEdit && (
<ScheduleAdminBar <ScheduleAdminBar
instances={week.instances.map((inst) => ({ instances={week.instances.map((inst) => ({
@@ -135,7 +150,7 @@ export default async function SchedulePage({
/> />
)} )}
{canEdit ? ( {canEdit ? (
<ScheduleGridEditor week={week} volunteers={await activeVolunteers(db)} /> <ScheduleGridEditor week={week} volunteers={volunteers} />
) : ( ) : (
<ScheduleGrid week={week} /> <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>
);
}
+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 };
});
}