@mccaskie-labs/workbench-roster 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,168 @@
1
+ import { type Words } from "./format.ts";
2
+ import { type Clash, type CoverNeed, type Gap, type Lang, type Leave, type ResourceTimes, type RosterConfig, type Shift, type Staff, type TickResult, type WeekState, type WeekView } from "./types.ts";
3
+ type DbError = {
4
+ message?: string;
5
+ code?: string;
6
+ details?: string;
7
+ } | null;
8
+ /** The part of a Supabase client the roster needs. Any supabase-js client fits; use the service client. */
9
+ export interface RosterClient {
10
+ rpc(fn: string, args: Record<string, unknown>): PromiseLike<{
11
+ data: unknown;
12
+ error: DbError;
13
+ }>;
14
+ }
15
+ /** The part of workbench-email's createMailer(...) the roster uses. */
16
+ export interface RosterMailer {
17
+ send(mail: {
18
+ to: string | string[];
19
+ subject: string;
20
+ text: string;
21
+ template: string;
22
+ replyTo?: string;
23
+ attachments?: {
24
+ filename: string;
25
+ mimeType: string;
26
+ bytes: Uint8Array;
27
+ }[];
28
+ idempotencyKey?: string;
29
+ }): Promise<unknown>;
30
+ }
31
+ export interface RosterOptions {
32
+ /** The service client. */
33
+ db: RosterClient;
34
+ /** workbench/roster.json, or ROSTER_CONFIG from src/roster.generated.ts. Checked here. */
35
+ config: unknown;
36
+ /** createMailer(...). Without it no email goes; the pages still work. */
37
+ mailer?: RosterMailer;
38
+ /** The business's name for emails and calendars. Default: the account. */
39
+ business?: (account: string) => Promise<{
40
+ name: string;
41
+ replyTo?: string;
42
+ }>;
43
+ /** A person's own page and calendar feed, from their secret. Needed for the links in emails. */
44
+ links?: {
45
+ mine?: (token: string) => string;
46
+ feed?: (token: string) => string;
47
+ };
48
+ /** The emails' language. Default en. */
49
+ lang?: Lang;
50
+ /** The project's strings lookup, for the emails' words. */
51
+ t?: Words;
52
+ /** For dates and times in emails. Default en-AU (fil-PH for Tagalog and Taglish). */
53
+ locale?: string;
54
+ /** An email that failed: the roster stands and the week is tried again on the next tick. Default: console.error with no address in it. */
55
+ onEmailError?: (error: unknown, what: string) => void;
56
+ /** How many weeks one tick sends at most. Default 50. */
57
+ batch?: number;
58
+ /** The clock, for tests. */
59
+ now?: () => Date;
60
+ }
61
+ export interface StaffInput {
62
+ /** Left out: a new person. */
63
+ id?: string;
64
+ name: string;
65
+ email: string;
66
+ /** Roles from roster.json they can work. */
67
+ roles?: readonly string[];
68
+ /** Their name in workbench/bookings.json's resources, when customers book them. */
69
+ resource?: string | null;
70
+ /** The app's signed-in user id for them. */
71
+ member?: string | null;
72
+ }
73
+ export interface ShiftInput {
74
+ staff: string;
75
+ start: string | Date;
76
+ end: string | Date;
77
+ role?: string | null;
78
+ /** Unpaid break minutes, 0 to 240. Default 0. */
79
+ break_minutes?: number;
80
+ note?: string | null;
81
+ }
82
+ export interface Roster {
83
+ /** The account's people, by name; all: include those taken off. */
84
+ staff(account: string, opts?: {
85
+ all?: boolean;
86
+ }): Promise<Staff[]>;
87
+ /** Adds a person, or changes one (with id). Refused with `taken` when someone on the roster has that email or resource. */
88
+ saveStaff(account: string, input: StaffInput): Promise<Staff>;
89
+ /** Takes a person off: their link stops, their shifts from now on go (and those weeks' changes are sent), their past shifts stay for the export. */
90
+ removeStaff(account: string, id: string): Promise<boolean>;
91
+ /** Makes a person a new link secret (the old one stops) and emails them their page and calendar feed. */
92
+ sendLink(account: string, id: string): Promise<{
93
+ token: string;
94
+ emailed: number;
95
+ }>;
96
+ /** Everything the owner's page shows for a week (any day in it). */
97
+ week(account: string, week: string): Promise<WeekView>;
98
+ addShift(account: string, input: ShiftInput): Promise<Shift>;
99
+ updateShift(account: string, id: string, input: ShiftInput): Promise<Shift>;
100
+ removeShift(account: string, id: string): Promise<boolean>;
101
+ /** Copies one week's shifts into an empty week, on the same days and local times. People away or gone are skipped. */
102
+ copyWeek(account: string, from: string, to: string): Promise<{
103
+ copied: number;
104
+ skipped: number;
105
+ }>;
106
+ /** Publishes a week and emails everyone whose shifts in it they haven't been sent yet. Again later: Send changes. */
107
+ publish(account: string, week: string): Promise<{
108
+ week: WeekState;
109
+ emailed: number;
110
+ }>;
111
+ /** Times the cover rules (and the app's own needs, such as sessions) aren't met, and shifts their person can't work. */
112
+ gaps(account: string, week: string, opts?: {
113
+ needs?: readonly CoverNeed[];
114
+ closed?: readonly string[];
115
+ }): Promise<{
116
+ gaps: Gap[];
117
+ clashes: Clash[];
118
+ }>;
119
+ /** Adds days away (first and last day, YYYY-MM-DD, on the business's clock); answers the shifts it clashes with. */
120
+ addLeave(account: string, input: {
121
+ staff: string;
122
+ from: string;
123
+ to: string;
124
+ }): Promise<{
125
+ leave: Leave;
126
+ clashes: Shift[];
127
+ }>;
128
+ removeLeave(account: string, id: string): Promise<boolean>;
129
+ /** Leave overlapping a range (default from today for a year). */
130
+ leave(account: string, opts?: {
131
+ from?: string;
132
+ to?: string;
133
+ staff?: string;
134
+ }): Promise<Leave[]>;
135
+ /** For workbench-bookings' settings option: each bookable person's published shifts and leave, by their resource name. */
136
+ hoursFor(account: string, range?: {
137
+ from?: string | Date;
138
+ to?: string | Date;
139
+ }): Promise<Record<string, ResourceTimes>>;
140
+ /** A person's own page, from their secret: their upcoming published shifts and leave. Null for a wrong or replaced secret. */
141
+ mine(token: string): Promise<{
142
+ staff: Staff;
143
+ shifts: Shift[];
144
+ leave: Leave[];
145
+ } | null>;
146
+ /** A person's calendar feed (text/calendar), or null. */
147
+ feed(token: string): Promise<string | null>;
148
+ /** Published shifts from the first day to the last (YYYY-MM-DD), as a CSV for the owner's payroll. */
149
+ exportHours(account: string, range: {
150
+ from: string;
151
+ to: string;
152
+ lang?: Lang;
153
+ }): Promise<string>;
154
+ /** From the app's cron (every 15 minutes is plenty): emails changes to published weeks once the owner has stopped editing. */
155
+ tick(): Promise<TickResult>;
156
+ /** Once a day: deletes what is past retention_months. */
157
+ cleanup(): Promise<{
158
+ shifts: number;
159
+ leave: number;
160
+ weeks: number;
161
+ staff: number;
162
+ }>;
163
+ /** The business's local time for a day and clock ("09:00"), for building a shift from the page's fields. */
164
+ at(day: string, clock: string): Date;
165
+ readonly config: RosterConfig;
166
+ }
167
+ export declare function createRoster(opts: RosterOptions): Roster;
168
+ export {};
package/dist/roster.js ADDED
@@ -0,0 +1,433 @@
1
+ // createRoster: staff, shifts and leave in the app's own database
2
+ // (docs/capabilities/21-roster.md). The owner builds a week on the app's
3
+ // page, publishes it, and each person gets an email with their shifts and a
4
+ // calendar file, plus their own page and calendar feed; later changes to a
5
+ // published week are emailed to the people they touch. A gaps check compares
6
+ // the week with who must be on. hoursFor() is what the app passes to
7
+ // workbench-bookings' settings option, so nobody is booked outside a shift,
8
+ // and exportHours() is a spreadsheet for the owner's own payroll: the roster
9
+ // holds no pay.
10
+ //
11
+ // No AI. Email goes through workbench-email (the Gateway). Use it with the
12
+ // service client, server side: the functions are the service role's only
13
+ // (see migration.ts).
14
+ import { checkRosterConfig } from "./config.js";
15
+ import { hoursCsv } from "./csv.js";
16
+ import { RosterError } from "./errors.js";
17
+ import { dateText, localeFor, spanText, words } from "./format.js";
18
+ import { clashes, findGaps } from "./gaps.js";
19
+ import { cancelIcs, feedIcs, shiftsIcs } from "./ical.js";
20
+ import { addDays, clockIn, durationMinutes, localInstant, todayIn, validDate, weekOf } from "./time.js";
21
+ import { WEEKDAYS } from "./types.js";
22
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
23
+ const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
24
+ const NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
25
+ const DAY = 86_400_000;
26
+ const CODES = { WBR01: "clash", WBR02: "on_leave", WBR03: "unknown_staff", WBR04: "not_empty", "23505": "taken" };
27
+ const hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
28
+ const sha256 = async (s) => hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)));
29
+ /** A new secret: 32 random bytes, base64url (43 characters). */
30
+ function newToken() {
31
+ const b = crypto.getRandomValues(new Uint8Array(32));
32
+ return btoa(String.fromCharCode(...b)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
33
+ }
34
+ async function call(db, what, fn, args) {
35
+ const { data, error } = await db.rpc(fn, args);
36
+ if (error) {
37
+ const code = error.code ? CODES[error.code] : undefined;
38
+ if (code)
39
+ throw new RosterError(code, `${what}: ${code === "taken" ? "someone on the roster already has that email or bookings name" : (error.message ?? code).replace(/^roster: /, "")}`);
40
+ if (error.code === "23514" || error.code === "22023" || error.code === "22007" || error.code === "22P02")
41
+ throw new RosterError("bad_input", `${what}: ${error.message || "refused"}`);
42
+ throw new RosterError("store_failed", `${what}: ${error.message || "no answer"}${error.code ? ` (${error.code})` : ""}`);
43
+ }
44
+ return data;
45
+ }
46
+ function text(v, what, max) {
47
+ if (typeof v !== "string" || !v.trim() || v.trim().length > max)
48
+ throw new RosterError("bad_input", `${what} must be text, 1 to ${max} characters`);
49
+ return v.trim();
50
+ }
51
+ function optional(v, what, max) {
52
+ if (v === undefined || v === null || (typeof v === "string" && !v.trim()))
53
+ return null;
54
+ return text(v, what, max);
55
+ }
56
+ function idOf(v, what) {
57
+ if (typeof v !== "string" || !UUID.test(v))
58
+ throw new RosterError("bad_input", `${what} must be an id`);
59
+ return v.toLowerCase();
60
+ }
61
+ function instant(v, what) {
62
+ const d = v instanceof Date ? v : typeof v === "string" ? new Date(v) : new Date(NaN);
63
+ if (Number.isNaN(d.getTime()))
64
+ throw new RosterError("bad_input", `${what} must be a time`);
65
+ return d;
66
+ }
67
+ function day(v, what) {
68
+ if (!validDate(v))
69
+ throw new RosterError("bad_input", `${what} must be a day, YYYY-MM-DD`);
70
+ return v;
71
+ }
72
+ const iso = (v) => new Date(v).toISOString();
73
+ const isoOrNull = (v) => (typeof v === "string" && v ? iso(v) : null);
74
+ function normShift(s) {
75
+ return { ...s, week: String(s.week).slice(0, 10), starts_at: iso(s.starts_at), ends_at: iso(s.ends_at), role: s.role ?? null, note: s.note ?? null, resource: s.resource ?? null, break_minutes: s.break_minutes ?? 0, sequence: s.sequence ?? 0 };
76
+ }
77
+ const normLeave = (l) => ({ ...l, starts_at: iso(l.starts_at), ends_at: iso(l.ends_at) });
78
+ const normStaff = (s) => ({ ...s, roles: s.roles ?? [], resource: s.resource ?? null, member: s.member ?? null, created_at: iso(s.created_at) });
79
+ function normWeek(w, week) {
80
+ if (!w)
81
+ return { week, status: "draft", published_at: null, changed_at: null, sent_at: null, unsent: false };
82
+ return { ...w, week: String(w.week).slice(0, 10), published_at: isoOrNull(w.published_at), changed_at: isoOrNull(w.changed_at), sent_at: isoOrNull(w.sent_at), unsent: w.unsent === true };
83
+ }
84
+ /** Touching or overlapping spans as one, so a booking across two back-to-back shifts fits. */
85
+ function merged(spans) {
86
+ const out = [];
87
+ for (const [a, b] of [...spans].sort((x, y) => x[0] - y[0])) {
88
+ const last = out[out.length - 1];
89
+ if (last && a <= last[1])
90
+ last[1] = Math.max(last[1], b);
91
+ else
92
+ out.push([a, b]);
93
+ }
94
+ return out.map(([a, b]) => [new Date(a).toISOString(), new Date(b).toISOString()]);
95
+ }
96
+ export function createRoster(opts) {
97
+ const config = checkRosterConfig(opts.config);
98
+ const { db } = opts;
99
+ const now = opts.now ?? (() => new Date());
100
+ const tz = config.time_zone;
101
+ const lang = opts.lang ?? "en";
102
+ const locale = localeFor(lang, opts.locale);
103
+ const say = words({ t: opts.t, lang });
104
+ const weekStarts = WEEKDAYS.indexOf(config.week_starts ?? "mon");
105
+ const q = (what, fn, args) => call(db, what, fn, args);
106
+ const report = opts.onEmailError ?? ((e, what) => console.error(`roster: ${what} email failed: ${e?.message ?? e}`));
107
+ const business = async (account) => (opts.business ? await opts.business(account) : { name: account });
108
+ const roleTitle = (r) => (r ? (config.roles?.[r]?.title ?? r) : null);
109
+ const weekOfDay = (d) => weekOf(d, weekStarts);
110
+ const weekArg = (v, what = "week") => weekOfDay(day(v, what));
111
+ const days = (week) => Array.from({ length: 7 }, (_, i) => addDays(week, i));
112
+ function roles(v) {
113
+ if (v === undefined || v === null)
114
+ return [];
115
+ if (!Array.isArray(v) || v.length > 30 || !v.every((r) => typeof r === "string"))
116
+ throw new RosterError("bad_input", "roles must be a list of role names");
117
+ const known = Object.keys(config.roles ?? {});
118
+ const bad = v.filter((r) => !known.includes(r));
119
+ if (bad.length)
120
+ throw new RosterError("bad_input", `roles: ${bad.join(", ")} ${bad.length === 1 ? "isn't a role" : "aren't roles"} in roster.json`);
121
+ return [...new Set(v)];
122
+ }
123
+ function shiftArgs(account, input) {
124
+ if (!input || typeof input !== "object")
125
+ throw new RosterError("bad_input", "a shift needs { staff, start, end }");
126
+ const start = instant(input.start, "start");
127
+ const end = instant(input.end, "end");
128
+ const minutes = (end.getTime() - start.getTime()) / 60_000;
129
+ if (minutes < 15 || minutes > 1440)
130
+ throw new RosterError("bad_input", "a shift is 15 minutes to 24 hours long, ending after it starts");
131
+ const role = input.role === undefined || input.role === null || input.role === "" ? null : input.role;
132
+ if (role !== null && !config.roles?.[role])
133
+ throw new RosterError("bad_input", `role ${JSON.stringify(role)} isn't in roster.json`);
134
+ const brk = input.break_minutes ?? 0;
135
+ if (!Number.isInteger(brk) || brk < 0 || brk > 240 || brk >= minutes)
136
+ throw new RosterError("bad_input", "break_minutes is a whole number from 0 to 240, shorter than the shift");
137
+ return {
138
+ p_account: text(account, "account", 200),
139
+ p_staff: idOf(input.staff, "staff"),
140
+ p_week: weekOfDay(todayIn(tz, start)),
141
+ p_start: start.toISOString(),
142
+ p_end: end.toISOString(),
143
+ p_role: role,
144
+ p_break: brk,
145
+ p_note: optional(input.note, "note", 200),
146
+ p_now: now().toISOString(),
147
+ };
148
+ }
149
+ /** The line a shift is in an email: "Saturday 6 December, 9:00 am – 12:00 pm · Instructor · 30 min break · Open up". */
150
+ const shiftLine = (s) => [spanText(s.starts_at, s.ends_at, tz, locale), roleTitle(s.role), s.break_minutes ? say("shift.break", { minutes: s.break_minutes }) : null, s.note].filter(Boolean).join(" · ");
151
+ const digestOf = (shifts) => sha256(JSON.stringify(shifts.map((s) => [s.id, s.starts_at, s.ends_at, s.role, s.break_minutes, s.note, s.sequence])));
152
+ const mailKey = async (key, email) => `roster:${await sha256(`${key}\n${email.toLowerCase()}`)}`;
153
+ /** Emails each active person whose shifts in a published week differ from what they were last sent. Marks the week sent when nothing failed. */
154
+ async function sendWeek(account, week) {
155
+ const state = normWeek(await q("send", "roster_week_get", { p_account: account, p_week: week }), week);
156
+ if (state.status !== "published" || !opts.mailer)
157
+ return 0;
158
+ const [shifts, staff, sent] = await Promise.all([
159
+ q("send", "roster_week_shifts", { p_account: account, p_week: week }).then((r) => r.map(normShift)),
160
+ q("send", "roster_staff_list", { p_account: account, p_all: false }).then((r) => r.map(normStaff)),
161
+ q("send", "roster_sent_list", { p_account: account, p_week: week }),
162
+ ]);
163
+ const before = new Map(sent.map((s) => [s.staff, s]));
164
+ const biz = await business(account);
165
+ const weekName = dateText(week, locale);
166
+ const title = (s) => [roleTitle(s.role) ?? say("gaps.anyone"), biz.name].join(" · ");
167
+ let emailed = 0;
168
+ let failed = false;
169
+ for (const person of staff) {
170
+ const theirs = shifts.filter((s) => s.staff === person.id);
171
+ const last = before.get(person.id);
172
+ if (!theirs.length && !last)
173
+ continue;
174
+ const digest = await digestOf(theirs);
175
+ if (last?.digest === digest)
176
+ continue;
177
+ const ids = new Set(theirs.map((s) => s.id));
178
+ const gone = (last?.lines ?? []).filter((l) => !ids.has(l.id));
179
+ const changed = !!last;
180
+ const p = { week: weekName, name: person.name, business: biz.name };
181
+ const body = [
182
+ say("email.hello", p),
183
+ "",
184
+ say(changed ? "email.changed.intro" : "email.week.intro", p),
185
+ "",
186
+ ...(theirs.length ? theirs.map((s) => `- ${shiftLine(s)}`) : [say("email.none", p)]),
187
+ ...(gone.length ? ["", ...gone.map((g) => say("email.gone", { when: spanText(iso(g.starts_at), iso(g.ends_at), tz, locale) }))] : []),
188
+ ...(theirs.length ? ["", say("email.calendar", p)] : []),
189
+ "",
190
+ say("email.footer", p),
191
+ ].join("\n");
192
+ const files = [
193
+ ...(theirs.length ? [{ filename: "shifts.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(shiftsIcs(theirs, title, now())) }] : []),
194
+ ...(gone.length ? [{ filename: "cancelled.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(cancelIcs(gone.map((g) => ({ ...g, starts_at: iso(g.starts_at), ends_at: iso(g.ends_at) })), say("ics.cancelled"), now())) }] : []),
195
+ ];
196
+ try {
197
+ await opts.mailer.send({
198
+ to: person.email,
199
+ subject: say(changed ? "email.changed.subject" : "email.week.subject", p),
200
+ text: body,
201
+ template: changed ? "roster.changed" : "roster.week",
202
+ ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
203
+ ...(files.length ? { attachments: files } : {}),
204
+ idempotencyKey: await mailKey(`week:${week}:${person.id}:${digest}`, person.email),
205
+ });
206
+ emailed++;
207
+ await q("send", "roster_sent_set", { p_account: account, p_week: week, p_staff: person.id, p_digest: digest, p_lines: theirs.map((s) => ({ id: s.id, starts_at: s.starts_at, ends_at: s.ends_at, sequence: s.sequence })), p_now: now().toISOString() });
208
+ }
209
+ catch (e) {
210
+ failed = true;
211
+ report(e, changed ? "roster.changed" : "roster.week");
212
+ }
213
+ }
214
+ if (!failed)
215
+ await q("send", "roster_week_sent", { p_account: account, p_week: week, p_at: state.changed_at ?? now().toISOString() });
216
+ return emailed;
217
+ }
218
+ async function staffList(account, all = false) {
219
+ return (await q("staff", "roster_staff_list", { p_account: text(account, "account", 200), p_all: all })).map(normStaff);
220
+ }
221
+ async function leaveIn(account, from, to, staff) {
222
+ return (await q("leave", "roster_leave_list", { p_account: account, p_from: from.toISOString(), p_to: to.toISOString(), p_staff: staff })).map(normLeave);
223
+ }
224
+ async function weekView(account, w) {
225
+ const a = text(account, "account", 200);
226
+ const week = weekArg(w);
227
+ const start = localInstant(week, "00:00", tz);
228
+ const end = localInstant(addDays(week, 7), "00:00", tz);
229
+ const [state, shifts, leave, staff] = await Promise.all([
230
+ q("week", "roster_week_get", { p_account: a, p_week: week }),
231
+ q("week", "roster_week_shifts", { p_account: a, p_week: week }),
232
+ leaveIn(a, start, new Date(end.getTime() + DAY), null),
233
+ staffList(a, true),
234
+ ]);
235
+ return { ...normWeek(state, week), days: days(week), shifts: shifts.map(normShift), leave, staff };
236
+ }
237
+ return {
238
+ config,
239
+ at: (d, clock) => localInstant(day(d, "day"), clock, tz),
240
+ staff: (account, o = {}) => staffList(account, o.all === true),
241
+ async saveStaff(account, input) {
242
+ if (!input || typeof input !== "object")
243
+ throw new RosterError("bad_input", "a person needs { name, email }");
244
+ const email = text(input.email, "email", 254).toLowerCase();
245
+ if (!EMAIL.test(email))
246
+ throw new RosterError("bad_input", "email must be an email address");
247
+ const resource = input.resource === undefined || input.resource === null || input.resource === "" ? null : input.resource;
248
+ if (resource !== null && (typeof resource !== "string" || !NAME.test(resource)))
249
+ throw new RosterError("bad_input", "resource is a name from bookings.json: lower case letters, digits and -");
250
+ const s = await q("saveStaff", "roster_staff_save", {
251
+ p_account: text(account, "account", 200),
252
+ p_id: input.id === undefined ? null : idOf(input.id, "id"),
253
+ p_name: text(input.name, "name", 100).replace(/\s+/g, " "),
254
+ p_email: email,
255
+ p_roles: roles(input.roles),
256
+ p_resource: resource,
257
+ p_member: optional(input.member, "member", 200),
258
+ p_now: now().toISOString(),
259
+ });
260
+ if (!s)
261
+ throw new RosterError("unknown_staff", "no such person on the roster");
262
+ return normStaff(s);
263
+ },
264
+ async removeStaff(account, id) {
265
+ const a = text(account, "account", 200);
266
+ const done = await q("removeStaff", "roster_staff_remove", { p_account: a, p_id: idOf(id, "id"), p_now: now().toISOString() });
267
+ return done;
268
+ },
269
+ async sendLink(account, id) {
270
+ const token = newToken();
271
+ const s = await q("sendLink", "roster_feed_set", { p_account: text(account, "account", 200), p_id: idOf(id, "id"), p_hash: await sha256(token), p_now: now().toISOString() });
272
+ if (!s)
273
+ throw new RosterError("unknown_staff", "no such person on the roster");
274
+ const page = opts.links?.mine?.(token);
275
+ if (!opts.mailer || !page)
276
+ return { token, emailed: 0 };
277
+ const biz = await business(account);
278
+ const feed = opts.links?.feed?.(token);
279
+ const p = { name: s.name, business: biz.name, url: page };
280
+ try {
281
+ await opts.mailer.send({
282
+ to: s.email,
283
+ subject: say("email.link.subject", p),
284
+ text: [say("email.hello", p), "", say("email.link.body", p), ...(feed ? ["", say("email.link.feed", { url: feed })] : []), "", say("email.link.keep", p), "", say("email.footer", p)].join("\n"),
285
+ template: "roster.link",
286
+ ...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
287
+ idempotencyKey: await mailKey(`link:${token}`, s.email),
288
+ });
289
+ return { token, emailed: 1 };
290
+ }
291
+ catch (e) {
292
+ report(e, "roster.link");
293
+ return { token, emailed: 0 };
294
+ }
295
+ },
296
+ week: weekView,
297
+ async addShift(account, input) {
298
+ const s = await q("addShift", "roster_shift_save", { ...shiftArgs(account, input), p_id: null });
299
+ return normShift(s);
300
+ },
301
+ async updateShift(account, id, input) {
302
+ const s = await q("updateShift", "roster_shift_save", { ...shiftArgs(account, input), p_id: idOf(id, "id") });
303
+ if (!s)
304
+ throw new RosterError("unknown_shift", "no such shift");
305
+ return normShift(s);
306
+ },
307
+ async removeShift(account, id) {
308
+ return q("removeShift", "roster_shift_remove", { p_account: text(account, "account", 200), p_id: idOf(id, "id"), p_now: now().toISOString() });
309
+ },
310
+ async copyWeek(account, from, to) {
311
+ const a = text(account, "account", 200);
312
+ const src = weekArg(from, "from");
313
+ const dst = weekArg(to, "to");
314
+ if (src === dst)
315
+ throw new RosterError("bad_input", "copy a week into a different week");
316
+ const shift = Math.round((Date.parse(`${dst}T00:00:00Z`) - Date.parse(`${src}T00:00:00Z`)) / DAY);
317
+ const shifts = (await q("copyWeek", "roster_week_shifts", { p_account: a, p_week: src })).map(normShift);
318
+ // The same local day and clock, so 9 am stays 9 am across a daylight saving change.
319
+ const move = (at) => localInstant(addDays(todayIn(tz, new Date(at)), shift), clockIn(tz, new Date(at)), tz).toISOString();
320
+ const rows = shifts.map((s) => ({ staff: s.staff, start: move(s.starts_at), end: move(s.ends_at), role: s.role, break: s.break_minutes, note: s.note }));
321
+ return q("copyWeek", "roster_shifts_copy", { p_account: a, p_week: dst, p_rows: rows, p_now: now().toISOString() });
322
+ },
323
+ async publish(account, w) {
324
+ const a = text(account, "account", 200);
325
+ const week = weekArg(w);
326
+ await q("publish", "roster_week_publish", { p_account: a, p_week: week, p_now: now().toISOString() });
327
+ const emailed = await sendWeek(a, week);
328
+ const state = normWeek(await q("publish", "roster_week_get", { p_account: a, p_week: week }), week);
329
+ return { week: state, emailed };
330
+ },
331
+ async gaps(account, w, o = {}) {
332
+ const v = await weekView(account, w);
333
+ const active = v.staff.filter((s) => s.active);
334
+ return { gaps: findGaps({ config, days: v.days, shifts: v.shifts, leave: v.leave, staff: active, needs: o.needs ?? [], closed: o.closed ?? [] }), clashes: clashes(v.shifts, v.leave, v.staff) };
335
+ },
336
+ async addLeave(account, input) {
337
+ if (!input || typeof input !== "object")
338
+ throw new RosterError("bad_input", "leave needs { staff, from, to }");
339
+ const a = text(account, "account", 200);
340
+ const from = day(input.from, "from");
341
+ const to = day(input.to, "to");
342
+ if (to < from)
343
+ throw new RosterError("bad_input", "the last day away is on or after the first");
344
+ const start = localInstant(from, "00:00", tz);
345
+ const end = localInstant(addDays(to, 1), "00:00", tz);
346
+ const staff = idOf(input.staff, "staff");
347
+ const l = await q("addLeave", "roster_leave_add", { p_account: a, p_staff: staff, p_start: start.toISOString(), p_end: end.toISOString(), p_now: now().toISOString() });
348
+ if (!l)
349
+ throw new RosterError("unknown_staff", "no such person on the roster");
350
+ const theirs = (await q("addLeave", "roster_shifts_list", { p_account: a, p_from: new Date(start.getTime() - DAY).toISOString(), p_to: end.toISOString(), p_staff: staff, p_published: false })).map(normShift);
351
+ return { leave: normLeave(l), clashes: theirs.filter((s) => Date.parse(s.ends_at) > start.getTime() && Date.parse(s.starts_at) < end.getTime()) };
352
+ },
353
+ async removeLeave(account, id) {
354
+ return q("removeLeave", "roster_leave_remove", { p_account: text(account, "account", 200), p_id: idOf(id, "id") });
355
+ },
356
+ async leave(account, o = {}) {
357
+ const a = text(account, "account", 200);
358
+ const today = todayIn(tz, now());
359
+ const from = localInstant(o.from === undefined ? today : day(o.from, "from"), "00:00", tz);
360
+ const to = localInstant(addDays(o.to === undefined ? addDays(today, 365) : day(o.to, "to"), 1), "00:00", tz);
361
+ return leaveIn(a, from, to, o.staff === undefined ? null : idOf(o.staff, "staff"));
362
+ },
363
+ async hoursFor(account, range = {}) {
364
+ const a = text(account, "account", 200);
365
+ const from = range.from === undefined ? new Date(now().getTime() - DAY) : instant(range.from, "from");
366
+ const to = range.to === undefined ? new Date(from.getTime() + 61 * DAY) : instant(range.to, "to");
367
+ if (to <= from || to.getTime() - from.getTime() > 400 * DAY)
368
+ throw new RosterError("bad_input", "hoursFor's range is up to 400 days, ending after it starts");
369
+ const [staff, shifts, leave] = await Promise.all([
370
+ staffList(a, false),
371
+ // A shift that started the day before may still be on at `from`.
372
+ q("hoursFor", "roster_shifts_list", { p_account: a, p_from: new Date(from.getTime() - DAY).toISOString(), p_to: to.toISOString(), p_staff: null, p_published: true }).then((r) => r.map(normShift)),
373
+ leaveIn(a, from, to, null),
374
+ ]);
375
+ const out = {};
376
+ for (const p of staff) {
377
+ if (!p.resource)
378
+ continue;
379
+ out[p.resource] = {
380
+ shifts: merged(shifts.filter((s) => s.staff === p.id && Date.parse(s.ends_at) > from.getTime()).map((s) => [Date.parse(s.starts_at), Date.parse(s.ends_at)])),
381
+ away: leave.filter((l) => l.staff === p.id).map((l) => [l.starts_at, l.ends_at]),
382
+ };
383
+ }
384
+ return out;
385
+ },
386
+ async mine(token) {
387
+ if (typeof token !== "string" || token.length < 20 || token.length > 100)
388
+ return null;
389
+ const s = await q("mine", "roster_by_hash", { p_hash: await sha256(token) });
390
+ if (!s)
391
+ return null;
392
+ const at = now();
393
+ const [shifts, leave] = await Promise.all([
394
+ q("mine", "roster_shifts_list", { p_account: s.account, p_from: new Date(at.getTime() - DAY).toISOString(), p_to: new Date(at.getTime() + 120 * DAY).toISOString(), p_staff: s.id, p_published: true }),
395
+ leaveIn(s.account, at, new Date(at.getTime() + 366 * DAY), s.id),
396
+ ]);
397
+ return { staff: normStaff(s), shifts: shifts.map(normShift).filter((x) => Date.parse(x.ends_at) > at.getTime()), leave };
398
+ },
399
+ async feed(token) {
400
+ if (typeof token !== "string" || token.length < 20 || token.length > 100)
401
+ return null;
402
+ const s = await q("feed", "roster_by_hash", { p_hash: await sha256(token) });
403
+ if (!s)
404
+ return null;
405
+ const at = now();
406
+ const shifts = (await q("feed", "roster_shifts_list", { p_account: s.account, p_from: new Date(at.getTime() - 30 * DAY).toISOString(), p_to: new Date(at.getTime() + 366 * DAY).toISOString(), p_staff: s.id, p_published: true })).map(normShift);
407
+ const biz = await business(s.account);
408
+ return feedIcs(shifts, (x) => [roleTitle(x.role) ?? say("gaps.anyone"), biz.name].join(" · "), biz.name, at);
409
+ },
410
+ async exportHours(account, range) {
411
+ const a = text(account, "account", 200);
412
+ const from = day(range?.from, "from");
413
+ const to = day(range?.to, "to");
414
+ if (to < from || Date.parse(to) - Date.parse(from) > 400 * DAY)
415
+ throw new RosterError("bad_input", "export up to 400 days, the last day on or after the first");
416
+ const shifts = (await q("exportHours", "roster_shifts_list", { p_account: a, p_from: localInstant(from, "00:00", tz).toISOString(), p_to: localInstant(addDays(to, 1), "00:00", tz).toISOString(), p_staff: null, p_published: true })).map(normShift);
417
+ return hoursCsv(shifts, { lang: range.lang ?? lang, config });
418
+ },
419
+ async tick() {
420
+ if (!opts.mailer || (config.changes ?? "auto") === "manual")
421
+ return { weeks: 0, emailed: 0 };
422
+ const quiet = durationMinutes(config.changes_after ?? "1h") ?? 60;
423
+ const due = await q("tick", "roster_due", { p_before: new Date(now().getTime() - quiet * 60_000).toISOString(), p_limit: opts.batch ?? 50 });
424
+ let emailed = 0;
425
+ for (const d of due)
426
+ emailed += await sendWeek(d.account, String(d.week).slice(0, 10));
427
+ return { weeks: due.length, emailed };
428
+ },
429
+ async cleanup() {
430
+ return q("cleanup", "roster_cleanup", { p_now: now().toISOString(), p_months: config.retention_months ?? 24 });
431
+ },
432
+ };
433
+ }
@@ -0,0 +1,28 @@
1
+ export declare const STARTER_ROSTER: {
2
+ readonly format: 1;
3
+ readonly time_zone: "Australia/Sydney";
4
+ readonly week_starts: "mon";
5
+ readonly roles: {
6
+ readonly instructor: {
7
+ readonly title: "Instructor";
8
+ };
9
+ readonly "front-desk": {
10
+ readonly title: "Front desk";
11
+ };
12
+ };
13
+ readonly cover: {
14
+ readonly sat: readonly [{
15
+ readonly from: "09:00";
16
+ readonly to: "12:00";
17
+ readonly role: "instructor";
18
+ readonly people: 2;
19
+ }, {
20
+ readonly from: "08:30";
21
+ readonly to: "12:30";
22
+ readonly role: "front-desk";
23
+ }];
24
+ };
25
+ readonly changes: "auto";
26
+ readonly changes_after: "1h";
27
+ readonly retention_months: 24;
28
+ };
@@ -0,0 +1,21 @@
1
+ // What `npx workbench-roster init` writes: workbench/roster.json with
2
+ // Workbench's recommended answers, before the client's own. A swim school's
3
+ // week: instructors and the front desk, Saturday mornings covered.
4
+ export const STARTER_ROSTER = {
5
+ format: 1,
6
+ time_zone: "Australia/Sydney",
7
+ week_starts: "mon",
8
+ roles: {
9
+ instructor: { title: "Instructor" },
10
+ "front-desk": { title: "Front desk" },
11
+ },
12
+ cover: {
13
+ sat: [
14
+ { from: "09:00", to: "12:00", role: "instructor", people: 2 },
15
+ { from: "08:30", to: "12:30", role: "front-desk" },
16
+ ],
17
+ },
18
+ changes: "auto",
19
+ changes_after: "1h",
20
+ retention_months: 24,
21
+ };