Compare commits
6 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b42700a943 | |||
| f71952f838 | |||
| ade21425d4 | |||
| aaa3fd9ed1 | |||
| 7bad1e8293 | |||
| f75178de69 |
+1
-1
@@ -29,7 +29,7 @@ RUN pnpm build
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
FROM builder AS tools
|
FROM builder AS tools
|
||||||
ENV NODE_ENV=development
|
ENV NODE_ENV=development
|
||||||
CMD ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
|
CMD ["pnpm", "db:migrate"]
|
||||||
|
|
||||||
FROM base AS runner
|
FROM base AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
+5
-2
@@ -159,14 +159,17 @@ services:
|
|||||||
retries: 10
|
retries: 10
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# One-shot migrations + seed. Run on demand:
|
# One-shot migrations. Run on demand:
|
||||||
# docker compose --profile tools run --rm migrate
|
# 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:
|
migrate:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
target: tools
|
target: tools
|
||||||
command: ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
|
command: ["pnpm", "db:migrate"]
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media}
|
DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media}
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -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} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { NextRequest } from "next/server";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { approveUser } from "@/auth/invites";
|
import { approveUser } from "@/auth/invites";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { getUserById } from "@/db/users";
|
import { getUserById } from "@/db/users";
|
||||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||||
|
|
||||||
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
const approved = await getUserById(user.id);
|
const approved = await getUserById(user.id);
|
||||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||||
if (approved) {
|
if (approved) {
|
||||||
const token = await signMagicToken(approved.email);
|
const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -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");
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { validateUsername } from "@/auth/password";
|
import { validateUsername } from "@/auth/password";
|
||||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
@@ -128,8 +133,9 @@ export const POST = async (req: NextRequest) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||||
// link only works once the account is active.
|
// link only works once the account is active. It is an invite, not a
|
||||||
const token = await signMagicToken(user.email);
|
// just-requested sign-in, so it gets the invite lifetime.
|
||||||
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import { useState } from "react";
|
import { useEffect, useState } from "react";
|
||||||
import { signIn } from "next-auth/react";
|
import { signIn } from "next-auth/react";
|
||||||
import {
|
import {
|
||||||
Card,
|
Card,
|
||||||
@@ -27,11 +27,27 @@ export function LoginForm({ magicLinkEnabled }: { magicLinkEnabled: boolean }) {
|
|||||||
}>({ kind: "idle" });
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
const [email, setEmail] = useState("");
|
const [email, setEmail] = useState("");
|
||||||
|
const [linkNotice, setLinkNotice] = useState<string | null>(null);
|
||||||
const [linkStatus, setLinkStatus] = useState<{
|
const [linkStatus, setLinkStatus] = useState<{
|
||||||
kind: "idle" | "sending" | "sent" | "error";
|
kind: "idle" | "sending" | "sent" | "error";
|
||||||
message?: string;
|
message?: string;
|
||||||
}>({ kind: "idle" });
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
|
// /api/dev/complete redirects here when a link is dead. Say why, instead of
|
||||||
|
// dropping people on a bare sign-in form after the link fails.
|
||||||
|
useEffect(() => {
|
||||||
|
const error = new URLSearchParams(window.location.search).get("error");
|
||||||
|
if (error === "invalid_link") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has expired or is invalid. Ask a media team admin for a new one.",
|
||||||
|
);
|
||||||
|
} else if (error === "link_used") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has already been used. Ask a media team admin for a new one.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
async function onPasswordSubmit(e: React.FormEvent) {
|
async function onPasswordSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setPasswordStatus({ kind: "signing" });
|
setPasswordStatus({ kind: "signing" });
|
||||||
@@ -99,6 +115,11 @@ export function LoginForm({ magicLinkEnabled }: { magicLinkEnabled: boolean }) {
|
|||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-5">
|
<CardContent className="space-y-5">
|
||||||
|
{linkNotice && (
|
||||||
|
<p role="alert" className="rounded border border-border bg-muted p-3 text-sm">
|
||||||
|
{linkNotice}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
||||||
<div className="flex flex-col gap-2">
|
<div className="flex flex-col gap-2">
|
||||||
<Label htmlFor="login">Username or email</Label>
|
<Label htmlFor="login">Username or email</Label>
|
||||||
|
|||||||
+8
-2
@@ -18,7 +18,13 @@ import { db } from "@/db";
|
|||||||
import { users } from "@/db/schema";
|
import { users } from "@/db/schema";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
getUser,
|
||||||
|
normalizeEmail,
|
||||||
|
signMagicToken,
|
||||||
|
} from "./magic-link";
|
||||||
import type { UserStatus } from "@/db/schema";
|
import type { UserStatus } from "@/db/schema";
|
||||||
|
|
||||||
export type UserAction = "invite" | "approve" | "deny";
|
export type UserAction = "invite" | "approve" | "deny";
|
||||||
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
|
|||||||
appOrigin?: string;
|
appOrigin?: string;
|
||||||
}) {
|
}) {
|
||||||
const user = await resolveOrCreateInvitee(input.email);
|
const user = await resolveOrCreateInvitee(input.email);
|
||||||
const token = await signMagicToken(user.email);
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = input.appOrigin ?? APP_ORIGIN;
|
const origin = input.appOrigin ?? APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,10 +1,25 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { requestOrigin } from "./magic-link";
|
import { decodeJwt } from "jose";
|
||||||
|
import { INVITE_LINK_TTL, requestOrigin, signMagicToken } from "./magic-link";
|
||||||
|
|
||||||
function req(url: string, headers: Record<string, string>) {
|
function req(url: string, headers: Record<string, string>) {
|
||||||
return { url, headers: new Headers(headers) };
|
return { url, headers: new Headers(headers) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe("magic token lifetimes", () => {
|
||||||
|
it("keeps a just-requested sign-in link short", async () => {
|
||||||
|
const payload = decodeJwt(await signMagicToken("person@example.com"));
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(10 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an invite link survive days in an inbox", async () => {
|
||||||
|
const payload = decodeJwt(
|
||||||
|
await signMagicToken("person@example.com", INVITE_LINK_TTL),
|
||||||
|
);
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(7 * 24 * 60 * 60);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("requestOrigin", () => {
|
describe("requestOrigin", () => {
|
||||||
it("uses the proxy's forwarded scheme and host", () => {
|
it("uses the proxy's forwarded scheme and host", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
+13
-2
@@ -228,7 +228,18 @@ export async function getOrCreateUser(email: string) {
|
|||||||
return raced;
|
return raced;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function signMagicToken(email: string): Promise<string> {
|
/**
|
||||||
|
* Sign-in links are short-lived because they are requested and clicked in the
|
||||||
|
* same sitting. Invites and welcome mails are not: they land in an inbox and may
|
||||||
|
* be opened days later, so they get their own lifetime (still single use).
|
||||||
|
*/
|
||||||
|
export const SIGN_IN_LINK_TTL = "10m";
|
||||||
|
export const INVITE_LINK_TTL = "7d";
|
||||||
|
|
||||||
|
export async function signMagicToken(
|
||||||
|
email: string,
|
||||||
|
ttl: string = SIGN_IN_LINK_TTL,
|
||||||
|
): Promise<string> {
|
||||||
return new SignJWT({
|
return new SignJWT({
|
||||||
email,
|
email,
|
||||||
purpose: "magic-link",
|
purpose: "magic-link",
|
||||||
@@ -236,7 +247,7 @@ export async function signMagicToken(email: string): Promise<string> {
|
|||||||
.setProtectedHeader({ alg: "HS256" })
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
.setJti(uuidv7())
|
.setJti(uuidv7())
|
||||||
.setIssuedAt()
|
.setIssuedAt()
|
||||||
.setExpirationTime("10m")
|
.setExpirationTime(ttl)
|
||||||
.sign(SECRET);
|
.sign(SECRET);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
@@ -105,7 +105,7 @@ export async function listPendingCoverageRequests(): Promise<
|
|||||||
assignmentId: coverageRequests.assignmentId,
|
assignmentId: coverageRequests.assignmentId,
|
||||||
slotId: slots.id,
|
slotId: slots.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
@@ -386,7 +386,7 @@ export async function listPendingAlternativeProposals(): Promise<
|
|||||||
requesterName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
requesterName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||||
requesterEmail: users.email,
|
requesterEmail: users.email,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
currentStartsAt: serviceInstances.startsAt,
|
currentStartsAt: serviceInstances.startsAt,
|
||||||
proposedStartsAt: proposedInstance.startsAt,
|
proposedStartsAt: proposedInstance.startsAt,
|
||||||
note: assignmentProposals.note,
|
note: assignmentProposals.note,
|
||||||
|
|||||||
+2
-2
@@ -37,7 +37,7 @@ export async function scheduleExportRows(
|
|||||||
return db
|
return db
|
||||||
.select({
|
.select({
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
@@ -103,7 +103,7 @@ export async function servingHistoryCsv(userId?: string): Promise<string> {
|
|||||||
const rows = await db
|
const rows = await db
|
||||||
.select({
|
.select({
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||||
email: users.email,
|
email: users.email,
|
||||||
|
|||||||
+1
-1
@@ -162,7 +162,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
|
|||||||
instance = {
|
instance = {
|
||||||
id: row.instanceId,
|
id: row.instanceId,
|
||||||
serviceId: row.serviceId,
|
serviceId: row.serviceId,
|
||||||
serviceName: row.serviceName,
|
serviceName: row.titleOverride ?? row.serviceName,
|
||||||
occursOn: occursOnISO(row.occursOn),
|
occursOn: occursOnISO(row.occursOn),
|
||||||
startsAt: row.startsAt ?? new Date(0),
|
startsAt: row.startsAt ?? new Date(0),
|
||||||
titleOverride: row.titleOverride ?? null,
|
titleOverride: row.titleOverride ?? null,
|
||||||
|
|||||||
+2
-2
@@ -66,7 +66,7 @@ export async function enqueuePublishNotifications(
|
|||||||
displayName: users.displayName,
|
displayName: users.displayName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
@@ -242,7 +242,7 @@ export async function enqueueAssignmentProposed(
|
|||||||
firstName: users.firstName,
|
firstName: users.firstName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export async function rankedCandidatesForSlot(
|
|||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
isTraineeSlot: slots.isTraineeSlot,
|
isTraineeSlot: slots.isTraineeSlot,
|
||||||
serviceInstanceId: slots.serviceInstanceId,
|
serviceInstanceId: slots.serviceInstanceId,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
|
|||||||
+2
-2
@@ -10,7 +10,7 @@
|
|||||||
* so republishing or a retry cannot double-book a reminder.
|
* 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 { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
@@ -158,7 +158,7 @@ export async function enqueueRemindersForInstance(
|
|||||||
firstName: users.firstName,
|
firstName: users.firstName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
})
|
})
|
||||||
|
|||||||
+2
-2
@@ -8,7 +8,7 @@
|
|||||||
* and writes the audit row — all in one transaction.
|
* 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 { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
@@ -73,7 +73,7 @@ export async function getRespondAssignment(
|
|||||||
displayName: users.displayName,
|
displayName: users.displayName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
|
|||||||
+1
-1
@@ -154,7 +154,7 @@ export async function getRunSheet(
|
|||||||
const [instance] = await db
|
const [instance] = await db
|
||||||
.select({
|
.select({
|
||||||
id: serviceInstances.id,
|
id: serviceInstances.id,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
endsAt: serviceInstances.endsAt,
|
endsAt: serviceInstances.endsAt,
|
||||||
|
|||||||
+34
-6
@@ -1,10 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* Seed script for Media Team Hub (Phase A2).
|
* Seed script for Media Team Hub (Phase A2).
|
||||||
*
|
*
|
||||||
* Idempotent: every insert uses ON CONFLICT DO NOTHING, so it is safe to run
|
* Populates the core scheduling tables with a small, browsable dataset — 3
|
||||||
* repeatedly. Populates the core scheduling tables with a small, browsable
|
* roles, 2 services, the next 2 Sundays of instances, their slots, and a few
|
||||||
* dataset — 3 roles, 2 services, the next 2 Sundays of instances, their slots,
|
* volunteers assigned to 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)
|
* 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";
|
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
|
// Tables the seed owns. Truncating these (and cascading) gives a clean slate
|
||||||
// for E2E resets without touching schema/migration tables.
|
// for E2E resets without touching schema/migration tables.
|
||||||
const RESET_TABLES = [
|
const RESET_TABLES = [
|
||||||
@@ -60,6 +75,16 @@ const RESET_TABLES = [
|
|||||||
|
|
||||||
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
||||||
export async function seed() {
|
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) */
|
/* 1. Roles — production positions (audio, livestream, slides) */
|
||||||
const roleRows: (typeof roles.$inferInsert)[] = [
|
const roleRows: (typeof roles.$inferInsert)[] = [
|
||||||
{
|
{
|
||||||
@@ -144,7 +169,7 @@ export async function seed() {
|
|||||||
|
|
||||||
const slotRows: (typeof slots.$inferInsert)[] = [];
|
const slotRows: (typeof slots.$inferInsert)[] = [];
|
||||||
for (const inst of instanceRows) {
|
for (const inst of instanceRows) {
|
||||||
roleRows2.forEach((role, i) => {
|
roleRows2.forEach((role) => {
|
||||||
const callTime = role.callTimeOffsetMinutes
|
const callTime = role.callTimeOffsetMinutes
|
||||||
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
|
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
|
||||||
: null;
|
: null;
|
||||||
@@ -153,7 +178,10 @@ export async function seed() {
|
|||||||
serviceInstanceId: inst.id,
|
serviceInstanceId: inst.id,
|
||||||
eventId: null,
|
eventId: null,
|
||||||
roleId: role.id,
|
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,
|
callTime,
|
||||||
status: "open",
|
status: "open",
|
||||||
slotNote: null,
|
slotNote: null,
|
||||||
|
|||||||
@@ -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
@@ -55,7 +55,7 @@ function serveSelect() {
|
|||||||
slotId: slots.id,
|
slotId: slots.id,
|
||||||
instanceId: serviceInstances.id,
|
instanceId: serviceInstances.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
status: assignments.status,
|
status: assignments.status,
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
@@ -248,7 +248,7 @@ export async function calendarFeedForUser(
|
|||||||
.select({
|
.select({
|
||||||
id: assignments.id,
|
id: assignments.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
endsAt: serviceInstances.endsAt,
|
endsAt: serviceInstances.endsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ export async function sendWelcomeEmail(
|
|||||||
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<p style="font-size: 12px; color: #6b7280;">
|
||||||
The link expires in 10 minutes and works once. If it has expired, open the
|
The link expires in 7 days and works once. If it has expired, open the
|
||||||
sign-in page and request a fresh link with this email address. After
|
sign-in page and request a fresh link with this email address. After
|
||||||
signing in you can set a password from your profile.
|
signing in you can set a password from your profile.
|
||||||
</p>
|
</p>
|
||||||
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
|
|||||||
`Sign in: ${user.email}`,
|
`Sign in: ${user.email}`,
|
||||||
`Username: ${user.username || user.email}`,
|
`Username: ${user.username || user.email}`,
|
||||||
"",
|
"",
|
||||||
`Open this link to sign in (expires in 10 minutes, single use):`,
|
`Open this link to sign in (expires in 7 days, single use):`,
|
||||||
url,
|
url,
|
||||||
"",
|
"",
|
||||||
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
||||||
|
|||||||
Reference in New Issue
Block a user