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
1 change: 1 addition & 0 deletions client/e2e/helpers/actorGuard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
129 changes: 129 additions & 0 deletions client/e2e/tests/39-forms.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
});
});
1 change: 1 addition & 0 deletions client/src/app/emails/Emails.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { EMAIL_TEMPLATES } from "@/lib/emailTemplates";

const FIELD_HELP: Record<string, string> = {
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)",
Expand Down
118 changes: 113 additions & 5 deletions client/src/app/forms/[formId]/answers/FormAnswers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { fetcherGet, fetcherTrigger } from "@/utils/fetcher";

interface IResponse {
answers: Answers;
decisions: Record<string, string>;
playaName: string;
shiftboardId: number;
submittedAt: string;
Expand Down Expand Up @@ -66,25 +67,32 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
`/api/forms/${formId}`,
fetcherGet
);
const { data: rows, error: rowsError } = useSWR<IResponse[]>(
`/api/forms/${formId}/responses`,
fetcherGet
);
const {
data: rows,
error: rowsError,
mutate: mutateRows,
} = useSWR<IResponse[]>(`/api/forms/${formId}/responses`, fetcherGet);
const { data: roles } = useSWR<IResRoleRowItem[]>("/api/roles", fetcherGet);
const { enqueueSnackbar } = useSnackbar();
const [filter, setFilter] = useState({ answer: "", questionId: "" });
const [picked, setPicked] = useState<Set<number>>(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 <ErrorPage />;
Expand All @@ -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 = [
Expand All @@ -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])),
]),
];
Expand All @@ -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(<SnackbarText>{(err as Error).message}</SnackbarText>, {
variant: "error",
});
}
};

const addRole = async () => {
const role = roles?.find((r) => r.id === Number(roleId));
if (!role) return;
Expand Down Expand Up @@ -165,6 +195,36 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
answered. <Link href={`/forms/${formId}`}>See the form</Link>
</Typography>

{form.decisions.map((d) => (
<Card key={d.key} sx={{ mb: 2 }}>
<CardContent>
<Typography sx={{ mb: 1 }} variant="subtitle1">
Decision: {d.label}
</Typography>
<Stack direction="row" flexWrap="wrap" gap={3}>
{[
...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 (
<Typography
color={over ? "error" : undefined}
key={o.value}
>
{o.label}: <strong>{n}</strong>
{o.capacity != null && ` of ${o.capacity}`}
</Typography>
);
})}
</Stack>
</CardContent>
</Card>
))}

{form.questions.map((q) => {
const choices = choicesOf(q);
if (!choices) return null;
Expand Down Expand Up @@ -243,6 +303,28 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
)}
</TextField>
)}
{form.decisions.length > 0 && (
<TextField
label="Decision"
onChange={(e) => setDecidedFilter(e.target.value)}
select
size="small"
sx={{ minWidth: 200 }}
value={decidedFilter}
>
<MenuItem value="">Any</MenuItem>
{form.decisions.flatMap((d) =>
[...d.options, { label: "Undecided", value: "" }].map((o) => (
<MenuItem
key={`${d.key}|${o.value}`}
value={`${d.key}|${o.value}`}
>
{d.label}: {o.label}
</MenuItem>
))
)}
</TextField>
)}
<Button onClick={downloadCsv}>Download CSV ({shown.length})</Button>
</Stack>

Expand Down Expand Up @@ -293,6 +375,9 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
/>
</TableCell>
<TableCell>Volunteer</TableCell>
{form.decisions.map((d) => (
<TableCell key={d.key}>{d.label}</TableCell>
))}
{answerable.map((q) => (
<TableCell key={q.id}>{q.label}</TableCell>
))}
Expand All @@ -318,6 +403,29 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
{name(r)}
</Link>
</TableCell>
{form.decisions.map((d) => (
<TableCell key={d.key}>
<TextField
inputProps={{
"aria-label": `${d.label} for ${name(r)}`,
}}
onChange={(e) =>
decide(r.shiftboardId, d.key, e.target.value || null)
}
select
size="small"
sx={{ minWidth: 140 }}
value={r.decisions[d.key] ?? ""}
>
<MenuItem value="">Undecided</MenuItem>
{d.options.map((o) => (
<MenuItem key={o.value} value={o.value}>
{o.label}
</MenuItem>
))}
</TextField>
</TableCell>
))}
{answerable.map((q) => (
<TableCell key={q.id}>{show(r.answers[q.id])}</TableCell>
))}
Expand Down
Loading
Loading