Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions client/e2e/tests/39-forms.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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)", () => {
Expand Down Expand Up @@ -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);
});
});
8 changes: 5 additions & 3 deletions client/src/app/emails/Emails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import { EMAIL_TEMPLATES } from "@/lib/emailTemplates";

const FIELD_HELP: Record<string, string> = {
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",
};
Expand All @@ -29,9 +31,9 @@ export const Emails = () => {
/>
<Container component="main" sx={{ mb: 6 }}>
<Typography sx={{ mb: 2 }}>
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.
</Typography>
{EMAIL_TEMPLATES.map((t) => (
<Card key={t.slug} sx={{ mb: 2 }}>
Expand Down
43 changes: 41 additions & 2 deletions client/src/app/forms/[formId]/edit/FormEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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<IResRoleRowItem[]>("/api/roles", fetcherGet);
const { enqueueSnackbar } = useSnackbar();
const [form, setForm] = useState<IForm | null>(null);
useEffect(() => {
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -140,6 +144,41 @@ export const FormEdit = ({ formId }: { formId: number }) => {
value={toInput(form.closesAt)}
/>
</Stack>
<Stack direction={{ xs: "column", sm: "row" }} gap={2}>
{(
[
[
"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]) => (
<TextField
fullWidth
helperText={help}
key={key}
label={label}
onChange={(e) =>
setForm({ ...form, [key]: Number(e.target.value) || null })
}
select
value={form[key] ?? ""}
>
<MenuItem value="">None</MenuItem>
{(roles ?? []).map((r) => (
<MenuItem key={r.id} value={r.id}>
{r.name}
</MenuItem>
))}
</TextField>
))}
</Stack>
</Stack>

{form.questions.map((q, i) => (
Expand Down
2 changes: 1 addition & 1 deletion client/src/components/layout/Footer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ export const Footer = () => {
color: theme.palette.common.white,
}}
>
2027.G.00894.C
2027.G.00895.C
</Typography>
</Stack>
</Container>
Expand Down
6 changes: 6 additions & 0 deletions client/src/lib/emailTemplates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,12 @@ export const EMAIL_TEMPLATES = [
label: "Canceled shift is back on",
slug: "email.shift-restored",
},
{
fields: ["name", "form", "opens", "link"],
html: "<p>Hi {{name}},</p><p>You're invited to fill in {{form}}.{{opens}}</p><p>You'll find it on your Census checklist: {{link}}</p>",
label: "Invited to fill in a form",
slug: "email.form-invite",
},
] as const;

export type EmailSlug = (typeof EMAIL_TEMPLATES)[number]["slug"];
Expand Down
2 changes: 1 addition & 1 deletion client/src/lib/exclusions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)`;
Expand Down
69 changes: 69 additions & 0 deletions client/src/lib/formInvites.ts
Original file line number Diff line number Diff line change
@@ -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:<id>). 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<RowDataPacket[]>(
`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);
}
};
2 changes: 2 additions & 0 deletions client/src/lib/forms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ export type FormAnswers = Record<string, FormAnswer>;
export interface IForm {
closesAt: string | null;
formId: number;
hiddenRoleId: number | null;
intro: string;
inviteRoleId: number | null;
isOpen: boolean;
opensAt: string | null;
questions: IFormQuestion[];
Expand Down
13 changes: 12 additions & 1 deletion client/src/lib/formsDb.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(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,
Expand Down
Loading
Loading