From 1b78a06f72ba6470506d8ff23b0e0e4525be94c9 Mon Sep 17 00:00:00 2001 From: blake Date: Thu, 29 Oct 2026 18:02:08 -0500 Subject: [PATCH] feat: enhance shift cancellation process and update templates Improved the shift cancellation functionality to ensure that selected shifts are properly marked as cancelled, with corresponding emails queued for affected signups. Updated the admin interface to reflect these changes, including clearer messaging for cancelled shifts. Enhanced the handling of weekly templates to ensure that shifts are accurately updated or removed based on their status. Adjusted related tests to verify the new behavior and ensure consistency across the application. --- README.md | 16 +- public/css/app.css | 99 ++++++++- public/js/confirm-dialog.js | 13 +- src/admin-http.tsx | 145 ++++++++----- src/admin-pages.tsx | 283 ++++++++++++++---------- src/admin/store.ts | 416 ++++++++++++++++++++++++++++-------- src/recurrence.ts | 16 +- tests/admin.test.ts | 83 ++++++- tests/recurrence.test.ts | 54 ++--- tests/template.test.ts | 183 +++++++++++++--- 10 files changed, 956 insertions(+), 352 deletions(-) diff --git a/README.md b/README.md index 73ab642..b08a57f 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ You should have received a copy of the GNU General Public License along with thi | Move a signup to another shift | Done | | Switch your own signup to another shift | Done | | Manage other signups from one private link | Disabled; requires a separate verified identity flow | -| Add weekly shifts for the next three months | Done | +| Saving a template updates the next three months | Done | | Add, change, or end a weekly template | Done | | Remove a cancelled person, a finished shift, an ended template, or an empty hidden event | Done | | Reminder emails, 48 hours and 2 hours, with a way to stop them | Done | @@ -80,7 +80,7 @@ Each active coordinator gets an email when someone signs up, cancels, or changes Coordinator sign-in is at `/login`. The first time the app starts with an empty coordinators table, it creates one administrator from `BOOTSTRAP_ADMIN_EMAIL`. The name on that account is Administrator. It does not create another account on later starts, and it does not change an account that is already there. More administrators are added from **Administrators** after someone is signed in. Sign-in emails a link that expires in 15 minutes and works once. Opening the link does not sign you in. Use the button on that page. The link is printed in the development server log with the rest of the mail. There is no password. -After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling keeps the roster. It does not delete the shift or the signup. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued. +After sign-in, `/admin` lists events, including events that are off the public list. A coordinator can add and edit an event, show or hide it, add and edit a one-off shift, read that shift's roster, cancel one signup, or cancel the shift. Cancelling a shift marks each confirmed signup cancelled, queues a cancellation email, and takes that shift off the upcoming list. The shift stays stored, so a template does not add that date again. **Cancel selected**, on the event page, does this for each open shift that is checked. A shift that has already ended is left out of that batch. A time, role, or location change emails the people who are signed up and replaces their private links. The old link stops working when that email is queued. On an open shift, **Add a walk-in** records one person who is here. It takes one spot, uses the same person rule as the public form, and queues a confirmation email. The name is listed on the public sign-up page when that shift is posted there. Email and notes stay off that page. A full, cancelled, or ended shift does not take a walk-in. @@ -92,11 +92,11 @@ Public switching permits 10 validated attempts per IP per 10-minute window and 5 **Management link scope:** names and email addresses entered in a public form are unverified. Each private link authorizes only its own signup, including links from confirmation cookies and email. Cross-signup listing, cancellation, and switching are disabled, and the old `/m/:token/also/...` routes return 404. This also applies to existing links. A future multi-signup view must verify identity separately. -**Add weekly shifts**, on a coordinator event page, fills the next three months from that event's active weekly templates. Starting the app does the same thing for every event. A shift that is already on that date stays as it is, including a cancelled one, so the template cannot recreate it. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped. +Saving a weekly template updates shifts from that template that have not ended, and adds any missing dates for the next three months. Starting the app does the same fill for every event. A shift that already ended stays as it was. A shift a coordinator edited on its own stays as they saved it. A cancelled shift stays cancelled, so the template does not add that date again. Changing the role or time emails the people who are signed up. A date that is no longer part of the template is cancelled when someone is signed up, and removed when nobody is. A 9:00 shift stays 9:00 when daylight saving time changes. A local time that does not exist, or that happens twice, is skipped. -**Add a weekly template** saves a repeating role, day, and time. **Edit this template** changes later weeks only. Shifts already on the schedule keep their role, time, and number of spots. **End this template** stops later weeks from being added. It does not cancel shifts already listed, and it does not email anyone. +**Add a weekly template** saves a repeating role, day, and time and adds those shifts. On the event page these are listed under **Templates**. **Edit this template** updates shifts from it that have not ended, and adds any missing dates. **End this template** stops later weeks from being added. Shifts from it that have not ended are cancelled and leave the upcoming list, and a cancellation email is queued for each person signed up. Shifts from it that have already ended are deleted, including the names and emails on those rosters. That part does not send email. -**Remove from roster** deletes a cancelled signup, including the name, email, and notes. A confirmed signup has to be cancelled first. **Remove this shift** deletes a cancelled or ended shift after the roster is empty. If that date came from a weekly template that is still active, the next weekly fill can add the date again. **Remove this template** deletes an ended template. The shifts stay on the schedule and are no longer tied to that weekly pattern. **Remove this event** asks for confirmation, then deletes that event and the shifts, weekly templates, and signups on it, including names and emails. An event on the public list comes off that list. It does not send email. Other events stay. +**Remove from roster** deletes a cancelled signup, including the name, email, and notes. A confirmed signup has to be cancelled first. **Remove this shift** deletes a cancelled or ended shift after the roster is empty. If that date came from a weekly template that is still active, saving that template can add the date again. **Remove this template** deletes an ended template. Any shifts left are no longer tied to that weekly pattern. Cancelled shifts stay off the upcoming list. **Remove this event** asks for confirmation, then deletes that event and the shifts, weekly templates, and signups on it, including names and emails. An event on the public list comes off that list. It does not send email. Other events stay. A reminder is queued at each saved time before a confirmed signup, while the shift has not started. The defaults are 48 hours before and 2 hours before. The check runs every five minutes. If the app was off and more than one reminder is already due, only the closest one is sent. A person who signs up after an earlier reminder was due does not get that missed reminder. A reminder is not sent after the shift starts. Changing the shift, moving the signup, or cancelling it drops a reminder that has not been sent yet. Mail that was already accepted cannot be recalled. **Stop reminder emails**, on the private signup page or in the reminder itself, turns reminders off for that signup. The signup stays. Confirmation, change, and cancellation emails still arrive. The reminder asks the person to use the link in the confirmation email to cancel. Mail sent to the reply-to address is read by the pantry. @@ -108,7 +108,7 @@ A reminder is queued at each saved time before a confirmed signup, while the shi **Administrators**, on the coordinator page, lists who can sign in. **Add an administrator** saves a name and email. It does not send email. That person requests a sign-in link at `/login`. Saving an address that was removed earlier gives that person access again and updates the name. **Remove** takes away access, signs that person out, and stops unused sign-in links. It does not send email. A roster notice that has not been sent yet is not sent to that address. The last administrator cannot be removed. Any administrator can add or remove the others, including themselves when someone else still has access. -Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and **Add weekly shifts**, still fill the schedule as well. +Around 1:00 AM in an event's time zone, the app adds any missing shifts from that event's active weekly templates. It does this once for that local date. If 1:00 happens twice when the clocks change, the second hour does not add them again. If 1:00 does not exist that day, the fill runs once the local clock is past 1:00. A restart later that day still fills the date if it was missed. A date that already has a shift, including a cancelled one, stays as it is. Starting the app, and saving a template, still fill the schedule as well. After 1:00 AM Central Time, once that local date, the app removes the name, email, phone, notes, and private link from each signup whose shift ended more than the saved number of months ago. The default is 24. The shift and the signup status stay, so the count remains. Legacy guardian columns, when present, are cleared too. A spreadsheet downloaded from an old shift leaves those personal cells blank. This changes the live database. It does not change a spreadsheet already on a coordinator's computer, a message already in someone's inbox, or an older database backup. Clearing a value does not promise that the old bytes are immediately gone from the disk. The contact list is separate. Clearing an old signup does not remove that person from the contact list. @@ -149,13 +149,13 @@ Development may use the console driver and the always-pass Turnstile test keys i Stored instants look like `2026-01-15T15:00:00.000Z`. Local dates stay `YYYY-MM-DD`. Local times stay `HH:MM`. Weekday `0` is Sunday. A 9:00 shift in `America/Chicago` stays 9:00 local in January and in July. The default zone is `America/Chicago`. -Shifts in this version must start and end on the same day. Overnight templates are later work. A coordinator can add, change, or end a weekly template. Ending it does not cancel shifts already on the schedule. The eight-week fill also runs around 1:00 AM in each event's time zone, once that local date. It still runs when the app starts and when a coordinator uses Add weekly shifts. +Shifts in this version must start and end on the same day. Overnight templates are later work. A coordinator can add, change, or end a weekly template. Ending it cancels shifts from that template that have not ended, and deletes shifts from it that have already ended. The three-month fill also runs around 1:00 AM in each event's time zone, once that local date. It still runs when the app starts and when a coordinator saves a template. ## Database SQLite runs in WAL mode with foreign keys on. Migrations in `migrations/` are applied once, in order, at startup. Each applied file is stored with a SHA-256 checksum. A failed migration stops startup and rolls back that file. In production, a database that already has migrations is backed up with SQLite's backup API before a new migration runs. Copying the live `app.db` file by itself is not a consistent backup while WAL mode is on. -There is no cascade delete. A shift that still has signups cannot be deleted out from under the roster. A coordinator cancels a signup or a shift first. Removing a cancelled person, then an empty finished shift, is a separate step. Removing an ended template leaves its shifts in place. An event can be removed only when it is off the public list and nothing remains on it. +There is no cascade delete. **Remove this shift** still refuses a shift that has anyone on the roster. A coordinator cancels a signup, or cancels or ends the shift, before that removal. Ending a template deletes each shift from it that has already ended, including the signups on it. A shift from that template that has not ended is cancelled instead, so the cancellation email can still be sent. Removing an ended template detaches any shifts that are still stored. An event can be removed when it is taken off the public list; that removal deletes the shifts, templates, and signups on it. Confirmed signups have a partial unique index on shift, normalized email, and name, without regard to case. Normalization of the email is trim, Unicode normalize, and lowercase. Dots and plus-tags stay. A different person can use that email and takes their own spot. Anonymized rows clear the name and email, so they do not collide with that index. New signups always store `is_minor` as 0 with null guardian fields; legacy columns remain for older rows. `group_size` cannot be anything but 1. diff --git a/public/css/app.css b/public/css/app.css index 69fb6f8..d0a8b1f 100644 --- a/public/css/app.css +++ b/public/css/app.css @@ -2715,6 +2715,32 @@ button.btn-quiet::before { color: #6a5314; } +.need-day-count.is-full { + color: #1f7a43; +} + +.event-page .need-pick { + display: grid; + grid-template-columns: auto minmax(0, 1fr); + align-items: center; + gap: 0.35rem; +} + +.event-page .need-pick .desk-row { + min-width: 0; +} + +.event-page .desk-row.is-ended { + background: #eef1f4; + color: #6b7784; +} + +.event-page .desk-row.is-ended:hover, +.event-page .desk-row.is-ended:focus-visible { + background: #e4e9ee; + color: #6b7784; +} + .need-day .desk-rows { gap: 0.35rem; } @@ -2847,13 +2873,10 @@ button.btn-quiet::before { color: #1f7a43; } -.need-day .desk-row.is-covered { - background: #f3faf5; -} - -.need-day .desk-row.is-covered:hover, -.need-day .desk-row.is-covered:focus-visible { - background: #e5f6eb; +.desk-row .need-pill, +.fill-pill { + justify-content: center; + min-width: 8.75rem; } .desk-full { @@ -4383,6 +4406,68 @@ main > .crumb, color: #7d8b99; } +.event-panel-actions { + display: flex; + flex-wrap: wrap; + justify-content: flex-end; + gap: 0.35rem; +} + +/* Cancel and Remove sit in the heading row. Showing them stays inside that line, so the shift list does not move down. */ +.event-page .event-panel-head:has(> .event-panel-actions) { + flex-wrap: nowrap; + align-items: center; + justify-content: flex-start; +} + +.event-page .event-panel-head:has(> .event-panel-actions) > :first-child { + min-width: 0; +} + +.event-page .event-panel-head > .event-panel-actions { + flex: none; + flex-wrap: nowrap; + align-items: center; + margin-left: auto; +} + +.event-page .event-panel-head > .event-panel-tools { + flex: none; +} + +.event-page .event-panel-actions .btn { + min-height: 2.2rem; + padding: 0.2rem 0.9rem; + box-shadow: none; + font-size: 0.92rem; + line-height: 1.2; + width: auto; + flex: 0 0 auto; +} + +.event-page .event-panel-actions .btn:hover, +.event-page .event-panel-actions .btn:active { + transform: none; +} + +@media (max-width: 42em) { + .event-page .event-panel-head:has(> .event-panel-actions) { + flex-wrap: wrap; + } + + .event-page .event-panel-head:has(> .event-panel-actions) > :first-child { + flex: 1 1 auto; + } + + .event-page .event-panel-head > .event-panel-actions { + flex: 1 1 100%; + order: 3; + justify-content: flex-end; + margin-left: 0; + min-height: 2.2rem; + } +} + .event-panel-note { margin: 0.15rem 0 0; color: #7d8b99; diff --git a/public/js/confirm-dialog.js b/public/js/confirm-dialog.js index 5c4835e..31ba6a9 100644 --- a/public/js/confirm-dialog.js +++ b/public/js/confirm-dialog.js @@ -47,12 +47,17 @@ } var pick = link.getAttribute('data-confirm-pick'); if (!pick) return; + var gate = text(link, 'data-confirm-gate') || 'removable'; + var flag = gate === 'open' ? 'data-open' : 'data-removable'; + var verb = text(link, 'data-confirm-verb') || 'removed'; + var blockedBody = text(link, 'data-confirm-blocked') || 'Cancel this shift, or wait until it has ended, before removing it.'; + var partialNote = text(link, 'data-confirm-partial') || 'The others stay until they are cancelled or have ended.'; var chosen = chosenFor(pick); var kept = []; var blocked = 0; var weekly = false; chosen.forEach(function (box) { - if (box.getAttribute('data-removable') === 'false') { + if (box.getAttribute(flag) === 'false') { blocked += 1; return; } @@ -62,7 +67,7 @@ var weeklyNote = text(link, 'data-confirm-note-weekly'); var notes = []; if (kept.length === 0 && blocked > 0) { - body.textContent = 'Cancel this shift, or wait until it has ended, before removing it.'; + body.textContent = blockedBody; submit.hidden = true; submit.disabled = true; cancel.textContent = 'Close'; @@ -78,10 +83,10 @@ input.setAttribute('data-picked', ''); form.appendChild(input); }); - if (blocked > 0) notes.push('The others stay until they are cancelled or have ended.'); + if (blocked > 0) notes.push(partialNote); } if (blocked > 0 && kept.length > 0) { - detail.textContent = kept.length + ' of ' + chosen.length + ' can be removed'; + detail.textContent = kept.length + ' of ' + chosen.length + ' can be ' + verb; } else { detail.textContent = chosen.length === 1 ? '1 selected' : chosen.length + ' selected'; } diff --git a/src/admin-http.tsx b/src/admin-http.tsx index eae3c59..28a01b5 100644 --- a/src/admin-http.tsx +++ b/src/admin-http.tsx @@ -17,6 +17,7 @@ import { import { addWalkIn, cancelShift, + cancelShifts, cancelSignupAsCoordinator, createEvent, createShift, @@ -106,7 +107,6 @@ import { type SettingsErrors, type SettingsForm, } from './settings.js'; -import { expandTemplates } from './recurrence.js'; import { Layout } from './pages.js'; import { EMPTY_SIGNUP, parseSignupForm, spotsLeftMessage, type SignupValues } from './signup-form.js'; import { confirmedPersonOnShift } from './signup.js'; @@ -164,7 +164,6 @@ export function registerAdmin(app: Hono, services: AdminServices): void { app.get(appPath(config, '/admin/events/:id'), (c) => showEvent(c, services)); app.post(appPath(config, '/admin/events/:id/export'), (c) => submitExportEvent(c, services)); app.post(appPath(config, '/admin/events/:id'), (c) => submitEvent(c, services)); - app.post(appPath(config, '/admin/events/:id/generate'), (c) => generateWeeklyShifts(c, services)); app.get(appPath(config, '/admin/events/:id/templates/new'), (c) => showNewTemplate(c, services)); app.post(appPath(config, '/admin/events/:id/templates'), (c) => submitNewTemplate(c, services)); app.get(appPath(config, '/admin/events/:id/templates/:templateId'), (c) => showTemplate(c, services)); @@ -174,6 +173,7 @@ export function registerAdmin(app: Hono, services: AdminServices): void { app.post(appPath(config, '/admin/events/:id/templates/:templateId/remove'), (c) => submitRemoveTemplate(c, services)); app.post(appPath(config, '/admin/events/:id/templates/:templateId'), (c) => submitTemplate(c, services)); app.get(appPath(config, '/admin/events/:id/shifts/new'), (c) => showNewShift(c, services)); + app.post(appPath(config, '/admin/events/:id/shifts/cancel'), (c) => submitCancelShifts(c, services)); app.post(appPath(config, '/admin/events/:id/shifts/remove'), (c) => submitRemoveShifts(c, services)); app.post(appPath(config, '/admin/events/:id/shifts'), (c) => submitNewShift(c, services)); app.get(appPath(config, '/admin/shifts/:id'), (c) => showShift(c, services)); @@ -761,6 +761,8 @@ function showEvent( status: 200 | 400 | 403 = 200, confirm?: ConfirmPrompt, eventId = idFrom(c), + scheduleNote?: string, + notice?: string, ) { const session = requireSession(c, services); if (session instanceof Response) return session; @@ -785,7 +787,8 @@ function showEvent( }} event={event} error={error} - notice={knownNotice(c.req.query('notice'))} + notice={notice ?? knownNotice(c.req.query('notice'))} + generateNote={scheduleNote} now={services.now()} submitLabel="Save event" confirm={confirm} @@ -794,49 +797,6 @@ function showEvent( ); } -async function generateWeeklyShifts(c: Context, services: AdminServices): Promise { - const session = await postedSession(c, services); - if (session instanceof Response) return session; - const id = idFrom(c); - const event = getAdminEvent(services.db, id); - if (!event) return missing(c, services); - try { - const result = expandTemplates(services.db, services.now(), { eventId: id, coordinatorId: session.coordinatorId }); - if (result.templates === 0) { - return c.redirect(appPath(services.config, `/admin/events/${id}?notice=no-template`), 303); - } - if (result.skipped.length > 0) { - return html( - c, - services, - `${event.title} ยท Hope Volunteer`, - , - { account: session, status: 200 }, - ); - } - return c.redirect(appPath(services.config, `/admin/events/${id}?notice=generated`), 303); - } catch (err) { - return saveFailed(c, services, session, err); - } -} - async function submitEvent(c: Context, services: AdminServices): Promise { const session = await postedSession(c, services); if (session instanceof Response) return session; @@ -887,7 +847,7 @@ async function submitNewTemplate(c: Context, services: AdminServices): Promise 0 ? 'template-saved-mailed' : 'template-saved'; + if (saved.skipped && saved.skipped.length > 0) { + return showEvent(c, services, undefined, 200, undefined, eventId, saved.skipped.join(' '), notice); + } + return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=${notice}`), 303); +} + async function submitTemplate(c: Context, services: AdminServices): Promise { const session = await postedSession(c, services); if (session instanceof Response) return session; @@ -939,9 +912,17 @@ async function submitTemplate(c: Context, services: AdminServices): Promise 0 ? 'template-ended-mailed' : 'template-ended'; + return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=${notice}`), 303); } catch (err) { return saveFailed(c, services, session, err); } @@ -1048,6 +1037,52 @@ async function submitRemoveTemplate(c: Context, services: AdminServices): Promis } } +function showCancelShifts(c: Context, services: AdminServices, error: string, status: 200 | 400 | 403 = 400) { + return showEvent( + c, + services, + undefined, + status, + { + action: appPath(services.config, `/admin/events/${idFrom(c)}/shifts/cancel`), + title: 'Cancel selected shifts', + body: error, + }, + idFrom(c), + ); +} + +async function submitCancelShifts(c: Context, services: AdminServices): Promise { + const session = await postedSession(c, services); + if (session instanceof Response) return session; + const eventId = idFrom(c); + if (!getAdminEvent(services.db, eventId)) return missing(c, services); + const shiftIds = idList(session.body, 'shift[]'); + if (!shiftIds) return showCancelShifts(c, services, 'That shift is not available.'); + try { + const result = cancelShifts( + services.db, + session.coordinatorId, + eventId, + shiftIds, + services.now(), + mailIdentity(services.db, services.config), + ); + if (!result.ok) return showCancelShifts(c, services, result.error); + const notice = + result.mailed > 0 + ? result.count === 1 + ? 'shift-cancelled' + : 'shifts-cancelled' + : result.count === 1 + ? 'shift-closed' + : 'shifts-closed'; + return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=${notice}`), 303); + } catch (err) { + return saveFailed(c, services, session, err); + } +} + function showRemoveShifts(c: Context, services: AdminServices, error: string, status: 200 | 400 | 403 = 400) { return showEvent( c, @@ -1395,10 +1430,12 @@ async function submitCancelShift(c: Context, services: AdminServices): Promise {props.error ?

{props.error}

: null} -

This weekly template has ended. Shifts already on the schedule stay.

+

{TEMPLATE_ENDED_BODY}

) : ( <>

- This repeats one role each week. Saving it does not change shifts already on the schedule. Use Add weekly shifts to fill dates that are not there yet. + This repeats one role each week. Saving it updates shifts that have not ended and adds any missing dates for the next three months. A person signed up for a shift that changes gets an email. A date that no longer fits is cancelled when someone is signed up, and removed when nobody is. A shift you edited on its own stays as you saved it. A shift that already ended stays as it was.

@@ -907,7 +911,7 @@ export function ShiftRoster(props: { const confirmed = props.shift.people.filter((person) => person.status === 'confirmed').length; const formError = props.shift.cancelled ? undefined : props.editError; const bannerError = props.error ?? (props.shift.cancelled ? props.editError : undefined); - const detailLine = props.shift.cancelled ? 'Cancelled. The roster stays until you remove it.' : props.shift.whenLabel; + const detailLine = props.shift.cancelled ? 'Cancelled. It is off the upcoming list.' : props.shift.whenLabel; const walkInOpen = Boolean( props.walkIn && (props.walkIn.message || Object.values(props.walkIn.errors).some((message) => Boolean(message))), ); @@ -1126,7 +1130,7 @@ function NeedShift(props: { config: AppConfig; shift: HomeShift; today: string } const when = shiftWhen(shift.date, shift.timeLabel, props.today); return (
  • - + {shift.timeLabel} @@ -1161,8 +1165,8 @@ function FullMark() { ); } -function groupShiftsByDate(shifts: HomeShift[]): { date: string; shifts: HomeShift[] }[] { - const groups: { date: string; shifts: HomeShift[] }[] = []; +function groupShiftsByDate(shifts: T[]): { date: string; shifts: T[] }[] { + const groups: { date: string; shifts: T[] }[] = []; for (const shift of shifts) { const last = groups.at(-1); if (last?.date === shift.date) last.shifts.push(shift); @@ -1171,16 +1175,19 @@ function groupShiftsByDate(shifts: HomeShift[]): { date: string; shifts: HomeShi return groups; } -function dayOpenLabel(shifts: HomeShift[]): { text: string; tone: 'open' | 'needs' } { +function dayOpenLabel(shifts: { capacity: number; occupied: number; ended?: boolean }[]): { text: string; tone: 'open' | 'needs' | 'full' } { + const live = shifts.filter((shift) => !shift.ended); + if (live.length === 0) return { tone: 'full', text: 'Ended' }; let open = 0; let needs = false; - for (const shift of shifts) { - if (shift.full) continue; + for (const shift of live) { const filled = Math.min(shift.capacity, Math.max(0, shift.occupied)); const spots = Math.max(0, shift.capacity - filled); + if (spots === 0) continue; open += spots; if (spots * 2 > shift.capacity) needs = true; } + if (open === 0) return { tone: 'full', text: 'Full' }; return { tone: needs ? 'needs' : 'open', text: open === 1 ? '1 open' : `${open} open`, @@ -1307,34 +1314,42 @@ function joinAnd(parts: string[]): string { function ShiftList(props: { config: AppConfig; event: AdminEvent; csrf: string; generateNote?: string; now?: string }) { const now = props.now; const today = now ? todayInZone(props.event.tz, Temporal.Instant.from(now)) : ''; - const blocks = shiftListBlocks(props.event.shifts, props.event.tz, props.now); - const tail = blocks[blocks.length - 1]; - const footerMore = tail?.kind === 'more' ? tail : undefined; - const body = footerMore ? blocks.slice(0, -1) : blocks; + const cutoff = today ? addLocalDays(today, DESK_WINDOW_DAYS) : ''; + const listed = props.event.shifts.filter((shift) => !shift.cancelled); + const near = listed.filter((shift) => today !== '' && shift.date >= today && shift.date <= cutoff); + const rest = listed.filter((shift) => today === '' || shift.date < today || shift.date > cutoff); return ( <>
    -
    -

    Upcoming shifts

    -
    - ? -

    - Shifts show on the public list when this event is public and the shift is not cancelled. A shift that has already ended stays on today's card, grayed out, until midnight. Then that day leaves the list. Repeating shifts add dates for the next three months. Add weekly shifts fills those dates. Shifts already on the schedule stay as they are, including cancelled ones. -

    -
    +
    +
    +

    Upcoming shifts

    +
    + ? +

    + Shifts show on the public list when this event is public and the shift is not cancelled. A shift that has already ended stays on today's card, grayed out, until midnight. Then that day leaves the list. Saving a template updates shifts that have not ended and adds any missing dates for the next three months. Cancelling a shift takes it off this list. The date stays stored, so the template does not add it again. +

    +
    +
    +

    Next 2 weeks

    -
    - - Add a shift - - {props.event.shifts.length > 1 ? ( - - ) : null} - {props.event.shifts.length > 0 ? ( + {listed.length > 0 ? ( +
    + + Cancel selected + Remove selected +
    + ) : null} +
    + + Add a shift + + {listed.length > 1 ? ( + ) : null}
    - {blocks.length === 0 ? ( -

    No shifts yet.

    + {listed.length === 0 ? ( +

    {props.event.shifts.length === 0 ? 'No shifts yet.' : 'No shifts on this list.'}

    ) : ( <> -
      - {body.map((block) => - block.kind === 'shift' ? ( - - ) : ( -
    • - -
    • - ), - )} -
    + {near.length > 0 ? ( + + ) : ( +

    No shifts in the next 2 weeks.

    + )}
    - {footerMore ? : null} + {rest.length > 0 ? : null}
    )}
    - + ); } +function EventWindow(props: { config: AppConfig; eventTitle: string; shifts: AdminShiftSummary[]; now?: string; today: string }) { + return ( +
    + {groupShiftsByDate(props.shifts).map((day) => { + const summary = dayOpenLabel(day.shifts.map((shift) => ({ ...shift, ended: props.now ? shift.endsAtUtc <= props.now : false }))); + return ( +
    +
    +

    {dayHeading(day.date, props.today)}

    +

    {summary.text}

    +
    +
      + {day.shifts.map((shift) => ( + + ))} +
    +
    + ); + })} +
    + ); +} + +function EventNeedShift(props: { config: AppConfig; eventTitle: string; shift: AdminShiftSummary; now?: string; today: string }) { + const shift = props.shift; + const ended = Boolean(props.now && shift.endsAtUtc <= props.now); + const removable = props.now ? shift.cancelled || ended : false; + const open = Boolean(props.now && !shift.cancelled && !ended); + const time = clockLabel(shift.start); + const when = shiftWhen(shift.date, time, props.today); + const need = ended ? { tone: 'hidden' as const, text: 'Ended' } : shift.occupied >= shift.capacity ? { tone: 'full' as const, text: 'Full' } : needCopy(shift.occupied, shift.capacity); + const rowClass = ended ? 'desk-row is-ended' : 'desk-row'; + return ( +
  • + + + + {time} + + {shift.role} + {props.eventTitle} + + + {need.text} + +
  • + ); +} + function ShiftMore(props: { config: AppConfig; shifts: AdminShiftSummary[]; now?: string; today: string }) { - const count = props.shifts.length; return (
    - - Show {count} more {count === 1 ? 'shift' : 'shifts'} - - Show fewer + See more + See less
      {props.shifts.map((shift) => ( @@ -1416,6 +1492,7 @@ function FillLegend() { function ShiftLine(props: { config: AppConfig; shift: AdminShiftSummary; now?: string; today: string }) { const shift = props.shift; const removable = props.now ? shift.cancelled || shift.endsAtUtc <= props.now : false; + const open = Boolean(props.now && !shift.cancelled && shift.endsAtUtc > props.now); const date = shiftDateParts(shift.date); const fill = fillStatus(shift); return ( @@ -1425,6 +1502,7 @@ function ShiftLine(props: { config: AppConfig; shift: AdminShiftSummary; now?: s type="checkbox" data-pick="shift" data-removable={removable ? 'true' : 'false'} + data-open={open ? 'true' : 'false'} value={String(shift.id)} data-weekly={shift.weeklyActive ? 'true' : undefined} /> @@ -1457,64 +1535,21 @@ function FillCheck() { ); } -type ShiftListBlock = { kind: 'shift'; shift: AdminShiftSummary } | { kind: 'more'; shifts: AdminShiftSummary[] }; - -function shiftListBlocks(shifts: AdminShiftSummary[], timeZone: string, now?: string): ShiftListBlock[] { - if (!now) return shifts.map((shift) => ({ kind: 'shift', shift })); - const cutoff = addLocalDays(todayInZone(timeZone, Temporal.Instant.from(now)), DESK_WINDOW_DAYS); - const blocks: ShiftListBlock[] = []; - let later: AdminShiftSummary[] = []; - const flush = () => { - if (later.length === 0) return; - blocks.push({ kind: 'more', shifts: later }); - later = []; - }; - for (const shift of shifts) { - const tucked = !shift.cancelled && shift.endsAtUtc > now && shift.date > cutoff; - if (tucked) later.push(shift); - else { - flush(); - blocks.push({ kind: 'shift', shift }); - } - } - flush(); - const hasOpenShown = blocks.some((block) => block.kind === 'shift' && !block.shift.cancelled && block.shift.endsAtUtc > now); - if (hasOpenShown) return blocks; - const moreIndex = blocks.findIndex((block) => block.kind === 'more'); - const more = blocks[moreIndex]; - if (!more || more.kind !== 'more') return blocks; - const firstDate = more.shifts[0]?.date; - const lead = more.shifts.filter((shift) => shift.date === firstDate); - more.shifts = more.shifts.filter((shift) => shift.date !== firstDate); - const leadBlocks: ShiftListBlock[] = lead.map((shift) => ({ kind: 'shift', shift })); - if (more.shifts.length === 0) blocks.splice(moreIndex, 1, ...leadBlocks); - else blocks.splice(moreIndex, 0, ...leadBlocks); - return blocks; -} - -function WeeklyTemplates(props: { config: AppConfig; event: AdminEvent; csrf: string; generateNote?: string }) { +function WeeklyTemplates(props: { config: AppConfig; event: AdminEvent; generateNote?: string }) { return (
      -

      Repeating shifts

      -

      - Each one adds three months ahead.{' '} - -

      +

      Templates

      +

      Each one keeps three months of shifts filled.

      - Add a repeating shift + Add a template
      - {props.generateNote ?

      {props.generateNote}

      : null} {props.event.templates.length === 0 ? ( -

      No repeating shifts yet.

      +

      No templates yet.

      ) : (
        {props.event.templates.map((template) => ( @@ -1962,7 +1997,19 @@ function Notice(props: { notice?: string; text?: string }) { ); } -function MassRemove(props: { pick: 'shift' | 'signup'; action: string; title: string; body: string; submit: string; note?: string; children: string }) { +function MassRemove(props: { + pick: 'shift' | 'signup'; + action: string; + title: string; + body: string; + submit: string; + note?: string; + gate?: 'open' | 'removable'; + verb?: string; + blocked?: string; + partial?: string; + children: string; +}) { return (