diff --git a/src/app/(app)/admin/page.tsx b/src/app/(app)/admin/page.tsx index f48197d..e624892 100644 --- a/src/app/(app)/admin/page.tsx +++ b/src/app/(app)/admin/page.tsx @@ -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() { ({ + 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, diff --git a/src/app/(app)/schedule/page.tsx b/src/app/(app)/schedule/page.tsx index 340b1d0..409dfd3 100644 --- a/src/app/(app)/schedule/page.tsx +++ b/src/app/(app)/schedule/page.tsx @@ -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 (
{header} {toggle} + {canEdit && ( + ({ id: role.id, name: role.name }))} + volunteers={volunteers.map((person) => ({ + id: person.id, + displayName: person.displayName, + }))} + defaultDate={weekStart} + /> + )} {canEdit && ( ({ @@ -135,7 +150,7 @@ export default async function SchedulePage({ /> )} {canEdit ? ( - + ) : ( )} diff --git a/src/app/api/dev/schedule/special/route.ts b/src/app/api/dev/schedule/special/route.ts new file mode 100644 index 0000000..52629d4 --- /dev/null +++ b/src/app/api/dev/schedule/special/route.ts @@ -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"); + } +}; diff --git a/src/components/app/special-service-form.tsx b/src/components/app/special-service-form.tsx new file mode 100644 index 0000000..3dd389a --- /dev/null +++ b/src/components/app/special-service-form.tsx @@ -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([]); + const [photographerId, setPhotographerId] = useState(""); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const [message, setMessage] = useState(null); + const [eventId, setEventId] = useState(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 ( +
+
+
+

Special service

+

+ A one-off dated service with only the positions it needs. +

+
+ +
+ + {open && ( +
+
+
+ + setTitle(e.target.value)} + placeholder="Good Friday service" + /> +
+
+ + setDate(e.target.value)} + /> +
+
+ + setStartTime(e.target.value)} + /> +
+
+ + setDuration(e.target.value)} + /> +
+
+ + setLocation(e.target.value)} + placeholder="Main Auditorium" + /> +
+
+ +
+ + Positions needed + +

+ Only the selected positions get seats. Leave all unchecked if the + service needs no media team. +

+
+ {roles.map((role) => ( + + ))} +
+
+ +
+ + +

+ Creates a media event for this service and assigns them to it. +

+
+ +
+ + {message && ( +

+ {message} + {eventId && ( + <> + {" "} + + Open the event + + + )} +

+ )} + {error && ( +

+ {error} +

+ )} +
+
+ )} +
+ ); +} diff --git a/src/db/specials.ts b/src/db/specials.ts new file mode 100644 index 0000000..4b9d500 --- /dev/null +++ b/src/db/specials.ts @@ -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[0]>[0]; + +async function getSpecialTemplateId(tx: Tx): Promise { + 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 { + 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 }; + }); +}