From 5298019d1ffeec4d0c2565e7ff523b72e5216f05 Mon Sep 17 00:00:00 2001 From: Mew Date: Sun, 29 Nov 2026 01:20:27 -0800 Subject: [PATCH 1/3] feat: yearly forms engine, VIS first (#844) Mew 2026-11-27/29: forms are authored in the app, each year independent, draft -> leadership review (preview) -> publish. - migration 032: op_forms (questions as JSON, one row per slug+year) and op_form_responses, both system-versioned with changed_by; FormEditor role - /forms list (admins), editor (SuperAdmin / FormEditor), fill page, answers page: per-question totals, filter by answer, CSV, tick people then Add role (never automatic) - question types: short/long answer, pick one, pick any, yes/no, 1-5, ranking, text-only block; "Other: ___" on pick one / pick any - every open form is a checklist item; answers editable until it closes; a new year's draft copies the latest earlier year's questions Co-Authored-By: Claude Opus 5.5 --- client/e2e/helpers/actorGuard.ts | 2 + client/e2e/tests/39-forms.spec.ts | 226 ++++++++++++ client/src/app/forms/Forms.tsx | 190 ++++++++++ client/src/app/forms/[formId]/FormFill.tsx | 312 ++++++++++++++++ .../forms/[formId]/answers/FormAnswers.tsx | 332 ++++++++++++++++++ .../src/app/forms/[formId]/answers/page.tsx | 17 + .../src/app/forms/[formId]/edit/FormEdit.tsx | 297 ++++++++++++++++ client/src/app/forms/[formId]/edit/page.tsx | 17 + client/src/app/forms/[formId]/page.tsx | 17 + client/src/app/forms/page.tsx | 14 + .../[shiftboardId]/info/VolunteerInfo.tsx | 37 ++ client/src/components/layout/pageList.tsx | 7 + client/src/constants.ts | 1 + client/src/lib/authz.ts | 14 +- client/src/lib/forms.ts | 120 +++++++ client/src/lib/formsDb.ts | 38 ++ client/src/pages/api/forms/[formId]/index.ts | 145 ++++++++ .../src/pages/api/forms/[formId]/responses.ts | 41 +++ client/src/pages/api/forms/index.ts | 98 ++++++ client/src/utils/checkIsRoleExist.ts | 8 + migrations/032_forms.sql | 36 ++ 21 files changed, 1968 insertions(+), 1 deletion(-) create mode 100644 client/e2e/tests/39-forms.spec.ts create mode 100644 client/src/app/forms/Forms.tsx create mode 100644 client/src/app/forms/[formId]/FormFill.tsx create mode 100644 client/src/app/forms/[formId]/answers/FormAnswers.tsx create mode 100644 client/src/app/forms/[formId]/answers/page.tsx create mode 100644 client/src/app/forms/[formId]/edit/FormEdit.tsx create mode 100644 client/src/app/forms/[formId]/edit/page.tsx create mode 100644 client/src/app/forms/[formId]/page.tsx create mode 100644 client/src/app/forms/page.tsx create mode 100644 client/src/lib/forms.ts create mode 100644 client/src/lib/formsDb.ts create mode 100644 client/src/pages/api/forms/[formId]/index.ts create mode 100644 client/src/pages/api/forms/[formId]/responses.ts create mode 100644 client/src/pages/api/forms/index.ts create mode 100644 migrations/032_forms.sql diff --git a/client/e2e/helpers/actorGuard.ts b/client/e2e/helpers/actorGuard.ts index 32672d5d..29f93c8d 100644 --- a/client/e2e/helpers/actorGuard.ts +++ b/client/e2e/helpers/actorGuard.ts @@ -6,6 +6,8 @@ import path from "node:path"; // (covers pool.query, execute and transaction connections alike). export const VERSIONED = [ "op_dates", + "op_form_responses", + "op_forms", "op_position_trainings", "op_position_type", "op_qr_codes", diff --git a/client/e2e/tests/39-forms.spec.ts b/client/e2e/tests/39-forms.spec.ts new file mode 100644 index 00000000..aebcc119 --- /dev/null +++ b/client/e2e/tests/39-forms.spec.ts @@ -0,0 +1,226 @@ +import { test, expect } from "@playwright/test"; + +import { + assignRole, + cleanupAllTestData, + closePool, + getPool, + insertVolunteer, +} from "../helpers/db"; +import { buildSessionCookieHeader } from "../helpers/session"; +import { + makeTestVolunteer, + ROLE_ADMIN_ID, + signInAs, + ROLE_BEHAVIORAL_STANDARDS_ID, +} from "../fixtures/test-data"; + +// #844: yearly forms authored in the app. Draft → publish; volunteers answer +// while it's open; FormEditor edits; admins see the answers. +const ROLE_FORM_EDITOR_ID = 2000044; +const SLUG = "e2e-vis"; +const editor = makeTestVolunteer({ + shiftboardId: 9_000_520, + playaName: "E2E Form Editor", + worldName: "Form Editor", + email: "e2e-form-editor@test.local", + passcode: "5200", +}); +const volunteer = makeTestVolunteer({ + shiftboardId: 9_000_521, + playaName: "E2E Form Filler", + worldName: "Form Filler", + email: "e2e-form-filler@test.local", + passcode: "5210", +}); +const as = (id: number) => ({ Cookie: buildSessionCookieHeader(id) }); +const QUESTIONS = [ + { + id: "plans", + label: "Plans", + options: ["Yes", "No"], + other: true, + required: true, + type: "choice", + }, + { + id: "roles", + label: "Roles", + options: ["Gate", "Lab", ""], + type: "checkboxes", + }, + { id: "rank", label: "Rank", options: ["A", "B", "C"], type: "ranking" }, + { id: "note", label: "Join the list", type: "info" }, + { id: "else", label: "Anything else", type: "textarea" }, +]; +const cleanup = async () => { + const db = getPool(); + await db.execute( + "DELETE r FROM op_form_responses r JOIN op_forms f USING (form_id) WHERE f.slug = ?", + [SLUG] + ); + await db.execute("DELETE FROM op_forms WHERE slug = ?", [SLUG]); +}; + +test.describe("Yearly forms (#844)", () => { + test.beforeAll(async () => { + await cleanupAllTestData(); + await cleanup(); + for (const v of [editor, volunteer]) { + await insertVolunteer(v); + await assignRole(v.shiftboardId, ROLE_BEHAVIORAL_STANDARDS_ID); + } + await assignRole(editor.shiftboardId, ROLE_FORM_EDITOR_ID); + await assignRole(editor.shiftboardId, ROLE_ADMIN_ID); + }); + + test.afterAll(async () => { + await cleanup(); + await cleanupAllTestData(); + await closePool(); + }); + + test("draft → publish → answer → admin sees it", async ({ request }) => { + const create = (who: number, year: number) => + request.post("/api/forms", { + data: JSON.stringify({ slug: SLUG, title: "E2E VIS", year }), + headers: as(who), + }); + expect((await create(volunteer.shiftboardId, 2098)).status()).toBe(403); + const made = await create(editor.shiftboardId, 2098); + expect(made.status()).toBe(201); + const { formId } = await made.json(); + expect((await create(editor.shiftboardId, 2098)).status()).toBe(409); + + const patch = (body: object, who = editor.shiftboardId) => + request.patch(`/api/forms/${formId}`, { + data: JSON.stringify(body), + headers: as(who), + }); + expect( + ( + await patch({ + questions: [ + { id: "x", label: "One", options: ["a"], type: "choice" }, + ], + }) + ).status() + ).toBe(400); + expect( + (await patch({ questions: QUESTIONS }, volunteer.shiftboardId)).status() + ).toBe(403); + expect((await patch({ questions: QUESTIONS })).status()).toBe(200); + + // a draft is hidden from volunteers, visible to the editor (the review) + const get = (who: number) => + request.get(`/api/forms/${formId}`, { headers: as(who) }); + expect((await get(volunteer.shiftboardId)).status()).toBe(404); + const draft = await (await get(editor.shiftboardId)).json(); + expect(draft.form.questions[1].options).toEqual(["Gate", "Lab"]); // blank choice dropped + const open = async () => + ( + await ( + await request.get("/api/forms", { + headers: as(volunteer.shiftboardId), + }) + ).json() + ).find((f: { formId: number }) => f.formId === formId); + expect(await open()).toBeUndefined(); + + expect((await patch({ status: "published" })).status()).toBe(200); + expect((await open())?.submittedAt).toBeNull(); + + const put = (answers: object) => + request.put(`/api/forms/${formId}`, { + data: JSON.stringify({ answers }), + headers: as(volunteer.shiftboardId), + }); + expect((await put({ roles: ["Gate"] })).status()).toBe(400); // required + expect((await put({ plans: "Maybe" })).status()).toBe(400); // not a choice + const saved = await put({ + else: " hi ", + plans: "Other: if I get a ticket", + rank: ["C", "A", "Nope", "B"], + roles: ["Gate", "Bogus"], + }); + expect(saved.status()).toBe(200); + expect((await saved.json()).answers).toEqual({ + else: "hi", + plans: "Other: if I get a ticket", + rank: ["C", "A", "B"], + roles: ["Gate"], + }); + expect((await open())?.submittedAt).toBeTruthy(); + + const answers = (who: number) => + request.get(`/api/forms/${formId}/responses`, { headers: as(who) }); + expect((await answers(volunteer.shiftboardId)).status()).toBe(403); + const rows = await (await answers(editor.shiftboardId)).json(); + expect(rows).toHaveLength(1); + expect(rows[0]).toMatchObject({ + playaName: volunteer.playaName, + shiftboardId: volunteer.shiftboardId, + }); + + // closed: no more changes + expect((await patch({ closesAt: "2000-01-01 00:00" })).status()).toBe(200); + expect((await put({ plans: "Yes" })).status()).toBe(409); + expect(await open()).toBeUndefined(); + + // next year's draft starts from this year's questions + const next = await create(editor.shiftboardId, 2099); + const copy = await ( + await request.get(`/api/forms/${(await next.json()).formId}`, { + headers: as(editor.shiftboardId), + }) + ).json(); + expect(copy.form.status).toBe("draft"); + expect(copy.form.questions.map((q: { id: string }) => q.id)).toEqual( + QUESTIONS.map((q) => q.id) + ); + }); + + test("volunteer fills it in from the checklist", async ({ + page, + request, + }) => { + const made = await request.post("/api/forms", { + data: JSON.stringify({ + slug: SLUG, + title: "E2E Checklist Form", + year: 2097, + }), + headers: as(editor.shiftboardId), + }); + const { formId } = await made.json(); + await request.patch(`/api/forms/${formId}`, { + data: JSON.stringify({ questions: QUESTIONS, status: "published" }), + headers: as(editor.shiftboardId), + }); + + await signInAs(page, volunteer); + await page + .getByRole("link", { name: "Fill in E2E Checklist Form" }) + .click(); + await page.waitForURL(`**/forms/${formId}`); + await page.getByRole("radio", { name: "Other:" }).check(); + await page.getByRole("textbox", { name: "Plans: other" }).fill("depends"); + await page.getByRole("checkbox", { name: "Lab" }).check(); + await page.getByRole("button", { name: "Move B up" }).click(); + await page.getByRole("button", { name: "Submit" }).click(); + await expect( + page.getByText("Thanks, your answers are saved.") + ).toBeVisible(); + + const [rows] = await getPool().query( + "SELECT answers FROM op_form_responses WHERE form_id = ? AND shiftboard_id = ?", + [formId, volunteer.shiftboardId] + ); + const saved = (rows as { answers: string }[])[0].answers; + expect(JSON.parse(saved)).toEqual({ + plans: "Other: depends", + rank: ["B", "A", "C"], + roles: ["Lab"], + }); + }); +}); diff --git a/client/src/app/forms/Forms.tsx b/client/src/app/forms/Forms.tsx new file mode 100644 index 00000000..20fd5fbf --- /dev/null +++ b/client/src/app/forms/Forms.tsx @@ -0,0 +1,190 @@ +"use client"; + +import { + Button, + Card, + CardContent, + Container, + Stack, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography, +} from "@mui/material"; +import Link from "next/link"; +import { useRouter } from "next/navigation"; +import { useSnackbar } from "notistack"; +import { useContext, useState } from "react"; +import useSWR from "swr"; + +import { ErrorPage } from "@/components/general/ErrorPage"; +import { Loading } from "@/components/general/Loading"; +import { SnackbarText } from "@/components/general/SnackbarText"; +import { Hero } from "@/components/layout/Hero"; +import type { IForm } from "@/lib/forms"; +import { DeveloperModeContext } from "@/state/developer-mode/context"; +import { SessionContext } from "@/state/session/context"; +import { checkIsFormEditor } from "@/utils/checkIsRoleExist"; +import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; + +// /forms (#844): every yearly form. Admins preview drafts (the leadership +// review) and see answers; SuperAdmins and FormEditors also create and edit. +export const Forms = () => { + const { + developerModeState: { accountType }, + } = useContext(DeveloperModeContext); + const { + sessionState: { + user: { roleList }, + }, + } = useContext(SessionContext); + const isEditor = checkIsFormEditor(accountType, roleList); + const { data, error } = useSWR("/api/forms?all=1", fetcherGet); + const router = useRouter(); + const { enqueueSnackbar } = useSnackbar(); + const [draft, setDraft] = useState({ + slug: "vis", + title: "Volunteer Interest Survey", + year: String(new Date().getFullYear() + 1), + }); + + if (error) return ; + if (!data) return ; + + const create = async () => { + try { + const { formId } = await fetcherTrigger("/api/forms", { + arg: { body: { ...draft, year: Number(draft.year) }, method: "POST" }, + }); + router.push(`/forms/${formId}/edit`); + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + variant: "error", + }); + } + }; + const when = (f: IForm) => + [ + f.opensAt && `opens ${f.opensAt.slice(0, 16)}`, + f.closesAt && `closes ${f.closesAt.slice(0, 16)}`, + ] + .filter(Boolean) + .join(", ") || "no dates"; + + return ( + <> + + + + + + Year + Form + Status + + + + + {data.map((f) => ( + + {f.year} + {f.title} + + {f.status === "draft" + ? "Draft" + : f.isOpen + ? "Open" + : "Published, not open"} + + {when(f)} + + + + + + {isEditor && ( + + )} + + + + + ))} + {!data.length && ( + + No forms yet. + + )} + +
+ {isEditor && ( + + + + New form + + + Starts as a draft. If there's an earlier year with the same + short name, its questions are copied in. + + + setDraft({ ...draft, slug: e.target.value })} + size="small" + value={draft.slug} + /> + setDraft({ ...draft, year: e.target.value })} + size="small" + type="number" + value={draft.year} + /> + + setDraft({ ...draft, title: e.target.value }) + } + size="small" + value={draft.title} + /> + + + + + )} +
+ + ); +}; diff --git a/client/src/app/forms/[formId]/FormFill.tsx b/client/src/app/forms/[formId]/FormFill.tsx new file mode 100644 index 00000000..0e29d307 --- /dev/null +++ b/client/src/app/forms/[formId]/FormFill.tsx @@ -0,0 +1,312 @@ +"use client"; + +import { + ArrowDownward as ArrowDownwardIcon, + ArrowUpward as ArrowUpwardIcon, +} from "@mui/icons-material"; +import { + Alert, + Button, + Checkbox, + Container, + FormControl, + FormControlLabel, + FormGroup, + FormLabel, + IconButton, + List, + ListItem, + ListItemText, + Radio, + RadioGroup, + Stack, + TextField, + Typography, +} from "@mui/material"; +import { useSnackbar } from "notistack"; +import { useEffect, useState } from "react"; +import useSWR from "swr"; + +import { ErrorPage } from "@/components/general/ErrorPage"; +import { ContentHtml } from "@/components/general/FormattedText"; +import { Loading } from "@/components/general/Loading"; +import { SnackbarText } from "@/components/general/SnackbarText"; +import { Hero } from "@/components/layout/Hero"; +import { + choicesOf, + type FormAnswers, + type IForm, + type IFormQuestion, + OTHER, +} from "@/lib/forms"; +import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; + +const Question = ({ + onChange, + q, + value, +}: { + onChange: (v: string | string[]) => void; + q: IFormQuestion; + value: string | string[] | undefined; +}) => { + const choices = choicesOf(q); + const label = `${q.label}${q.required ? " *" : ""}`; + if (q.type === "info") + return ( + <> + + {q.label} + + {q.help && ( + + {q.help} + + )} + + ); + if (!choices) + return ( + onChange(e.target.value)} + value={value ?? ""} + /> + ); + const picked = Array.isArray(value) ? value : []; + // "Other: ___": the typed text rides in the answer after OTHER + const otherOf = (v: string | undefined) => + v?.startsWith(OTHER) ? v.slice(OTHER.length) : undefined; + const pickedOther = picked.map(otherOf).find((x) => x !== undefined); + const single = typeof value === "string" ? value : ""; + const order = picked.length ? picked : choices; + return ( + + + {label} + + {q.help && ( + + {q.help} + + )} + {q.type === "ranking" ? ( + + {order.map((c, i) => ( + + { + const next = [...order]; + [next[i - 1], next[i]] = [next[i], next[i - 1]]; + onChange(next); + }} + > + + + { + const next = [...order]; + [next[i + 1], next[i]] = [next[i], next[i + 1]]; + onChange(next); + }} + > + + + + } + > + + + ))} + {!picked.length && ( + + )} + + ) : q.type === "checkboxes" ? ( + + {choices.map((c) => ( + + onChange( + e.target.checked + ? [...picked, c] + : picked.filter((x) => x !== c) + ) + } + /> + } + key={c} + label={c} + /> + ))} + {q.other && ( + + + onChange( + e.target.checked + ? [...picked, OTHER] + : picked.filter((x) => otherOf(x) === undefined) + ) + } + /> + } + label="Other:" + /> + + onChange([ + ...picked.filter((x) => otherOf(x) === undefined), + OTHER + e.target.value, + ]) + } + size="small" + value={pickedOther ?? ""} + variant="standard" + /> + + )} + + ) : ( + onChange(e.target.value)} + row={q.type !== "choice"} + value={otherOf(single) !== undefined ? OTHER : single} + > + {choices.map((c) => ( + } key={c} label={c} value={c} /> + ))} + {q.other && ( + + } + label="Other:" + value={OTHER} + /> + onChange(OTHER + e.target.value)} + size="small" + value={otherOf(single) ?? ""} + variant="standard" + /> + + )} + + )} + + ); +}; + +// /forms/[formId] (#844): a volunteer fills in a yearly form. Signed-in only, +// so no identity questions. Answers can be changed until the form closes. +// Admins can open a draft here to review it; saving is off until it's open. +export const FormFill = ({ formId }: { formId: number }) => { + const { data, error, mutate } = useSWR<{ + answers: FormAnswers | null; + form: IForm; + }>(`/api/forms/${formId}`, fetcherGet); + const { enqueueSnackbar } = useSnackbar(); + const [answers, setAnswers] = useState({}); + const [isSaving, setIsSaving] = useState(false); + useEffect(() => { + if (data?.answers) setAnswers(data.answers); + }, [data?.answers]); + + if (error) return ; + if (!data) return ; + const { form } = data; + + const save = async () => { + setIsSaving(true); + try { + await fetcherTrigger(`/api/forms/${formId}`, { + arg: { body: { answers }, method: "PUT" }, + }); + await mutate(); + enqueueSnackbar( + Thanks, your answers are saved., + { + variant: "success", + } + ); + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + variant: "error", + }); + } finally { + setIsSaving(false); + } + }; + + return ( + <> + + + {form.status === "draft" && ( + + Draft preview: volunteers can't see this yet. + + )} + {form.status === "published" && !form.isOpen && ( + + This form isn't open right now. + + )} + {data.answers && form.isOpen && ( + + You've filled this in. You can change your answers until it + closes{form.closesAt ? ` (${form.closesAt.slice(0, 10)})` : ""}. + + )} + {form.intro && ( + + + + )} + {form.questions.map((q) => ( + + setAnswers({ ...answers, [q.id]: v })} + q={q} + value={answers[q.id]} + /> + + ))} + + + + ); +}; diff --git a/client/src/app/forms/[formId]/answers/FormAnswers.tsx b/client/src/app/forms/[formId]/answers/FormAnswers.tsx new file mode 100644 index 00000000..2c1408bc --- /dev/null +++ b/client/src/app/forms/[formId]/answers/FormAnswers.tsx @@ -0,0 +1,332 @@ +"use client"; + +import { + Box, + Button, + Card, + CardContent, + Checkbox, + Container, + LinearProgress, + MenuItem, + Stack, + Table, + TableBody, + TableCell, + TableHead, + TableRow, + TextField, + Typography, +} from "@mui/material"; +import Link from "next/link"; +import { useSnackbar } from "notistack"; +import { useMemo, useState } from "react"; +import useSWR from "swr"; + +import { ErrorPage } from "@/components/general/ErrorPage"; +import { Loading } from "@/components/general/Loading"; +import { SnackbarText } from "@/components/general/SnackbarText"; +import { Hero } from "@/components/layout/Hero"; +import type { IResRoleRowItem } from "@/components/types/roles"; +import { + choicesOf, + type FormAnswers as Answers, + type IForm, + OTHER, +} from "@/lib/forms"; +import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; + +interface IResponse { + answers: Answers; + playaName: string; + shiftboardId: number; + submittedAt: string; + worldName: string; +} + +const show = (a: Answers[string] | undefined) => + Array.isArray(a) ? a.join("; ") : (a ?? ""); +// does answer a count for choice c? ranking: c ranked first; OTHER: any "Other: …" +const matches = ( + type: string | undefined, + a: Answers[string] | undefined, + c: string +) => { + const hit = (x: string) => (c === OTHER ? x.startsWith(OTHER) : x === c); + if (type === "ranking") return Array.isArray(a) && a.length > 0 && hit(a[0]); + return Array.isArray(a) ? a.some(hit) : typeof a === "string" && hit(a); +}; +const csvCell = (v: string | number) => `"${String(v).replace(/"/g, '""')}"`; + +// /forms/[formId]/answers (#844), admins: per-question totals, every answer, +// a CSV, and "Add role" for the people ticked (always a person's call, never +// automatic). Filter by an answer to pick, e.g., everyone who said Gate. +export const FormAnswers = ({ formId }: { formId: number }) => { + const { data: formData, error: formError } = useSWR<{ form: IForm }>( + `/api/forms/${formId}`, + fetcherGet + ); + const { data: rows, error: rowsError } = useSWR( + `/api/forms/${formId}/responses`, + fetcherGet + ); + const { data: roles } = useSWR("/api/roles", fetcherGet); + const { enqueueSnackbar } = useSnackbar(); + const [filter, setFilter] = useState({ answer: "", questionId: "" }); + const [picked, setPicked] = useState>(new Set()); + const [roleId, setRoleId] = useState(""); + + const form = formData?.form; + const shown = useMemo( + () => + (rows ?? []).filter((r) => { + if (!filter.questionId || !filter.answer) return true; + const q = form?.questions.find((x) => x.id === filter.questionId); + return matches(q?.type, r.answers[filter.questionId], filter.answer); + }), + [form, rows, filter] + ); + + if (formError || rowsError) return ; + if (!form || !rows) return ; + + const answerable = form.questions.filter((q) => q.type !== "info"); + const name = (r: IResponse) => + r.playaName || r.worldName || `#${r.shiftboardId}`; + const filterQ = form.questions.find((q) => q.id === filter.questionId); + + const downloadCsv = () => { + const head = [ + "shiftboard_id", + "playa_name", + "world_name", + "submitted_at", + ...answerable.map((q) => q.label), + ]; + const lines = [ + head, + ...shown.map((r) => [ + r.shiftboardId, + r.playaName, + r.worldName, + r.submittedAt, + ...answerable.map((q) => show(r.answers[q.id])), + ]), + ]; + const url = URL.createObjectURL( + new Blob([lines.map((l) => l.map(csvCell).join(",")).join("\n")], { + type: "text/csv", + }) + ); + Object.assign(document.createElement("a"), { + download: `${form.slug}-${form.year}-answers.csv`, + href: url, + }).click(); + URL.revokeObjectURL(url); + }; + + const addRole = async () => { + const role = roles?.find((r) => r.id === Number(roleId)); + if (!role) return; + let done = 0; + for (const shiftboardId of picked) { + try { + await fetcherTrigger(`/api/roles/${role.id}/volunteers`, { + arg: { body: { shiftboardId }, method: "POST" }, + }); + done += 1; + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + variant: "error", + }); + } + } + enqueueSnackbar( + + {role.name} added to {done} of {picked.size} + , + { variant: done === picked.size ? "success" : "warning" } + ); + setPicked(new Set()); + }; + + return ( + <> + + + + {rows.length} {rows.length === 1 ? "person has" : "people have"}{" "} + answered. See the form + + + {form.questions.map((q) => { + const choices = choicesOf(q); + if (!choices) return null; + const counts = [...choices, ...(q.other ? [OTHER] : [])].map((c) => ({ + c: c === OTHER ? "Other" : c, + n: rows.filter((r) => matches(q.type, r.answers[q.id], c)).length, + })); + return ( + + + + {q.label} + {q.type === "ranking" && " (ranked first)"} + + {counts.map(({ c, n }) => ( + + + {c} + + {n} + {rows.length + ? ` (${Math.round((100 * n) / rows.length)}%)` + : ""} + + + + + ))} + + + ); + })} + + + + setFilter({ answer: "", questionId: e.target.value }) + } + select + size="small" + sx={{ minWidth: 240 }} + value={filter.questionId} + > + Everyone + {form.questions + .filter((q) => choicesOf(q)) + .map((q) => ( + + {q.label} + + ))} + + {filterQ && ( + setFilter({ ...filter, answer: e.target.value })} + select + size="small" + sx={{ minWidth: 160 }} + value={filter.answer} + > + {[...choicesOf(filterQ)!, ...(filterQ.other ? [OTHER] : [])].map( + (c) => ( + + {c === OTHER ? "Other" : c} + {filterQ.type === "ranking" && " (ranked first)"} + + ) + )} + + )} + + + + + setRoleId(e.target.value)} + select + size="small" + sx={{ minWidth: 220 }} + value={roleId} + > + {(roles ?? []).map((r) => ( + + {r.name} + + ))} + + + + + + + + + + 0 && + shown.every((r) => picked.has(r.shiftboardId)) + } + inputProps={{ "aria-label": "Tick everyone shown" }} + onChange={(e) => + setPicked( + new Set( + e.target.checked + ? shown.map((r) => r.shiftboardId) + : [] + ) + ) + } + /> + + Volunteer + {answerable.map((q) => ( + {q.label} + ))} + + + + {shown.map((r) => ( + + + { + const next = new Set(picked); + if (e.target.checked) next.add(r.shiftboardId); + else next.delete(r.shiftboardId); + setPicked(next); + }} + /> + + + + {name(r)} + + + {answerable.map((q) => ( + {show(r.answers[q.id])} + ))} + + ))} + +
+
+
+ + ); +}; diff --git a/client/src/app/forms/[formId]/answers/page.tsx b/client/src/app/forms/[formId]/answers/page.tsx new file mode 100644 index 00000000..625732ac --- /dev/null +++ b/client/src/app/forms/[formId]/answers/page.tsx @@ -0,0 +1,17 @@ +import { FormAnswers } from "@/app/forms/[formId]/answers/FormAnswers"; +import { AuthGate } from "@/components/general/AuthGate"; +import { ACCOUNT_TYPE_ADMIN } from "@/constants"; + +export const metadata = { + title: "Census | Form answers", +}; +const Page = async ({ params }: { params: Promise<{ formId: string }> }) => { + const { formId } = await params; + return ( + + + + ); +}; + +export default Page; diff --git a/client/src/app/forms/[formId]/edit/FormEdit.tsx b/client/src/app/forms/[formId]/edit/FormEdit.tsx new file mode 100644 index 00000000..68c5774f --- /dev/null +++ b/client/src/app/forms/[formId]/edit/FormEdit.tsx @@ -0,0 +1,297 @@ +"use client"; + +import { + ArrowDownward as ArrowDownwardIcon, + ArrowUpward as ArrowUpwardIcon, + Delete as DeleteIcon, +} from "@mui/icons-material"; +import { + Box, + Button, + Card, + CardContent, + Checkbox, + Container, + FormControlLabel, + IconButton, + MenuItem, + Stack, + TextField, + Typography, +} from "@mui/material"; +import Link from "next/link"; +import { useSnackbar } from "notistack"; +import { useEffect, useState } from "react"; +import useSWR from "swr"; + +import { DescriptionField } from "@/components/content/DescriptionField"; +import { ErrorPage } from "@/components/general/ErrorPage"; +import { Loading } from "@/components/general/Loading"; +import { SnackbarText } from "@/components/general/SnackbarText"; +import { Hero } from "@/components/layout/Hero"; +import { + type IForm, + type IFormQuestion, + QUESTION_TYPES, + type QuestionType, +} from "@/lib/forms"; +import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; + +const newId = () => `q${Date.now().toString(36)}`; +const toInput = (v: string | null) => + v ? v.slice(0, 16).replace(" ", "T") : ""; + +// /forms/[formId]/edit (#844), SuperAdmin / FormEditor (the API enforces it): the form's text, questions, dates +// and status. Draft → admins review it via Preview → Publish. +export const FormEdit = ({ formId }: { formId: number }) => { + const { data, error, mutate } = useSWR<{ form: IForm }>( + `/api/forms/${formId}`, + fetcherGet + ); + const { enqueueSnackbar } = useSnackbar(); + const [form, setForm] = useState(null); + useEffect(() => { + if (data) setForm(data.form); + }, [data]); + + if (error) return ; + if (!form) return ; + + const setQ = (i: number, patch: Partial) => + setForm({ + ...form, + questions: form.questions.map((q, j) => + j === i ? { ...q, ...patch } : q + ), + }); + const move = (i: number, by: number) => { + const qs = [...form.questions]; + [qs[i], qs[i + by]] = [qs[i + by], qs[i]]; + setForm({ ...form, questions: qs }); + }; + const save = async (status = form.status) => { + try { + await fetcherTrigger(`/api/forms/${formId}`, { + arg: { + body: { + closesAt: form.closesAt || null, + intro: form.intro, + opensAt: form.opensAt || null, + questions: form.questions, + status, + title: form.title, + }, + method: "PATCH", + }, + }); + await mutate(); + enqueueSnackbar( + + {status === "published" && form.status === "draft" + ? "Published" + : "Saved"} + , + { variant: "success" } + ); + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + persist: true, + variant: "error", + }); + } + }; + + return ( + <> + + + + setForm({ ...form, title: e.target.value })} + value={form.title} + /> + setForm({ ...form, intro })} + value={form.intro} + /> + + setForm({ ...form, opensAt: e.target.value })} + type="datetime-local" + value={toInput(form.opensAt)} + /> + setForm({ ...form, closesAt: e.target.value })} + type="datetime-local" + value={toInput(form.closesAt)} + /> + + + + {form.questions.map((q, i) => ( + + + + + setQ(i, { label: e.target.value })} + value={q.label} + /> + + setQ(i, { type: e.target.value as QuestionType }) + } + select + sx={{ minWidth: 150 }} + value={q.type} + > + {Object.entries(QUESTION_TYPES).map(([k, v]) => ( + + {v} + + ))} + + + setQ(i, { help: e.target.value })} + size="small" + value={q.help ?? ""} + /> + {(q.type === "choice" || + q.type === "checkboxes" || + q.type === "ranking") && ( + + setQ(i, { options: e.target.value.split("\n") }) + } + value={(q.options ?? []).join("\n")} + /> + )} + + + {q.type !== "info" && ( + + setQ(i, { required: e.target.checked }) + } + /> + } + label="Required" + /> + )} + {(q.type === "choice" || q.type === "checkboxes") && ( + + setQ(i, { other: e.target.checked }) + } + /> + } + label={'Offer "Other: ___"'} + /> + )} + + move(i, -1)} + > + + + move(i, 1)} + > + + + + setForm({ + ...form, + questions: form.questions.filter((_, j) => j !== i), + }) + } + > + + + + + + + ))} + + + + {form.status === "draft" + ? "Draft: only admins can see it, from Preview. Publish when leadership has reviewed it." + : "Published: volunteers see it while it's open. Changes show up right away."} + + + + + {form.status === "draft" ? ( + + ) : ( + + )} + + + + ); +}; diff --git a/client/src/app/forms/[formId]/edit/page.tsx b/client/src/app/forms/[formId]/edit/page.tsx new file mode 100644 index 00000000..e46aabd8 --- /dev/null +++ b/client/src/app/forms/[formId]/edit/page.tsx @@ -0,0 +1,17 @@ +import { FormEdit } from "@/app/forms/[formId]/edit/FormEdit"; +import { AuthGate } from "@/components/general/AuthGate"; +import { ACCOUNT_TYPE_ADMIN } from "@/constants"; + +export const metadata = { + title: "Census | Edit form", +}; +const Page = async ({ params }: { params: Promise<{ formId: string }> }) => { + const { formId } = await params; + return ( + + + + ); +}; + +export default Page; diff --git a/client/src/app/forms/[formId]/page.tsx b/client/src/app/forms/[formId]/page.tsx new file mode 100644 index 00000000..3108a9b9 --- /dev/null +++ b/client/src/app/forms/[formId]/page.tsx @@ -0,0 +1,17 @@ +import { FormFill } from "@/app/forms/[formId]/FormFill"; +import { AuthGate } from "@/components/general/AuthGate"; +import { ACCOUNT_TYPE_AUTHENTICATED } from "@/constants"; + +export const metadata = { + title: "Census | Form", +}; +const Page = async ({ params }: { params: Promise<{ formId: string }> }) => { + const { formId } = await params; + return ( + + + + ); +}; + +export default Page; diff --git a/client/src/app/forms/page.tsx b/client/src/app/forms/page.tsx new file mode 100644 index 00000000..78d5a3f3 --- /dev/null +++ b/client/src/app/forms/page.tsx @@ -0,0 +1,14 @@ +import { Forms } from "@/app/forms/Forms"; +import { AuthGate } from "@/components/general/AuthGate"; +import { ACCOUNT_TYPE_ADMIN } from "@/constants"; + +export const metadata = { + title: "Census | Forms", +}; +const Page = () => ( + + + +); + +export default Page; diff --git a/client/src/app/volunteers/[shiftboardId]/info/VolunteerInfo.tsx b/client/src/app/volunteers/[shiftboardId]/info/VolunteerInfo.tsx index 6ddb8c0a..167db913 100644 --- a/client/src/app/volunteers/[shiftboardId]/info/VolunteerInfo.tsx +++ b/client/src/app/volunteers/[shiftboardId]/info/VolunteerInfo.tsx @@ -61,6 +61,7 @@ import { helpChecklistPage } from "@/components/help/helpContent"; import { Hero } from "@/components/layout/Hero"; import type { IResVolunteerInfo } from "@/components/types/volunteer-info"; import type { IResRoleRowItem } from "@/components/types/roles"; +import type { IForm } from "@/lib/forms"; import type { IResVolunteerAccount, IResVolunteerRoleItem, @@ -221,6 +222,12 @@ export const VolunteerInfo = ({ data: IResRoleRowItem[]; } = useSWR(`/api/roles`, fetcherGet); + // yearly forms open now (#844), each a checklist item + const { data: openForms }: { data: IForm[] | undefined } = useSWR( + `/api/forms?for=${shiftboardId}`, + fetcherGet + ); + // other hooks // ------------------------------------------------------------ const { control, handleSubmit, reset } = useForm({ @@ -685,6 +692,36 @@ export const VolunteerInfo = ({ ), }); + // Yearly forms (#844): every open form (VIS for everyone from mid-January) + for (const f of openForms ?? []) { + checklistItems.push({ + id: `form-${f.formId}`, + label: f.title, + done: Boolean(f.submittedAt), + content: ( + + + {f.submittedAt + ? `Thanks for filling this in. You can change your answers${f.closesAt ? ` until ${f.closesAt.slice(0, 10)}` : ""}.` + : "Please fill in this year\u2019s form."} + + + {f.submittedAt + ? "See or change your answers" + : `Fill in ${f.title}`} + + + ), + }); + } + // Burner Profile — the step is "visit profiles.burningman.org", which is // dead without internet on the offline on-playa tablets. OfflineLink lets // the volunteer email themselves the link to do it from home instead of diff --git a/client/src/components/layout/pageList.tsx b/client/src/components/layout/pageList.tsx index 77733cf2..eaad2257 100644 --- a/client/src/components/layout/pageList.tsx +++ b/client/src/components/layout/pageList.tsx @@ -1,4 +1,5 @@ import { + Assignment as AssignmentIcon, BarChart as BarChartIcon, CalendarMonth as CalendarMonthIcon, ConfirmationNumber as ConfirmationNumberIcon, @@ -58,6 +59,12 @@ export const pageListAdmin = [ label: "Volunteers", path: "/volunteers", }, + { + // yearly forms: preview, answers; editors also edit (#844) + icon: , + label: "Forms", + path: "/forms", + }, { icon: , label: "Roles", diff --git a/client/src/constants.ts b/client/src/constants.ts index 40d123dc..20b2933c 100644 --- a/client/src/constants.ts +++ b/client/src/constants.ts @@ -106,6 +106,7 @@ export const ROLE_NO_LOGIN_ID = 2000040; export const ROLE_NO_CAMPING_ID = 2000041; export const ROLE_NO_TICKET_HELP_ID = 2000042; export const ROLE_DO_NOT_CONTACT_ID = 2000043; +export const ROLE_FORM_EDITOR_ID = 2000044; // #844: edits forms alongside SuperAdmin export const ROLE_PUMPKIN_USER_ID = 2000030; export const ROLE_SUPER_ADMIN_ID = 1; diff --git a/client/src/lib/authz.ts b/client/src/lib/authz.ts index 58cdf649..2d7c0e92 100644 --- a/client/src/lib/authz.ts +++ b/client/src/lib/authz.ts @@ -1,6 +1,10 @@ import type { RowDataPacket } from "mysql2"; -import { ROLE_ADMIN_ID, ROLE_SUPER_ADMIN_ID } from "@/constants"; +import { + ROLE_ADMIN_ID, + ROLE_FORM_EDITOR_ID, + ROLE_SUPER_ADMIN_ID, +} from "@/constants"; import { pool } from "lib/database"; // Server-side authorization helpers for the /api/volunteers/[shiftboardId]/* @@ -52,6 +56,14 @@ export async function isSuperAdmin(shiftboardId: number): Promise { return rows.length > 0; } +// #844: SuperAdmin or FormEditor may create and edit forms. +export async function isFormEditor(shiftboardId: number): Promise { + return ( + (await isSuperAdmin(shiftboardId)) || + (await hasRole(shiftboardId, ROLE_FORM_EDITOR_ID)) + ); +} + // True if the session may act on `requestedShiftboardId`: it's their own // record, or they're an admin. export async function isOwnerOrAdmin( diff --git a/client/src/lib/forms.ts b/client/src/lib/forms.ts new file mode 100644 index 00000000..d3ba6da5 --- /dev/null +++ b/client/src/lib/forms.ts @@ -0,0 +1,120 @@ +// #844 yearly forms: question/answer shapes and checks, shared by the API and +// the pages (no database imports here). + +export const QUESTION_TYPES = { + text: "Short answer", + textarea: "Long answer", + choice: "Pick one", + checkboxes: "Pick any", + yesno: "Yes / No", + scale: "1 to 5", + ranking: "Rank in order", + info: "Text only (no answer)", +} as const; +export type QuestionType = keyof typeof QUESTION_TYPES; + +export interface IFormQuestion { + help?: string; + id: string; + label: string; + options?: string[]; + // choice / checkboxes: also offer "Other: ___" (answer stored as "Other: …") + other?: boolean; + required?: boolean; + type: QuestionType; +} +export type FormAnswer = string | string[]; +export type FormAnswers = Record; + +export interface IForm { + closesAt: string | null; + formId: number; + intro: string; + isOpen: boolean; + opensAt: string | null; + questions: IFormQuestion[]; + slug: string; + status: "draft" | "published"; + submittedAt?: string | null; + title: string; + year: number; +} + +export const SCALE = ["1", "2", "3", "4", "5"]; +export const OTHER = "Other: "; +export const YESNO = ["Yes", "No"]; +// the fixed choices a question offers, or null for free text +export const choicesOf = (q: IFormQuestion): string[] | null => + q.type === "choice" || q.type === "checkboxes" || q.type === "ranking" + ? (q.options ?? []) + : q.type === "scale" + ? SCALE + : q.type === "yesno" + ? YESNO + : null; + +const MAX_TEXT = 5000; + +// Drop blank choices (the editor's one-per-line box leaves them while typing). +export const tidyQuestions = (questions: IFormQuestion[]): IFormQuestion[] => + questions.map((q) => + q.options + ? { ...q, options: q.options.map((o) => o.trim()).filter(Boolean) } + : q + ); + +// A form's questions as saved by the editor. Returns an error message or null. +export const checkQuestions = (questions: unknown): string | null => { + if (!Array.isArray(questions)) return "Questions must be a list."; + const ids = new Set(); + for (const q of questions as IFormQuestion[]) { + if (!q || typeof q.id !== "string" || !/^[a-z0-9_-]{1,40}$/i.test(q.id)) + return "Every question needs an id."; + if (ids.has(q.id)) return `Two questions share the id "${q.id}".`; + ids.add(q.id); + if (!(q.type in QUESTION_TYPES)) return `Unknown question type ${q.type}.`; + if (typeof q.label !== "string" || !q.label.trim()) + return "Every question needs its text."; + if ( + (q.type === "choice" || + q.type === "checkboxes" || + q.type === "ranking") && + (!Array.isArray(q.options) || q.options.filter(Boolean).length < 2) + ) + return `"${q.label}" needs at least two choices.`; + } + return null; +}; + +// A volunteer's answers against the form. Unknown question ids are dropped; +// returns { answers } (cleaned) or { error }. +export const checkAnswers = ( + questions: IFormQuestion[], + raw: unknown +): { answers: FormAnswers } | { error: string } => { + const given = (raw && typeof raw === "object" ? raw : {}) as FormAnswers; + const answers: FormAnswers = {}; + for (const q of questions) { + if (q.type === "info") continue; + const a = given[q.id]; + const choices = choicesOf(q); + const ok = (x: unknown): x is string => + typeof x === "string" && + (choices!.includes(x) || + (Boolean(q.other) && x.startsWith(OTHER) && x.length > OTHER.length)); + if (q.type === "checkboxes" || q.type === "ranking") { + // ranking: the options in the volunteer's order, best first + const picked = Array.isArray(a) + ? [...new Set(a.filter(ok).map((x) => x.slice(0, MAX_TEXT)))] + : []; + if (picked.length) answers[q.id] = picked; + } else if (typeof a === "string" && a.trim()) { + if (choices && !ok(a)) + return { error: `"${q.label}": pick one of the choices.` }; + answers[q.id] = a.trim().slice(0, MAX_TEXT); + } + if (q.required && answers[q.id] === undefined) + return { error: `"${q.label}" needs an answer.` }; + } + return { answers }; +}; diff --git a/client/src/lib/formsDb.ts b/client/src/lib/formsDb.ts new file mode 100644 index 00000000..ff7924c0 --- /dev/null +++ b/client/src/lib/formsDb.ts @@ -0,0 +1,38 @@ +import type { RowDataPacket } from "mysql2"; + +import { NOW_PT } from "@/lib/content"; +import type { IForm } from "@/lib/forms"; + +export const FORM_COLS = `f.form_id, f.slug, f.year, f.title, f.intro, f.questions, + f.status, f.opens_at, f.closes_at, + (f.status = 'published' + AND (f.opens_at IS NULL OR f.opens_at <= ${NOW_PT}) + AND (f.closes_at IS NULL OR f.closes_at > ${NOW_PT})) AS is_open`; + +// MariaDB JSON is LONGTEXT, so mysql2 hands it back as a string +export const parseJson = (v: unknown, fallback: T): T => + typeof v === "string" ? (JSON.parse(v) as T) : ((v as T) ?? fallback); + +export const toForm = (r: RowDataPacket): IForm => ({ + closesAt: r.closes_at, + formId: r.form_id, + intro: r.intro ?? "", + isOpen: Boolean(r.is_open), + opensAt: r.opens_at, + questions: parseJson(r.questions, []), + slug: r.slug, + status: r.status, + ...(r.submitted_at !== undefined && { submittedAt: r.submitted_at }), + title: r.title, + year: r.year, +}); + +export const parseBody = (body: unknown): Record => { + try { + return typeof body === "string" + ? JSON.parse(body || "{}") + : ((body ?? {}) as Record); + } catch { + return {}; + } +}; diff --git a/client/src/pages/api/forms/[formId]/index.ts b/client/src/pages/api/forms/[formId]/index.ts new file mode 100644 index 00000000..72b57897 --- /dev/null +++ b/client/src/pages/api/forms/[formId]/index.ts @@ -0,0 +1,145 @@ +import type { RowDataPacket } from "mysql2"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { isAdmin, isFormEditor } from "@/lib/authz"; +import { sanitizeContent } from "@/lib/content"; +import { + checkAnswers, + checkQuestions, + type IFormQuestion, + tidyQuestions, +} from "@/lib/forms"; +import { FORM_COLS, parseBody, parseJson, toForm } from "@/lib/formsDb"; +import { withAuth } from "@/lib/withAuth"; +import { pool } from "lib/database"; + +const DATETIME_RE = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/; + +// /api/forms/[formId] (#844) +// GET → { form, answers } — answers = the signed-in volunteer's, or null. +// Drafts are admins / form editors only (the preview is the leadership review step). +// PUT { answers } → save the signed-in volunteer's answers; open forms only. +// Editable until the form closes. +// PATCH (SuperAdmin / FormEditor) { title?, intro?, questions?, status?, opensAt?, closesAt? } +const form = async ( + req: NextApiRequest, + res: NextApiResponse, + session: { shiftboardId: number } +) => { + const formId = Number(req.query.formId); + const [rows] = await pool.query( + `SELECT ${FORM_COLS} FROM op_forms f WHERE f.form_id = ?`, + [formId] + ); + const found = rows[0] && toForm(rows[0]); + const notFound = () => + res.status(404).json({ statusCode: 404, message: "Not found" }); + if (!found) return notFound(); + + switch (req.method) { + case "GET": { + if ( + found.status !== "published" && + !(await isAdmin(session.shiftboardId)) && + !(await isFormEditor(session.shiftboardId)) + ) + return notFound(); + const [mine] = await pool.query( + `SELECT answers FROM op_form_responses + WHERE form_id = ? AND shiftboard_id = ?`, + [formId, session.shiftboardId] + ); + return res + .status(200) + .json({ + answers: mine[0] ? parseJson(mine[0].answers, {}) : null, + form: found, + }); + } + case "PUT": { + if (!found.isOpen) + return res + .status(409) + .json({ statusCode: 409, message: "This form isn't open." }); + const checked = checkAnswers( + found.questions, + parseBody(req.body).answers + ); + if ("error" in checked) + return res + .status(400) + .json({ statusCode: 400, message: checked.error }); + await pool.query( + `INSERT INTO op_form_responses (form_id, shiftboard_id, answers, changed_by) + VALUES (?, ?, ?, ?) + ON DUPLICATE KEY UPDATE answers = VALUES(answers), + submitted_at = CURRENT_TIMESTAMP, changed_by = VALUES(changed_by)`, + [ + formId, + session.shiftboardId, + JSON.stringify(checked.answers), + session.shiftboardId, + ] + ); + return res.status(200).json({ answers: checked.answers }); + } + case "PATCH": { + if (!(await isFormEditor(session.shiftboardId))) + return res.status(403).json({ statusCode: 403, message: "Forbidden" }); + const body = parseBody(req.body); + const sets: string[] = []; + const params: unknown[] = []; + const bad = (message: string) => + res.status(400).json({ statusCode: 400, message }); + if (body.title !== undefined) { + if (typeof body.title !== "string" || !body.title.trim()) + return bad("Title can't be blank."); + sets.push("title = ?"); + params.push(body.title.trim()); + } + if (body.intro !== undefined) { + sets.push("intro = ?"); + params.push(sanitizeContent(String(body.intro))); + } + if (body.questions !== undefined) { + const err = checkQuestions(body.questions); + if (err) return bad(err); + const questions = tidyQuestions(body.questions as IFormQuestion[]); + // ponytail: questions stay editable after publishing; answers are + // keyed by question id, so a removed question's answers stay in the + // response rows and the CSV. Lock it if editors trip over this. + sets.push("questions = ?"); + params.push(JSON.stringify(questions)); + } + if (body.status !== undefined) { + if (body.status !== "draft" && body.status !== "published") + return bad("Status is draft or published."); + sets.push("status = ?"); + params.push(body.status); + } + for (const [key, col] of [ + ["opensAt", "opens_at"], + ["closesAt", "closes_at"], + ] as const) { + const v = body[key]; + if (v === undefined) continue; + if (v !== null && !(typeof v === "string" && DATETIME_RE.test(v))) + return bad("Dates look like 2027-01-15 09:00 (Pacific)."); + sets.push(`${col} = ?`); + params.push(v === null ? null : v.replace("T", " ")); + } + if (!sets.length) return bad("Nothing to change."); + await pool.query( + `UPDATE op_forms SET ${sets.join(", ")}, changed_by = ? WHERE form_id = ?`, + [...params, session.shiftboardId, formId] + ); + return res.status(200).json({ ok: true }); + } + default: + return res + .status(405) + .json({ statusCode: 405, message: "Method not allowed" }); + } +}; + +export default withAuth(form); diff --git a/client/src/pages/api/forms/[formId]/responses.ts b/client/src/pages/api/forms/[formId]/responses.ts new file mode 100644 index 00000000..34a8f2d3 --- /dev/null +++ b/client/src/pages/api/forms/[formId]/responses.ts @@ -0,0 +1,41 @@ +import type { RowDataPacket } from "mysql2"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { isAdmin } from "@/lib/authz"; +import { parseJson } from "@/lib/formsDb"; +import { withAuth } from "@/lib/withAuth"; +import { pool } from "lib/database"; + +// GET /api/forms/[formId]/responses (#844), admins only: every answer to one +// form, with who gave it. Totals and the CSV are worked out on the page. +const responses = async ( + req: NextApiRequest, + res: NextApiResponse, + session: { shiftboardId: number } +) => { + if (req.method !== "GET") + return res + .status(405) + .json({ statusCode: 405, message: "Method not allowed" }); + if (!(await isAdmin(session.shiftboardId))) + return res.status(403).json({ statusCode: 403, message: "Forbidden" }); + const [rows] = await pool.query( + `SELECT r.shiftboard_id, r.answers, r.submitted_at, v.playa_name, v.world_name + FROM op_form_responses r + LEFT JOIN op_volunteers v ON v.shiftboard_id = r.shiftboard_id + WHERE r.form_id = ? + ORDER BY r.submitted_at`, + [Number(req.query.formId)] + ); + return res.status(200).json( + rows.map((r) => ({ + answers: parseJson(r.answers, {}), + playaName: r.playa_name ?? "", + shiftboardId: r.shiftboard_id, + submittedAt: r.submitted_at, + worldName: r.world_name ?? "", + })) + ); +}; + +export default withAuth(responses); diff --git a/client/src/pages/api/forms/index.ts b/client/src/pages/api/forms/index.ts new file mode 100644 index 00000000..a5219b90 --- /dev/null +++ b/client/src/pages/api/forms/index.ts @@ -0,0 +1,98 @@ +import type { RowDataPacket } from "mysql2"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { isAdmin, isFormEditor, isOwnerOrAdmin } from "@/lib/authz"; +import { FORM_COLS, parseBody, toForm } from "@/lib/formsDb"; +import { withAuth } from "@/lib/withAuth"; +import { pool } from "lib/database"; + +// /api/forms (#844) +// GET → the open forms for the signed-in volunteer, with +// submittedAt (checklist). ?for=: that volunteer's +// (owner or admin). ?all=1 (admin): every form, every year. +// POST (SuperAdmin / FormEditor) { slug, year, title } → new draft. Questions and intro are +// copied from the latest earlier year of the same slug. +const forms = async ( + req: NextApiRequest, + res: NextApiResponse, + session: { shiftboardId: number } +) => { + switch (req.method) { + case "GET": { + if (req.query.all) { + if (!(await isAdmin(session.shiftboardId))) + return res + .status(403) + .json({ statusCode: 403, message: "Forbidden" }); + const [rows] = await pool.query( + `SELECT ${FORM_COLS} FROM op_forms f ORDER BY f.year DESC, f.slug` + ); + return res.status(200).json(rows.map(toForm)); + } + const who = Number(req.query.for ?? session.shiftboardId); + if (!(await isOwnerOrAdmin(session, who))) + return res.status(403).json({ statusCode: 403, message: "Forbidden" }); + const [rows] = await pool.query( + `SELECT ${FORM_COLS}, r.submitted_at + FROM op_forms f + LEFT JOIN op_form_responses r + ON r.form_id = f.form_id AND r.shiftboard_id = ? + HAVING is_open + ORDER BY f.opens_at, f.form_id`, + [who] + ); + return res.status(200).json(rows.map(toForm)); + } + case "POST": { + if (!(await isFormEditor(session.shiftboardId))) + return res.status(403).json({ statusCode: 403, message: "Forbidden" }); + const { slug, title, year } = parseBody(req.body); + if ( + typeof slug !== "string" || + !/^[a-z0-9-]{1,40}$/.test(slug) || + !Number.isInteger(year) || + typeof title !== "string" || + !title.trim() + ) + return res + .status(400) + .json({ statusCode: 400, message: "Need slug, year and title" }); + const [prev] = await pool.query( + `SELECT intro, questions FROM op_forms + WHERE slug = ? AND year < ? ORDER BY year DESC LIMIT 1`, + [slug, year] + ); + const questions = prev[0]?.questions ?? "[]"; + try { + const [ins] = await pool.query( + `INSERT INTO op_forms (slug, year, title, intro, questions, changed_by) + VALUES (?, ?, ?, ?, ?, ?)`, + [ + slug, + year, + title.trim(), + prev[0]?.intro ?? "", + questions, + session.shiftboardId, + ] + ); + return res + .status(201) + .json({ formId: (ins as { insertId: number }).insertId }); + } catch (err) { + if ((err as { code?: string }).code === "ER_DUP_ENTRY") + return res.status(409).json({ + statusCode: 409, + message: `There is already a ${slug} form for ${year}.`, + }); + throw err; + } + } + default: + return res + .status(405) + .json({ statusCode: 405, message: "Method not allowed" }); + } +}; + +export default withAuth(forms); diff --git a/client/src/utils/checkIsRoleExist.ts b/client/src/utils/checkIsRoleExist.ts index 0a545ba2..4a4c48c5 100644 --- a/client/src/utils/checkIsRoleExist.ts +++ b/client/src/utils/checkIsRoleExist.ts @@ -4,6 +4,7 @@ import { ACCOUNT_TYPE_AUTHENTICATED, ROLE_ADMIN_ID, ROLE_BEHAVIORAL_STANDARDS_ID, + ROLE_FORM_EDITOR_ID, ROLE_SUPER_ADMIN_ID, } from "@/constants"; import { IAccountTypePayload } from "@/state/developer-mode/reducer"; @@ -41,6 +42,13 @@ export const checkIsBehavioralStandardsSigned = ( ) => { return checkIsRoleExist(ROLE_BEHAVIORAL_STANDARDS_ID, roleList); }; +// #844: SuperAdmin or FormEditor may edit forms +export const checkIsFormEditor = ( + accountType: IAccountTypePayload, + roleList: IResVolunteerRoleItem[] +) => + checkIsSuperAdmin(accountType, roleList) || + (!accountType.isEnabled && checkIsRoleExist(ROLE_FORM_EDITOR_ID, roleList)); // check for super admin role, including when dev mode is on export const checkIsSuperAdmin = ( { isEnabled }: IAccountTypePayload, diff --git a/migrations/032_forms.sql b/migrations/032_forms.sql new file mode 100644 index 00000000..a25faa25 --- /dev/null +++ b/migrations/032_forms.sql @@ -0,0 +1,36 @@ +-- #844: yearly forms (VIS first; Camping / Ticketing / Driver later), authored +-- in the app. One row per (slug, year): each year's form is independent, with +-- its own questions and answers. Questions live in the row as JSON, answers +-- keyed by question id, so editing a form never needs a schema change. +-- Both tables are system-versioned (#620) with changed_by (#878). +CREATE TABLE IF NOT EXISTS op_forms ( + form_id INT NOT NULL AUTO_INCREMENT, + slug VARCHAR(40) NOT NULL, + year SMALLINT NOT NULL, + title VARCHAR(200) NOT NULL, + intro TEXT NULL, + questions JSON NOT NULL, + -- draft: editors + admins (preview = the review step); published: shown + -- to volunteers between opens_at and closes_at (Pacific, NULL = no limit) + status ENUM('draft', 'published') NOT NULL DEFAULT 'draft', + opens_at DATETIME NULL, + closes_at DATETIME NULL, + changed_by BIGINT NULL, + PRIMARY KEY (form_id), + UNIQUE KEY uq_form_slug_year (slug, year) +) WITH SYSTEM VERSIONING; + +CREATE TABLE IF NOT EXISTS op_form_responses ( + form_id INT NOT NULL, + shiftboard_id BIGINT NOT NULL, + answers JSON NOT NULL, + submitted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP, + changed_by BIGINT NULL, + PRIMARY KEY (form_id, shiftboard_id) +) WITH SYSTEM VERSIONING; + +-- FormEditor (Mew 2026-11-29, Rescue first): edits forms alongside SuperAdmin. +SET @@system_versioning_alter_history = KEEP; +INSERT INTO op_roles (role_id, role, display, role_src) VALUES + (2000044, 'FormEditor', 1, 'system') +ON DUPLICATE KEY UPDATE role = VALUES(role), role_src = VALUES(role_src); From 8b4494e64d39a121f7bd29c7dcea369ab6e5249b Mon Sep 17 00:00:00 2001 From: Mew Date: Sun, 29 Nov 2026 01:20:53 -0800 Subject: [PATCH 2/3] chore: footer 2027.G.00894.C Co-Authored-By: Claude Opus 5.5 --- client/src/components/layout/Footer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/src/components/layout/Footer.tsx b/client/src/components/layout/Footer.tsx index 6984e44e..4d694721 100644 --- a/client/src/components/layout/Footer.tsx +++ b/client/src/components/layout/Footer.tsx @@ -255,7 +255,7 @@ export const Footer = () => { color: theme.palette.common.white, }} > - 2027.G.00893.C + 2027.G.00894.C From 530e08337182247193f39f7b7069dccd0cbf1f8c Mon Sep 17 00:00:00 2001 From: Mew Date: Sun, 29 Nov 2026 01:24:47 -0800 Subject: [PATCH 3/3] feat(forms): answers and drafts are FormEditor-only (Mew 2026-11-29) Mew: the people who edit forms are the ones who see the answers, for now. Pages are open to signed-in users and the API enforces FormEditor, so a FormEditor doesn't also need Admin. Co-Authored-By: Claude Opus 5.5 --- client/e2e/tests/39-forms.spec.ts | 4 +--- client/src/app/forms/Forms.tsx | 4 ++-- client/src/app/forms/[formId]/FormFill.tsx | 2 +- .../app/forms/[formId]/answers/FormAnswers.tsx | 2 +- client/src/app/forms/[formId]/answers/page.tsx | 4 ++-- client/src/app/forms/[formId]/edit/FormEdit.tsx | 4 ++-- client/src/app/forms/[formId]/edit/page.tsx | 4 ++-- client/src/app/forms/page.tsx | 4 ++-- client/src/lib/authz.ts | 3 ++- client/src/pages/api/forms/[formId]/index.ts | 15 ++++++--------- client/src/pages/api/forms/[formId]/responses.ts | 6 +++--- client/src/pages/api/forms/index.ts | 6 +++--- 12 files changed, 27 insertions(+), 31 deletions(-) diff --git a/client/e2e/tests/39-forms.spec.ts b/client/e2e/tests/39-forms.spec.ts index aebcc119..e707dc29 100644 --- a/client/e2e/tests/39-forms.spec.ts +++ b/client/e2e/tests/39-forms.spec.ts @@ -10,13 +10,12 @@ import { import { buildSessionCookieHeader } from "../helpers/session"; import { makeTestVolunteer, - ROLE_ADMIN_ID, signInAs, ROLE_BEHAVIORAL_STANDARDS_ID, } from "../fixtures/test-data"; // #844: yearly forms authored in the app. Draft → publish; volunteers answer -// while it's open; FormEditor edits; admins see the answers. +// while it's open; FormEditor edits and sees the answers (no Admin needed). const ROLE_FORM_EDITOR_ID = 2000044; const SLUG = "e2e-vis"; const editor = makeTestVolunteer({ @@ -71,7 +70,6 @@ test.describe("Yearly forms (#844)", () => { await assignRole(v.shiftboardId, ROLE_BEHAVIORAL_STANDARDS_ID); } await assignRole(editor.shiftboardId, ROLE_FORM_EDITOR_ID); - await assignRole(editor.shiftboardId, ROLE_ADMIN_ID); }); test.afterAll(async () => { diff --git a/client/src/app/forms/Forms.tsx b/client/src/app/forms/Forms.tsx index 20fd5fbf..d151a3d0 100644 --- a/client/src/app/forms/Forms.tsx +++ b/client/src/app/forms/Forms.tsx @@ -30,8 +30,8 @@ import { SessionContext } from "@/state/session/context"; import { checkIsFormEditor } from "@/utils/checkIsRoleExist"; import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; -// /forms (#844): every yearly form. Admins preview drafts (the leadership -// review) and see answers; SuperAdmins and FormEditors also create and edit. +// /forms (#844), SuperAdmin / FormEditor (the API enforces it): every yearly +// form; preview drafts (the leadership review), edit, see answers. export const Forms = () => { const { developerModeState: { accountType }, diff --git a/client/src/app/forms/[formId]/FormFill.tsx b/client/src/app/forms/[formId]/FormFill.tsx index 0e29d307..a84216c0 100644 --- a/client/src/app/forms/[formId]/FormFill.tsx +++ b/client/src/app/forms/[formId]/FormFill.tsx @@ -220,7 +220,7 @@ const Question = ({ // /forms/[formId] (#844): a volunteer fills in a yearly form. Signed-in only, // so no identity questions. Answers can be changed until the form closes. -// Admins can open a draft here to review it; saving is off until it's open. +// Form editors can open a draft here to review it; saving is off until it's open. export const FormFill = ({ formId }: { formId: number }) => { const { data, error, mutate } = useSWR<{ answers: FormAnswers | null; diff --git a/client/src/app/forms/[formId]/answers/FormAnswers.tsx b/client/src/app/forms/[formId]/answers/FormAnswers.tsx index 2c1408bc..7f5dbad1 100644 --- a/client/src/app/forms/[formId]/answers/FormAnswers.tsx +++ b/client/src/app/forms/[formId]/answers/FormAnswers.tsx @@ -58,7 +58,7 @@ const matches = ( }; const csvCell = (v: string | number) => `"${String(v).replace(/"/g, '""')}"`; -// /forms/[formId]/answers (#844), admins: per-question totals, every answer, +// /forms/[formId]/answers (#844), SuperAdmin / FormEditor: per-question totals, every answer, // a CSV, and "Add role" for the people ticked (always a person's call, never // automatic). Filter by an answer to pick, e.g., everyone who said Gate. export const FormAnswers = ({ formId }: { formId: number }) => { diff --git a/client/src/app/forms/[formId]/answers/page.tsx b/client/src/app/forms/[formId]/answers/page.tsx index 625732ac..555f8706 100644 --- a/client/src/app/forms/[formId]/answers/page.tsx +++ b/client/src/app/forms/[formId]/answers/page.tsx @@ -1,6 +1,6 @@ import { FormAnswers } from "@/app/forms/[formId]/answers/FormAnswers"; import { AuthGate } from "@/components/general/AuthGate"; -import { ACCOUNT_TYPE_ADMIN } from "@/constants"; +import { ACCOUNT_TYPE_AUTHENTICATED } from "@/constants"; export const metadata = { title: "Census | Form answers", @@ -8,7 +8,7 @@ export const metadata = { const Page = async ({ params }: { params: Promise<{ formId: string }> }) => { const { formId } = await params; return ( - + ); diff --git a/client/src/app/forms/[formId]/edit/FormEdit.tsx b/client/src/app/forms/[formId]/edit/FormEdit.tsx index 68c5774f..c814eabd 100644 --- a/client/src/app/forms/[formId]/edit/FormEdit.tsx +++ b/client/src/app/forms/[formId]/edit/FormEdit.tsx @@ -42,7 +42,7 @@ const toInput = (v: string | null) => v ? v.slice(0, 16).replace(" ", "T") : ""; // /forms/[formId]/edit (#844), SuperAdmin / FormEditor (the API enforces it): the form's text, questions, dates -// and status. Draft → admins review it via Preview → Publish. +// and status. Draft → the form editors review it via Preview → Publish. export const FormEdit = ({ formId }: { formId: number }) => { const { data, error, mutate } = useSWR<{ form: IForm }>( `/api/forms/${formId}`, @@ -267,7 +267,7 @@ export const FormEdit = ({ formId }: { formId: number }) => { {form.status === "draft" - ? "Draft: only admins can see it, from Preview. Publish when leadership has reviewed it." + ? "Draft: only form editors can see it, from Preview. Publish when leadership has reviewed it." : "Published: volunteers see it while it's open. Changes show up right away."} diff --git a/client/src/app/forms/[formId]/edit/page.tsx b/client/src/app/forms/[formId]/edit/page.tsx index e46aabd8..176a0a18 100644 --- a/client/src/app/forms/[formId]/edit/page.tsx +++ b/client/src/app/forms/[formId]/edit/page.tsx @@ -1,6 +1,6 @@ import { FormEdit } from "@/app/forms/[formId]/edit/FormEdit"; import { AuthGate } from "@/components/general/AuthGate"; -import { ACCOUNT_TYPE_ADMIN } from "@/constants"; +import { ACCOUNT_TYPE_AUTHENTICATED } from "@/constants"; export const metadata = { title: "Census | Edit form", @@ -8,7 +8,7 @@ export const metadata = { const Page = async ({ params }: { params: Promise<{ formId: string }> }) => { const { formId } = await params; return ( - + ); diff --git a/client/src/app/forms/page.tsx b/client/src/app/forms/page.tsx index 78d5a3f3..e12e4571 100644 --- a/client/src/app/forms/page.tsx +++ b/client/src/app/forms/page.tsx @@ -1,12 +1,12 @@ import { Forms } from "@/app/forms/Forms"; import { AuthGate } from "@/components/general/AuthGate"; -import { ACCOUNT_TYPE_ADMIN } from "@/constants"; +import { ACCOUNT_TYPE_AUTHENTICATED } from "@/constants"; export const metadata = { title: "Census | Forms", }; const Page = () => ( - + ); diff --git a/client/src/lib/authz.ts b/client/src/lib/authz.ts index 2d7c0e92..5d3699d1 100644 --- a/client/src/lib/authz.ts +++ b/client/src/lib/authz.ts @@ -56,7 +56,8 @@ export async function isSuperAdmin(shiftboardId: number): Promise { return rows.length > 0; } -// #844: SuperAdmin or FormEditor may create and edit forms. +// #844: SuperAdmin or FormEditor may create, edit and preview forms and see +// the answers (Mew 2026-11-29: the same group, for now). export async function isFormEditor(shiftboardId: number): Promise { return ( (await isSuperAdmin(shiftboardId)) || diff --git a/client/src/pages/api/forms/[formId]/index.ts b/client/src/pages/api/forms/[formId]/index.ts index 72b57897..dbe74996 100644 --- a/client/src/pages/api/forms/[formId]/index.ts +++ b/client/src/pages/api/forms/[formId]/index.ts @@ -1,7 +1,7 @@ import type { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; -import { isAdmin, isFormEditor } from "@/lib/authz"; +import { isFormEditor } from "@/lib/authz"; import { sanitizeContent } from "@/lib/content"; import { checkAnswers, @@ -17,7 +17,7 @@ const DATETIME_RE = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/; // /api/forms/[formId] (#844) // GET → { form, answers } — answers = the signed-in volunteer's, or null. -// Drafts are admins / form editors only (the preview is the leadership review step). +// Drafts are FormEditor only (the preview is the leadership review step). // PUT { answers } → save the signed-in volunteer's answers; open forms only. // Editable until the form closes. // PATCH (SuperAdmin / FormEditor) { title?, intro?, questions?, status?, opensAt?, closesAt? } @@ -40,7 +40,6 @@ const form = async ( case "GET": { if ( found.status !== "published" && - !(await isAdmin(session.shiftboardId)) && !(await isFormEditor(session.shiftboardId)) ) return notFound(); @@ -49,12 +48,10 @@ const form = async ( WHERE form_id = ? AND shiftboard_id = ?`, [formId, session.shiftboardId] ); - return res - .status(200) - .json({ - answers: mine[0] ? parseJson(mine[0].answers, {}) : null, - form: found, - }); + return res.status(200).json({ + answers: mine[0] ? parseJson(mine[0].answers, {}) : null, + form: found, + }); } case "PUT": { if (!found.isOpen) diff --git a/client/src/pages/api/forms/[formId]/responses.ts b/client/src/pages/api/forms/[formId]/responses.ts index 34a8f2d3..9de56beb 100644 --- a/client/src/pages/api/forms/[formId]/responses.ts +++ b/client/src/pages/api/forms/[formId]/responses.ts @@ -1,12 +1,12 @@ import type { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; -import { isAdmin } from "@/lib/authz"; +import { isFormEditor } from "@/lib/authz"; import { parseJson } from "@/lib/formsDb"; import { withAuth } from "@/lib/withAuth"; import { pool } from "lib/database"; -// GET /api/forms/[formId]/responses (#844), admins only: every answer to one +// GET /api/forms/[formId]/responses (#844), SuperAdmin / FormEditor only (Mew 2026-11-29): every answer to one // form, with who gave it. Totals and the CSV are worked out on the page. const responses = async ( req: NextApiRequest, @@ -17,7 +17,7 @@ const responses = async ( return res .status(405) .json({ statusCode: 405, message: "Method not allowed" }); - if (!(await isAdmin(session.shiftboardId))) + if (!(await isFormEditor(session.shiftboardId))) return res.status(403).json({ statusCode: 403, message: "Forbidden" }); const [rows] = await pool.query( `SELECT r.shiftboard_id, r.answers, r.submitted_at, v.playa_name, v.world_name diff --git a/client/src/pages/api/forms/index.ts b/client/src/pages/api/forms/index.ts index a5219b90..7339f4d0 100644 --- a/client/src/pages/api/forms/index.ts +++ b/client/src/pages/api/forms/index.ts @@ -1,7 +1,7 @@ import type { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; -import { isAdmin, isFormEditor, isOwnerOrAdmin } from "@/lib/authz"; +import { isFormEditor, isOwnerOrAdmin } from "@/lib/authz"; import { FORM_COLS, parseBody, toForm } from "@/lib/formsDb"; import { withAuth } from "@/lib/withAuth"; import { pool } from "lib/database"; @@ -9,7 +9,7 @@ import { pool } from "lib/database"; // /api/forms (#844) // GET → the open forms for the signed-in volunteer, with // submittedAt (checklist). ?for=: that volunteer's -// (owner or admin). ?all=1 (admin): every form, every year. +// (owner or admin). ?all=1 (FormEditor): every form, every year. // POST (SuperAdmin / FormEditor) { slug, year, title } → new draft. Questions and intro are // copied from the latest earlier year of the same slug. const forms = async ( @@ -20,7 +20,7 @@ const forms = async ( switch (req.method) { case "GET": { if (req.query.all) { - if (!(await isAdmin(session.shiftboardId))) + if (!(await isFormEditor(session.shiftboardId))) return res .status(403) .json({ statusCode: 403, message: "Forbidden" });