From b7361939ec0f220272be5fe351d4a8ea8c01afe8 Mon Sep 17 00:00:00 2001 From: Mew Date: Sun, 29 Nov 2026 03:35:41 -0800 Subject: [PATCH] feat(shifts): edit a shift from its page; reschedule notice; per-type instance (#731) Roadmap item 5 (Mew 2026-11-29, "yes to all"): - SuperAdmins get "Edit this shift" on the shift page: day, start/end, notes, canceled, slots + CSP per position (single-time PATCH). - Moving a shift stamps op_shift_times.rescheduled_at and emails the people on it the new time + updated invite (email.shift-rescheduled, editable on Emails); free to drop. Not checking in to a rescheduled shift scores 0, not -1 (op_shift_history.penalty_exempt, carried by the ETL). Same from the Shift Types editor. - #466: shift_instance unique per type, not across all types. - #533: new times in the type editor get a unique temporary id, so editing or removing one no longer hits every new time. - Part B: canceled shifts stay on the Shifts agenda, struck through. Migration 037. Footer 2027.G.00901.C. Co-Authored-By: Claude Opus 5.5 --- client/e2e/tests/40-shift-page-edit.spec.ts | 135 +++++++++++ client/src/app/emails/Emails.tsx | 1 + .../[timeId]/volunteers/ShiftVolunteers.tsx | 30 ++- .../volunteers/ShiftVolunteersDialogEdit.tsx | 225 ++++++++++++++++++ .../app/shifts/types/type/ShiftTypesForm.tsx | 4 +- .../[shiftboardId]/schedule/Schedule.tsx | 24 +- client/src/components/api/assignmentNotify.ts | 73 ++++-- client/src/components/layout/Footer.tsx | 2 +- client/src/components/types/shifts/index.ts | 1 + client/src/lib/emailTemplates.ts | 6 + client/src/lib/involvementScore.ts | 4 +- .../api/shifts/[timeId]/volunteers/index.ts | 2 + .../pages/api/shifts/types/[typeId]/index.ts | 56 ++++- .../shifts/types/[typeId]/times/[timeId].ts | 20 +- etl/shift_history.py | 9 +- migrations/037_shift_reschedule.sql | 15 ++ 16 files changed, 558 insertions(+), 49 deletions(-) create mode 100644 client/e2e/tests/40-shift-page-edit.spec.ts create mode 100644 client/src/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogEdit.tsx create mode 100644 migrations/037_shift_reschedule.sql diff --git a/client/e2e/tests/40-shift-page-edit.spec.ts b/client/e2e/tests/40-shift-page-edit.spec.ts new file mode 100644 index 00000000..6c79b1e9 --- /dev/null +++ b/client/e2e/tests/40-shift-page-edit.spec.ts @@ -0,0 +1,135 @@ +import { test, expect, type APIRequestContext } from "@playwright/test"; +import type { RowDataPacket } from "mysql2"; + +import { + cleanupAllTestData, + closePool, + getPool, + insertFullShift, + insertVolunteer, + insertVolunteerShift, +} from "../helpers/db"; +import { buildSessionCookieHeader } from "../helpers/session"; +import { + FUTURE_SHIFT, + makeTestVolunteer, + signInAsBuiltinAdmin, +} from "../fixtures/test-data"; + +// Item 5 (#731, Mew 2026-11-29): edit a shift from its page. Moving it stamps +// rescheduled_at and emails the people on it; #466: shift_instance is unique +// per type, not across all types. +const volunteer = makeTestVolunteer({ + shiftboardId: 9_000_700, + playaName: "E2E Rescheduled", + worldName: "Re Scheduled", + email: "e2e-rescheduled@test.local", + passcode: "6000", +}); +const ADMIN = 1; +const day = FUTURE_SHIFT.startTime.slice(0, 10); +const path = `/api/shifts/types/${FUTURE_SHIFT.shiftNameId}/times/${FUTURE_SHIFT.shiftTimesId}`; +const patch = (request: APIRequestContext, body: object) => + request.patch(path, { + headers: { cookie: buildSessionCookieHeader(ADMIN) }, + data: JSON.stringify(body), + }); +const queued = async () => { + const [rows] = await getPool().query( + "SELECT category FROM op_email_queue WHERE `to` = ? ORDER BY id", + [volunteer.email] + ); + return rows.map((r) => r.category); +}; + +test.describe("edit a shift from its page (#731)", () => { + test.beforeAll(async () => { + await cleanupAllTestData(); + await insertFullShift(FUTURE_SHIFT); + await insertVolunteer(volunteer); + await insertVolunteerShift( + volunteer.shiftboardId, + FUTURE_SHIFT.timePositionId + ); + await getPool().execute("DELETE FROM op_email_queue WHERE `to` = ?", [ + volunteer.email, + ]); + }); + + test.afterAll(async () => { + await getPool().execute("DELETE FROM op_email_queue WHERE `to` = ?", [ + volunteer.email, + ]); + await cleanupAllTestData(); + await closePool(); + }); + + test("moving it stamps rescheduled_at and emails the people on it", async ({ + request, + }) => { + expect((await patch(request, { notes: "same time" })).status()).toBe(200); + expect(await queued()).toEqual([]); + + expect((await patch(request, { startTime: "11:00" })).status()).toBe(200); + const [[row]] = await getPool().query( + "SELECT rescheduled_at, start_time FROM op_shift_times WHERE shift_times_id = ?", + [FUTURE_SHIFT.shiftTimesId] + ); + expect(row.rescheduled_at).not.toBeNull(); + expect(row.start_time).toBe(`${day} 11:00`); + expect(await queued()).toEqual(["shift-rescheduled"]); + }); + + test("shift instance names are unique per type, not across types (#466)", async () => { + const db = getPool(); + await db.execute( + "UPDATE op_shift_times SET shift_instance = 'E2E shared instance' WHERE shift_times_id = ?", + [FUTURE_SHIFT.shiftTimesId] + ); + // another type may reuse the name… + await db.execute( + `INSERT IGNORE INTO op_shift_name (shift_name_id, shift_name, shift_category_id, off_playa, delete_shift, create_shift) + VALUES (9000702, 'E2E other type', ?, 0, 0, 1)`, + [FUTURE_SHIFT.categoryId] + ); + await db.execute( + `INSERT INTO op_shift_times (shift_times_id, shift_name_id, shift_instance, start_time, end_time, remove_shift_time, add_shift_time) + VALUES (9000701, 9000702, 'E2E shared instance', ?, ?, 0, 1)`, + [FUTURE_SHIFT.startTime, FUTURE_SHIFT.endTime] + ); + await db.execute( + "DELETE FROM op_shift_times WHERE shift_times_id = 9000701" + ); + await db.execute("DELETE FROM op_shift_name WHERE shift_name_id = 9000702"); + // …the same type may not + await expect( + db.execute( + `INSERT INTO op_shift_times (shift_times_id, shift_name_id, shift_instance, start_time, end_time, remove_shift_time, add_shift_time) + VALUES (9000701, ?, 'E2E shared instance', ?, ?, 0, 1)`, + [FUTURE_SHIFT.shiftNameId, FUTURE_SHIFT.startTime, FUTURE_SHIFT.endTime] + ) + ).rejects.toThrow(/Duplicate/); + }); + + test("SuperAdmin edits notes and slots from the shift page", async ({ + page, + }) => { + test.setTimeout(120_000); + await signInAsBuiltinAdmin(page); + await page.goto(`/shifts/${FUTURE_SHIFT.shiftTimesId}/volunteers`); + await page.getByRole("button", { name: "Edit this shift" }).click(); + const dialog = page.getByRole("dialog"); + await dialog.getByLabel("Notes").fill("E2E bring water"); + await dialog.getByLabel("Slots").fill("7"); + await dialog.getByRole("button", { name: "Save" }).click(); + await expect(dialog).toBeHidden(); + await expect(page.getByText("E2E bring water")).toBeVisible(); + const [[row]] = await getPool().query( + `SELECT st.notes, stp.slots FROM op_shift_times st + JOIN op_shift_time_position stp ON stp.shift_times_id = st.shift_times_id + WHERE st.shift_times_id = ?`, + [FUTURE_SHIFT.shiftTimesId] + ); + expect(row).toMatchObject({ notes: "E2E bring water", slots: 7 }); + }); +}); diff --git a/client/src/app/emails/Emails.tsx b/client/src/app/emails/Emails.tsx index ef58259e..3f33250b 100644 --- a/client/src/app/emails/Emails.tsx +++ b/client/src/app/emails/Emails.tsx @@ -7,6 +7,7 @@ import { Hero } from "@/components/layout/Hero"; import { EMAIL_TEMPLATES } from "@/lib/emailTemplates"; const FIELD_HELP: Record = { + before: 'the old day and time, e.g. "2027-08-28 09:00–12:00"', by: 'who did it, e.g. "by Chipper"', decision: 'the choice made, e.g. "Census Lab"', form: "the form's title", diff --git a/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteers.tsx b/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteers.tsx index 61b68df9..3bf838c6 100644 --- a/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteers.tsx +++ b/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteers.tsx @@ -2,6 +2,7 @@ import { Chat as ChatIcon, + Edit as EditIcon, Groups3 as Groups3Icon, ManageAccounts as ManageAccountsIcon, MoreHoriz as MoreHorizIcon, @@ -38,6 +39,7 @@ import useSWRMutation from "swr/mutation"; import { FormattedText } from "@/components/general/FormattedText"; import { ShiftVolunteersDialogAdd } from "@/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogAdd"; +import { ShiftVolunteersDialogEdit } from "@/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogEdit"; import { ShiftVolunteersDialogRemove } from "@/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogRemove"; import { ShiftVolunteersDialogReview } from "@/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogReview"; import { BreadcrumbsNav } from "@/components/general/BreadcrumbsNav"; @@ -69,7 +71,11 @@ import { useIsOnPlaya } from "@/hooks/useIsOnPlaya"; import { useNow } from "@/hooks/useNow"; import { DeveloperModeContext } from "@/state/developer-mode/context"; import { SessionContext } from "@/state/session/context"; -import { checkIsAdmin, checkIsAuthenticated } from "@/utils/checkIsRoleExist"; +import { + checkIsAdmin, + checkIsAuthenticated, + checkIsSuperAdmin, +} from "@/utils/checkIsRoleExist"; import { confirmUncheckIn } from "@/utils/confirmUncheckIn"; import { fetcherGet, fetcherTrigger } from "@/utils/fetcher"; import { formatDateName, formatTime } from "@/utils/formatDateTime"; @@ -151,6 +157,7 @@ export const ShiftVolunteers = ({ }, }); const [isDialogOpen, setIsDialogOpen] = useState(false); + const [isEditOpen, setIsEditOpen] = useState(false); // fetching, mutation, and revalidation // ------------------------------------------------------------ @@ -307,6 +314,7 @@ export const ShiftVolunteers = ({ isAuthenticatedSession ); const isAdmin = checkIsAdmin(accountType, roleList); + const isSuperAdmin = checkIsSuperAdmin(accountType, roleList); const handleCheckInToggle = async ({ shift: { positionName, timePositionId }, @@ -763,6 +771,26 @@ export const ShiftVolunteers = ({
{dataShiftVolunteersItem.shift.typeName} + {isSuperAdmin && ( + <> + + setIsEditOpen(false)} + handleSaved={() => mutateShiftVolunteersItem()} + isDialogOpen={isEditOpen} + timeId={Number(timeIdParam)} + /> + + )} {!isShiftCanceled && ( // Add-this-shift is the primary action and sits on top (Chipper diff --git a/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogEdit.tsx b/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogEdit.tsx new file mode 100644 index 00000000..0cf73196 --- /dev/null +++ b/client/src/app/shifts/[timeId]/volunteers/ShiftVolunteersDialogEdit.tsx @@ -0,0 +1,225 @@ +import { Close as CloseIcon, Save as SaveIcon } from "@mui/icons-material"; +import { + Button, + Checkbox, + DialogActions, + FormControlLabel, + Stack, + TextField, + Typography, +} from "@mui/material"; +import Link from "next/link"; +import { useSnackbar } from "notistack"; +import { useEffect, useState } from "react"; + +import { DialogContainer } from "@/components/general/DialogContainer"; +import { SnackbarText } from "@/components/general/SnackbarText"; +import type { IResShiftVolunteerInformation } from "@/components/types/shifts"; +import { fetcherTrigger } from "@/utils/fetcher"; + +interface IShiftVolunteersDialogEditProps { + data: IResShiftVolunteerInformation; + handleDialogClose: () => void; + handleSaved: () => void; + isDialogOpen: boolean; + timeId: number; +} + +// "HH:mm" from a stored "YYYY-MM-DD HH:mm" (or bare "HH:mm") +const hhmm = (t: string) => t.match(/\d{2}:\d{2}/)?.[0] ?? ""; +// the shift's day; a time with no op_dates link still has it in start_time +const dayOf = (shift: { date: string | null; startTime: string }) => + shift.date || (shift.startTime.match(/^\d{4}-\d{2}-\d{2}/)?.[0] ?? ""); + +// Item 5 (#731, Mew 2026-11-29): edit this one shift time from its page, +// SuperAdmins only (same as the Shift Types editor). Saves through +// PATCH /api/shifts/types/{typeId}/times/{timeId}, which emails the people on +// it when it's canceled, restored or moved. +export const ShiftVolunteersDialogEdit = ({ + data, + handleDialogClose, + handleSaved, + isDialogOpen, + timeId, +}: IShiftVolunteersDialogEditProps) => { + const { enqueueSnackbar } = useSnackbar(); + const { shift, positionList } = data; + const [date, setDate] = useState(dayOf(shift)); + const [startTime, setStartTime] = useState(hhmm(shift.startTime)); + const [endTime, setEndTime] = useState(hhmm(shift.endTime)); + const [notes, setNotes] = useState(shift.notes ?? ""); + const [canceled, setCanceled] = useState(shift.canceled); + const [positions, setPositions] = useState(positionList); + const [isSaving, setIsSaving] = useState(false); + // start from the saved values every time it opens + useEffect(() => { + if (!isDialogOpen) return; + setDate(dayOf(shift)); + setStartTime(hhmm(shift.startTime)); + setEndTime(hhmm(shift.endTime)); + setNotes(shift.notes ?? ""); + setCanceled(shift.canceled); + setPositions(positionList); + }, [isDialogOpen, shift, positionList]); + + const isMoved = + date !== dayOf(shift) || + startTime !== hhmm(shift.startTime) || + endTime !== hhmm(shift.endTime); + const filled = data.volunteerList.length; + + const save = async () => { + setIsSaving(true); + try { + await fetcherTrigger( + `/api/shifts/types/${shift.typeId}/times/${timeId}`, + { + arg: { + body: { + canceled, + date, + endTime, + notes, + positionList: positions.map( + ({ csp, slotsTotal, timePositionId }) => ({ + sapPoints: Number(csp), + slots: Number(slotsTotal), + timePositionId, + }) + ), + startTime, + }, + method: "PATCH", + }, + } + ); + handleSaved(); + handleDialogClose(); + enqueueSnackbar(Shift saved, { + variant: "success", + }); + } catch (err) { + enqueueSnackbar({(err as Error).message}, { + persist: true, + variant: "error", + }); + } finally { + setIsSaving(false); + } + }; + + return ( + + + + setDate(e.target.value)} + slotProps={{ inputLabel: { shrink: true } }} + type="date" + value={date} + /> + setStartTime(e.target.value)} + slotProps={{ inputLabel: { shrink: true } }} + type="time" + value={startTime} + /> + setEndTime(e.target.value)} + slotProps={{ inputLabel: { shrink: true } }} + type="time" + value={endTime} + /> + + {isMoved && filled > 0 && !canceled && ( + + Moving it emails the {filled} people on it the new time with an + updated calendar invite. They can drop it without penalty, and not + checking in to it won't count against them. + + )} + setNotes(e.target.value)} + value={notes} + /> + {positions.map((p, i) => { + const set = (patch: Partial) => + setPositions( + positions.map((q, j) => (j === i ? { ...q, ...patch } : q)) + ); + return ( + + {p.positionName} + set({ slotsTotal: Number(e.target.value) })} + size="small" + slotProps={{ htmlInput: { max: 1000, min: 1 } }} + sx={{ width: 100 }} + type="number" + value={p.slotsTotal} + /> + set({ csp: Number(e.target.value) })} + size="small" + slotProps={{ htmlInput: { max: 100, min: 0 } }} + sx={{ width: 100 }} + type="number" + value={p.csp} + /> + + ); + })} + setCanceled(e.target.checked)} + /> + } + label="Canceled (emails the people on it)" + /> + + Name, details, meal and positions are on the{" "} + shift type. + + + + + + + + ); +}; diff --git a/client/src/app/shifts/types/type/ShiftTypesForm.tsx b/client/src/app/shifts/types/type/ShiftTypesForm.tsx index ad8c7f2f..b6a9d24a 100644 --- a/client/src/app/shifts/types/type/ShiftTypesForm.tsx +++ b/client/src/app/shifts/types/type/ShiftTypesForm.tsx @@ -361,7 +361,9 @@ export const ShiftTypesForm = ({ notes, positionList, startTime: `${dateNew} ${startTimeNew}`, - timeId: 0, + // a unique temporary id (#533): with every new time at 0, editing one + // new time overwrote all of them; the API treats <= 0 as new + timeId: -Date.now(), }; const timeFieldsMutate = structuredClone(timeFields); diff --git a/client/src/app/volunteers/[shiftboardId]/schedule/Schedule.tsx b/client/src/app/volunteers/[shiftboardId]/schedule/Schedule.tsx index eddc5a4d..5c2656f4 100644 --- a/client/src/app/volunteers/[shiftboardId]/schedule/Schedule.tsx +++ b/client/src/app/volunteers/[shiftboardId]/schedule/Schedule.tsx @@ -150,19 +150,21 @@ export const Schedule = ({ shiftboardId }: IScheduleProps) => { } for (const o of open) { - if (o.canceled || myTimeIds.has(o.id)) continue; // shown as "mine" already + // canceled shifts stay listed, struck through (#731 Part B) + if (myTimeIds.has(o.id)) continue; // shown as "mine" already const isFull = o.slotsTotal - o.slotsFilled <= 0; // Flag an open shift that overlaps one you're already on (our edge over // Shiftboard — it doesn't stop cross-department double-booking). const clash = mine.find( (m) => + !o.canceled && !m.shift.canceled && overlaps(o.startTime, o.endTime, m.shift.startTime, m.shift.endTime) ); // role-gated: every position needs a role this volunteer lacks const requiredRoles = dataElig?.[o.id]; const isIneligible = - Array.isArray(requiredRoles) && requiredRoles.length > 0; + !o.canceled && Array.isArray(requiredRoles) && requiredRoles.length > 0; agenda.push({ key: `open-${o.id}`, timeId: o.id, @@ -174,17 +176,19 @@ export const Schedule = ({ shiftboardId }: IScheduleProps) => { type: o.type, department: o.department.name, csp: cspLabel(o.cspMin, o.cspMax), - canceled: false, + canceled: Boolean(o.canceled), // Full first: a full shift can't be taken by anyone, so "Full" is the // truer label than "not eligible" (which reads as singling the viewer // out). Then role-ineligible, then a time conflict, else open. - state: isFull - ? "full" - : isIneligible - ? "ineligible" - : clash - ? "conflict" - : "open", + state: o.canceled + ? "open" + : isFull + ? "full" + : isIneligible + ? "ineligible" + : clash + ? "conflict" + : "open", slots: { filled: o.slotsFilled, total: o.slotsTotal }, conflictWith: clash ? clash.shift.positionName : undefined, // Shown even when full (Chipper 2026-07-07): both facts are useful — diff --git a/client/src/components/api/assignmentNotify.ts b/client/src/components/api/assignmentNotify.ts index 8ec4aa5c..5c1ef2e7 100644 --- a/client/src/components/api/assignmentNotify.ts +++ b/client/src/components/api/assignmentNotify.ts @@ -455,10 +455,14 @@ export async function notifyRemoval( // recent CANCEL. Repeated cancel→restore cycles would need // further bumps; out of scope until/unless that becomes a real // workflow (in practice an un-cancel is the end of the story). +// +// With `before` (the old day/time) it's the reschedule notice instead (#731, +// Mew 2026-09-05): new time + updated invite, free to drop without penalty. export async function notifyRestoration( pool: Pool, shiftboardId: number, - timePositionId: number | string + timePositionId: number | string, + before?: string ): Promise { const [rows] = await pool.query(SHIFT_CONTEXT_QUERY, [ shiftboardId, @@ -476,11 +480,16 @@ export async function notifyRestoration( const dayLabel = ctx.datename ? `${ctx.datename} ${ctx.date}` : ctx.date; const timeLabel = timeLabelFor(ctx); - const bodyText = await emailBody(pool, "email.shift-restored", { - link: `${APP_BASE_URL}/`, - name: nameFor(ctx), - shift: renderShiftBody(ctx, dayLabel, timeLabel), - }); + const bodyText = await emailBody( + pool, + before ? "email.shift-rescheduled" : "email.shift-restored", + { + before: before ?? "", + link: `${APP_BASE_URL}/`, + name: nameFor(ctx), + shift: renderShiftBody(ctx, dayLabel, timeLabel), + } + ); const icsDate = dateToIcs(ctx.date); const icsStart = timeToIcs(ctx.start_time); @@ -495,22 +504,26 @@ export async function notifyRestoration( startTime: icsStart, endTime: icsEnd, method: "PUBLISH", - sequence: 2, + // ponytail: fixed bump; a second reschedule reuses 3, which most + // clients still apply (they match on UID + DTSTAMP) + sequence: before ? 3 : 2, }) : null; await enqueueEmail({ to: ctx.email, recipientShiftboardId: shiftboardId, - subject: `Census: ${ctx.shift_name} on ${dayLabel} is back on`, + subject: before + ? `Census: ${ctx.shift_name} moved to ${dayLabel}${timeLabel ? ` ${timeLabel}` : ""}` + : `Census: ${ctx.shift_name} on ${dayLabel} is back on`, bodyText, ics: icsContent ? { - filename: `census-${ctx.position.replace(/\s+/g, "-").toLowerCase()}-restored.ics`, + filename: `census-${ctx.position.replace(/\s+/g, "-").toLowerCase()}-${before ? "moved" : "restored"}.ics`, content: Buffer.from(icsContent, "utf8"), } : undefined, - category: "shift-restored", + category: before ? "shift-rescheduled" : "shift-restored", }); } @@ -524,7 +537,37 @@ export async function notifyCancelFlip( timeId: number, isCanceled: boolean ): Promise { - const tag = isCanceled ? "shift-canceled" : "shift-restored"; + await eachOnShift( + pool, + timeId, + isCanceled ? "shift-canceled" : "shift-restored", + (v) => + isCanceled + ? notifyRemoval(pool, v.shiftboard_id, v.time_position_id, { + kind: "shift-canceled", + }) + : notifyRestoration(pool, v.shiftboard_id, v.time_position_id) + ); +} + +// A shift time's date or start/end changed (#731): email everyone on it the +// new time (`before` = the old one) with an updated calendar invite. +export async function notifyRescheduled( + pool: Pool, + timeId: number, + before: string +): Promise { + await eachOnShift(pool, timeId, "shift-rescheduled", (v) => + notifyRestoration(pool, v.shiftboard_id, v.time_position_id, before) + ); +} + +async function eachOnShift( + pool: Pool, + timeId: number, + tag: string, + send: (v: RowDataPacket) => Promise +): Promise { try { const [rows] = await pool.query( `SELECT DISTINCT vs.shiftboard_id, vs.time_position_id @@ -537,13 +580,7 @@ export async function notifyCancelFlip( ); for (const v of rows) { try { - if (isCanceled) { - await notifyRemoval(pool, v.shiftboard_id, v.time_position_id, { - kind: "shift-canceled", - }); - } else { - await notifyRestoration(pool, v.shiftboard_id, v.time_position_id); - } + await send(v); } catch (err) { console.error( `[${tag}-notify] enqueue failed for shiftboard_id=${v.shiftboard_id} time_position_id=${v.time_position_id}:`, diff --git a/client/src/components/layout/Footer.tsx b/client/src/components/layout/Footer.tsx index 31e0a4d1..6f1d8d00 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.00900.C + 2027.G.00901.C diff --git a/client/src/components/types/shifts/index.ts b/client/src/components/types/shifts/index.ts index 4f3b3d1c..48b55cfb 100644 --- a/client/src/components/types/shifts/index.ts +++ b/client/src/components/types/shifts/index.ts @@ -83,6 +83,7 @@ export interface IResShiftVolunteerInformation { meal: string; notes: string; startTime: string; + typeId: number; typeName: string; }; volunteerList: IResShiftVolunteerRowItem[]; diff --git a/client/src/lib/emailTemplates.ts b/client/src/lib/emailTemplates.ts index e2cc34f1..29fea26a 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", "shift", "before", "link"], + html: "

Hi {{name}},

A Census shift you're on has moved. It was {{before}}; it's now:

{{shift}}

An updated calendar invite is attached. If the new time doesn't work for you, you can remove yourself from this shift without penalty: {{link}}

", + label: "Shift rescheduled", + slug: "email.shift-rescheduled", + }, { 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}}

", diff --git a/client/src/lib/involvementScore.ts b/client/src/lib/involvementScore.ts index 7ca712ea..f486d1b0 100644 --- a/client/src/lib/involvementScore.ts +++ b/client/src/lib/involvementScore.ts @@ -9,7 +9,7 @@ import { pool } from "lib/database"; // // score = 16 × ( Σ shift value × decay + 25 if Core Crew ) // value = canceled : CSP × lead × sampling (counts, never a penalty) -// not checked in : −1 +// not checked in : −1 (0 if the shift was rescheduled, #731) // CSP > 0 : CSP × lead × sampling × review // off-playa, CSP 0 : 0.25 (meetings, Mew 11/11) // on-playa, CSP 0 : hours / 4 @@ -30,7 +30,7 @@ const valueSql = (asOfYear: number) => { 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 NOT h.checked_in THEN IF(h.penalty_exempt, 0, -1) WHEN h.csp > 0 THEN h.csp * ${lead} * ${sampling} * ${review} WHEN h.off_playa THEN 0.25 ELSE h.hours / 4 diff --git a/client/src/pages/api/shifts/[timeId]/volunteers/index.ts b/client/src/pages/api/shifts/[timeId]/volunteers/index.ts index 1cadaf8a..fd8fe52e 100644 --- a/client/src/pages/api/shifts/[timeId]/volunteers/index.ts +++ b/client/src/pages/api/shifts/[timeId]/volunteers/index.ts @@ -75,6 +75,7 @@ const shiftVolunteers = async ( pt.min_scheduled_csp, sn.shift_details, sn.shift_name, + sn.shift_name_id, st.canceled, st.end_time, st.end_time_text, @@ -264,6 +265,7 @@ const shiftVolunteers = async ( startTime: resShiftPositionFirst.start_time ?? resShiftPositionFirst.start_time_text, + typeId: resShiftPositionFirst.shift_name_id, typeName: resShiftPositionFirst.shift_name, }, volunteerList: resShiftVolunteerList, diff --git a/client/src/pages/api/shifts/types/[typeId]/index.ts b/client/src/pages/api/shifts/types/[typeId]/index.ts index e06bf08e..20dc9666 100644 --- a/client/src/pages/api/shifts/types/[typeId]/index.ts +++ b/client/src/pages/api/shifts/types/[typeId]/index.ts @@ -1,7 +1,10 @@ import { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; -import { notifyCancelFlip } from "@/components/api/assignmentNotify"; +import { + notifyCancelFlip, + notifyRescheduled, +} from "@/components/api/assignmentNotify"; import { IReqShiftTypeItem, IResShiftTypeCurrent, @@ -310,31 +313,48 @@ const shiftTypeUpdate = async (req: NextApiRequest, res: NextApiResponse) => { // assigned volunteers exactly once per cancellation. Done before // the UPDATEs fire. const wasCanceledMap = new Map(); + // and the prior start/end, to spot a reschedule (#731) + const wasTimeMap = new Map(); if (timeListUpdate.length > 0) { const [priorStates] = await pool.query( - `SELECT shift_times_id, canceled FROM op_shift_times + `SELECT shift_times_id, canceled, start_time, end_time FROM op_shift_times WHERE shift_times_id IN (?)`, [timeListUpdate.map(({ timeId }) => timeId)] ); for (const row of priorStates) { wasCanceledMap.set(row.shift_times_id, Boolean(row.canceled)); + wasTimeMap.set(row.shift_times_id, { + end: String(row.end_time).slice(0, 16), + start: String(row.start_time).slice(0, 16), + }); } } + const isMoved = ({ endTime, startTime, timeId }: (typeof timeList)[0]) => { + const was = wasTimeMap.get(timeId); + // only a full stored datetime (an old bare "HH:mm" row isn't comparable) + return ( + !!was && + /^\d{4}-\d\d-\d\d \d\d:\d\d$/.test(was.start) && + (was.start !== String(startTime).slice(0, 16) || + was.end !== String(endTime).slice(0, 16)) + ); + }; // Await the UPDATEs so transition detection / notify happens // after the writes land (the previous forEach(async) pattern // raced the route's response). await Promise.all( timeListUpdate.map( - async ({ - canceled, - endTime, - timeId, - instance, - meal, - notes, - startTime, - }) => { + async (timeItem) => { + const { + canceled, + endTime, + timeId, + instance, + meal, + notes, + startTime, + } = timeItem; // Refresh start_date_id / end_date_id alongside the start_time / // end_time change — a date edit must update the FK or downstream // joins keep pointing at the old date row. See [[fix-handleTimeListAdd]]. @@ -354,7 +374,8 @@ const shiftTypeUpdate = async (req: NextApiRequest, res: NextApiResponse) => { shift_instance=?, start_date_id=(SELECT date_id FROM op_dates WHERE date = DATE(?) AND delete_date = false LIMIT 1), start_time=?, - start_time_text=DATE_FORMAT(?, '%H:%i') + start_time_text=DATE_FORMAT(?, '%H:%i'), + rescheduled_at=IF(?, NOW(), rescheduled_at) WHERE shift_times_id=?`, [ Boolean(canceled), @@ -367,6 +388,7 @@ const shiftTypeUpdate = async (req: NextApiRequest, res: NextApiResponse) => { startTime, startTime, startTime, + isMoved(timeItem), timeId, ] ); @@ -383,6 +405,13 @@ const shiftTypeUpdate = async (req: NextApiRequest, res: NextApiResponse) => { const isCanceled = Boolean(t.canceled); if (wasCanceled !== isCanceled) { await notifyCancelFlip(pool, t.timeId, isCanceled); + } else if (isMoved(t) && !isCanceled) { + const was = wasTimeMap.get(t.timeId)!; + await notifyRescheduled( + pool, + t.timeId, + `${was.start}–${was.end.slice(11)}` + ); } } // Sequential for-of so each write is awaited before the handler responds @@ -475,7 +504,8 @@ const shiftTypeUpdate = async (req: NextApiRequest, res: NextApiResponse) => { const timePositionListAdd = timePositionList.filter( ({ timeId, timePositionId }) => { return !( - timeId === 0 || + // new times (timeId <= 0, a temporary id) add their own positions + timeId <= 0 || dbTimePositionList.some( ({ time_position_id }) => time_position_id === timePositionId ) diff --git a/client/src/pages/api/shifts/types/[typeId]/times/[timeId].ts b/client/src/pages/api/shifts/types/[typeId]/times/[timeId].ts index d908d6d9..bc8ba967 100644 --- a/client/src/pages/api/shifts/types/[typeId]/times/[timeId].ts +++ b/client/src/pages/api/shifts/types/[typeId]/times/[timeId].ts @@ -1,7 +1,10 @@ import type { RowDataPacket } from "mysql2"; import type { NextApiRequest, NextApiResponse } from "next"; -import { notifyCancelFlip } from "@/components/api/assignmentNotify"; +import { + notifyCancelFlip, + notifyRescheduled, +} from "@/components/api/assignmentNotify"; import { actor } from "@/lib/actor"; import { ensureDateId, isDate, isDupEntry, isTime } from "@/lib/shiftTimes"; import { withWriteGuard } from "@/lib/withWriteGuard"; @@ -12,7 +15,8 @@ import { pool } from "lib/database"; // { date: "YYYY-MM-DD", startTime: "HH:mm", endTime: "HH:mm", notes, // canceled, dateName, positionList: [{ timePositionId, slots?, sapPoints? }] } // Canceling or restoring emails the volunteers on it (notifyCancelFlip), the -// same as the Shift Types form. Like the form, a date/time change sends no email. +// same as the Shift Types form. A date/time change is a reschedule (#731): +// rescheduled_at is stamped and the volunteers on it are emailed the new time. const updateShiftTime = async (req: NextApiRequest, res: NextApiResponse) => { if (req.method !== "PATCH") { return res @@ -104,6 +108,10 @@ const updateShiftTime = async (req: NextApiRequest, res: NextApiResponse) => { canceled === undefined ? Boolean(current.canceled) : canceled; const startValue = `${newDate} ${newStart}`; const endValue = `${newDate} ${newEnd}`; + const isMoved = + newDate !== curDate || + newStart !== curStart.slice(0, 5) || + newEnd !== curEnd.slice(0, 5); await pool.query( `UPDATE op_shift_times SET @@ -115,6 +123,7 @@ const updateShiftTime = async (req: NextApiRequest, res: NextApiResponse) => { start_date_id = (SELECT date_id FROM op_dates WHERE date = DATE(?) AND delete_date = false LIMIT 1), start_time = ?, start_time_text = ?, + rescheduled_at = IF(?, NOW(), rescheduled_at), update_shift_time = true WHERE shift_times_id = ?`, [ @@ -126,6 +135,7 @@ const updateShiftTime = async (req: NextApiRequest, res: NextApiResponse) => { startValue, startValue, newStart, + isMoved, timeId, ] ); @@ -146,6 +156,12 @@ const updateShiftTime = async (req: NextApiRequest, res: NextApiResponse) => { } if (isCanceled !== Boolean(current.canceled)) { await notifyCancelFlip(pool, timeId, isCanceled); + } else if (isMoved && !isCanceled) { + await notifyRescheduled( + pool, + timeId, + `${curDate} ${curStart.slice(0, 5)}–${curEnd.slice(0, 5)}` + ); } return res.status(200).json({ statusCode: 200, message: "OK" }); diff --git a/etl/shift_history.py b/etl/shift_history.py index 997fe1e3..67330540 100644 --- a/etl/shift_history.py +++ b/etl/shift_history.py @@ -89,7 +89,7 @@ "name_is_current", "date", "day_name", "start_time", "end_time", "hours", "department", "shift_category", "shift_name", "alias", "position", "instance", "shift_key", "is_lead", "is_critical", "is_core", "off_playa", "csp", "canceled", - "checked_in", "raw_score", "score_scale", "score", "review_notes", "details", + "checked_in", "penalty_exempt", "raw_score", "score_scale", "score", "review_notes", "details", "is_placeholder", "category_guessed", "signed_up_at", "linked_from_id", ) STATS_COLUMNS = ( @@ -273,6 +273,7 @@ def load_legacy(db, extra_rows=()) -> tuple[dict, list[dict]]: "is_lead": bool(cat and cat["lead"]), "is_critical": bool(cat and cat["critical"]), "is_core": bool(cat and cat["core"]), "off_playa": off_playa, "csp": csp, "canceled": False, "checked_in": (r["noshow"] or "").strip() != "Yes", + "penalty_exempt": False, "raw_score": rev.get("score"), "score_scale": "legacy0-10" if rev.get("score") is not None else None, "score": legacy_score(rev.get("score")), "review_notes": notes or None, @@ -319,6 +320,9 @@ def load_app_dump(db, year: int) -> list[dict]: source_id = "st.shift_times_id * 1000 + sp.shift_position_id" points = "COALESCE(stp.sap_points, sp.wap_points)" canceled = "st.canceled" if has_column(db, "op_shift_times", "canceled") else "0" + # migration 037: a rescheduled shift's not-checked-in costs nothing + moved = ("st.rescheduled_at IS NOT NULL" + if has_column(db, "op_shift_times", "rescheduled_at") else "0") # noshow '' = checked in until migration 029 replaced it with checked_in checked = ("vs.checked_in" if has_column(db, "op_volunteer_shifts", "checked_in") else "COALESCE(vs.noshow, 'X') = ''") @@ -327,6 +331,7 @@ def load_app_dump(db, year: int) -> list[dict]: SELECT {source_id} AS source_id, vs.shiftboard_id, vs.shiftboard_shift_id, vs.add_shift, {checked} AS checked_in, vs.rating, vs.notes, {signed} AS signed_up_at, {points} AS points, {canceled} AS canceled, + {moved} AS penalty_exempt, NULLIF(stp.position_alias, '') AS alias, pt.position, pt.`lead`, pt.critical, pt.position_details, st.shift_times_id, st.shift_instance, CAST(st.start_time AS DATETIME) AS start_time, @@ -370,6 +375,7 @@ def load_app_dump(db, year: int) -> list[dict]: "is_lead": bool(r["lead"]), "is_critical": bool(r["critical"]), "is_core": bool(r["core"]), "off_playa": off_playa, "csp": csp, "canceled": bool(r["canceled"]), "checked_in": bool(r["checked_in"]), + "penalty_exempt": bool(r["penalty_exempt"]), "raw_score": r["rating"] or None, "score_scale": "app1-5" if r["rating"] else None, "score": app_score(r["rating"]), "review_notes": fix_text(r["notes"]), "details": details or None, @@ -424,6 +430,7 @@ def merge_app(signups: dict, app_rows: list[dict], year: int, people) -> Counter if a["checked_in"] and not match["checked_in"]: match["checked_in"] = True # disagree -> credit (Mew) tally["credit given"] += 1 + match["penalty_exempt"] = match["penalty_exempt"] or a["penalty_exempt"] if match["raw_score"] is None and a["raw_score"]: for k in ("raw_score", "score_scale", "score"): match[k] = a[k] diff --git a/migrations/037_shift_reschedule.sql b/migrations/037_shift_reschedule.sql new file mode 100644 index 00000000..ba91e955 --- /dev/null +++ b/migrations/037_shift_reschedule.sql @@ -0,0 +1,15 @@ +-- Item 5 (#731, Mew 2026-09-05 / 2026-11-29): editing a shift from its page. +-- A reschedule (date or start/end changed) stamps rescheduled_at; the people +-- on it are emailed and may drop it without penalty, and not checking in to a +-- rescheduled shift costs nothing in the involvement score (#771) — carried +-- into the permanent record as op_shift_history.penalty_exempt. +-- #466: shift_instance was unique across ALL types, but the editor only checks +-- the type being edited, so a name another type already used failed to save. +-- Unique per type instead. +SET @@system_versioning_alter_history = KEEP; +ALTER TABLE op_shift_times + ADD COLUMN IF NOT EXISTS rescheduled_at DATETIME NULL AFTER canceled, + DROP INDEX IF EXISTS shift_instance, + ADD UNIQUE KEY IF NOT EXISTS uq_type_instance (shift_name_id, shift_instance); +ALTER TABLE op_shift_history + ADD COLUMN IF NOT EXISTS penalty_exempt BOOLEAN NOT NULL DEFAULT FALSE AFTER checked_in;