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.
This commit is contained in:
1 parent
e363cdaef9
commit
1b78a06f72
10 files changed
+956
-352
No files matched your search
@@ -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.
|
||||
|
||||
|
||||
+92
-7
@@ -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;
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
|
||||
+93
-52
@@ -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<Response> {
|
||||
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`,
|
||||
<EventEditor
|
||||
config={services.config}
|
||||
heading={event.title}
|
||||
action={appPath(services.config, `/admin/events/${event.id}`)}
|
||||
csrf={session.csrf}
|
||||
values={{
|
||||
title: event.title,
|
||||
slug: event.slug,
|
||||
description: event.description,
|
||||
location: event.location,
|
||||
tz: event.tz,
|
||||
published: event.published,
|
||||
}}
|
||||
event={getAdminEvent(services.db, id) ?? event}
|
||||
generateNote={result.skipped.join(' ')}
|
||||
now={services.now()}
|
||||
submitLabel="Save event"
|
||||
/>,
|
||||
{ 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<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
@@ -887,7 +847,7 @@ async function submitNewTemplate(c: Context, services: AdminServices): Promise<R
|
||||
try {
|
||||
const saved = createTemplate(services.db, session.coordinatorId, eventId, parsed.value, services.now());
|
||||
if (!saved.ok) return showNewTemplate(c, services, values, saved.error, 400);
|
||||
return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=template-saved`), 303);
|
||||
return templateSaved(c, services, eventId, saved);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
@@ -930,6 +890,19 @@ function showTemplate(c: Context, services: AdminServices, values?: TemplateValu
|
||||
);
|
||||
}
|
||||
|
||||
function templateSaved(
|
||||
c: Context,
|
||||
services: AdminServices,
|
||||
eventId: number,
|
||||
saved: { mailed: number; skipped?: string[] },
|
||||
): Response {
|
||||
const notice = saved.mailed > 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<Response> {
|
||||
const session = await postedSession(c, services);
|
||||
if (session instanceof Response) return session;
|
||||
@@ -939,9 +912,17 @@ async function submitTemplate(c: Context, services: AdminServices): Promise<Resp
|
||||
const parsed = parseTemplate(values);
|
||||
if (!parsed.ok) return showTemplate(c, services, values, parsed.error, 400);
|
||||
try {
|
||||
const saved = updateTemplate(services.db, session.coordinatorId, eventId, templateId, parsed.value, services.now());
|
||||
const saved = updateTemplate(
|
||||
services.db,
|
||||
session.coordinatorId,
|
||||
eventId,
|
||||
templateId,
|
||||
parsed.value,
|
||||
services.now(),
|
||||
mailIdentity(services.db, services.config),
|
||||
);
|
||||
if (!saved.ok) return showTemplate(c, services, values, saved.error, 400);
|
||||
return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=template-saved`), 303);
|
||||
return templateSaved(c, services, eventId, saved);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
@@ -971,9 +952,17 @@ async function submitEndTemplate(c: Context, services: AdminServices): Promise<R
|
||||
const eventId = idFrom(c);
|
||||
const templateId = templateIdFrom(c);
|
||||
try {
|
||||
const ended = endTemplate(services.db, session.coordinatorId, eventId, templateId, services.now());
|
||||
const ended = endTemplate(
|
||||
services.db,
|
||||
session.coordinatorId,
|
||||
eventId,
|
||||
templateId,
|
||||
services.now(),
|
||||
mailIdentity(services.db, services.config),
|
||||
);
|
||||
if (!ended.ok) return missing(c, services);
|
||||
return c.redirect(appPath(services.config, `/admin/events/${eventId}?notice=template-ended`), 303);
|
||||
const notice = ended.mailed > 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<Response> {
|
||||
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<R
|
||||
if (session instanceof Response) return session;
|
||||
const id = idFrom(c);
|
||||
try {
|
||||
const shift = getAdminShift(services.db, id);
|
||||
if (!shift) return missing(c, services);
|
||||
const result = cancelShift(services.db, session.coordinatorId, id, services.now(), mailIdentity(services.db, services.config));
|
||||
if (!result.ok) return missing(c, services);
|
||||
const notice = result.already || result.mailed === 0 ? 'shift-closed' : 'shift-cancelled';
|
||||
return c.redirect(appPath(services.config, `/admin/shifts/${id}?notice=${notice}`), 303);
|
||||
return c.redirect(appPath(services.config, `/admin/events/${shift.eventId}?notice=${notice}`), 303);
|
||||
} catch (err) {
|
||||
return saveFailed(c, services, session, err);
|
||||
}
|
||||
@@ -1581,13 +1618,17 @@ function knownNotice(value: string | undefined): string | undefined {
|
||||
value === 'signup-cancelled' ||
|
||||
value === 'already-cancelled' ||
|
||||
value === 'shift-cancelled' ||
|
||||
value === 'shifts-cancelled' ||
|
||||
value === 'shift-closed' ||
|
||||
value === 'shifts-closed' ||
|
||||
value === 'walk-in' ||
|
||||
value === 'moved' ||
|
||||
value === 'generated' ||
|
||||
value === 'no-template' ||
|
||||
value === 'template-saved' ||
|
||||
value === 'template-saved-mailed' ||
|
||||
value === 'template-ended' ||
|
||||
value === 'template-ended-mailed' ||
|
||||
value === 'signup-removed' ||
|
||||
value === 'signups-removed' ||
|
||||
value === 'shift-removed' ||
|
||||
|
||||
+169
-114
@@ -44,19 +44,24 @@ const SHIFT_DELETE_BODY = 'This deletes the shift. It does not send email.';
|
||||
const SHIFT_PEOPLE_BODY = 'Remove everyone on this roster first.';
|
||||
const SHIFT_WAIT_BODY = 'Cancel this shift, or wait until it has ended, before removing it.';
|
||||
const SHIFT_WEEKLY_NOTE =
|
||||
'This date came from a weekly template that is still active. Add weekly shifts can put this date back. End that template first if the date should stay gone.';
|
||||
'This date came from a weekly template that is still active. Saving that template puts this date back. End that template first if the date should stay gone.';
|
||||
const PERSON_DELETE_BODY = 'This deletes their name, email, phone, and notes from the roster. It does not send email.';
|
||||
const PERSON_WAIT_BODY = 'Cancel this signup before removing it.';
|
||||
const PERSON_CANCEL_BODY = 'Cancelling a signup emails them. Their old private link stops working, and the email includes a new one.';
|
||||
const SHIFT_CANCEL_EMPTY = 'No one is signed up. Cancelling closes the shift and does not send email.';
|
||||
const SHIFT_CANCEL_STAY = 'The roster stays. After it is empty, the shift can be removed.';
|
||||
const SHIFT_CANCEL_EMPTY = 'No one is signed up. Cancelling closes the shift, takes it off this list, and does not send email.';
|
||||
const SHIFT_CANCEL_MANY =
|
||||
'This closes the selected shifts and takes them off this list. A cancellation email is queued for each person who is signed up.';
|
||||
const SHIFT_CANCEL_KEEP = 'A template will not add these dates again.';
|
||||
const SHIFT_CANCEL_ENDED = 'Those shifts have ended.';
|
||||
const SHIFT_CANCEL_PARTIAL = 'Shifts that have ended stay on the list.';
|
||||
const SHIFT_ALREADY = 'This shift is already cancelled.';
|
||||
const SHORT_WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] as const;
|
||||
const SHORT_MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] as const;
|
||||
const TEMPLATE_END_BODY = 'Ending it stops later weeks from being added. Shifts already on the schedule stay.';
|
||||
const TEMPLATE_ENDED_BODY = 'This weekly template has ended. Shifts already on the schedule stay.';
|
||||
const TEMPLATE_END_BODY =
|
||||
'Ending it stops later weeks from being added. Shifts that have not ended are cancelled and leave this list, and a cancellation email is queued for each person signed up. Shifts that already ended are deleted, including the names and emails on those rosters. That part does not send email.';
|
||||
const TEMPLATE_ENDED_BODY = 'This template has ended. The shifts it added are off this list.';
|
||||
const TEMPLATE_DELETE_BODY =
|
||||
'This deletes the weekly template. Shifts already on the schedule stay. They are no longer tied to this weekly pattern, so later weekly fills will not change them.';
|
||||
'This deletes the template. Any shifts left are no longer tied to this weekly pattern. Cancelled shifts stay off this list.';
|
||||
const TEMPLATE_WAIT_BODY = 'End this template before removing it.';
|
||||
|
||||
export function shiftRemovalPrompt(
|
||||
@@ -109,8 +114,7 @@ export function shiftCancelPrompt(shift: { role: string; whenLabel?: string; can
|
||||
body:
|
||||
confirmed === 0
|
||||
? SHIFT_CANCEL_EMPTY
|
||||
: `This closes the shift. ${confirmed} confirmed ${confirmed === 1 ? 'signup' : 'signups'} will be marked cancelled, and a cancellation email is queued for each.`,
|
||||
note: SHIFT_CANCEL_STAY,
|
||||
: `This closes the shift and takes it off this list. ${confirmed} confirmed ${confirmed === 1 ? 'signup' : 'signups'} will be marked cancelled, and a cancellation email is queued for each.`,
|
||||
submit: 'Cancel this shift',
|
||||
};
|
||||
}
|
||||
@@ -840,12 +844,12 @@ export function TemplateEditor(props: {
|
||||
{props.ended ? (
|
||||
<>
|
||||
{props.error ? <p class="error">{props.error}</p> : null}
|
||||
<p>This weekly template has ended. Shifts already on the schedule stay.</p>
|
||||
<p>{TEMPLATE_ENDED_BODY}</p>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
<TemplateForm action={props.action} csrf={props.csrf} values={props.values} error={props.error} submitLabel={props.submitLabel} />
|
||||
</>
|
||||
@@ -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 (
|
||||
<li>
|
||||
<a class={shift.full ? 'desk-row is-covered' : 'desk-row'} href={appPath(props.config, `/admin/shifts/${shift.id}`)} aria-label={`${when}. ${shift.role}. ${shift.eventTitle}. ${need.text}.`}>
|
||||
<a class="desk-row" href={appPath(props.config, `/admin/shifts/${shift.id}`)} aria-label={`${when}. ${shift.role}. ${shift.eventTitle}. ${need.text}.`}>
|
||||
<span class="desk-row-main">
|
||||
<span class="desk-row-when">{shift.timeLabel}</span>
|
||||
<span class="desk-row-copy">
|
||||
@@ -1161,8 +1165,8 @@ function FullMark() {
|
||||
);
|
||||
}
|
||||
|
||||
function groupShiftsByDate(shifts: HomeShift[]): { date: string; shifts: HomeShift[] }[] {
|
||||
const groups: { date: string; shifts: HomeShift[] }[] = [];
|
||||
function groupShiftsByDate<T extends { date: string }>(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 (
|
||||
<>
|
||||
<section class="event-panel" aria-labelledby="shifts-heading">
|
||||
<div class="event-panel-head">
|
||||
<div class="event-panel-title">
|
||||
<h2 id="shifts-heading">Upcoming shifts</h2>
|
||||
<details class="help-tip">
|
||||
<summary aria-label="About upcoming shifts">?</summary>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</details>
|
||||
<div>
|
||||
<div class="event-panel-title">
|
||||
<h2 id="shifts-heading">Upcoming shifts</h2>
|
||||
<details class="help-tip">
|
||||
<summary aria-label="About upcoming shifts">?</summary>
|
||||
<p>
|
||||
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.
|
||||
</p>
|
||||
</details>
|
||||
</div>
|
||||
<p class="event-panel-note">Next 2 weeks</p>
|
||||
</div>
|
||||
<div class="event-panel-tools">
|
||||
<a class="btn" href={appPath(props.config, `/admin/events/${props.event.id}/shifts/new`)}>
|
||||
Add a shift
|
||||
</a>
|
||||
{props.event.shifts.length > 1 ? (
|
||||
<label class="pick-all">
|
||||
<input type="checkbox" data-pick-all="shift" />
|
||||
Select all
|
||||
</label>
|
||||
) : null}
|
||||
{props.event.shifts.length > 0 ? (
|
||||
{listed.length > 0 ? (
|
||||
<div class="event-panel-actions">
|
||||
<MassRemove
|
||||
pick="shift"
|
||||
gate="open"
|
||||
verb="cancelled"
|
||||
blocked={SHIFT_CANCEL_ENDED}
|
||||
partial={SHIFT_CANCEL_PARTIAL}
|
||||
action={appPath(props.config, `/admin/events/${props.event.id}/shifts/cancel`)}
|
||||
title="Cancel selected shifts"
|
||||
body={SHIFT_CANCEL_MANY}
|
||||
submit="Cancel selected"
|
||||
note={SHIFT_CANCEL_KEEP}
|
||||
>
|
||||
Cancel selected
|
||||
</MassRemove>
|
||||
<MassRemove
|
||||
pick="shift"
|
||||
action={appPath(props.config, `/admin/events/${props.event.id}/shifts/remove`)}
|
||||
@@ -1345,45 +1360,106 @@ function ShiftList(props: { config: AppConfig; event: AdminEvent; csrf: string;
|
||||
>
|
||||
Remove selected
|
||||
</MassRemove>
|
||||
</div>
|
||||
) : null}
|
||||
<div class="event-panel-tools">
|
||||
<a class="btn" href={appPath(props.config, `/admin/events/${props.event.id}/shifts/new`)}>
|
||||
Add a shift
|
||||
</a>
|
||||
{listed.length > 1 ? (
|
||||
<label class="pick-all">
|
||||
<input type="checkbox" data-pick-all="shift" />
|
||||
Select all
|
||||
</label>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
{blocks.length === 0 ? (
|
||||
<p class="empty">No shifts yet.</p>
|
||||
{listed.length === 0 ? (
|
||||
<p class="empty">{props.event.shifts.length === 0 ? 'No shifts yet.' : 'No shifts on this list.'}</p>
|
||||
) : (
|
||||
<>
|
||||
<ul class="shift-lines">
|
||||
{body.map((block) =>
|
||||
block.kind === 'shift' ? (
|
||||
<ShiftLine key={block.shift.id} config={props.config} shift={block.shift} now={props.now} today={today} />
|
||||
) : (
|
||||
<li key={`more-${block.shifts[0]?.id ?? 'later'}`}>
|
||||
<ShiftMore config={props.config} shifts={block.shifts} now={props.now} today={today} />
|
||||
</li>
|
||||
),
|
||||
)}
|
||||
</ul>
|
||||
{near.length > 0 ? (
|
||||
<EventWindow config={props.config} eventTitle={props.event.title} shifts={near} now={props.now} today={today} />
|
||||
) : (
|
||||
<p class="empty">No shifts in the next 2 weeks.</p>
|
||||
)}
|
||||
<div class="shift-tail">
|
||||
{footerMore ? <ShiftMore config={props.config} shifts={footerMore.shifts} now={props.now} today={today} /> : null}
|
||||
{rest.length > 0 ? <ShiftMore config={props.config} shifts={rest} now={props.now} today={today} /> : null}
|
||||
<FillLegend />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</section>
|
||||
<WeeklyTemplates config={props.config} event={props.event} csrf={props.csrf} generateNote={props.generateNote} />
|
||||
<WeeklyTemplates config={props.config} event={props.event} generateNote={props.generateNote} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function EventWindow(props: { config: AppConfig; eventTitle: string; shifts: AdminShiftSummary[]; now?: string; today: string }) {
|
||||
return (
|
||||
<div class="need-days">
|
||||
{groupShiftsByDate(props.shifts).map((day) => {
|
||||
const summary = dayOpenLabel(day.shifts.map((shift) => ({ ...shift, ended: props.now ? shift.endsAtUtc <= props.now : false })));
|
||||
return (
|
||||
<section class={day.date === props.today ? 'need-day is-today' : 'need-day'} aria-labelledby={`event-day-${day.date}`} key={day.date}>
|
||||
<div class="need-day-head">
|
||||
<h3 id={`event-day-${day.date}`}>{dayHeading(day.date, props.today)}</h3>
|
||||
<p class={`need-day-count is-${summary.tone}`}>{summary.text}</p>
|
||||
</div>
|
||||
<ul class="desk-rows">
|
||||
{day.shifts.map((shift) => (
|
||||
<EventNeedShift key={shift.id} config={props.config} eventTitle={props.eventTitle} shift={shift} now={props.now} today={props.today} />
|
||||
))}
|
||||
</ul>
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<li class="need-pick">
|
||||
<label class="pick">
|
||||
<input
|
||||
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}
|
||||
/>
|
||||
<span class="sr-only">Select {shift.role}</span>
|
||||
</label>
|
||||
<a class={rowClass} href={appPath(props.config, `/admin/shifts/${shift.id}`)} aria-label={`${when}. ${shift.role}. ${props.eventTitle}. ${need.text}.`}>
|
||||
<span class="desk-row-main">
|
||||
<span class="desk-row-when">{time}</span>
|
||||
<span class="desk-row-copy">
|
||||
<strong>{shift.role}</strong>
|
||||
<span>{props.eventTitle}</span>
|
||||
</span>
|
||||
</span>
|
||||
<span class={`need-pill is-${need.tone}`}>{need.text}</span>
|
||||
</a>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
function ShiftMore(props: { config: AppConfig; shifts: AdminShiftSummary[]; now?: string; today: string }) {
|
||||
const count = props.shifts.length;
|
||||
return (
|
||||
<details class="shift-more">
|
||||
<summary>
|
||||
<span class="shift-more-closed">
|
||||
Show {count} more {count === 1 ? 'shift' : 'shifts'}
|
||||
</span>
|
||||
<span class="shift-more-open">Show fewer</span>
|
||||
<span class="shift-more-closed">See more</span>
|
||||
<span class="shift-more-open">See less</span>
|
||||
</summary>
|
||||
<ul class="shift-lines">
|
||||
{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 (
|
||||
<section class="event-panel" aria-labelledby="templates-heading">
|
||||
<div class="event-panel-head">
|
||||
<div>
|
||||
<h2 id="templates-heading">Repeating shifts</h2>
|
||||
<p class="event-panel-note">
|
||||
Each one adds three months ahead.{' '}
|
||||
<button type="submit" class="text-action" form="add-weekly">
|
||||
Add weekly shifts
|
||||
</button>
|
||||
</p>
|
||||
<h2 id="templates-heading">Templates</h2>
|
||||
<p class="event-panel-note">Each one keeps three months of shifts filled.</p>
|
||||
</div>
|
||||
<a class="btn btn-line" href={appPath(props.config, `/admin/events/${props.event.id}/templates/new`)}>
|
||||
Add a repeating shift
|
||||
Add a template
|
||||
</a>
|
||||
</div>
|
||||
<form id="add-weekly" method="post" action={appPath(props.config, `/admin/events/${props.event.id}/generate`)} hidden>
|
||||
<input type="hidden" name="csrf" value={props.csrf} />
|
||||
</form>
|
||||
{props.generateNote ? <p class="error">{props.generateNote}</p> : null}
|
||||
{props.event.templates.length === 0 ? (
|
||||
<p class="empty">No repeating shifts yet.</p>
|
||||
<p class="empty">No templates yet.</p>
|
||||
) : (
|
||||
<ul class="repeat-lines">
|
||||
{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 (
|
||||
<button
|
||||
type="button"
|
||||
@@ -1970,6 +2017,10 @@ function MassRemove(props: { pick: 'shift' | 'signup'; action: string; title: st
|
||||
hidden={true}
|
||||
data-confirm=""
|
||||
data-confirm-pick={props.pick}
|
||||
data-confirm-gate={props.gate}
|
||||
data-confirm-verb={props.verb}
|
||||
data-confirm-blocked={props.blocked}
|
||||
data-confirm-partial={props.partial}
|
||||
data-confirm-action={props.action}
|
||||
data-confirm-title={props.title}
|
||||
data-confirm-body={props.body}
|
||||
@@ -1995,19 +2046,23 @@ const NOTICES: Record<string, string> = {
|
||||
saved: 'Saved.',
|
||||
'signup-cancelled': 'The signup is cancelled. A cancellation email is queued.',
|
||||
'already-cancelled': 'That signup was already cancelled.',
|
||||
'shift-cancelled': 'The shift is cancelled. Cancellation emails are queued.',
|
||||
'shift-closed': 'The shift is cancelled. No one needed an email.',
|
||||
'shift-cancelled': 'The shift is cancelled and off this list. Cancellation emails are queued.',
|
||||
'shifts-cancelled': 'Those shifts are cancelled and off this list. Cancellation emails are queued.',
|
||||
'shift-closed': 'The shift is cancelled and off this list. No one needed an email.',
|
||||
'shifts-closed': 'Those shifts are cancelled and off this list. No one needed an email.',
|
||||
'walk-in': 'They are on this shift. A confirmation email is queued.',
|
||||
moved: 'They are on this shift. A change email is queued.',
|
||||
generated: 'Weekly shifts for the next three months are on the schedule. Existing shifts were left as they are.',
|
||||
'no-template': 'There is no active weekly template.',
|
||||
'template-saved': 'The weekly template is saved. Shifts already on the schedule were not changed.',
|
||||
'template-ended': 'This weekly template has ended. Shifts already on the schedule stay.',
|
||||
'template-saved': 'The template is saved. Shifts that have not ended match it.',
|
||||
'template-saved-mailed': 'The template is saved. Shifts that have not ended match it. Emails are queued for the people those changes affect.',
|
||||
'template-ended': 'This template has ended. The shifts it added are off this list.',
|
||||
'template-ended-mailed': 'This template has ended. The shifts it added are off this list. Cancellation emails are queued.',
|
||||
'signup-removed': 'That person is removed from the roster.',
|
||||
'signups-removed': 'Those people are removed from the roster.',
|
||||
'shift-removed': 'That shift is removed.',
|
||||
'shifts-removed': 'Those shifts are removed.',
|
||||
'template-removed': 'That weekly template is removed. Shifts already on the schedule stay, and they are no longer tied to the weekly pattern.',
|
||||
'template-removed': 'That weekly template is removed. Any shifts left are no longer tied to the weekly pattern.',
|
||||
'event-removed': 'That event is removed.',
|
||||
'settings-saved': 'Settings saved.',
|
||||
'admin-added': 'That person can sign in. Ask them to request a sign-in link. This did not send email.',
|
||||
|
||||
+332
-84
@@ -7,6 +7,7 @@ import { cancelPendingConfirmations, cancelPendingReminders, queueCancellation,
|
||||
import type { MailShift } from '../mail/templates.js';
|
||||
import type { MailIdentity } from '../mail/types.js';
|
||||
import { confirmedPersonOnShift, confirmedPersonShiftIds, reserveSignup, type ReserveInput, type ReserveResult } from '../signup.js';
|
||||
import { expandTemplates } from '../recurrence.js';
|
||||
import { isWithinSignupWindow } from '../signup-window.js';
|
||||
import { isUniqueConstraint } from '../sqlite-error.js';
|
||||
import { addLocalDays, assertSameDayShift, assertValidTimeZone, formatInstantInZone, formatUtc, localShiftToUtc, LocalTimeError, todayInZone } from '../time.js';
|
||||
@@ -144,7 +145,7 @@ export type MoveTarget = {
|
||||
label: string;
|
||||
};
|
||||
|
||||
type SaveResult = { ok: true; id: number; mailed: number } | { ok: false; error: string };
|
||||
type SaveResult = { ok: true; id: number; mailed: number; skipped?: string[] } | { ok: false; error: string };
|
||||
type CancelResult = { ok: true; already: boolean; mailed: number } | { ok: false; error: string };
|
||||
|
||||
export function listAdminEvents(db: Database.Database): AdminEventSummary[] {
|
||||
@@ -436,9 +437,10 @@ export function createTemplate(
|
||||
.run(eventId, input.role, input.weekday, input.start, input.end, input.capacity, input.startsOn, input.endsOn);
|
||||
const id = Number(result.lastInsertRowid);
|
||||
writeAudit(db, coordinatorId, 'template.create', { templateId: id, eventId }, now);
|
||||
return id;
|
||||
const filled = expandTemplates(db, now, { eventId, templateId: id, coordinatorId });
|
||||
return { id, skipped: filled.skipped };
|
||||
}).immediate();
|
||||
return { ok: true, id: inserted, mailed: 0 };
|
||||
return { ok: true, id: inserted.id, mailed: 0, skipped: inserted.skipped };
|
||||
}
|
||||
|
||||
export function updateTemplate(
|
||||
@@ -448,64 +450,209 @@ export function updateTemplate(
|
||||
templateId: number,
|
||||
input: TemplateInput,
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): SaveResult {
|
||||
const checked = templateInput(input);
|
||||
if (!checked.ok) return checked;
|
||||
return db.transaction((): SaveResult => {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`SELECT role, weekday, start_local, end_local, capacity, starts_on, ends_on, active
|
||||
FROM shift_templates
|
||||
WHERE id = ? AND event_id = ?`,
|
||||
)
|
||||
.get(templateId, eventId) as
|
||||
| {
|
||||
role: string;
|
||||
weekday: number;
|
||||
start_local: string;
|
||||
end_local: string;
|
||||
capacity: number;
|
||||
starts_on: string;
|
||||
ends_on: string | null;
|
||||
active: number;
|
||||
}
|
||||
| undefined;
|
||||
if (!existing) return { ok: false as const, error: 'That weekly template is not available.' };
|
||||
if (existing.active !== 1) return { ok: false as const, error: 'This weekly template has ended.' };
|
||||
const same =
|
||||
existing.role === input.role &&
|
||||
existing.weekday === input.weekday &&
|
||||
existing.start_local === input.start &&
|
||||
existing.end_local === input.end &&
|
||||
Number(existing.capacity) === input.capacity &&
|
||||
existing.starts_on === input.startsOn &&
|
||||
existing.ends_on === input.endsOn;
|
||||
if (same) return { ok: true as const, id: templateId, mailed: 0 };
|
||||
try {
|
||||
return db.transaction((): SaveResult => {
|
||||
const existing = db
|
||||
.prepare(
|
||||
`SELECT t.role AS role, t.weekday AS weekday, t.start_local AS start_local, t.end_local AS end_local,
|
||||
t.capacity AS capacity, t.starts_on AS starts_on, t.ends_on AS ends_on, t.active AS active, e.tz AS tz
|
||||
FROM shift_templates t
|
||||
JOIN events e ON e.id = t.event_id
|
||||
WHERE t.id = ? AND t.event_id = ?`,
|
||||
)
|
||||
.get(templateId, eventId) as
|
||||
| {
|
||||
role: string;
|
||||
weekday: number;
|
||||
start_local: string;
|
||||
end_local: string;
|
||||
capacity: number;
|
||||
starts_on: string;
|
||||
ends_on: string | null;
|
||||
active: number;
|
||||
tz: string;
|
||||
}
|
||||
| undefined;
|
||||
if (!existing) return { ok: false as const, error: 'That weekly template is not available.' };
|
||||
if (existing.active !== 1) return { ok: false as const, error: 'This weekly template has ended.' };
|
||||
const same =
|
||||
existing.role === input.role &&
|
||||
existing.weekday === input.weekday &&
|
||||
existing.start_local === input.start &&
|
||||
existing.end_local === input.end &&
|
||||
Number(existing.capacity) === input.capacity &&
|
||||
existing.starts_on === input.startsOn &&
|
||||
existing.ends_on === input.endsOn;
|
||||
if (same) {
|
||||
const filled = expandTemplates(db, now, { eventId, templateId, coordinatorId });
|
||||
return { ok: true as const, id: templateId, mailed: 0, skipped: filled.skipped };
|
||||
}
|
||||
const tooSmall = capacityBelowSignups(db, templateId, input, now);
|
||||
if (tooSmall) return { ok: false as const, error: tooSmall };
|
||||
const saved = db
|
||||
.prepare(
|
||||
`UPDATE shift_templates
|
||||
SET role = ?, weekday = ?, start_local = ?, end_local = ?, capacity = ?,
|
||||
starts_on = ?, ends_on = ?, revision = revision + 1
|
||||
WHERE id = ? AND event_id = ? AND active = 1`,
|
||||
)
|
||||
.run(
|
||||
input.role,
|
||||
input.weekday,
|
||||
input.start,
|
||||
input.end,
|
||||
input.capacity,
|
||||
input.startsOn,
|
||||
input.endsOn,
|
||||
templateId,
|
||||
eventId,
|
||||
);
|
||||
if (saved.changes !== 1) return { ok: false as const, error: 'This weekly template has ended.' };
|
||||
const revision = db.prepare('SELECT revision AS revision FROM shift_templates WHERE id = ?').get(templateId) as {
|
||||
revision: number;
|
||||
};
|
||||
const synced = syncTemplateShifts(db, coordinatorId, templateId, input, Number(revision.revision), existing.tz, now, mail);
|
||||
const filled = expandTemplates(db, now, { eventId, templateId, coordinatorId });
|
||||
writeAudit(
|
||||
db,
|
||||
coordinatorId,
|
||||
'template.update',
|
||||
{
|
||||
templateId,
|
||||
eventId,
|
||||
revision: Number(revision.revision),
|
||||
updated: synced.updated,
|
||||
removed: synced.removed,
|
||||
cancelled: synced.cancelled,
|
||||
mailed: synced.mailed,
|
||||
},
|
||||
now,
|
||||
);
|
||||
return { ok: true as const, id: templateId, mailed: synced.mailed, skipped: [...synced.skipped, ...filled.skipped] };
|
||||
}).immediate();
|
||||
} catch (err) {
|
||||
if (err instanceof BatchRemovalError) return { ok: false, error: err.message };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
type TemplateShiftRow = {
|
||||
id: number;
|
||||
occurrence_date: string;
|
||||
role: string;
|
||||
starts_at_utc: string;
|
||||
ends_at_utc: string;
|
||||
capacity: number;
|
||||
cancelled: number;
|
||||
manually_modified: number;
|
||||
};
|
||||
|
||||
/** Future shifts from this template follow the saved pattern. A shift edited on its own, a cancelled date, and a shift that already ended stay as they are. */
|
||||
function syncTemplateShifts(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
templateId: number,
|
||||
input: TemplateInput,
|
||||
revision: number,
|
||||
tz: string,
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): { updated: number; removed: number; cancelled: number; mailed: number; skipped: string[] } {
|
||||
const shifts = db
|
||||
.prepare(
|
||||
`SELECT id AS id, occurrence_date AS occurrence_date, role AS role, starts_at_utc AS starts_at_utc,
|
||||
ends_at_utc AS ends_at_utc, capacity AS capacity, cancelled AS cancelled, manually_modified AS manually_modified
|
||||
FROM shifts
|
||||
WHERE template_id = ?
|
||||
ORDER BY occurrence_date`,
|
||||
)
|
||||
.all(templateId) as TemplateShiftRow[];
|
||||
let updated = 0;
|
||||
let removed = 0;
|
||||
let cancelled = 0;
|
||||
let mailed = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const shift of shifts) {
|
||||
if (shift.ends_at_utc <= now || shift.cancelled === 1 || shift.manually_modified === 1) continue;
|
||||
if (!occurrenceStillMatches(shift.occurrence_date, input)) {
|
||||
const roster = shiftRoster(db, shift.id);
|
||||
if (roster.signups > 0) {
|
||||
const result = cancelOpenShift(db, coordinatorId, shift.id, now, mail);
|
||||
if (!result.ok) throw new BatchRemovalError(result.error);
|
||||
mailed += result.mailed;
|
||||
if (!result.already) cancelled += 1;
|
||||
} else {
|
||||
purgeShift(db, shift.id);
|
||||
removed += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let times: { startsAtUtc: string; endsAtUtc: string };
|
||||
try {
|
||||
times = localShiftToUtc(shift.occurrence_date, input.start, input.end, tz);
|
||||
} catch (err) {
|
||||
if (err instanceof LocalTimeError) {
|
||||
skipped.push(err.message);
|
||||
continue;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
const material = shift.role !== input.role || shift.starts_at_utc !== times.startsAtUtc || shift.ends_at_utc !== times.endsAtUtc;
|
||||
const saved = db
|
||||
.prepare(
|
||||
`UPDATE shift_templates
|
||||
SET role = ?, weekday = ?, start_local = ?, end_local = ?, capacity = ?,
|
||||
starts_on = ?, ends_on = ?, revision = revision + 1
|
||||
WHERE id = ? AND event_id = ? AND active = 1`,
|
||||
`UPDATE shifts
|
||||
SET role = ?, starts_at_utc = ?, ends_at_utc = ?, capacity = ?, template_revision = ?
|
||||
WHERE id = ? AND cancelled = 0 AND manually_modified = 0 AND ends_at_utc > ?`,
|
||||
)
|
||||
.run(
|
||||
input.role,
|
||||
input.weekday,
|
||||
input.start,
|
||||
input.end,
|
||||
input.capacity,
|
||||
input.startsOn,
|
||||
input.endsOn,
|
||||
templateId,
|
||||
eventId,
|
||||
);
|
||||
if (saved.changes !== 1) return { ok: false as const, error: 'This weekly template has ended.' };
|
||||
const revision = db.prepare('SELECT revision AS revision FROM shift_templates WHERE id = ?').get(templateId) as {
|
||||
revision: number;
|
||||
};
|
||||
writeAudit(db, coordinatorId, 'template.update', { templateId, eventId, revision: Number(revision.revision) }, now);
|
||||
return { ok: true as const, id: templateId, mailed: 0 };
|
||||
}).immediate();
|
||||
.run(input.role, times.startsAtUtc, times.endsAtUtc, input.capacity, revision, shift.id, now);
|
||||
if (saved.changes !== 1) continue;
|
||||
updated += 1;
|
||||
if (material) mailed += bumpAndNotify(db, shift.id, now, mail, false);
|
||||
}
|
||||
return { updated, removed, cancelled, mailed, skipped };
|
||||
}
|
||||
|
||||
function capacityBelowSignups(db: Database.Database, templateId: number, input: TemplateInput, now: string): string | null {
|
||||
const shifts = db
|
||||
.prepare(
|
||||
`SELECT id AS id, occurrence_date AS occurrence_date, ends_at_utc AS ends_at_utc,
|
||||
cancelled AS cancelled, manually_modified AS manually_modified
|
||||
FROM shifts
|
||||
WHERE template_id = ?`,
|
||||
)
|
||||
.all(templateId) as Array<Pick<TemplateShiftRow, 'id' | 'occurrence_date' | 'ends_at_utc' | 'cancelled' | 'manually_modified'>>;
|
||||
for (const shift of shifts) {
|
||||
if (shift.ends_at_utc <= now || shift.cancelled === 1 || shift.manually_modified === 1) continue;
|
||||
if (!occurrenceStillMatches(shift.occurrence_date, input)) continue;
|
||||
if (shiftRoster(db, shift.id).occupied > input.capacity) {
|
||||
return 'Capacity cannot be lower than the number of people signed up.';
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function occurrenceStillMatches(date: string, input: TemplateInput): boolean {
|
||||
const weekday = Temporal.PlainDate.from(date).dayOfWeek % 7;
|
||||
if (weekday !== input.weekday) return false;
|
||||
if (date < input.startsOn) return false;
|
||||
if (input.endsOn !== null && date > input.endsOn) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
function shiftRoster(db: Database.Database, shiftId: number): { occupied: number; signups: number } {
|
||||
const row = db
|
||||
.prepare(
|
||||
`SELECT COALESCE(SUM(CASE WHEN status = 'confirmed' THEN group_size ELSE 0 END), 0) AS occupied,
|
||||
COUNT(*) AS signups
|
||||
FROM signups
|
||||
WHERE shift_id = ?`,
|
||||
)
|
||||
.get(shiftId) as { occupied: number; signups: number };
|
||||
return { occupied: Number(row.occupied), signups: Number(row.signups) };
|
||||
}
|
||||
|
||||
export function endTemplate(
|
||||
@@ -514,20 +661,45 @@ export function endTemplate(
|
||||
eventId: number,
|
||||
templateId: number,
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): CancelResult {
|
||||
return db.transaction((): CancelResult => {
|
||||
const existing = db
|
||||
.prepare('SELECT active AS active FROM shift_templates WHERE id = ? AND event_id = ?')
|
||||
.get(templateId, eventId) as { active: number } | undefined;
|
||||
if (!existing) return { ok: false as const, error: 'That weekly template is not available.' };
|
||||
if (existing.active !== 1) return { ok: true as const, already: true, mailed: 0 };
|
||||
const saved = db
|
||||
.prepare('UPDATE shift_templates SET active = 0 WHERE id = ? AND event_id = ? AND active = 1')
|
||||
.run(templateId, eventId);
|
||||
if (saved.changes !== 1) return { ok: true as const, already: true, mailed: 0 };
|
||||
writeAudit(db, coordinatorId, 'template.end', { templateId, eventId }, now);
|
||||
return { ok: true as const, already: false, mailed: 0 };
|
||||
}).immediate();
|
||||
try {
|
||||
return db.transaction((): CancelResult => {
|
||||
const existing = db
|
||||
.prepare('SELECT active AS active FROM shift_templates WHERE id = ? AND event_id = ?')
|
||||
.get(templateId, eventId) as { active: number } | undefined;
|
||||
if (!existing) return { ok: false as const, error: 'That weekly template is not available.' };
|
||||
if (existing.active !== 1) return { ok: true as const, already: true, mailed: 0 };
|
||||
const saved = db
|
||||
.prepare('UPDATE shift_templates SET active = 0 WHERE id = ? AND event_id = ? AND active = 1')
|
||||
.run(templateId, eventId);
|
||||
if (saved.changes !== 1) return { ok: true as const, already: true, mailed: 0 };
|
||||
const shifts = db
|
||||
.prepare('SELECT id AS id, ends_at_utc AS ends_at_utc, cancelled AS cancelled FROM shifts WHERE template_id = ?')
|
||||
.all(templateId) as { id: number; ends_at_utc: string; cancelled: number }[];
|
||||
let mailed = 0;
|
||||
let removed = 0;
|
||||
let cancelled = 0;
|
||||
for (const shift of shifts) {
|
||||
if (shift.ends_at_utc <= now) {
|
||||
purgeShift(db, shift.id);
|
||||
writeAudit(db, coordinatorId, 'shift.delete', { shiftId: shift.id, eventId, templateId }, now);
|
||||
removed += 1;
|
||||
continue;
|
||||
}
|
||||
if (shift.cancelled === 1) continue;
|
||||
const result = cancelOpenShift(db, coordinatorId, shift.id, now, mail);
|
||||
if (!result.ok) throw new BatchRemovalError(result.error);
|
||||
mailed += result.mailed;
|
||||
if (!result.already) cancelled += 1;
|
||||
}
|
||||
writeAudit(db, coordinatorId, 'template.end', { templateId, eventId, removed, cancelled, mailed }, now);
|
||||
return { ok: true as const, already: false, mailed };
|
||||
}).immediate();
|
||||
} catch (err) {
|
||||
if (err instanceof BatchRemovalError) return { ok: false, error: err.message };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export function readSignupRemoval(db: Database.Database, signupId: number): SignupRemoval | null {
|
||||
@@ -912,20 +1084,78 @@ export function cancelShift(
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): CancelResult {
|
||||
return db.transaction((): CancelResult => {
|
||||
const shift = db.prepare('SELECT id AS id, cancelled AS cancelled FROM shifts WHERE id = ?').get(id) as
|
||||
| { id: number; cancelled: number }
|
||||
| undefined;
|
||||
if (!shift) return { ok: false, error: 'That shift is not available.' };
|
||||
if (shift.cancelled === 1) return { ok: true, already: true, mailed: 0 };
|
||||
const marked = db
|
||||
.prepare('UPDATE shifts SET cancelled = 1, version = version + 1, manually_modified = 1 WHERE id = ? AND cancelled = 0')
|
||||
.run(id);
|
||||
if (marked.changes !== 1) return { ok: true, already: true, mailed: 0 };
|
||||
const mailed = cancelConfirmedOnShift(db, id, now, mail);
|
||||
writeAudit(db, coordinatorId, 'shift.cancel', { shiftId: id, mailed }, now);
|
||||
return { ok: true, already: false, mailed };
|
||||
}).immediate();
|
||||
return db.transaction((): CancelResult => cancelOpenShift(db, coordinatorId, id, now, mail)).immediate();
|
||||
}
|
||||
|
||||
export function cancelShifts(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
eventId: number,
|
||||
shiftIds: number[],
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): { ok: true; eventId: number; count: number; mailed: number } | { ok: false; error: string } {
|
||||
const ids = [...new Set(shiftIds)];
|
||||
if (ids.length === 0) return { ok: false, error: 'Choose a shift to cancel.' };
|
||||
if (ids.length > BATCH_LIMIT) return { ok: false, error: 'Choose fewer shifts to cancel.' };
|
||||
try {
|
||||
return db
|
||||
.transaction((): { ok: true; eventId: number; count: number; mailed: number } | { ok: false; error: string } => {
|
||||
const rows = ids.map((id) => readCancelTarget(db, id));
|
||||
for (const row of rows) {
|
||||
if (!row || row.eventId !== eventId) return { ok: false, error: 'That shift is not available.' };
|
||||
}
|
||||
for (const row of rows) {
|
||||
if (row && !row.cancelled && row.endsAtUtc <= now) return { ok: false, error: 'That shift has ended.' };
|
||||
}
|
||||
let count = 0;
|
||||
let mailed = 0;
|
||||
for (const row of rows) {
|
||||
if (!row || row.cancelled) continue;
|
||||
const result = cancelOpenShift(db, coordinatorId, row.id, now, mail);
|
||||
if (!result.ok) throw new BatchRemovalError(result.error);
|
||||
if (!result.already) count += 1;
|
||||
mailed += result.mailed;
|
||||
}
|
||||
return { ok: true, eventId, count, mailed };
|
||||
})
|
||||
.immediate();
|
||||
} catch (err) {
|
||||
if (err instanceof BatchRemovalError) return { ok: false, error: err.message };
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
function readCancelTarget(
|
||||
db: Database.Database,
|
||||
shiftId: number,
|
||||
): { id: number; eventId: number; endsAtUtc: string; cancelled: boolean } | null {
|
||||
const row = db
|
||||
.prepare('SELECT id AS id, event_id AS event_id, ends_at_utc AS ends_at_utc, cancelled AS cancelled FROM shifts WHERE id = ?')
|
||||
.get(shiftId) as { id: number; event_id: number; ends_at_utc: string; cancelled: number } | undefined;
|
||||
if (!row) return null;
|
||||
return { id: row.id, eventId: row.event_id, endsAtUtc: row.ends_at_utc, cancelled: row.cancelled === 1 };
|
||||
}
|
||||
|
||||
function cancelOpenShift(
|
||||
db: Database.Database,
|
||||
coordinatorId: number,
|
||||
id: number,
|
||||
now: string,
|
||||
mail: MailIdentity,
|
||||
): CancelResult {
|
||||
const shift = db.prepare('SELECT id AS id, cancelled AS cancelled FROM shifts WHERE id = ?').get(id) as
|
||||
| { id: number; cancelled: number }
|
||||
| undefined;
|
||||
if (!shift) return { ok: false, error: 'That shift is not available.' };
|
||||
if (shift.cancelled === 1) return { ok: true, already: true, mailed: 0 };
|
||||
const marked = db
|
||||
.prepare('UPDATE shifts SET cancelled = 1, version = version + 1, manually_modified = 1 WHERE id = ? AND cancelled = 0')
|
||||
.run(id);
|
||||
if (marked.changes !== 1) return { ok: true, already: true, mailed: 0 };
|
||||
const mailed = cancelConfirmedOnShift(db, id, now, mail);
|
||||
writeAudit(db, coordinatorId, 'shift.cancel', { shiftId: id, mailed }, now);
|
||||
return { ok: true, already: false, mailed };
|
||||
}
|
||||
|
||||
export function cancelSignupAsCoordinator(
|
||||
@@ -1392,9 +1622,13 @@ export function addWalkIn(
|
||||
});
|
||||
}
|
||||
|
||||
function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail: MailIdentity): number {
|
||||
function bumpAndNotify(db: Database.Database, shiftId: number, now: string, mail: MailIdentity, manual = true): number {
|
||||
const bumped = db
|
||||
.prepare('UPDATE shifts SET version = version + 1, manually_modified = 1 WHERE id = ? AND cancelled = 0')
|
||||
.prepare(
|
||||
manual
|
||||
? 'UPDATE shifts SET version = version + 1, manually_modified = 1 WHERE id = ? AND cancelled = 0'
|
||||
: 'UPDATE shifts SET version = version + 1 WHERE id = ? AND cancelled = 0 AND manually_modified = 0',
|
||||
)
|
||||
.run(shiftId);
|
||||
if (bumped.changes !== 1) return 0;
|
||||
db.prepare(
|
||||
@@ -1607,6 +1841,20 @@ function deleteShiftMail(db: Database.Database, shiftId: number): void {
|
||||
db.prepare('DELETE FROM outbox WHERE shift_id = ?').run(shiftId);
|
||||
}
|
||||
|
||||
/** Deletes an ended template shift and the roster on it. Pending mail for that shift is dropped. */
|
||||
function purgeShift(db: Database.Database, shiftId: number): void {
|
||||
deleteShiftMail(db, shiftId);
|
||||
db.prepare(
|
||||
`DELETE FROM reminders_sent
|
||||
WHERE signup_id IN (SELECT id FROM signups WHERE shift_id = ?)
|
||||
OR outbox_id IN (SELECT id FROM outbox WHERE signup_id IN (SELECT id FROM signups WHERE shift_id = ?))`,
|
||||
).run(shiftId, shiftId);
|
||||
db.prepare('DELETE FROM outbox WHERE signup_id IN (SELECT id FROM signups WHERE shift_id = ?)').run(shiftId);
|
||||
db.prepare('DELETE FROM signups WHERE shift_id = ?').run(shiftId);
|
||||
const removed = db.prepare('DELETE FROM shifts WHERE id = ?').run(shiftId);
|
||||
if (removed.changes !== 1) throw new BatchRemovalError('That shift is not available.');
|
||||
}
|
||||
|
||||
function timeZone(tz: string): { ok: true; tz: string } | { ok: false; error: string } {
|
||||
try {
|
||||
return { ok: true, tz: assertValidTimeZone(tz) };
|
||||
|
||||
+13
-3
@@ -33,13 +33,14 @@ type TemplateRow = {
|
||||
export function expandTemplates(
|
||||
db: Database.Database,
|
||||
now: string,
|
||||
options?: { eventId?: number; timeZone?: string; coordinatorId?: number | null },
|
||||
options?: { eventId?: number; templateId?: number; timeZone?: string; coordinatorId?: number | null },
|
||||
): ExpandResult {
|
||||
const coordinatorId = options?.coordinatorId ?? null;
|
||||
const eventId = options?.eventId;
|
||||
const templateId = options?.templateId;
|
||||
const timeZone = options?.timeZone;
|
||||
const run = db.transaction((): ExpandResult => {
|
||||
const templates = listTemplates(db, eventId, timeZone);
|
||||
const templates = listTemplates(db, eventId, timeZone, templateId);
|
||||
let created = 0;
|
||||
const skipped: string[] = [];
|
||||
for (const template of templates) {
|
||||
@@ -52,13 +53,22 @@ export function expandTemplates(
|
||||
return run.immediate();
|
||||
}
|
||||
|
||||
function listTemplates(db: Database.Database, eventId: number | undefined, timeZone: string | undefined): TemplateRow[] {
|
||||
function listTemplates(
|
||||
db: Database.Database,
|
||||
eventId: number | undefined,
|
||||
timeZone: string | undefined,
|
||||
templateId: number | undefined,
|
||||
): TemplateRow[] {
|
||||
const filters = ['t.active = 1'];
|
||||
const params: Array<number | string> = [];
|
||||
if (eventId !== undefined) {
|
||||
filters.push('t.event_id = ?');
|
||||
params.push(eventId);
|
||||
}
|
||||
if (templateId !== undefined) {
|
||||
filters.push('t.id = ?');
|
||||
params.push(templateId);
|
||||
}
|
||||
if (timeZone !== undefined) {
|
||||
filters.push('e.tz = ?');
|
||||
params.push(timeZone);
|
||||
|
||||
+72
-11
@@ -380,12 +380,16 @@ describe('coordinator screens', () => {
|
||||
|
||||
const closed = await postForm(app, `/admin/shifts/${shiftId}/cancel`, cookie, {});
|
||||
expect(closed.status).toBe(303);
|
||||
expect(closed.headers.get('location')).toBe(`/admin/events/${eventId}?notice=shift-cancelled`);
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(shiftId)).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare("SELECT status AS status FROM signups WHERE email_norm = 'sam@example.invalid'").get()).toEqual({ status: 'cancelled' });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM signups')).toBe(2);
|
||||
expect(await (await app.request('/')).text()).not.toContain('Ladle');
|
||||
const eventPage = await (await app.request(closed.headers.get('location') ?? '', { headers: { cookie } })).text();
|
||||
expect(eventPage).toContain('The shift is cancelled and off this list. Cancellation emails are queued.');
|
||||
expect(eventPage).not.toContain('Ladle');
|
||||
const closedAdmin = await (await app.request(`/admin/shifts/${shiftId}`, { headers: { cookie } })).text();
|
||||
expect(closedAdmin).toContain('Cancelled. The roster stays until you remove it.');
|
||||
expect(closedAdmin).toContain('Cancelled. It is off the upcoming list.');
|
||||
expect(closedAdmin).not.toContain('Edit details');
|
||||
expect(closedAdmin).toContain('Remove this shift');
|
||||
const closedPage = await (await app.request(`/s/${shiftId}`)).text();
|
||||
@@ -665,7 +669,7 @@ describe('coordinator screens', () => {
|
||||
expect(db.prepare('SELECT status, shift_id FROM signups WHERE id = ?').get(signupId)).toEqual({ status: 'cancelled', shift_id: sourceId });
|
||||
});
|
||||
|
||||
it('keeps the next two weeks of shifts in view and tucks later ones under see more', async () => {
|
||||
it('shows the next two weeks as day cards and tucks the rest under see more', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
@@ -678,20 +682,22 @@ describe('coordinator screens', () => {
|
||||
expect((await postForm(app, `/admin/shifts/${eveningId}/cancel`, cookie, {})).status).toBe(303);
|
||||
|
||||
const html = await (await app.request(`/admin/events/${eventId}`, { headers: { cookie } })).text();
|
||||
const moreAt = html.indexOf('Show 2 more shifts');
|
||||
const moreAt = html.indexOf('See more');
|
||||
expect(moreAt).toBeGreaterThan(0);
|
||||
const before = html.slice(0, moreAt);
|
||||
const after = html.slice(moreAt);
|
||||
expect(before).toContain('Morning');
|
||||
expect(before).toContain('need-day');
|
||||
expect(before).toContain('Sorting');
|
||||
expect(before).toContain('Distribution');
|
||||
expect(before).not.toContain('Morning');
|
||||
expect(before).not.toContain('Intake');
|
||||
expect(before).not.toContain('Packing');
|
||||
expect(before).not.toContain('Evening');
|
||||
expect(after.indexOf('Intake')).toBeGreaterThan(-1);
|
||||
expect(after.indexOf('Morning')).toBeGreaterThan(-1);
|
||||
expect(after.indexOf('Intake')).toBeGreaterThan(after.indexOf('Morning'));
|
||||
expect(after.indexOf('Packing')).toBeGreaterThan(after.indexOf('Intake'));
|
||||
expect(after.indexOf('Evening')).toBeGreaterThan(after.indexOf('Packing'));
|
||||
expect(after).toContain('Show fewer');
|
||||
expect(html).not.toContain('Evening');
|
||||
expect(after).toContain('See less');
|
||||
expect(html).not.toContain('<details class="shift-more" open');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(6);
|
||||
|
||||
@@ -699,17 +705,72 @@ describe('coordinator screens', () => {
|
||||
await addShift(app, cookie, soon, { role: 'Ladle', date: '2026-10-16', capacity: '2' });
|
||||
const short = await (await app.request(`/admin/events/${soon}`, { headers: { cookie } })).text();
|
||||
expect(short).toContain('Ladle');
|
||||
expect(short).not.toContain('Show 1 more shift');
|
||||
expect(short).toContain('need-day');
|
||||
expect(short).not.toContain('See more');
|
||||
expect(short).not.toContain('shift-more');
|
||||
|
||||
const distant = await createEvent(app, cookie, 'Holiday', true);
|
||||
await addShift(app, cookie, distant, { role: 'Early', date: '2026-11-04', capacity: '2' });
|
||||
await addShift(app, cookie, distant, { role: 'Later', date: '2026-11-18', capacity: '2' });
|
||||
const far = await (await app.request(`/admin/events/${distant}`, { headers: { cookie } })).text();
|
||||
const farMore = far.indexOf('Show 1 more shift');
|
||||
const farMore = far.indexOf('See more');
|
||||
expect(farMore).toBeGreaterThan(0);
|
||||
expect(far.slice(0, farMore)).toContain('Early');
|
||||
expect(far.slice(farMore)).toContain('Later');
|
||||
expect(far.slice(0, farMore)).toContain('No shifts in the next 2 weeks.');
|
||||
expect(far.slice(0, farMore)).not.toContain('Early');
|
||||
expect(far.slice(farMore).indexOf('Later')).toBeGreaterThan(far.slice(farMore).indexOf('Early'));
|
||||
});
|
||||
|
||||
it('cancels the open shifts that are selected and refuses one that has ended', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const cookie = await signIn(app, db);
|
||||
const eventId = await createEvent(app, cookie, 'Pantry', true);
|
||||
const endedId = await addShift(app, cookie, eventId, { role: 'Morning', date: '2026-10-14', capacity: '2' });
|
||||
const first = await addShift(app, cookie, eventId, { role: 'Sorting', date: '2026-10-21', capacity: '2' });
|
||||
const second = await addShift(app, cookie, eventId, { role: 'Packing', date: '2026-10-22', capacity: '2' });
|
||||
reserve(db, first, 'Bea Example', 'bea@example.invalid', 'bea-operation');
|
||||
const page = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('Cancel selected');
|
||||
expect(html).toContain('>Templates<');
|
||||
expect(html).toContain('Add a template');
|
||||
expect(html).toContain('data-confirm-gate="open"');
|
||||
const token = field(html, 'csrf');
|
||||
|
||||
const refused = await app.request(`/admin/events/${eventId}/shifts/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams([
|
||||
['csrf', token],
|
||||
['shift[]', String(endedId)],
|
||||
['shift[]', String(first)],
|
||||
]),
|
||||
});
|
||||
expect(refused.status).toBe(400);
|
||||
expect(await refused.text()).toContain('That shift has ended.');
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(first)).toEqual({ cancelled: 0 });
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(endedId)).toEqual({ cancelled: 0 });
|
||||
|
||||
const cancelled = await app.request(`/admin/events/${eventId}/shifts/cancel`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams([
|
||||
['csrf', token],
|
||||
['shift[]', String(first)],
|
||||
['shift[]', String(second)],
|
||||
]),
|
||||
});
|
||||
expect(cancelled.status).toBe(303);
|
||||
expect(cancelled.headers.get('location')).toBe(`/admin/events/${eventId}?notice=shifts-cancelled`);
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(first)).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(second)).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare("SELECT status AS status FROM signups WHERE email_norm = 'bea@example.invalid'").get()).toEqual({ status: 'cancelled' });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled' AND to_email = 'bea@example.invalid' AND status = 'pending'")).toBe(1);
|
||||
const after = await (await app.request(`/admin/events/${eventId}?notice=shifts-cancelled`, { headers: { cookie } })).text();
|
||||
expect(after).toContain('Those shifts are cancelled and off this list. Cancellation emails are queued.');
|
||||
expect(after).toContain('Morning');
|
||||
expect(after).not.toContain('Sorting');
|
||||
expect(after).not.toContain('Packing');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(3);
|
||||
});
|
||||
|
||||
it('treats an expired session as signed out', async () => {
|
||||
|
||||
+13
-41
@@ -131,34 +131,25 @@ describe('weekly template expansion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('add weekly shifts', () => {
|
||||
it('adds from the event page once and refuses a form that is out of date', async () => {
|
||||
describe('weekly schedule', () => {
|
||||
it('does not offer a separate button to fill shifts', async () => {
|
||||
const { app, db } = await buildApp();
|
||||
const eventId = insertEvent(db, 'weekly-pantry', ZONE);
|
||||
insertTemplate(db, eventId, { weekday: 3, startsOn: '2026-10-14' });
|
||||
const empty = insertEvent(db, 'plain', ZONE);
|
||||
const cookie = await signIn(app, db);
|
||||
|
||||
const missing = await postGenerate(app, eventId, cookie, { csrf: 'wrong' });
|
||||
expect(missing.status).toBe(403);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(0);
|
||||
|
||||
const added = await postGenerate(app, eventId, cookie);
|
||||
expect(added.status).toBe(303);
|
||||
expect(added.headers.get('location')).toBe(`/admin/events/${eventId}?notice=generated`);
|
||||
const page = await app.request(added.headers.get('location') ?? '', { headers: { cookie } });
|
||||
const page = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('Weekly shifts for the next three months are on the schedule.');
|
||||
expect(html).toContain('Add weekly shifts');
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(14);
|
||||
expect(html).toContain('Add a template');
|
||||
expect(html).toContain('Each one keeps three months of shifts filled.');
|
||||
expect(html).not.toContain('Fill missing shifts');
|
||||
expect(html).not.toContain('/generate');
|
||||
|
||||
const repeat = await postGenerate(app, eventId, cookie);
|
||||
expect(repeat.headers.get('location')).toBe(`/admin/events/${eventId}?notice=generated`);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts')).toBe(14);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'template.expand'")).toBe(1);
|
||||
|
||||
const none = await postGenerate(app, empty, cookie);
|
||||
expect(none.headers.get('location')).toBe(`/admin/events/${empty}?notice=no-template`);
|
||||
const generate = await app.request(`/admin/events/${eventId}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf: 'irrelevant' }),
|
||||
});
|
||||
expect(generate.status).toBe(404);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -248,22 +239,3 @@ async function signIn(app: Awaited<ReturnType<typeof buildApp>>['app'], db: Awai
|
||||
const cookie = /hope_session=([^;]+)/.exec(signedIn.headers.get('set-cookie') ?? '')?.[1] ?? '';
|
||||
return `hope_session=${cookie}`;
|
||||
}
|
||||
|
||||
async function postGenerate(
|
||||
app: Awaited<ReturnType<typeof buildApp>>['app'],
|
||||
eventId: number,
|
||||
cookie: string,
|
||||
options?: { csrf?: string },
|
||||
) {
|
||||
const current = await app.request(`/admin/events/${eventId}`, { headers: { cookie } });
|
||||
const csrf = options?.csrf ?? (/name="csrf"[^>]*value="([^"]*)"/.exec(await current.text())?.[1] ?? '');
|
||||
return app.request(`/admin/events/${eventId}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf }),
|
||||
});
|
||||
}
|
||||
|
||||
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string): number {
|
||||
return Number((db.prepare(sql).get() as { n: number }).n);
|
||||
}
|
||||
+155
-28
@@ -3,6 +3,7 @@ import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import { createTemplate, endTemplate, updateTemplate } from '../src/admin/store.js';
|
||||
import type { MailIdentity } from '../src/mail/types.js';
|
||||
import { createApp } from '../src/app.js';
|
||||
import { bootstrapAdmin } from '../src/auth/bootstrap.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
@@ -12,6 +13,12 @@ import { devEnv } from './env.js';
|
||||
|
||||
const NOW = '2026-10-14T18:00:00.000Z';
|
||||
const ORIGIN = 'http://127.0.0.1:3000';
|
||||
const MAIL: MailIdentity = {
|
||||
baseUrl: ORIGIN,
|
||||
basePath: '',
|
||||
from: 'Hope Food Pantry <volunteer@example.invalid>',
|
||||
replyTo: 'volunteer@example.invalid',
|
||||
};
|
||||
const ZONE = 'America/Chicago';
|
||||
const dirs: string[] = [];
|
||||
const databases: { close: () => void }[] = [];
|
||||
@@ -22,19 +29,27 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe('weekly template editing', () => {
|
||||
it('keeps generated shifts when a template changes or ends', async () => {
|
||||
it('updates shifts that have not ended when a template changes, and clears them when it ends', async () => {
|
||||
const db = await openDb();
|
||||
const eventId = insertEvent(db);
|
||||
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
|
||||
const before = shiftRows(db);
|
||||
expect(shiftRows(db)).toHaveLength(14);
|
||||
|
||||
const updated = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Intake', capacity: 9 }), NOW);
|
||||
expect(updated.ok).toBe(true);
|
||||
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
|
||||
expect(shiftRows(db)).toEqual(before);
|
||||
const updated = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Intake', capacity: 9 }), NOW, MAIL);
|
||||
expect(updated).toMatchObject({ ok: true, mailed: 0 });
|
||||
const changed = shiftRows(db);
|
||||
expect(changed.find((row) => row.occurrence_date === '2026-10-14')).toEqual({
|
||||
occurrence_date: '2026-10-14',
|
||||
role: 'Sorting',
|
||||
capacity: 6,
|
||||
template_revision: 1,
|
||||
cancelled: 0,
|
||||
});
|
||||
const upcoming = changed.filter((row) => row.occurrence_date !== '2026-10-14');
|
||||
expect(upcoming).toHaveLength(13);
|
||||
expect(upcoming.every((row) => row.role === 'Intake' && row.capacity === 9 && row.template_revision === 2 && row.cancelled === 0)).toBe(true);
|
||||
const template = db.prepare('SELECT role, capacity, revision, active FROM shift_templates WHERE id = ?').get(created.id) as {
|
||||
role: string;
|
||||
capacity: number;
|
||||
@@ -45,12 +60,118 @@ describe('weekly template editing', () => {
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM audit WHERE action = 'template.update'")).toBe(1);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(0);
|
||||
|
||||
const ended = endTemplate(db, 1, eventId, created.id, NOW);
|
||||
const ended = endTemplate(db, 1, eventId, created.id, NOW, MAIL);
|
||||
expect(ended.ok).toBe(true);
|
||||
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
|
||||
expect(shiftRows(db)).toEqual(before);
|
||||
const after = shiftRows(db);
|
||||
expect(after).toEqual(changed.filter((row) => row.occurrence_date !== '2026-10-14').map((row) => ({ ...row, cancelled: 1 })));
|
||||
expect(after.some((row) => row.occurrence_date === '2026-10-14')).toBe(false);
|
||||
expect((db.prepare('SELECT active FROM shift_templates WHERE id = ?').get(created.id) as { active: number }).active).toBe(0);
|
||||
expect(updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Sorting' }), NOW).ok).toBe(false);
|
||||
expect(updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Sorting' }), NOW, MAIL).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves a shift that was edited on its own, and a cancelled date, alone', async () => {
|
||||
const db = await openDb();
|
||||
const eventId = insertEvent(db);
|
||||
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
db.prepare(`UPDATE shifts SET role = 'Custom', manually_modified = 1 WHERE occurrence_date = '2026-10-21'`).run();
|
||||
db.prepare(`UPDATE shifts SET cancelled = 1 WHERE occurrence_date = '2026-10-28'`).run();
|
||||
insertSignup(db, shiftId(db, '2026-10-21'), 'Ada Example', 'ada@example.invalid');
|
||||
|
||||
const updated = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Intake' }), NOW, MAIL);
|
||||
expect(updated).toMatchObject({ ok: true, mailed: 0 });
|
||||
expect(db.prepare(`SELECT role, manually_modified, cancelled FROM shifts WHERE occurrence_date = '2026-10-21'`).get()).toEqual({
|
||||
role: 'Custom',
|
||||
manually_modified: 1,
|
||||
cancelled: 0,
|
||||
});
|
||||
expect(db.prepare(`SELECT role, cancelled FROM shifts WHERE occurrence_date = '2026-10-28'`).get()).toEqual({
|
||||
role: 'Sorting',
|
||||
cancelled: 1,
|
||||
});
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM shifts WHERE occurrence_date = '2026-10-28'`)).toBe(1);
|
||||
expect(db.prepare(`SELECT role FROM shifts WHERE occurrence_date = '2026-11-04'`).get()).toEqual({ role: 'Intake' });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'ada@example.invalid'")).toBe(0);
|
||||
});
|
||||
|
||||
it('emails a changed shift, cancels a date that no longer fits, and refuses a capacity below the roster', async () => {
|
||||
const db = await openDb();
|
||||
const eventId = insertEvent(db);
|
||||
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
insertSignup(db, shiftId(db, '2026-10-21'), 'Bea Example', 'bea@example.invalid');
|
||||
insertSignup(db, shiftId(db, '2026-11-04'), 'Cy Example', 'cy@example.invalid');
|
||||
insertSignup(db, shiftId(db, '2026-11-04'), 'Dee Example', 'dee@example.invalid');
|
||||
|
||||
const tooSmall = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, capacity: 1 }), NOW, MAIL);
|
||||
expect(tooSmall).toEqual({ ok: false, error: 'Capacity cannot be lower than the number of people signed up.' });
|
||||
expect((db.prepare('SELECT capacity, revision FROM shift_templates WHERE id = ?').get(created.id) as { capacity: number; revision: number })).toEqual({
|
||||
capacity: 6,
|
||||
revision: 1,
|
||||
});
|
||||
|
||||
const timed = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, start: '10:00', end: '13:00' }), NOW, MAIL);
|
||||
expect(timed).toMatchObject({ ok: true, mailed: 3 });
|
||||
expect(db.prepare(`SELECT starts_at_utc, ends_at_utc, role FROM shifts WHERE occurrence_date = '2026-10-21'`).get()).toEqual({
|
||||
starts_at_utc: '2026-10-21T15:00:00.000Z',
|
||||
ends_at_utc: '2026-10-21T18:00:00.000Z',
|
||||
role: 'Sorting',
|
||||
});
|
||||
expect(db.prepare(`SELECT starts_at_utc FROM shifts WHERE occurrence_date = '2026-10-14'`).get()).toEqual({
|
||||
starts_at_utc: '2026-10-14T14:00:00.000Z',
|
||||
});
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'changed' AND status = 'pending'")).toBe(3);
|
||||
|
||||
const moved = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 5, start: '10:00', end: '13:00' }), NOW, MAIL);
|
||||
expect(moved).toMatchObject({ ok: true, mailed: 3 });
|
||||
expect(db.prepare(`SELECT cancelled FROM shifts WHERE occurrence_date = '2026-10-21'`).get()).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare(`SELECT cancelled FROM shifts WHERE occurrence_date = '2026-11-04'`).get()).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare(`SELECT cancelled, role FROM shifts WHERE occurrence_date = '2026-10-14'`).get()).toEqual({ cancelled: 0, role: 'Sorting' });
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM shifts WHERE occurrence_date >= '2026-10-16' AND cancelled = 0`)).toBe(13);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled' AND status = 'pending'")).toBe(3);
|
||||
});
|
||||
|
||||
it('puts a removed date back when the template is saved again', async () => {
|
||||
const db = await openDb();
|
||||
const eventId = insertEvent(db);
|
||||
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
db.prepare(`DELETE FROM shifts WHERE occurrence_date = '2026-10-21'`).run();
|
||||
const again = updateTemplate(db, 1, eventId, created.id, templateInput({ weekday: 3, role: 'Sorting' }), NOW, MAIL);
|
||||
expect(again).toMatchObject({ ok: true, mailed: 0 });
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM shifts WHERE occurrence_date = '2026-10-21' AND role = 'Sorting'`)).toBe(1);
|
||||
expect((db.prepare('SELECT revision FROM shift_templates WHERE id = ?').get(created.id) as { revision: number }).revision).toBe(1);
|
||||
});
|
||||
|
||||
it('cancels upcoming template shifts and deletes shifts that already ended', async () => {
|
||||
const db = await openDb();
|
||||
const eventId = insertEvent(db);
|
||||
const created = createTemplate(db, 1, eventId, templateInput({ weekday: 3, role: 'Sorting' }), NOW);
|
||||
expect(created.ok).toBe(true);
|
||||
if (!created.ok) return;
|
||||
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
|
||||
const past = db.prepare(`SELECT id AS id FROM shifts WHERE occurrence_date = '2026-10-14'`).get() as { id: number };
|
||||
const future = db.prepare(`SELECT id AS id FROM shifts WHERE occurrence_date = '2026-10-21'`).get() as { id: number };
|
||||
insertSignup(db, past.id, 'Ada Example', 'ada@example.invalid');
|
||||
insertSignup(db, future.id, 'Bea Example', 'bea@example.invalid');
|
||||
|
||||
const ended = endTemplate(db, 1, eventId, created.id, NOW, MAIL);
|
||||
expect(ended).toMatchObject({ ok: true, already: false, mailed: 1 });
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM shifts WHERE id = ?', past.id)).toBe(0);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM signups WHERE email_norm = 'ada@example.invalid'")).toBe(0);
|
||||
expect(db.prepare('SELECT cancelled AS cancelled FROM shifts WHERE id = ?').get(future.id)).toEqual({ cancelled: 1 });
|
||||
expect(db.prepare("SELECT status AS status FROM signups WHERE email_norm = 'bea@example.invalid'").get()).toEqual({ status: 'cancelled' });
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE kind = 'cancelled' AND to_email = 'bea@example.invalid' AND status = 'pending'")).toBe(1);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM outbox WHERE to_email = 'ada@example.invalid'")).toBe(0);
|
||||
expandTemplates(db, NOW, { eventId, coordinatorId: 1 });
|
||||
expect(count(db, `SELECT COUNT(*) AS n FROM shifts WHERE occurrence_date = '2026-10-14'`)).toBe(0);
|
||||
expect(db.prepare('PRAGMA foreign_key_check').all()).toEqual([]);
|
||||
const audit = db.prepare(`SELECT detail_json AS detail_json FROM audit WHERE action = 'template.end'`).get() as { detail_json: string };
|
||||
expect(audit.detail_json).not.toContain('@');
|
||||
});
|
||||
|
||||
it('rejects an overnight template and an end date before the first date', async () => {
|
||||
@@ -74,17 +195,13 @@ describe('weekly template editing', () => {
|
||||
const saved = await postTemplate(app, eventId, cookie, { weekday: '3', role: 'Sorting' });
|
||||
expect(saved.status).toBe(303);
|
||||
expect(saved.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-saved`);
|
||||
const generated = await postGenerate(app, eventId, cookie);
|
||||
expect(generated.status).toBe(303);
|
||||
const wednesdays = count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Sorting'");
|
||||
expect(wednesdays).toBe(14);
|
||||
|
||||
const friday = await postTemplate(app, eventId, cookie, { weekday: '5', role: 'Intake', capacity: '4' });
|
||||
expect(friday.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-saved`);
|
||||
await postGenerate(app, eventId, cookie);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Sorting'")).toBe(wednesdays);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake' AND capacity = 4")).toBe(13);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE template_revision = 1")).toBe(wednesdays + 13);
|
||||
|
||||
const templateId = (
|
||||
db.prepare("SELECT id AS id FROM shift_templates WHERE role = 'Intake'").get() as { id: number }
|
||||
@@ -95,14 +212,21 @@ describe('weekly template editing', () => {
|
||||
revision: 2,
|
||||
role: 'Packing',
|
||||
});
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake'")).toBe(13);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake'")).toBe(0);
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Packing' AND template_revision = 2")).toBe(13);
|
||||
|
||||
const ended = await postEnd(app, eventId, templateId, cookie);
|
||||
expect(ended.headers.get('location')).toBe(`/admin/events/${eventId}?notice=template-ended`);
|
||||
const page = await app.request(`/admin/events/${eventId}?notice=template-ended`, { headers: { cookie } });
|
||||
const html = await page.text();
|
||||
expect(html).toContain('This weekly template has ended. Shifts already on the schedule stay.');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Intake'")).toBe(13);
|
||||
expect(html).toContain('This template has ended. The shifts it added are off this list.');
|
||||
expect(html).toContain('Templates');
|
||||
expect(html).toContain('Add a template');
|
||||
expect(html).toContain('Each one keeps three months of shifts filled.');
|
||||
expect(html).not.toContain('Repeating shifts');
|
||||
expect(html).not.toContain('Fill missing shifts');
|
||||
expect(html).not.toContain('Intake');
|
||||
expect(count(db, "SELECT COUNT(*) AS n FROM shifts WHERE role = 'Packing' AND cancelled = 1")).toBe(13);
|
||||
expect(count(db, 'SELECT COUNT(*) AS n FROM outbox')).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -211,15 +335,6 @@ async function postTemplate(
|
||||
});
|
||||
}
|
||||
|
||||
async function postGenerate(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId: number, cookie: string) {
|
||||
const csrf = await csrfFor(app, eventId, cookie);
|
||||
return app.request(`/admin/events/${eventId}/generate`, {
|
||||
method: 'POST',
|
||||
headers: { origin: ORIGIN, 'content-type': 'application/x-www-form-urlencoded', cookie },
|
||||
body: new URLSearchParams({ csrf }),
|
||||
});
|
||||
}
|
||||
|
||||
async function postEnd(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId: number, templateId: number, cookie: string) {
|
||||
const csrf = await csrfFor(app, eventId, cookie);
|
||||
return app.request(`/admin/events/${eventId}/templates/${templateId}/end`, {
|
||||
@@ -229,6 +344,18 @@ async function postEnd(app: Awaited<ReturnType<typeof buildApp>>['app'], eventId
|
||||
});
|
||||
}
|
||||
|
||||
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string): number {
|
||||
return Number((db.prepare(sql).get() as { n: number }).n);
|
||||
function count(db: Awaited<ReturnType<typeof openDb>>, sql: string, ...params: Array<number | string>): number {
|
||||
return Number((db.prepare(sql).get(...params) as { n: number }).n);
|
||||
}
|
||||
|
||||
function shiftId(db: Awaited<ReturnType<typeof openDb>>, date: string): number {
|
||||
return (db.prepare('SELECT id AS id FROM shifts WHERE occurrence_date = ?').get(date) as { id: number }).id;
|
||||
}
|
||||
|
||||
function insertSignup(db: Awaited<ReturnType<typeof openDb>>, shiftId: number, name: string, email: string): void {
|
||||
db.prepare(
|
||||
`INSERT INTO signups (
|
||||
shift_id, name, email, email_norm, is_minor, group_size, status, reminders_off, created_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, 0, 1, 'confirmed', 0, ?, ?)`,
|
||||
).run(shiftId, name, email, email, NOW, NOW);
|
||||
}
|
||||
Reference in new issue
Block a user