diff --git a/client/e2e/helpers/actorGuard.ts b/client/e2e/helpers/actorGuard.ts index 29f93c8d..b042c488 100644 --- a/client/e2e/helpers/actorGuard.ts +++ b/client/e2e/helpers/actorGuard.ts @@ -6,6 +6,7 @@ import path from "node:path"; // (covers pool.query, execute and transaction connections alike). export const VERSIONED = [ "op_dates", + "op_form_decisions", "op_form_responses", "op_forms", "op_position_trainings", diff --git a/client/e2e/tests/39-forms.spec.ts b/client/e2e/tests/39-forms.spec.ts index 0f33eebe..b95bef4f 100644 --- a/client/e2e/tests/39-forms.spec.ts +++ b/client/e2e/tests/39-forms.spec.ts @@ -60,6 +60,10 @@ const cleanup = async () => { "DELETE r FROM op_form_responses r JOIN op_forms f USING (form_id) WHERE f.slug = ?", [SLUG] ); + await db.execute( + "DELETE d FROM op_form_decisions d JOIN op_forms f USING (form_id) WHERE f.slug = ?", + [SLUG] + ); await db.execute("DELETE FROM op_forms WHERE slug = ?", [SLUG]); await db.execute("DELETE FROM op_email_queue WHERE `to` = ?", [ volunteer.email, @@ -289,4 +293,129 @@ test.describe("Yearly forms (#844)", () => { expect(await listed()).toBe(false); expect((await get()).status()).toBe(404); }); + + test("decisions: swap the camp role, email positive choices once", async ({ + request, + }) => { + const LAB_ROLE_ID = 9_000_526; + const CC_ROLE_ID = 9_000_527; + await insertRole(LAB_ROLE_ID, "E2E Lab Camp"); + await insertRole(CC_ROLE_ID, "E2E CC Camp"); + const editorH = as(editor.shiftboardId); + const made = await request.post("/api/forms", { + data: JSON.stringify({ + slug: SLUG, + title: "E2E Camping Decide", + year: 2095, + }), + headers: editorH, + }); + const { formId } = await made.json(); + const camp = { + key: "camp", + label: "Camp", + options: [ + { + capacity: 1, + email: true, + label: "Census Lab", + roleId: LAB_ROLE_ID, + value: "lab", + }, + { + email: true, + label: "Counter Culture", + roleId: CC_ROLE_ID, + value: "cc", + }, + { label: "Not this year", value: "no" }, + ], + }; + const patch = (body: object) => + request.patch(`/api/forms/${formId}`, { + data: JSON.stringify(body), + headers: editorH, + }); + expect( + ( + await patch({ decisions: [{ ...camp, options: [camp.options[0]] }] }) + ).status() + ).toBe(400); + expect( + ( + await patch({ + decisions: [camp], + questions: QUESTIONS, + status: "published", + }) + ).status() + ).toBe(200); + + const decide = (value: string | null, who = editor.shiftboardId) => + request.put(`/api/forms/${formId}/decisions`, { + data: JSON.stringify({ + key: "camp", + shiftboardId: volunteer.shiftboardId, + value, + }), + headers: as(who), + }); + expect((await decide("lab")).status()).toBe(404); // hasn't answered yet + await request.put(`/api/forms/${formId}`, { + data: JSON.stringify({ answers: { plans: "Yes" } }), + headers: as(volunteer.shiftboardId), + }); + expect((await decide("lab", volunteer.shiftboardId)).status()).toBe(403); + + const db = getPool(); + const holds = async (roleId: number) => { + const [rows] = await db.query( + "SELECT 1 FROM op_volunteer_roles WHERE shiftboard_id = ? AND role_id = ? AND remove_role = false", + [volunteer.shiftboardId, roleId] + ); + return (rows as unknown[]).length > 0; + }; + const emails = async () => { + const [rows] = await db.query( + "SELECT category FROM op_email_queue WHERE category LIKE ? AND `to` = ? ORDER BY id", + [`form-decision:${formId}:%`, volunteer.email] + ); + return (rows as { category: string }[]).map((r) => + r.category.split(":").pop() + ); + }; + + expect((await decide("lab")).status()).toBe(200); + expect([await holds(LAB_ROLE_ID), await holds(CC_ROLE_ID)]).toEqual([ + true, + false, + ]); + expect((await decide("cc")).status()).toBe(200); + expect([await holds(LAB_ROLE_ID), await holds(CC_ROLE_ID)]).toEqual([ + false, + true, + ]); + expect((await decide("no")).status()).toBe(200); + expect([await holds(LAB_ROLE_ID), await holds(CC_ROLE_ID)]).toEqual([ + false, + false, + ]); + expect((await decide("lab")).status()).toBe(200); + expect(await emails()).toEqual(["lab", "cc"]); // no email for "no", lab only once + + const rows = await ( + await request.get(`/api/forms/${formId}/responses`, { headers: editorH }) + ).json(); + expect(rows[0].decisions).toEqual({ camp: "lab" }); + const [hist] = await db.query( + "SELECT value, changed_by FROM op_form_decisions FOR SYSTEM_TIME ALL WHERE form_id = ?", + [formId] + ); + expect(hist).toHaveLength(4); + expect( + (hist as { changed_by: number }[]).every( + (h) => h.changed_by === editor.shiftboardId + ) + ).toBe(true); + }); }); diff --git a/client/src/app/emails/Emails.tsx b/client/src/app/emails/Emails.tsx index da15ff82..ef58259e 100644 --- a/client/src/app/emails/Emails.tsx +++ b/client/src/app/emails/Emails.tsx @@ -8,6 +8,7 @@ import { EMAIL_TEMPLATES } from "@/lib/emailTemplates"; const FIELD_HELP: Record = { by: 'who did it, e.g. "by Chipper"', + decision: 'the choice made, e.g. "Census Lab"', form: "the form's title", link: "the app's address", name: "playa name (or world name)", diff --git a/client/src/app/forms/[formId]/answers/FormAnswers.tsx b/client/src/app/forms/[formId]/answers/FormAnswers.tsx index 7f5dbad1..3a4c3809 100644 --- a/client/src/app/forms/[formId]/answers/FormAnswers.tsx +++ b/client/src/app/forms/[formId]/answers/FormAnswers.tsx @@ -38,6 +38,7 @@ import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; interface IResponse { answers: Answers; + decisions: Record; playaName: string; shiftboardId: number; submittedAt: string; @@ -66,25 +67,32 @@ export const FormAnswers = ({ formId }: { formId: number }) => { `/api/forms/${formId}`, fetcherGet ); - const { data: rows, error: rowsError } = useSWR( - `/api/forms/${formId}/responses`, - fetcherGet - ); + const { + data: rows, + error: rowsError, + mutate: mutateRows, + } = 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(""); + // "key|value" — value "" = undecided + const [decidedFilter, setDecidedFilter] = useState(""); const form = formData?.form; const shown = useMemo( () => (rows ?? []).filter((r) => { + if (decidedFilter) { + const [key, value] = decidedFilter.split("|"); + if ((r.decisions[key] ?? "") !== value) return false; + } 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] + [decidedFilter, form, rows, filter] ); if (formError || rowsError) return ; @@ -101,6 +109,7 @@ export const FormAnswers = ({ formId }: { formId: number }) => { "playa_name", "world_name", "submitted_at", + ...form.decisions.map((d) => d.label), ...answerable.map((q) => q.label), ]; const lines = [ @@ -110,6 +119,10 @@ export const FormAnswers = ({ formId }: { formId: number }) => { r.playaName, r.worldName, r.submittedAt, + ...form.decisions.map( + (d) => + d.options.find((o) => o.value === r.decisions[d.key])?.label ?? "" + ), ...answerable.map((q) => show(r.answers[q.id])), ]), ]; @@ -125,6 +138,23 @@ export const FormAnswers = ({ formId }: { formId: number }) => { URL.revokeObjectURL(url); }; + const decide = async ( + shiftboardId: number, + key: string, + value: string | null + ) => { + try { + await fetcherTrigger(`/api/forms/${formId}/decisions`, { + arg: { body: { key, shiftboardId, value }, method: "PUT" }, + }); + await mutateRows(); + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + variant: "error", + }); + } + }; + const addRole = async () => { const role = roles?.find((r) => r.id === Number(roleId)); if (!role) return; @@ -165,6 +195,36 @@ export const FormAnswers = ({ formId }: { formId: number }) => { answered. See the form + {form.decisions.map((d) => ( + + + + Decision: {d.label} + + + {[ + ...d.options, + { capacity: null, label: "Undecided", value: "" }, + ].map((o) => { + const n = rows.filter( + (r) => (r.decisions[d.key] ?? "") === o.value + ).length; + const over = o.capacity != null && n > o.capacity; + return ( + + {o.label}: {n} + {o.capacity != null && ` of ${o.capacity}`} + + ); + })} + + + + ))} + {form.questions.map((q) => { const choices = choicesOf(q); if (!choices) return null; @@ -243,6 +303,28 @@ export const FormAnswers = ({ formId }: { formId: number }) => { )} )} + {form.decisions.length > 0 && ( + setDecidedFilter(e.target.value)} + select + size="small" + sx={{ minWidth: 200 }} + value={decidedFilter} + > + Any + {form.decisions.flatMap((d) => + [...d.options, { label: "Undecided", value: "" }].map((o) => ( + + {d.label}: {o.label} + + )) + )} + + )} @@ -293,6 +375,9 @@ export const FormAnswers = ({ formId }: { formId: number }) => { /> Volunteer + {form.decisions.map((d) => ( + {d.label} + ))} {answerable.map((q) => ( {q.label} ))} @@ -318,6 +403,29 @@ export const FormAnswers = ({ formId }: { formId: number }) => { {name(r)} + {form.decisions.map((d) => ( + + + decide(r.shiftboardId, d.key, e.target.value || null) + } + select + size="small" + sx={{ minWidth: 140 }} + value={r.decisions[d.key] ?? ""} + > + Undecided + {d.options.map((o) => ( + + {o.label} + + ))} + + + ))} {answerable.map((q) => ( {show(r.answers[q.id])} ))} diff --git a/client/src/app/forms/[formId]/edit/DecisionsEditor.tsx b/client/src/app/forms/[formId]/edit/DecisionsEditor.tsx new file mode 100644 index 00000000..4349c722 --- /dev/null +++ b/client/src/app/forms/[formId]/edit/DecisionsEditor.tsx @@ -0,0 +1,154 @@ +"use client"; + +import { Delete as DeleteIcon } from "@mui/icons-material"; +import { + Button, + Card, + CardContent, + Checkbox, + FormControlLabel, + IconButton, + MenuItem, + Stack, + TextField, + Typography, +} from "@mui/material"; + +import type { IResRoleRowItem } from "@/components/types/roles"; +import type { IDecisionOption, IFormDecision } from "@/lib/forms"; + +const newId = (p: string) => `${p}${Date.now().toString(36)}`; + +// #845 / #846: what form editors decide per person on the answers page, e.g. +// Camp = Census Lab / Counter Culture / Not this year. Each choice can grant +// a role, have a capacity, and email the person when chosen. +export const DecisionsEditor = ({ + onChange, + roles, + value, +}: { + onChange: (decisions: IFormDecision[]) => void; + roles: IResRoleRowItem[]; + value: IFormDecision[]; +}) => { + const setD = (i: number, patch: Partial) => + onChange(value.map((d, j) => (j === i ? { ...d, ...patch } : d))); + const setO = (i: number, k: number, patch: Partial) => + setD(i, { + options: value[i].options.map((o, j) => + j === k ? { ...o, ...patch } : o + ), + }); + + return ( + <> + + Decisions + + + Made per person on the Answers page. Volunteers never see these here. + + {value.map((d, i) => ( + + + + setD(i, { label: e.target.value })} + value={d.label} + /> + onChange(value.filter((_, j) => j !== i))} + > + + + + {d.options.map((o, k) => ( + + setO(i, k, { label: e.target.value })} + size="small" + value={o.label} + /> + + setO(i, k, { roleId: Number(e.target.value) || null }) + } + select + size="small" + sx={{ minWidth: 180 }} + value={o.roleId ?? ""} + > + None + {roles.map((r) => ( + + {r.name} + + ))} + + + setO(i, k, { + capacity: + e.target.value === "" ? null : Number(e.target.value), + }) + } + size="small" + sx={{ width: 110 }} + type="number" + value={o.capacity ?? ""} + /> + setO(i, k, { email: e.target.checked })} + /> + } + label="Email them" + /> + + setD(i, { options: d.options.filter((_, j) => j !== k) }) + } + > + + + + ))} + + + + ))} + + + ); +}; diff --git a/client/src/app/forms/[formId]/edit/FormEdit.tsx b/client/src/app/forms/[formId]/edit/FormEdit.tsx index 4993d81a..0052f39c 100644 --- a/client/src/app/forms/[formId]/edit/FormEdit.tsx +++ b/client/src/app/forms/[formId]/edit/FormEdit.tsx @@ -24,6 +24,7 @@ import { useSnackbar } from "notistack"; import { useEffect, useState } from "react"; import useSWR from "swr"; +import { DecisionsEditor } from "@/app/forms/[formId]/edit/DecisionsEditor"; import { DescriptionField } from "@/components/content/DescriptionField"; import { ErrorPage } from "@/components/general/ErrorPage"; import { Loading } from "@/components/general/Loading"; @@ -77,6 +78,7 @@ export const FormEdit = ({ formId }: { formId: number }) => { arg: { body: { closesAt: form.closesAt || null, + decisions: form.decisions, hiddenRoleIds: form.hiddenRoleIds, intro: form.intro, inviteRoleIds: form.inviteRoleIds, @@ -313,6 +315,12 @@ export const FormEdit = ({ formId }: { formId: number }) => { Add a question + setForm({ ...form, decisions })} + roles={roles ?? []} + value={form.decisions} + /> + {form.status === "draft" ? "Draft: only form editors can see it, from Preview. Publish when leadership has reviewed it." diff --git a/client/src/components/layout/Footer.tsx b/client/src/components/layout/Footer.tsx index f3850526..1838cfc3 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.00896.C + 2027.G.00897.C diff --git a/client/src/lib/emailTemplates.ts b/client/src/lib/emailTemplates.ts index 5c9e1535..e2cc34f1 100644 --- a/client/src/lib/emailTemplates.ts +++ b/client/src/lib/emailTemplates.ts @@ -50,6 +50,12 @@ export const EMAIL_TEMPLATES = [ label: "Invited to fill in a form", slug: "email.form-invite", }, + { + fields: ["name", "form", "decision", "link"], + html: "

Hi {{name}},

Good news about your {{form}}: {{decision}}.

Watch your Census checklist for what's next: {{link}}

", + label: "Form decision (only choices marked to email)", + slug: "email.form-decision", + }, ] as const; export type EmailSlug = (typeof EMAIL_TEMPLATES)[number]["slug"]; diff --git a/client/src/lib/forms.ts b/client/src/lib/forms.ts index d3dce161..ba172619 100644 --- a/client/src/lib/forms.ts +++ b/client/src/lib/forms.ts @@ -26,8 +26,23 @@ export interface IFormQuestion { export type FormAnswer = string | string[]; export type FormAnswers = Record; +// #845 / #846: what FormEditors decide per person from the answers +export interface IDecisionOption { + capacity?: number | null; + email?: boolean; // email the person when this is chosen + label: string; + roleId?: number | null; // granted when chosen, removed when changed away + value: string; +} +export interface IFormDecision { + key: string; + label: string; + options: IDecisionOption[]; +} + export interface IForm { closesAt: string | null; + decisions: IFormDecision[]; formId: number; hiddenRoleIds: number[]; intro: string; @@ -88,6 +103,48 @@ export const checkQuestions = (questions: unknown): string | null => { return null; }; +const ID_RE = /^[a-z0-9_-]{1,40}$/i; +// A form's decisions as saved by the editor. Returns an error message or null. +export const checkDecisions = (decisions: unknown): string | null => { + if (!Array.isArray(decisions)) return "Decisions must be a list."; + const keys = new Set(); + for (const d of decisions as IFormDecision[]) { + if ( + !d || + typeof d.key !== "string" || + !ID_RE.test(d.key) || + keys.has(d.key) + ) + return "Every decision needs its own id."; + keys.add(d.key); + if (typeof d.label !== "string" || !d.label.trim()) + return "Every decision needs a name."; + if (!Array.isArray(d.options) || d.options.length < 2) + return `"${d.label}" needs at least two choices.`; + const values = new Set(); + for (const o of d.options) { + if ( + !o || + typeof o.value !== "string" || + !ID_RE.test(o.value) || + values.has(o.value) + ) + return `"${d.label}": every choice needs its own id.`; + values.add(o.value); + if (typeof o.label !== "string" || !o.label.trim()) + return `"${d.label}": every choice needs a name.`; + if (o.roleId != null && !Number.isSafeInteger(o.roleId)) + return `"${o.label}": bad role.`; + if ( + o.capacity != null && + !(Number.isInteger(o.capacity) && o.capacity >= 0) + ) + return `"${o.label}": capacity is a whole number.`; + } + } + return null; +}; + // A volunteer's answers against the form. Unknown question ids are dropped; // returns { answers } (cleaned) or { error }. export const checkAnswers = ( diff --git a/client/src/lib/formsDb.ts b/client/src/lib/formsDb.ts index 0d81c0e6..8440e52e 100644 --- a/client/src/lib/formsDb.ts +++ b/client/src/lib/formsDb.ts @@ -3,7 +3,7 @@ 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, +export const FORM_COLS = `f.form_id, f.slug, f.year, f.title, f.intro, f.questions, f.decisions, f.status, f.opens_at, f.closes_at, f.invite_role_ids, f.hidden_role_ids, (f.status = 'published' AND (f.opens_at IS NULL OR f.opens_at <= ${NOW_PT}) @@ -31,6 +31,7 @@ export const parseJson = (v: unknown, fallback: T): T => export const toForm = (r: RowDataPacket): IForm => ({ closesAt: r.closes_at, + decisions: parseJson(r.decisions, null) ?? [], formId: r.form_id, hiddenRoleIds: parseJson(r.hidden_role_ids, null) ?? [], inviteRoleIds: parseJson(r.invite_role_ids, null) ?? [], diff --git a/client/src/pages/api/forms/[formId]/decisions.ts b/client/src/pages/api/forms/[formId]/decisions.ts new file mode 100644 index 00000000..a718af27 --- /dev/null +++ b/client/src/pages/api/forms/[formId]/decisions.ts @@ -0,0 +1,124 @@ +import type { RowDataPacket } from "mysql2"; +import type { NextApiRequest, NextApiResponse } from "next"; + +import { isFormEditor } from "@/lib/authz"; +import { emailBody } from "@/lib/emailTemplates"; +import { sendFormInvites } from "@/lib/formInvites"; +import { FORM_COLS, parseBody, toForm } from "@/lib/formsDb"; +import { withAuth } from "@/lib/withAuth"; +import { pool } from "lib/database"; +import { enqueueEmail } from "lib/mail"; + +const APP_BASE_URL = + process.env.APP_BASE_URL ?? "https://volunteers.census.burningman.org"; + +// PUT /api/forms/[formId]/decisions (#845 / #846), FormEditor only: +// { shiftboardId, key, value } — value = one of the decision's options, or +// null to clear. Only for people who answered the form. +// - the chosen option's role is granted; the decision's other options' roles +// are removed (so changing Census Lab → Counter Culture swaps the role) +// - an option marked email sends email.form-decision, once per person per +// choice (Mew: positive decisions only, so only those options are marked) +// ponytail: removing the other options' roles also removes one granted by +// hand elsewhere; decision roles are meant to be owned by the decision. +const decisions = async ( + req: NextApiRequest, + res: NextApiResponse, + session: { shiftboardId: number } +) => { + if (req.method !== "PUT") + return res + .status(405) + .json({ statusCode: 405, message: "Method not allowed" }); + if (!(await isFormEditor(session.shiftboardId))) + return res.status(403).json({ statusCode: 403, message: "Forbidden" }); + const formId = Number(req.query.formId); + const { key, shiftboardId, value } = parseBody(req.body); + const bad = (message: string) => + res.status(400).json({ statusCode: 400, message }); + + const [rows] = await pool.query( + `SELECT ${FORM_COLS} FROM op_forms f WHERE f.form_id = ?`, + [formId] + ); + const form = rows[0] && toForm(rows[0]); + const decision = form?.decisions.find((d) => d.key === key); + if (!decision) return bad("Unknown decision."); + const option = + value === null ? null : decision.options.find((o) => o.value === value); + if (option === undefined) return bad("Unknown choice."); + const [person] = await pool.query( + `SELECT v.shiftboard_id, v.email, v.playa_name, v.world_name + FROM op_form_responses r + JOIN op_volunteers v ON v.shiftboard_id = r.shiftboard_id + WHERE r.form_id = ? AND r.shiftboard_id = ?`, + [formId, Number(shiftboardId)] + ); + if (!person[0]) + return res + .status(404) + .json({ statusCode: 404, message: "They haven't answered this form." }); + const who = person[0].shiftboard_id as number; + const by = session.shiftboardId; + + await pool.query( + `INSERT INTO op_form_decisions + (form_id, shiftboard_id, decision_key, value, changed_by) + VALUES (?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE value = VALUES(value), changed_by = VALUES(changed_by)`, + [formId, who, decision.key, option?.value ?? null, by] + ); + + const others = decision.options + .map((o) => o.roleId) + .filter((r): r is number => !!r && r !== option?.roleId); + if (others.length) + await pool.query( + `UPDATE op_volunteer_roles + SET changed_by = ?, add_role = false, remove_role = true + WHERE shiftboard_id = ? AND role_id IN (?) AND remove_role = false`, + [by, who, others] + ); + if (option?.roleId) { + const [upd] = await pool.query( + `UPDATE op_volunteer_roles + SET changed_by = ?, add_role = true, remove_role = false + WHERE shiftboard_id = ? AND role_id = ?`, + [by, who, option.roleId] + ); + if (!(upd as { affectedRows: number }).affectedRows) + await pool.query( + `INSERT INTO op_volunteer_roles + (changed_by, add_role, remove_role, role_id, shiftboard_id) + VALUES (?, true, false, ?, ?)`, + [by, option.roleId, who] + ); + await sendFormInvites({ roleId: option.roleId, shiftboardId: who }); + } + + if (option?.email && person[0].email) { + const category = `form-decision:${formId}:${decision.key}:${option.value}`; + const [sent] = await pool.query( + "SELECT 1 FROM op_email_queue WHERE category = ? AND `to` = ? LIMIT 1", + [category, person[0].email] + ); + if (!sent.length) { + const bodyText = await emailBody(pool, "email.form-decision", { + decision: option.label, + form: form!.title, + link: APP_BASE_URL, + name: person[0].playa_name || person[0].world_name || "", + }); + await enqueueEmail({ + bodyText, + category, + recipientShiftboardId: who, + subject: `Census: ${form!.title}: ${option.label}`, + to: person[0].email, + }); + } + } + return res.status(200).json({ ok: true }); +}; + +export default withAuth(decisions); diff --git a/client/src/pages/api/forms/[formId]/index.ts b/client/src/pages/api/forms/[formId]/index.ts index 20a1fdda..06c7b569 100644 --- a/client/src/pages/api/forms/[formId]/index.ts +++ b/client/src/pages/api/forms/[formId]/index.ts @@ -5,6 +5,7 @@ import { isFormEditor } from "@/lib/authz"; import { sanitizeContent } from "@/lib/content"; import { checkAnswers, + checkDecisions, checkQuestions, type IFormQuestion, tidyQuestions, @@ -28,7 +29,7 @@ const DATETIME_RE = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/; // 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?, inviteRoleIds?, hiddenRoleIds? }; then sends any +// opensAt?, closesAt?, inviteRoleIds?, hiddenRoleIds?, decisions? }; then sends any // invite emails now due (lib/formInvites) const form = async ( req: NextApiRequest, @@ -118,6 +119,12 @@ const form = async ( sets.push("questions = ?"); params.push(JSON.stringify(questions)); } + if (body.decisions !== undefined) { + const err = checkDecisions(body.decisions); + if (err) return bad(err); + sets.push("decisions = ?"); + params.push(JSON.stringify(body.decisions)); + } if (body.status !== undefined) { if (body.status !== "draft" && body.status !== "published") return bad("Status is draft or published."); diff --git a/client/src/pages/api/forms/[formId]/responses.ts b/client/src/pages/api/forms/[formId]/responses.ts index 9de56beb..53751bd7 100644 --- a/client/src/pages/api/forms/[formId]/responses.ts +++ b/client/src/pages/api/forms/[formId]/responses.ts @@ -27,9 +27,21 @@ const responses = async ( ORDER BY r.submitted_at`, [Number(req.query.formId)] ); + const [decided] = await pool.query( + `SELECT shiftboard_id, decision_key, value FROM op_form_decisions + WHERE form_id = ? AND value IS NOT NULL`, + [Number(req.query.formId)] + ); + const decisionsOf = (id: number) => + Object.fromEntries( + decided + .filter((d) => d.shiftboard_id === id) + .map((d) => [d.decision_key, d.value]) + ); return res.status(200).json( rows.map((r) => ({ answers: parseJson(r.answers, {}), + decisions: decisionsOf(r.shiftboard_id), playaName: r.playa_name ?? "", shiftboardId: r.shiftboard_id, submittedAt: r.submitted_at, diff --git a/client/src/pages/api/forms/index.ts b/client/src/pages/api/forms/index.ts index 5c424df9..990378ce 100644 --- a/client/src/pages/api/forms/index.ts +++ b/client/src/pages/api/forms/index.ts @@ -10,7 +10,7 @@ import { pool } from "lib/database"; // GET → the open forms for the signed-in volunteer, with // submittedAt (checklist). ?for=: that volunteer's // (owner or admin). ?all=1 (FormEditor): every form, every year. -// POST (SuperAdmin / FormEditor) { slug, year, title } → new draft. Questions and intro are +// POST (SuperAdmin / FormEditor) { slug, year, title } → new draft. Questions, intro and decisions are // copied from the latest earlier year of the same slug. const forms = async ( req: NextApiRequest, @@ -59,21 +59,22 @@ const forms = async ( .status(400) .json({ statusCode: 400, message: "Need slug, year and title" }); const [prev] = await pool.query( - `SELECT intro, questions FROM op_forms + `SELECT intro, questions, decisions 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 (?, ?, ?, ?, ?, ?)`, + `INSERT INTO op_forms (slug, year, title, intro, questions, decisions, changed_by) + VALUES (?, ?, ?, ?, ?, ?, ?)`, [ slug, year, title.trim(), prev[0]?.intro ?? "", questions, + prev[0]?.decisions ?? null, session.shiftboardId, ] ); diff --git a/migrations/035_form_decisions.sql b/migrations/035_form_decisions.sql new file mode 100644 index 00000000..647bb385 --- /dev/null +++ b/migrations/035_form_decisions.sql @@ -0,0 +1,15 @@ +-- #845 / #846: decisions on a form's answers (Camping: which camp; Ticketing: +-- ticket + vehicle pass; later the Driver approval). The form defines them +-- (op_forms.decisions, JSON: [{key, label, options: [{value, label, roleId, +-- capacity, email}]}]); one row per person per decision holds the choice. +-- Versioned with changed_by, so history says who decided and when. +SET @@system_versioning_alter_history = KEEP; +ALTER TABLE op_forms ADD COLUMN IF NOT EXISTS decisions JSON NULL AFTER questions; +CREATE TABLE IF NOT EXISTS op_form_decisions ( + form_id INT NOT NULL, + shiftboard_id BIGINT NOT NULL, + decision_key VARCHAR(40) NOT NULL, + value VARCHAR(40) NULL, + changed_by BIGINT NULL, + PRIMARY KEY (form_id, shiftboard_id, decision_key) +) WITH SYSTEM VERSIONING;