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
73 changes: 73 additions & 0 deletions client/e2e/tests/39-forms.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -514,4 +514,77 @@ test.describe("Yearly forms (#844)", () => {
await page.getByLabel("Tent", { exact: true }).check();
await expect(page.getByLabel("Tent size")).toBeVisible();
});

test("answers show the involvement score (#771)", async ({ request }) => {
const db = getPool();
const made = await request.post("/api/forms", {
data: JSON.stringify({ slug: SLUG, title: "E2E Score", year: 2093 }),
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 request.put(`/api/forms/${formId}`, {
data: JSON.stringify({ answers: { plans: "Yes" } }),
headers: as(volunteer.shiftboardId),
});
// [burn_year, csp, hours, lead, category, off_playa, canceled, checked_in, score]
const rows: [
number,
number,
number,
number,
string,
number,
number,
number,
number | null,
][] = [
[2093, 4, 4, 1, "Gate Sampling", 0, 0, 1, 4], // 4 × 2 × 1.5 × 1.25 = 15
[2092, 0, 1, 0, "Meeting", 1, 0, 1, null], // off-playa 0.25
[2093, 0, 2, 0, "Lab", 0, 0, 1, null], // hours / 4 = 0.5
[2091, 3, 3, 0, "Lab", 0, 0, 0, null], // no-show −1 × 0.5
[2087, 2, 2, 0, "Lab", 0, 1, 0, null], // canceled: CSP 2 × 0.1
[2094, 9, 9, 0, "Lab", 0, 0, 1, null], // after the form's year: ignored
];
for (const [
i,
[y, csp, hours, lead, cat, off, canc, inn, score],
] of rows.entries())
await db.execute(
`INSERT INTO op_shift_history (source, source_id, burn_year, shiftboard_id,
date, start_time, hours, shift_category, shift_name, shift_key, is_lead,
off_playa, csp, canceled, checked_in, score)
VALUES ('app', ?, ?, ?, ?, ?, ?, ?, 'E2E', 'e2e', ?, ?, ?, ?, ?, ?)`,
[
i + 1,
y,
volunteer.shiftboardId,
`${y}-08-30`,
`${y}-08-30 10:00:00`,
hours,
cat,
lead,
off,
csp,
canc,
inn,
score,
]
);
try {
const got = await (
await request.get(`/api/forms/${formId}/responses`, {
headers: as(editor.shiftboardId),
})
).json();
expect(got[0].score).toBe(Math.round(16 * (15 + 0.25 + 0.5 - 0.5 + 0.2))); // 247
} finally {
await db.execute("DELETE FROM op_shift_history WHERE shiftboard_id = ?", [
volunteer.shiftboardId,
]);
}
});
});
37 changes: 27 additions & 10 deletions client/src/app/forms/[formId]/answers/FormAnswers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
TableCell,
TableHead,
TableRow,
TableSortLabel,
TextField,
Typography,
} from "@mui/material";
Expand All @@ -39,6 +40,7 @@ import { fetcherGet, fetcherTrigger } from "@/utils/fetcher";
interface IResponse {
answers: Answers;
decisions: Record<string, string>;
score: number;
playaName: string;
shiftboardId: number;
submittedAt: string;
Expand Down Expand Up @@ -79,20 +81,23 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
const [roleId, setRoleId] = useState("");
// "key|value" — value "" = undecided
const [decidedFilter, setDecidedFilter] = useState("");
const [byScore, setByScore] = useState(false);

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);
}),
[decidedFilter, form, rows, filter]
(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);
})
.sort((a, b) => (byScore ? b.score - a.score : 0)),
[byScore, decidedFilter, form, rows, filter]
);

if (formError || rowsError) return <ErrorPage />;
Expand All @@ -109,6 +114,7 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
"playa_name",
"world_name",
"submitted_at",
"score",
...form.decisions.map((d) => d.label),
...answerable.map((q) => q.label),
];
Expand All @@ -119,6 +125,7 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
r.playaName,
r.worldName,
r.submittedAt,
r.score,
...form.decisions.map(
(d) =>
d.options.find((o) => o.value === r.decisions[d.key])?.label ?? ""
Expand Down Expand Up @@ -375,6 +382,15 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
/>
</TableCell>
<TableCell>Volunteer</TableCell>
<TableCell sortDirection={byScore ? "desc" : false}>
<TableSortLabel
active={byScore}
direction="desc"
onClick={() => setByScore(!byScore)}
>
Score
</TableSortLabel>
</TableCell>
{form.decisions.map((d) => (
<TableCell key={d.key}>{d.label}</TableCell>
))}
Expand Down Expand Up @@ -403,6 +419,7 @@ export const FormAnswers = ({ formId }: { formId: number }) => {
{name(r)}
</Link>
</TableCell>
<TableCell>{r.score}</TableCell>
{form.decisions.map((d) => (
<TableCell key={d.key}>
<TextField
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.00898.C
2027.G.00899.C
</Typography>
</Stack>
</Container>
Expand Down
59 changes: 59 additions & 0 deletions client/src/lib/involvementScore.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import type { RowDataPacket } from "mysql2";

import { pool } from "lib/database";

// #771: the Census involvement score, from the permanent shift record
// (op_shift_history, #808). Decided on #771 (Mew 2026-10-02, 11/11, 11/27);
// the no-show penalty, Core Crew bonus and decay keep the old postplaya.php
// values until they're discussed (Mew 2026-11-27).
//
// score = 16 × ( Σ shift value × decay + 25 if Core Crew )
// value = canceled : CSP × lead × sampling (counts, never a penalty)
// not checked in : −1
// CSP > 0 : CSP × lead × sampling × review
// off-playa, CSP 0 : 0.25 (meetings, Mew 11/11)
// on-playa, CSP 0 : hours / 4
// lead = lead 2, critical 1.5, else 1
// sampling = a "… Sampling" category 1.5 (not Random Sampling Training)
// review = exceeds / leadership 1.25, needs coaching 0.25, not a good
// fit 0.1, else 1
// decay = by burn year before `asOfYear`: 0–1 ×1, 2 ×0.5, 3 ×0.25, older ×0.1
// ponytail: reads the archive only, so this season's shifts count once its
// burn year is loaded into op_shift_history (etl/shift_history.py).
const valueSql = (asOfYear: number) => {
const age = `(${Math.trunc(asOfYear)} - h.burn_year)`;
const lead =
"CASE WHEN h.is_lead THEN 2 WHEN h.is_critical THEN 1.5 ELSE 1 END";
const sampling =
"CASE WHEN h.shift_category LIKE '%Sampling' THEN 1.5 ELSE 1 END";
const review = `CASE WHEN h.score_scale = 'app1-5' AND h.raw_score = 1 THEN 0.1
WHEN h.score = 2 THEN 0.25 WHEN h.score = 4 THEN 1.25 ELSE 1 END`;
return `(CASE
WHEN h.canceled THEN h.csp * ${lead} * ${sampling}
WHEN NOT h.checked_in THEN -1
WHEN h.csp > 0 THEN h.csp * ${lead} * ${sampling} * ${review}
WHEN h.off_playa THEN 0.25
ELSE h.hours / 4
END) * (CASE WHEN ${age} <= 1 THEN 1 WHEN ${age} = 2 THEN 0.5
WHEN ${age} = 3 THEN 0.25 ELSE 0.1 END)`;
};

// shiftboard_id → score as of burn year `asOfYear` (people with none → 0).
export const involvementScores = async (
ids: number[],
asOfYear: number
): Promise<Map<number, number>> => {
if (!ids.length) return new Map();
const [rows] = await pool.query<RowDataPacket[]>(
`SELECT id, ROUND(16 * SUM(pts)) AS score FROM (
SELECT h.shiftboard_id AS id, ${valueSql(asOfYear)} AS pts
FROM op_shift_history h
WHERE h.shiftboard_id IN (?) AND h.burn_year <= ?
UNION ALL
SELECT shiftboard_id, 25 FROM op_volunteers
WHERE core_crew AND shiftboard_id IN (?)
) x GROUP BY id`,
[ids, asOfYear, ids]
);
return new Map(rows.map((r) => [Number(r.id), Number(r.score)]));
};
11 changes: 11 additions & 0 deletions client/src/pages/api/forms/[formId]/responses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { NextApiRequest, NextApiResponse } from "next";

import { isFormEditor } from "@/lib/authz";
import { parseJson } from "@/lib/formsDb";
import { involvementScores } from "@/lib/involvementScore";
import { withAuth } from "@/lib/withAuth";
import { pool } from "lib/database";

Expand Down Expand Up @@ -38,11 +39,21 @@ const responses = async (
.filter((d) => d.shiftboard_id === id)
.map((d) => [d.decision_key, d.value])
);
const [form] = await pool.query<RowDataPacket[]>(
"SELECT year FROM op_forms WHERE form_id = ?",
[Number(req.query.formId)]
);
// #771: admin-only (credit is never an incentive), so only on this page
const scores = await involvementScores(
rows.map((r) => r.shiftboard_id),
form[0]?.year ?? new Date().getFullYear()
);
return res.status(200).json(
rows.map((r) => ({
answers: parseJson(r.answers, {}),
decisions: decisionsOf(r.shiftboard_id),
playaName: r.playa_name ?? "",
score: scores.get(r.shiftboard_id) ?? 0,
shiftboardId: r.shiftboard_id,
submittedAt: r.submitted_at,
worldName: r.world_name ?? "",
Expand Down
Loading