diff --git a/client/e2e/tests/39-forms.spec.ts b/client/e2e/tests/39-forms.spec.ts index e707dc29..3e1af30b 100644 --- a/client/e2e/tests/39-forms.spec.ts +++ b/client/e2e/tests/39-forms.spec.ts @@ -5,11 +5,13 @@ import { cleanupAllTestData, closePool, getPool, + insertRole, insertVolunteer, } from "../helpers/db"; import { buildSessionCookieHeader } from "../helpers/session"; import { makeTestVolunteer, + ROLE_ADMIN_ID, signInAs, ROLE_BEHAVIORAL_STANDARDS_ID, } from "../fixtures/test-data"; @@ -59,6 +61,9 @@ const cleanup = async () => { [SLUG] ); await db.execute("DELETE FROM op_forms WHERE slug = ?", [SLUG]); + await db.execute("DELETE FROM op_email_queue WHERE `to` = ?", [ + volunteer.email, + ]); }; test.describe("Yearly forms (#844)", () => { @@ -221,4 +226,67 @@ test.describe("Yearly forms (#844)", () => { roles: ["Lab"], }); }); + + test("invite-only: the invite role shows it and emails once; hidden wins", async ({ + request, + }) => { + const INVITE_ROLE_ID = 9_000_522; + const HIDE_ROLE_ID = 9_000_523; + await insertRole(INVITE_ROLE_ID, "E2E Camping Invite"); + await insertRole(HIDE_ROLE_ID, "E2E No Camping"); + await assignRole(editor.shiftboardId, ROLE_ADMIN_ID); // to grant roles + const made = await request.post("/api/forms", { + data: JSON.stringify({ slug: SLUG, title: "E2E Camping", year: 2096 }), + headers: as(editor.shiftboardId), + }); + const { formId } = await made.json(); + const patched = await request.patch(`/api/forms/${formId}`, { + data: JSON.stringify({ + hiddenRoleId: HIDE_ROLE_ID, + inviteRoleId: INVITE_ROLE_ID, + questions: QUESTIONS, + status: "published", + }), + headers: as(editor.shiftboardId), + }); + expect(patched.status()).toBe(200); + + const listed = async () => + ( + await ( + await request.get("/api/forms", { + headers: as(volunteer.shiftboardId), + }) + ).json() + ).some((f: { formId: number }) => f.formId === formId); + const get = () => + request.get(`/api/forms/${formId}`, { + headers: as(volunteer.shiftboardId), + }); + const invites = async () => { + const [rows] = await getPool().query( + "SELECT COUNT(*) AS n FROM op_email_queue WHERE category = ? AND `to` = ?", + [`form-invite:${formId}`, volunteer.email] + ); + return Number((rows as { n: number }[])[0].n); + }; + expect(await listed()).toBe(false); + expect((await get()).status()).toBe(404); + + const invite = () => + request.post(`/api/roles/${INVITE_ROLE_ID}/volunteers`, { + data: JSON.stringify({ shiftboardId: volunteer.shiftboardId }), + headers: as(editor.shiftboardId), + }); + expect((await invite()).status()).toBe(201); + expect(await listed()).toBe(true); + expect((await get()).status()).toBe(200); + expect(await invites()).toBe(1); + await invite(); // again: no second email + expect(await invites()).toBe(1); + + await assignRole(volunteer.shiftboardId, HIDE_ROLE_ID); + expect(await listed()).toBe(false); + expect((await get()).status()).toBe(404); + }); }); diff --git a/client/src/app/emails/Emails.tsx b/client/src/app/emails/Emails.tsx index 30c17c66..da15ff82 100644 --- a/client/src/app/emails/Emails.tsx +++ b/client/src/app/emails/Emails.tsx @@ -8,8 +8,10 @@ import { EMAIL_TEMPLATES } from "@/lib/emailTemplates"; const FIELD_HELP: Record = { by: 'who did it, e.g. "by Chipper"', + form: "the form's title", link: "the app's address", name: "playa name (or world name)", + opens: 'when it opens, e.g. " It opens 2027-01-15." (blank once open)', shift: "the shift's name, day, time, notes and location", via: "a note when it came through pumpkin, otherwise blank", }; @@ -29,9 +31,9 @@ export const Emails = () => { /> - The text of the emails volunteers get about their shifts. Words in - double curly brackets are filled in when the email is sent; keep them - as typed. + The text of the emails volunteers get about their shifts and forms. + Words in double curly brackets are filled in when the email is sent; + keep them as typed. {EMAIL_TEMPLATES.map((t) => ( diff --git a/client/src/app/forms/[formId]/edit/FormEdit.tsx b/client/src/app/forms/[formId]/edit/FormEdit.tsx index c814eabd..7f22cfc9 100644 --- a/client/src/app/forms/[formId]/edit/FormEdit.tsx +++ b/client/src/app/forms/[formId]/edit/FormEdit.tsx @@ -29,6 +29,7 @@ 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 { type IForm, type IFormQuestion, @@ -41,13 +42,14 @@ 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 → the form editors review it via Preview → Publish. +// /forms/[formId]/edit (#844), SuperAdmin / FormEditor (the API enforces it): +// the form's text, questions, dates, who it's for, 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}`, fetcherGet ); + const { data: roles } = useSWR("/api/roles", fetcherGet); const { enqueueSnackbar } = useSnackbar(); const [form, setForm] = useState(null); useEffect(() => { @@ -75,7 +77,9 @@ export const FormEdit = ({ formId }: { formId: number }) => { arg: { body: { closesAt: form.closesAt || null, + hiddenRoleId: form.hiddenRoleId, intro: form.intro, + inviteRoleId: form.inviteRoleId, opensAt: form.opensAt || null, questions: form.questions, status, @@ -140,6 +144,41 @@ export const FormEdit = ({ formId }: { formId: number }) => { value={toInput(form.closesAt)} /> + + {( + [ + [ + "inviteRoleId", + "Only for role", + "Blank = everyone. Invite people by giving them this role; they get the invite email.", + ], + [ + "hiddenRoleId", + "Hidden from role", + "e.g. NoCamping: never shown to them, even if invited.", + ], + ] as const + ).map(([key, label, help]) => ( + + setForm({ ...form, [key]: Number(e.target.value) || null }) + } + select + value={form[key] ?? ""} + > + None + {(roles ?? []).map((r) => ( + + {r.name} + + ))} + + ))} + {form.questions.map((q, i) => ( diff --git a/client/src/components/layout/Footer.tsx b/client/src/components/layout/Footer.tsx index 4d694721..fca8661a 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.00894.C + 2027.G.00895.C diff --git a/client/src/lib/emailTemplates.ts b/client/src/lib/emailTemplates.ts index ec7aa721..5c9e1535 100644 --- a/client/src/lib/emailTemplates.ts +++ b/client/src/lib/emailTemplates.ts @@ -44,6 +44,12 @@ export const EMAIL_TEMPLATES = [ label: "Canceled shift is back on", slug: "email.shift-restored", }, + { + fields: ["name", "form", "opens", "link"], + html: "

Hi {{name}},

You're invited to fill in {{form}}.{{opens}}

You'll find it on your Census checklist: {{link}}

", + label: "Invited to fill in a form", + slug: "email.form-invite", + }, ] as const; export type EmailSlug = (typeof EMAIL_TEMPLATES)[number]["slug"]; diff --git a/client/src/lib/exclusions.ts b/client/src/lib/exclusions.ts index 85d016c3..5eced94f 100644 --- a/client/src/lib/exclusions.ts +++ b/client/src/lib/exclusions.ts @@ -3,7 +3,7 @@ // holds that role doesn't see them and can't sign up. // SQL: true when volunteer `who` (a column or an integer) holds `roleCol`. -const holds = (roleCol: string, who: string) => +export const holds = (roleCol: string, who: string) => `EXISTS (SELECT 1 FROM op_volunteer_roles hvr WHERE hvr.role_id = ${roleCol} AND hvr.shiftboard_id = ${who} AND hvr.remove_role = false)`; diff --git a/client/src/lib/formInvites.ts b/client/src/lib/formInvites.ts new file mode 100644 index 00000000..70dd008d --- /dev/null +++ b/client/src/lib/formInvites.ts @@ -0,0 +1,69 @@ +import type { RowDataPacket } from "mysql2"; + +import { NOW_PT } from "@/lib/content"; +import { emailBody } from "@/lib/emailTemplates"; +import { holds } from "@/lib/exclusions"; +import { pool } from "lib/database"; +import { enqueueEmail } from "lib/mail"; + +const APP_BASE_URL = + process.env.APP_BASE_URL ?? "https://volunteers.census.burningman.org"; + +// #844: "you're invited to fill in X", once per person per form. Due when the +// form is published (not closed) and the person holds its invite role and not +// its hidden role. Called after a form is saved and after a role is granted, +// so whichever happens last sends it. The email queue is the record of who +// got one (category form-invite:). DoNotContact / unsubscribed are +// skipped by the queue itself. +// ponytail: a skipped (DNC) person is re-checked on every call; cheap. +export const sendFormInvites = async (scope: { + formId?: number; + roleId?: number; + shiftboardId?: number; +}) => { + const filters = [ + ["f.form_id", scope.formId], + ["f.invite_role_id", scope.roleId], + ["v.shiftboard_id", scope.shiftboardId], + ] as const; + const where = filters.filter(([, v]) => v).map(([col]) => `AND ${col} = ?`); + const params = filters.flatMap(([, v]) => (v ? [v] : [])); + try { + const [due] = await pool.query( + `SELECT f.form_id, f.title, f.opens_at, (f.opens_at > ${NOW_PT}) AS not_yet, + v.shiftboard_id, v.email, v.playa_name, v.world_name + FROM op_forms f + JOIN op_volunteer_roles ivr + ON ivr.role_id = f.invite_role_id AND ivr.remove_role = false + JOIN op_volunteers v + ON v.shiftboard_id = ivr.shiftboard_id AND v.delete_volunteer = false + WHERE f.status = 'published' + AND (f.closes_at IS NULL OR f.closes_at > ${NOW_PT}) + AND COALESCE(v.email, '') <> '' + AND (f.hidden_role_id IS NULL + OR NOT ${holds("f.hidden_role_id", "v.shiftboard_id")}) + AND NOT EXISTS (SELECT 1 FROM op_email_queue q + WHERE q.category = CONCAT('form-invite:', f.form_id) AND q.\`to\` = v.email) + ${where.join(" ")}`, + params + ); + for (const r of due) { + const bodyText = await emailBody(pool, "email.form-invite", { + form: r.title, + link: `${APP_BASE_URL}/forms/${r.form_id}`, + name: r.playa_name || r.world_name || "", + opens: r.not_yet ? ` It opens ${String(r.opens_at).slice(0, 10)}.` : "", + }); + await enqueueEmail({ + bodyText, + category: `form-invite:${r.form_id}`, + recipientShiftboardId: r.shiftboard_id, + subject: `Census: you're invited to fill in ${r.title}`, + to: r.email, + }); + } + } catch (err) { + // never fail the save / role grant over an email + console.error("[forms] invite emails failed", err); + } +}; diff --git a/client/src/lib/forms.ts b/client/src/lib/forms.ts index d3ba6da5..d18ce248 100644 --- a/client/src/lib/forms.ts +++ b/client/src/lib/forms.ts @@ -29,7 +29,9 @@ export type FormAnswers = Record; export interface IForm { closesAt: string | null; formId: number; + hiddenRoleId: number | null; intro: string; + inviteRoleId: number | null; isOpen: boolean; opensAt: string | null; questions: IFormQuestion[]; diff --git a/client/src/lib/formsDb.ts b/client/src/lib/formsDb.ts index ff7924c0..005ec59a 100644 --- a/client/src/lib/formsDb.ts +++ b/client/src/lib/formsDb.ts @@ -1,21 +1,32 @@ import type { RowDataPacket } from "mysql2"; import { NOW_PT } from "@/lib/content"; +import { holds } from "@/lib/exclusions"; 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, f.opens_at, f.closes_at, f.invite_role_id, f.hidden_role_id, (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 +// SQL: may volunteer `who` (an integer) see form `f`? Invite-only forms need +// the invite role; the hidden role (e.g. NoCamping) always wins (#848). +export const canSeeSql = (who: number) => { + const id = String(Math.trunc(who)); + return `((f.invite_role_id IS NULL OR ${holds("f.invite_role_id", id)}) + AND (f.hidden_role_id IS NULL OR NOT ${holds("f.hidden_role_id", id)}))`; +}; + 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, + hiddenRoleId: r.hidden_role_id ?? null, + inviteRoleId: r.invite_role_id ?? null, intro: r.intro ?? "", isOpen: Boolean(r.is_open), opensAt: r.opens_at, diff --git a/client/src/pages/api/forms/[formId]/index.ts b/client/src/pages/api/forms/[formId]/index.ts index dbe74996..94b13a61 100644 --- a/client/src/pages/api/forms/[formId]/index.ts +++ b/client/src/pages/api/forms/[formId]/index.ts @@ -9,7 +9,14 @@ import { type IFormQuestion, tidyQuestions, } from "@/lib/forms"; -import { FORM_COLS, parseBody, parseJson, toForm } from "@/lib/formsDb"; +import { sendFormInvites } from "@/lib/formInvites"; +import { + canSeeSql, + FORM_COLS, + parseBody, + parseJson, + toForm, +} from "@/lib/formsDb"; import { withAuth } from "@/lib/withAuth"; import { pool } from "lib/database"; @@ -20,7 +27,9 @@ const DATETIME_RE = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/; // 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? } +// PATCH (SuperAdmin / FormEditor) { title?, intro?, questions?, status?, +// opensAt?, closesAt?, inviteRoleId?, hiddenRoleId? }; then sends any +// invite emails now due (lib/formInvites) const form = async ( req: NextApiRequest, res: NextApiResponse, @@ -28,20 +37,20 @@ const form = async ( ) => { const formId = Number(req.query.formId); const [rows] = await pool.query( - `SELECT ${FORM_COLS} FROM op_forms f WHERE f.form_id = ?`, + `SELECT ${FORM_COLS}, ${canSeeSql(session.shiftboardId)} AS can_see + 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(); + // volunteers only reach published forms they're invited to / not hidden from + const canSee = found.status === "published" && Boolean(rows[0].can_see); switch (req.method) { case "GET": { - if ( - found.status !== "published" && - !(await isFormEditor(session.shiftboardId)) - ) + if (!canSee && !(await isFormEditor(session.shiftboardId))) return notFound(); const [mine] = await pool.query( `SELECT answers FROM op_form_responses @@ -54,6 +63,7 @@ const form = async ( }); } case "PUT": { + if (!canSee) return notFound(); if (!found.isOpen) return res .status(409) @@ -125,11 +135,23 @@ const form = async ( sets.push(`${col} = ?`); params.push(v === null ? null : v.replace("T", " ")); } + for (const [key, col] of [ + ["inviteRoleId", "invite_role_id"], + ["hiddenRoleId", "hidden_role_id"], + ] as const) { + const v = body[key]; + if (v === undefined) continue; + if (v !== null && !Number.isSafeInteger(v)) + return bad("Pick a role, or none."); + sets.push(`${col} = ?`); + params.push(v || null); + } 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] ); + await sendFormInvites({ formId }); return res.status(200).json({ ok: true }); } default: diff --git a/client/src/pages/api/forms/index.ts b/client/src/pages/api/forms/index.ts index 7339f4d0..5c424df9 100644 --- a/client/src/pages/api/forms/index.ts +++ b/client/src/pages/api/forms/index.ts @@ -2,7 +2,7 @@ import type { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; import { isFormEditor, isOwnerOrAdmin } from "@/lib/authz"; -import { FORM_COLS, parseBody, toForm } from "@/lib/formsDb"; +import { canSeeSql, FORM_COLS, parseBody, toForm } from "@/lib/formsDb"; import { withAuth } from "@/lib/withAuth"; import { pool } from "lib/database"; @@ -30,13 +30,14 @@ const forms = async ( return res.status(200).json(rows.map(toForm)); } const who = Number(req.query.for ?? session.shiftboardId); - if (!(await isOwnerOrAdmin(session, who))) + if (!Number.isSafeInteger(who) || !(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 = ? + WHERE ${canSeeSql(who)} HAVING is_open ORDER BY f.opens_at, f.form_id`, [who] diff --git a/client/src/pages/api/roles/[roleId]/volunteers/index.ts b/client/src/pages/api/roles/[roleId]/volunteers/index.ts index 42be8351..e8a538fb 100644 --- a/client/src/pages/api/roles/[roleId]/volunteers/index.ts +++ b/client/src/pages/api/roles/[roleId]/volunteers/index.ts @@ -10,6 +10,7 @@ import { isAdmin, isSuperAdmin } from "@/lib/authz"; import { withAuth } from "@/lib/withAuth"; import { pool } from "lib/database"; import { actor } from "@/lib/actor"; +import { sendFormInvites } from "@/lib/formInvites"; const roleVolunteers = async (req: NextApiRequest, res: NextApiResponse) => { const { roleId } = req.query; @@ -90,6 +91,12 @@ const roleVolunteers = async (req: NextApiRequest, res: NextApiResponse) => { ); } + // #844: an invite role for a published form sends its invite email + await sendFormInvites({ + roleId: Number(roleId), + shiftboardId: Number(shiftboardId), + }); + return res.status(201).json({ statusCode: 201, message: "Created", diff --git a/migrations/033_form_invites.sql b/migrations/033_form_invites.sql new file mode 100644 index 00000000..d5f6c50c --- /dev/null +++ b/migrations/033_form_invites.sql @@ -0,0 +1,7 @@ +-- #844 / #845 / #846: invite-only forms. Inviting = giving the invite role +-- (Mew 2026-11-29, same idea as the #848 exclusions): only holders of +-- invite_role_id see the form; holders of hidden_role_id (e.g. NoCamping) +-- never do. NULL = no limit. +SET @@system_versioning_alter_history = KEEP; +ALTER TABLE op_forms ADD COLUMN IF NOT EXISTS invite_role_id BIGINT NULL AFTER closes_at; +ALTER TABLE op_forms ADD COLUMN IF NOT EXISTS hidden_role_id BIGINT NULL AFTER invite_role_id;