@mccaskie-labs/workbench-roster 0.0.0-stage → 0.2.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.
- package/CHANGELOG.md +15 -0
- package/README.md +57 -2
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +124 -0
- package/dist/config.d.ts +9 -0
- package/dist/config.js +103 -0
- package/dist/confirm.d.ts +60 -0
- package/dist/confirm.js +85 -0
- package/dist/csv.d.ts +9 -0
- package/dist/csv.js +35 -0
- package/dist/errors.d.ts +25 -0
- package/dist/errors.js +10 -0
- package/dist/format.d.ts +19 -0
- package/dist/format.js +31 -0
- package/dist/gaps.d.ts +23 -0
- package/dist/gaps.js +89 -0
- package/dist/ical.d.ts +9 -0
- package/dist/ical.js +57 -0
- package/dist/index.d.ts +15 -0
- package/dist/index.js +22 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +642 -0
- package/dist/roster.d.ts +169 -0
- package/dist/roster.js +502 -0
- package/dist/starters.d.ts +28 -0
- package/dist/starters.js +21 -0
- package/dist/styles.d.ts +34 -0
- package/dist/styles.js +101 -0
- package/dist/time.d.ts +19 -0
- package/dist/time.js +92 -0
- package/dist/types.d.ts +158 -0
- package/dist/types.js +3 -0
- package/dist/ui.d.ts +80 -0
- package/dist/ui.js +255 -0
- package/dist/words.d.ts +3 -0
- package/dist/words.js +506 -0
- package/package.json +48 -4
package/dist/roster.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
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
|
+
/** The active people whose shifts in a week differ from what they were last sent: who a send emails. */
|
|
154
|
+
async function toEmail(shifts, staff, sent) {
|
|
155
|
+
const before = new Map(sent.map((s) => [s.staff, s]));
|
|
156
|
+
const out = [];
|
|
157
|
+
for (const person of staff) {
|
|
158
|
+
if (!person.active)
|
|
159
|
+
continue;
|
|
160
|
+
const theirs = shifts.filter((s) => s.staff === person.id);
|
|
161
|
+
const last = before.get(person.id);
|
|
162
|
+
if (!theirs.length && !last)
|
|
163
|
+
continue;
|
|
164
|
+
const digest = await digestOf(theirs);
|
|
165
|
+
if (last?.digest === digest)
|
|
166
|
+
continue;
|
|
167
|
+
out.push({ person, theirs, last, digest });
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
/** Emails each active person whose shifts in a published week differ from what they were last sent. Marks the week sent when nothing failed. */
|
|
172
|
+
async function sendWeek(account, week) {
|
|
173
|
+
const state = normWeek(await q("send", "roster_week_get", { p_account: account, p_week: week }), week);
|
|
174
|
+
if (state.status !== "published" || !opts.mailer)
|
|
175
|
+
return 0;
|
|
176
|
+
const [shifts, staff, sent] = await Promise.all([
|
|
177
|
+
q("send", "roster_week_shifts", { p_account: account, p_week: week }).then((r) => r.map(normShift)),
|
|
178
|
+
q("send", "roster_staff_list", { p_account: account, p_all: false }).then((r) => r.map(normStaff)),
|
|
179
|
+
q("send", "roster_sent_list", { p_account: account, p_week: week }),
|
|
180
|
+
]);
|
|
181
|
+
const biz = await business(account);
|
|
182
|
+
const weekName = dateText(week, locale);
|
|
183
|
+
const title = (s) => [roleTitle(s.role) ?? say("gaps.anyone"), biz.name].join(" · ");
|
|
184
|
+
let emailed = 0;
|
|
185
|
+
let failed = false;
|
|
186
|
+
for (const { person, theirs, last, digest } of await toEmail(shifts, staff, sent ?? [])) {
|
|
187
|
+
const ids = new Set(theirs.map((s) => s.id));
|
|
188
|
+
const gone = (last?.lines ?? []).filter((l) => !ids.has(l.id));
|
|
189
|
+
const changed = !!last;
|
|
190
|
+
const p = { week: weekName, name: person.name, business: biz.name };
|
|
191
|
+
const body = [
|
|
192
|
+
say("email.hello", p),
|
|
193
|
+
"",
|
|
194
|
+
say(changed ? "email.changed.intro" : "email.week.intro", p),
|
|
195
|
+
"",
|
|
196
|
+
...(theirs.length ? theirs.map((s) => `- ${shiftLine(s)}`) : [say("email.none", p)]),
|
|
197
|
+
...(gone.length ? ["", ...gone.map((g) => say("email.gone", { when: spanText(iso(g.starts_at), iso(g.ends_at), tz, locale) }))] : []),
|
|
198
|
+
...(theirs.length ? ["", say("email.calendar", p)] : []),
|
|
199
|
+
"",
|
|
200
|
+
say("email.footer", p),
|
|
201
|
+
].join("\n");
|
|
202
|
+
const files = [
|
|
203
|
+
...(theirs.length ? [{ filename: "shifts.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(shiftsIcs(theirs, title, now())) }] : []),
|
|
204
|
+
...(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())) }] : []),
|
|
205
|
+
];
|
|
206
|
+
try {
|
|
207
|
+
await opts.mailer.send({
|
|
208
|
+
to: person.email,
|
|
209
|
+
subject: say(changed ? "email.changed.subject" : "email.week.subject", p),
|
|
210
|
+
text: body,
|
|
211
|
+
template: changed ? "roster.changed" : "roster.week",
|
|
212
|
+
...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
|
|
213
|
+
...(files.length ? { attachments: files } : {}),
|
|
214
|
+
idempotencyKey: await mailKey(`week:${week}:${person.id}:${digest}`, person.email),
|
|
215
|
+
});
|
|
216
|
+
emailed++;
|
|
217
|
+
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() });
|
|
218
|
+
}
|
|
219
|
+
catch (e) {
|
|
220
|
+
failed = true;
|
|
221
|
+
report(e, changed ? "roster.changed" : "roster.week");
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (!failed)
|
|
225
|
+
await q("send", "roster_week_sent", { p_account: account, p_week: week, p_at: state.changed_at ?? now().toISOString() });
|
|
226
|
+
return emailed;
|
|
227
|
+
}
|
|
228
|
+
async function staffList(account, all = false) {
|
|
229
|
+
return (await q("staff", "roster_staff_list", { p_account: text(account, "account", 200), p_all: all })).map(normStaff);
|
|
230
|
+
}
|
|
231
|
+
async function leaveIn(account, from, to, staff) {
|
|
232
|
+
return (await q("leave", "roster_leave_list", { p_account: account, p_from: from.toISOString(), p_to: to.toISOString(), p_staff: staff })).map(normLeave);
|
|
233
|
+
}
|
|
234
|
+
async function weekView(account, w, count = false) {
|
|
235
|
+
const a = text(account, "account", 200);
|
|
236
|
+
const week = weekArg(w);
|
|
237
|
+
const start = localInstant(week, "00:00", tz);
|
|
238
|
+
const end = localInstant(addDays(week, 7), "00:00", tz);
|
|
239
|
+
const [state, shifts, leave, staff] = await Promise.all([
|
|
240
|
+
q("week", "roster_week_get", { p_account: a, p_week: week }),
|
|
241
|
+
q("week", "roster_week_shifts", { p_account: a, p_week: week }),
|
|
242
|
+
leaveIn(a, start, new Date(end.getTime() + DAY), null),
|
|
243
|
+
staffList(a, true),
|
|
244
|
+
]);
|
|
245
|
+
const view = { ...normWeek(state, week), days: days(week), shifts: shifts.map(normShift), leave, staff };
|
|
246
|
+
if (!count)
|
|
247
|
+
return view;
|
|
248
|
+
// Who Publish or Send the changes would email now, for its "Are you sure?".
|
|
249
|
+
if (!opts.mailer)
|
|
250
|
+
return { ...view, emailing: 0 };
|
|
251
|
+
if (view.status === "published" && !view.unsent)
|
|
252
|
+
return view;
|
|
253
|
+
const sent = (await q("week", "roster_sent_list", { p_account: a, p_week: week })) ?? [];
|
|
254
|
+
return { ...view, emailing: (await toEmail(view.shifts, staff, sent)).length };
|
|
255
|
+
}
|
|
256
|
+
/** The line a removed shift or a stretch of leave is in an email. */
|
|
257
|
+
const leaveText = (l) => ({ from: dateText(todayIn(tz, new Date(l.starts_at)), locale), to: dateText(todayIn(tz, new Date(Date.parse(l.ends_at) - 1)), locale) });
|
|
258
|
+
/** A notice email to one person; a failed email never fails what the owner did. */
|
|
259
|
+
async function notify(account, person, kind, key, params, lines, attachments = []) {
|
|
260
|
+
if (!opts.mailer)
|
|
261
|
+
return;
|
|
262
|
+
try {
|
|
263
|
+
const biz = await business(account);
|
|
264
|
+
const p = { ...params, name: person.name, business: biz.name };
|
|
265
|
+
await opts.mailer.send({
|
|
266
|
+
to: person.email,
|
|
267
|
+
subject: say(`email.${kind}.subject`, p),
|
|
268
|
+
text: [say("email.hello", p), "", say(`email.${kind}.body`, p), ...(lines.length ? ["", ...lines] : []), "", say(`email.${kind}.next`, p), "", say("email.footer", p)].join("\n"),
|
|
269
|
+
template: `roster.${kind}`,
|
|
270
|
+
...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
|
|
271
|
+
...(attachments.length ? { attachments } : {}),
|
|
272
|
+
idempotencyKey: await mailKey(key, person.email),
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
catch (e) {
|
|
276
|
+
report(e, `roster.${kind}`);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
return {
|
|
280
|
+
config,
|
|
281
|
+
at: (d, clock) => localInstant(day(d, "day"), clock, tz),
|
|
282
|
+
staff: (account, o = {}) => staffList(account, o.all === true),
|
|
283
|
+
async saveStaff(account, input) {
|
|
284
|
+
if (!input || typeof input !== "object")
|
|
285
|
+
throw new RosterError("bad_input", "a person needs { name, email }");
|
|
286
|
+
const email = text(input.email, "email", 254).toLowerCase();
|
|
287
|
+
if (!EMAIL.test(email))
|
|
288
|
+
throw new RosterError("bad_input", "email must be an email address");
|
|
289
|
+
const resource = input.resource === undefined || input.resource === null || input.resource === "" ? null : input.resource;
|
|
290
|
+
if (resource !== null && (typeof resource !== "string" || !NAME.test(resource)))
|
|
291
|
+
throw new RosterError("bad_input", "resource is a name from bookings.json: lower case letters, digits and -");
|
|
292
|
+
const s = await q("saveStaff", "roster_staff_save", {
|
|
293
|
+
p_account: text(account, "account", 200),
|
|
294
|
+
p_id: input.id === undefined ? null : idOf(input.id, "id"),
|
|
295
|
+
p_name: text(input.name, "name", 100).replace(/\s+/g, " "),
|
|
296
|
+
p_email: email,
|
|
297
|
+
p_roles: roles(input.roles),
|
|
298
|
+
p_resource: resource,
|
|
299
|
+
p_member: optional(input.member, "member", 200),
|
|
300
|
+
p_now: now().toISOString(),
|
|
301
|
+
});
|
|
302
|
+
if (!s)
|
|
303
|
+
throw new RosterError("unknown_staff", "no such person on the roster");
|
|
304
|
+
return normStaff(s);
|
|
305
|
+
},
|
|
306
|
+
async removeStaff(account, id) {
|
|
307
|
+
const a = text(account, "account", 200);
|
|
308
|
+
const sid = idOf(id, "id");
|
|
309
|
+
const at = now();
|
|
310
|
+
// Who they are and the published shifts they lose, read first so the email can name them. A failed read never stops the removal.
|
|
311
|
+
const before = opts.mailer
|
|
312
|
+
? await Promise.all([
|
|
313
|
+
staffList(a, false).then((r) => r.find((s) => s.id === sid)),
|
|
314
|
+
q("removeStaff", "roster_shifts_list", { p_account: a, p_from: at.toISOString(), p_to: new Date(at.getTime() + 400 * DAY).toISOString(), p_staff: sid, p_published: true }).then((r) => (r ?? []).map(normShift)),
|
|
315
|
+
]).catch(() => null)
|
|
316
|
+
: null;
|
|
317
|
+
const done = await q("removeStaff", "roster_staff_remove", { p_account: a, p_id: sid, p_now: at.toISOString() });
|
|
318
|
+
const person = before?.[0];
|
|
319
|
+
if (done && person) {
|
|
320
|
+
const gone = before[1];
|
|
321
|
+
const files = gone.length ? [{ filename: "cancelled.ics", mimeType: "text/calendar", bytes: new TextEncoder().encode(cancelIcs(gone, say("ics.cancelled"), at)) }] : [];
|
|
322
|
+
await notify(a, person, "removed", `removed:${sid}:${at.toISOString()}`, {}, gone.map((g) => say("email.gone", { when: spanText(g.starts_at, g.ends_at, tz, locale) })), files);
|
|
323
|
+
}
|
|
324
|
+
return done;
|
|
325
|
+
},
|
|
326
|
+
async sendLink(account, id) {
|
|
327
|
+
const token = newToken();
|
|
328
|
+
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() });
|
|
329
|
+
if (!s)
|
|
330
|
+
throw new RosterError("unknown_staff", "no such person on the roster");
|
|
331
|
+
const page = opts.links?.mine?.(token);
|
|
332
|
+
if (!opts.mailer || !page)
|
|
333
|
+
return { token, emailed: 0 };
|
|
334
|
+
const biz = await business(account);
|
|
335
|
+
const feed = opts.links?.feed?.(token);
|
|
336
|
+
const p = { name: s.name, business: biz.name, url: page };
|
|
337
|
+
try {
|
|
338
|
+
await opts.mailer.send({
|
|
339
|
+
to: s.email,
|
|
340
|
+
subject: say("email.link.subject", p),
|
|
341
|
+
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"),
|
|
342
|
+
template: "roster.link",
|
|
343
|
+
...(biz.replyTo ? { replyTo: biz.replyTo } : {}),
|
|
344
|
+
idempotencyKey: await mailKey(`link:${token}`, s.email),
|
|
345
|
+
});
|
|
346
|
+
return { token, emailed: 1 };
|
|
347
|
+
}
|
|
348
|
+
catch (e) {
|
|
349
|
+
report(e, "roster.link");
|
|
350
|
+
return { token, emailed: 0 };
|
|
351
|
+
}
|
|
352
|
+
},
|
|
353
|
+
week: (account, w) => weekView(account, w, true),
|
|
354
|
+
async addShift(account, input) {
|
|
355
|
+
const s = await q("addShift", "roster_shift_save", { ...shiftArgs(account, input), p_id: null });
|
|
356
|
+
return normShift(s);
|
|
357
|
+
},
|
|
358
|
+
async updateShift(account, id, input) {
|
|
359
|
+
const s = await q("updateShift", "roster_shift_save", { ...shiftArgs(account, input), p_id: idOf(id, "id") });
|
|
360
|
+
if (!s)
|
|
361
|
+
throw new RosterError("unknown_shift", "no such shift");
|
|
362
|
+
return normShift(s);
|
|
363
|
+
},
|
|
364
|
+
async removeShift(account, id) {
|
|
365
|
+
return q("removeShift", "roster_shift_remove", { p_account: text(account, "account", 200), p_id: idOf(id, "id"), p_now: now().toISOString() });
|
|
366
|
+
},
|
|
367
|
+
async copyWeek(account, from, to) {
|
|
368
|
+
const a = text(account, "account", 200);
|
|
369
|
+
const src = weekArg(from, "from");
|
|
370
|
+
const dst = weekArg(to, "to");
|
|
371
|
+
if (src === dst)
|
|
372
|
+
throw new RosterError("bad_input", "copy a week into a different week");
|
|
373
|
+
const shift = Math.round((Date.parse(`${dst}T00:00:00Z`) - Date.parse(`${src}T00:00:00Z`)) / DAY);
|
|
374
|
+
const shifts = (await q("copyWeek", "roster_week_shifts", { p_account: a, p_week: src })).map(normShift);
|
|
375
|
+
// The same local day and clock, so 9 am stays 9 am across a daylight saving change.
|
|
376
|
+
const move = (at) => localInstant(addDays(todayIn(tz, new Date(at)), shift), clockIn(tz, new Date(at)), tz).toISOString();
|
|
377
|
+
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 }));
|
|
378
|
+
return q("copyWeek", "roster_shifts_copy", { p_account: a, p_week: dst, p_rows: rows, p_now: now().toISOString() });
|
|
379
|
+
},
|
|
380
|
+
async publish(account, w) {
|
|
381
|
+
const a = text(account, "account", 200);
|
|
382
|
+
const week = weekArg(w);
|
|
383
|
+
await q("publish", "roster_week_publish", { p_account: a, p_week: week, p_now: now().toISOString() });
|
|
384
|
+
const emailed = await sendWeek(a, week);
|
|
385
|
+
const state = normWeek(await q("publish", "roster_week_get", { p_account: a, p_week: week }), week);
|
|
386
|
+
return { week: state, emailed };
|
|
387
|
+
},
|
|
388
|
+
async gaps(account, w, o = {}) {
|
|
389
|
+
const v = await weekView(account, w);
|
|
390
|
+
const active = v.staff.filter((s) => s.active);
|
|
391
|
+
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) };
|
|
392
|
+
},
|
|
393
|
+
async addLeave(account, input) {
|
|
394
|
+
if (!input || typeof input !== "object")
|
|
395
|
+
throw new RosterError("bad_input", "leave needs { staff, from, to }");
|
|
396
|
+
const a = text(account, "account", 200);
|
|
397
|
+
const from = day(input.from, "from");
|
|
398
|
+
const to = day(input.to, "to");
|
|
399
|
+
if (to < from)
|
|
400
|
+
throw new RosterError("bad_input", "the last day away is on or after the first");
|
|
401
|
+
const start = localInstant(from, "00:00", tz);
|
|
402
|
+
const end = localInstant(addDays(to, 1), "00:00", tz);
|
|
403
|
+
const staff = idOf(input.staff, "staff");
|
|
404
|
+
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() });
|
|
405
|
+
if (!l)
|
|
406
|
+
throw new RosterError("unknown_staff", "no such person on the roster");
|
|
407
|
+
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);
|
|
408
|
+
return { leave: normLeave(l), clashes: theirs.filter((s) => Date.parse(s.ends_at) > start.getTime() && Date.parse(s.starts_at) < end.getTime()) };
|
|
409
|
+
},
|
|
410
|
+
async removeLeave(account, id) {
|
|
411
|
+
const a = text(account, "account", 200);
|
|
412
|
+
const lid = idOf(id, "id");
|
|
413
|
+
const at = now();
|
|
414
|
+
// The leave and its person, read first so the email can say which days. A failed read never stops the removal.
|
|
415
|
+
const before = opts.mailer
|
|
416
|
+
? await Promise.all([leaveIn(a, new Date(at.getTime() - 400 * DAY), new Date(at.getTime() + 3 * 366 * DAY), null).then((r) => r.find((l) => l.id === lid)), staffList(a, false)]).catch(() => null)
|
|
417
|
+
: null;
|
|
418
|
+
const done = await q("removeLeave", "roster_leave_remove", { p_account: a, p_id: lid });
|
|
419
|
+
const leave = before?.[0];
|
|
420
|
+
const person = leave ? before[1].find((s) => s.id === leave.staff) : undefined;
|
|
421
|
+
if (done && leave && person)
|
|
422
|
+
await notify(a, person, "leave_removed", `leave-removed:${lid}`, leaveText(leave), []);
|
|
423
|
+
return done;
|
|
424
|
+
},
|
|
425
|
+
async leave(account, o = {}) {
|
|
426
|
+
const a = text(account, "account", 200);
|
|
427
|
+
const today = todayIn(tz, now());
|
|
428
|
+
const from = localInstant(o.from === undefined ? today : day(o.from, "from"), "00:00", tz);
|
|
429
|
+
const to = localInstant(addDays(o.to === undefined ? addDays(today, 365) : day(o.to, "to"), 1), "00:00", tz);
|
|
430
|
+
return leaveIn(a, from, to, o.staff === undefined ? null : idOf(o.staff, "staff"));
|
|
431
|
+
},
|
|
432
|
+
async hoursFor(account, range = {}) {
|
|
433
|
+
const a = text(account, "account", 200);
|
|
434
|
+
const from = range.from === undefined ? new Date(now().getTime() - DAY) : instant(range.from, "from");
|
|
435
|
+
const to = range.to === undefined ? new Date(from.getTime() + 61 * DAY) : instant(range.to, "to");
|
|
436
|
+
if (to <= from || to.getTime() - from.getTime() > 400 * DAY)
|
|
437
|
+
throw new RosterError("bad_input", "hoursFor's range is up to 400 days, ending after it starts");
|
|
438
|
+
const [staff, shifts, leave] = await Promise.all([
|
|
439
|
+
staffList(a, false),
|
|
440
|
+
// A shift that started the day before may still be on at `from`.
|
|
441
|
+
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)),
|
|
442
|
+
leaveIn(a, from, to, null),
|
|
443
|
+
]);
|
|
444
|
+
const out = {};
|
|
445
|
+
for (const p of staff) {
|
|
446
|
+
if (!p.resource)
|
|
447
|
+
continue;
|
|
448
|
+
out[p.resource] = {
|
|
449
|
+
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)])),
|
|
450
|
+
away: leave.filter((l) => l.staff === p.id).map((l) => [l.starts_at, l.ends_at]),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
return out;
|
|
454
|
+
},
|
|
455
|
+
async mine(token) {
|
|
456
|
+
if (typeof token !== "string" || token.length < 20 || token.length > 100)
|
|
457
|
+
return null;
|
|
458
|
+
const s = await q("mine", "roster_by_hash", { p_hash: await sha256(token) });
|
|
459
|
+
if (!s)
|
|
460
|
+
return null;
|
|
461
|
+
const at = now();
|
|
462
|
+
const [shifts, leave] = await Promise.all([
|
|
463
|
+
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 }),
|
|
464
|
+
leaveIn(s.account, at, new Date(at.getTime() + 366 * DAY), s.id),
|
|
465
|
+
]);
|
|
466
|
+
return { staff: normStaff(s), shifts: shifts.map(normShift).filter((x) => Date.parse(x.ends_at) > at.getTime()), leave };
|
|
467
|
+
},
|
|
468
|
+
async feed(token) {
|
|
469
|
+
if (typeof token !== "string" || token.length < 20 || token.length > 100)
|
|
470
|
+
return null;
|
|
471
|
+
const s = await q("feed", "roster_by_hash", { p_hash: await sha256(token) });
|
|
472
|
+
if (!s)
|
|
473
|
+
return null;
|
|
474
|
+
const at = now();
|
|
475
|
+
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);
|
|
476
|
+
const biz = await business(s.account);
|
|
477
|
+
return feedIcs(shifts, (x) => [roleTitle(x.role) ?? say("gaps.anyone"), biz.name].join(" · "), biz.name, at);
|
|
478
|
+
},
|
|
479
|
+
async exportHours(account, range) {
|
|
480
|
+
const a = text(account, "account", 200);
|
|
481
|
+
const from = day(range?.from, "from");
|
|
482
|
+
const to = day(range?.to, "to");
|
|
483
|
+
if (to < from || Date.parse(to) - Date.parse(from) > 400 * DAY)
|
|
484
|
+
throw new RosterError("bad_input", "export up to 400 days, the last day on or after the first");
|
|
485
|
+
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);
|
|
486
|
+
return hoursCsv(shifts, { lang: range.lang ?? lang, config });
|
|
487
|
+
},
|
|
488
|
+
async tick() {
|
|
489
|
+
if (!opts.mailer || (config.changes ?? "auto") === "manual")
|
|
490
|
+
return { weeks: 0, emailed: 0 };
|
|
491
|
+
const quiet = durationMinutes(config.changes_after ?? "1h") ?? 60;
|
|
492
|
+
const due = await q("tick", "roster_due", { p_before: new Date(now().getTime() - quiet * 60_000).toISOString(), p_limit: opts.batch ?? 50 });
|
|
493
|
+
let emailed = 0;
|
|
494
|
+
for (const d of due)
|
|
495
|
+
emailed += await sendWeek(d.account, String(d.week).slice(0, 10));
|
|
496
|
+
return { weeks: due.length, emailed };
|
|
497
|
+
},
|
|
498
|
+
async cleanup() {
|
|
499
|
+
return q("cleanup", "roster_cleanup", { p_now: now().toISOString(), p_months: config.retention_months ?? 24 });
|
|
500
|
+
},
|
|
501
|
+
};
|
|
502
|
+
}
|
|
@@ -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
|
+
};
|
package/dist/starters.js
ADDED
|
@@ -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
|
+
};
|
package/dist/styles.d.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/** One CSS custom property the rules read, with its default. */
|
|
2
|
+
interface StyleVariable {
|
|
3
|
+
/** `--wb-<tool>-<what>`. */
|
|
4
|
+
name: string;
|
|
5
|
+
value: string;
|
|
6
|
+
about: string;
|
|
7
|
+
}
|
|
8
|
+
/** A rule for a class in another state, or for an element inside it. */
|
|
9
|
+
interface StyleState {
|
|
10
|
+
selector: string;
|
|
11
|
+
about: string;
|
|
12
|
+
css: string;
|
|
13
|
+
}
|
|
14
|
+
/** One class the tool puts on an element, with its default rule. */
|
|
15
|
+
interface StyleClass {
|
|
16
|
+
name: string;
|
|
17
|
+
element: string;
|
|
18
|
+
about: string;
|
|
19
|
+
css: string;
|
|
20
|
+
states?: readonly StyleState[];
|
|
21
|
+
}
|
|
22
|
+
/** Every class and variable the tool draws with. */
|
|
23
|
+
export interface ToolStyles {
|
|
24
|
+
format: 1;
|
|
25
|
+
tool: string;
|
|
26
|
+
package: string;
|
|
27
|
+
title: string;
|
|
28
|
+
prefix: string;
|
|
29
|
+
variables: readonly StyleVariable[];
|
|
30
|
+
classes: readonly StyleClass[];
|
|
31
|
+
}
|
|
32
|
+
/** The style hooks of the owner's week (renderWeek) and staff (renderStaff) pages and a person's own page (renderMyShifts). */
|
|
33
|
+
export declare const ROSTER_STYLES: ToolStyles;
|
|
34
|
+
export {};
|