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:
blake committed 2026-10-29 18:02:08 -05:00
1 parent e363cdaef9
commit 1b78a06f72
10 files changed
+956 -352

No files matched your search

+93 -52
View File
@@ -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
View File
@@ -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
View File
@@ -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
View File
@@ -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);