@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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ # @mccaskie-labs/workbench-roster
2
+
3
+ ## 0.1.0
4
+
5
+ - First version: staff, shifts and leave in the app's own database; publish a week and email each person their shifts with a calendar file; their own page and feed; changes emailed to the people they touch; the gaps check; `hoursFor()` for workbench-bookings' `settings`; the hours export; English, Tagalog and Taglish (docs/capabilities/21-roster.md).
package/README.md CHANGED
@@ -1,3 +1,56 @@
1
- # Temporary Holding Version
1
+ # @mccaskie-labs/workbench-roster
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A staff roster for apps built on Workbench, a private platform: the owner builds each week's shifts on the app's own page, publishes it, and each person is emailed their shifts with a calendar file and has their own private page and calendar feed. Changes are emailed only to the people they touch. A gaps check finds times with too few people on, `hoursFor()` keeps bookings inside rostered shifts, and the hours download goes to the owner's own payroll. Spec: `docs/capabilities/21-roster.md`. Published publicly so Workbench projects can install it with no token; it is not supported for other uses.
4
+
5
+ ```sh
6
+ npm install @mccaskie-labs/workbench-roster
7
+ ```
8
+
9
+ No AI and no pay rates. The roster lives in the app's own database; email goes through `workbench-email` and the Gateway.
10
+
11
+ ## Set up
12
+
13
+ 1. `npx workbench-roster init` writes `workbench/roster.json`: a swim school's week in Sydney with instructors and the front desk, Saturday mornings covered, changes emailed an hour after the owner stops editing, shifts kept 2 years. Edit it; the client questions in `capabilities/roster.json` say how. Set `time_zone` from the country pack and put its public holidays in `closed`.
14
+ 2. `npx workbench-roster generate` checks it and writes `src/roster.generated.ts` (`ROSTER_CONFIG`). Checks can run `npx workbench-roster generate --check`.
15
+ 3. `npx workbench-roster migration` writes `rosterMigration` and its down file. It creates functions, so Control asks for approval even on staging.
16
+ 4. Add `"*/15 * * * *"` to `triggers.crons` in `wrangler.jsonc` (the same cron bookings uses).
17
+
18
+ ## Use
19
+
20
+ ```ts
21
+ import { createRoster, renderMyShifts, renderStaff, renderWeek, rosterAction } from '@mccaskie-labs/workbench-roster'
22
+ import { ROSTER_CONFIG } from './roster.generated'
23
+
24
+ const roster = createRoster({
25
+ db: serviceClient, mailer, config: ROSTER_CONFIG,
26
+ business: async (account) => ({ name: 'Riverside Swim School' }),
27
+ links: { mine: (t) => `https://${host}/roster/me/${t}`, feed: (t) => `webcal://${host}/roster/feed/${t}.ics` },
28
+ })
29
+
30
+ // The owner's pages, behind their sign-in; their buttons post to rosterAction.
31
+ const view = await roster.week(account, '2026-12-05') // any day in the week
32
+ html(renderWeek(view, { config: roster.config, endpoint: '/app/roster', weekUrl: (w) => `/app/roster?week=${w}`, gaps: await roster.gaps(account, view.week) }))
33
+ html(renderStaff(await roster.staff(account), { config: roster.config, endpoint: '/app/roster', leave: await roster.leave(account) }))
34
+ const result = await rosterAction(roster, fields, account)
35
+
36
+ // A person's own page and feed, by their secret (sent with roster.sendLink):
37
+ html(renderMyShifts((await roster.mine(token))!, { config: roster.config, feedUrl: `webcal://${host}/roster/feed/${token}.ics` }))
38
+ new Response(await roster.feed(token), { headers: { 'content-type': 'text/calendar; charset=utf-8' } })
39
+
40
+ // Customers book a person only inside a published shift, never on leave:
41
+ createBookings({ ..., settings: async (account) => ({ resources: await roster.hoursFor(account) }) })
42
+
43
+ // The owner's payroll spreadsheet:
44
+ await roster.exportHours(account, { from: '2026-11-30', to: '2026-12-06' })
45
+
46
+ // scheduled(): tick() every 15 minutes, cleanup() once a day.
47
+ ctx.waitUntil(roster.tick())
48
+ ```
49
+
50
+ ## Restyling
51
+
52
+ Every element has a `wb-roster-*` class with a default rule in `ROSTER_STYLES` (`@mccaskie-labs/workbench-roster/styles`), written into the project's `public/styles/workbench.css` by `npx workbench-ui styles`. Restyle in `public/styles/project.css`.
53
+
54
+ ## Words
55
+
56
+ `ROSTER_WORDS` has English, Tagalog and Taglish under `ui.wbroster.*`. Pass the project's `t` to use its own catalogue. The Tagalog and Taglish are starter words: have a fluent reader check them before a client sees them.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import type { RosterConfig } from "./types.ts";
3
+ export declare const ROSTER_FILE = "workbench/roster.json";
4
+ export declare const ROSTER_MODULE = "src/roster.generated.ts";
5
+ /** The generated module for checked settings. */
6
+ export declare function moduleText(c: RosterConfig): string;
7
+ /** Reads and checks the project's roster.json. Throws naming every problem. */
8
+ export declare function readRoster(dir: string): RosterConfig;
9
+ /** Runs one command; returns the exit code. */
10
+ export declare function run(argv: string[], log?: (s: string) => void, err?: (s: string) => void): number;
package/dist/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ // `npx workbench-roster init [dir]`, run in a project's folder: writes
3
+ // workbench/roster.json with the recommended answers. A file already there
4
+ // is left as it is.
5
+ //
6
+ // `npx workbench-roster generate [--check] [dir]` reads
7
+ // workbench/roster.json, checks it, and writes src/roster.generated.ts:
8
+ // ROSTER_CONFIG for createRoster. --check writes nothing and fails when
9
+ // the file is out of date or wrong.
10
+ //
11
+ // `npx workbench-roster migration [dir]` writes rosterMigration into
12
+ // supabase/migrations/<timestamp>_workbench_roster.sql, and its down file
13
+ // into supabase/rollback/, unless a roster migration is already there.
14
+ import { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
15
+ import { dirname, join, resolve } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import { rosterProblems } from "./config.js";
18
+ import { rosterMigration } from "./migration.js";
19
+ import { STARTER_ROSTER } from "./starters.js";
20
+ const USAGE = "usage: workbench-roster init [dir]\n workbench-roster generate [--check] [dir]\n workbench-roster migration [dir]";
21
+ export const ROSTER_FILE = "workbench/roster.json";
22
+ export const ROSTER_MODULE = "src/roster.generated.ts";
23
+ const read = (path) => readFileSync(path, "utf8").replace(/\r\n/g, "\n");
24
+ /** The generated module for checked settings. */
25
+ export function moduleText(c) {
26
+ return [
27
+ `// Generated by \`npx workbench-roster generate\` from ${ROSTER_FILE}. Don't edit: change the`,
28
+ "// JSON and generate again (Checks runs `npx workbench-roster generate --check`).",
29
+ "",
30
+ 'import type { RosterConfig } from "@mccaskie-labs/workbench-roster";',
31
+ "",
32
+ `export const ROSTER_CONFIG = ${JSON.stringify(c, null, 2)} as const satisfies RosterConfig;`,
33
+ "",
34
+ ].join("\n");
35
+ }
36
+ /** Reads and checks the project's roster.json. Throws naming every problem. */
37
+ export function readRoster(dir) {
38
+ const path = join(dir, ROSTER_FILE);
39
+ if (!existsSync(path))
40
+ throw new Error(`${ROSTER_FILE} is missing: run npx workbench-roster init, then answer the roster questions (capabilities/roster.json, offer)`);
41
+ let parsed;
42
+ try {
43
+ parsed = JSON.parse(read(path));
44
+ }
45
+ catch (e) {
46
+ throw new Error(`${ROSTER_FILE}: not valid JSON (${e.message})`);
47
+ }
48
+ const problems = rosterProblems(parsed, ROSTER_FILE);
49
+ if (problems.length)
50
+ throw new Error(problems.join("\n"));
51
+ return parsed;
52
+ }
53
+ function migrationStamp(at) {
54
+ return at.toISOString().replace(/[-:T]/g, "").slice(0, 14);
55
+ }
56
+ /** Runs one command; returns the exit code. */
57
+ export function run(argv, log = console.log, err = console.error) {
58
+ const [command, ...args] = argv;
59
+ const check = args.includes("--check");
60
+ const rest = args.filter((a) => a !== "--check");
61
+ const bad = rest.find((a) => a.startsWith("--"));
62
+ if (!["init", "generate", "migration"].includes(command ?? "") || bad || (check && command !== "generate") || rest.length > 1) {
63
+ err(bad ? `${bad} isn't an option\n${USAGE}` : USAGE);
64
+ return 2;
65
+ }
66
+ const dir = resolve(rest[0] ?? ".");
67
+ try {
68
+ if (command === "init") {
69
+ const at = join(dir, ROSTER_FILE);
70
+ if (existsSync(at)) {
71
+ log(`${ROSTER_FILE} is already there; left as it is`);
72
+ return 0;
73
+ }
74
+ mkdirSync(dirname(at), { recursive: true });
75
+ writeFileSync(at, `${JSON.stringify(STARTER_ROSTER, null, 2)}\n`);
76
+ log(`wrote ${ROSTER_FILE}`);
77
+ log("Now set time_zone and week_starts from the country pack, answer the roster questions, and run `npx workbench-roster generate`.");
78
+ return 0;
79
+ }
80
+ if (command === "migration") {
81
+ const folder = join(dir, "supabase/migrations");
82
+ if (existsSync(folder) && readdirSync(folder).some((f) => f.endsWith("_workbench_roster.sql"))) {
83
+ log("supabase/migrations already has the roster migration; nothing written");
84
+ return 0;
85
+ }
86
+ const name = `${migrationStamp(new Date())}_workbench_roster.sql`;
87
+ mkdirSync(folder, { recursive: true });
88
+ mkdirSync(join(dir, "supabase/rollback"), { recursive: true });
89
+ writeFileSync(join(folder, name), `-- workbench-roster: staff roster\n${rosterMigration.up}`);
90
+ writeFileSync(join(dir, "supabase/rollback", name.replace(/\.sql$/, "_down.sql")), `-- Reverses ${name}\n${rosterMigration.down}`);
91
+ log(`wrote supabase/migrations/${name} and its down file`);
92
+ return 0;
93
+ }
94
+ const settings = readRoster(dir);
95
+ const text = moduleText(settings);
96
+ const out = join(dir, ROSTER_MODULE);
97
+ if (check) {
98
+ if (!existsSync(out) || read(out) !== text) {
99
+ err(`${ROSTER_MODULE} is out of date: run npx workbench-roster generate`);
100
+ return 1;
101
+ }
102
+ log(`${ROSTER_MODULE} is up to date`);
103
+ return 0;
104
+ }
105
+ mkdirSync(dirname(out), { recursive: true });
106
+ writeFileSync(out, text);
107
+ log(`wrote ${ROSTER_MODULE}: ${Object.keys(settings.roles ?? {}).length} roles; changes ${settings.changes ?? "auto"}`);
108
+ return 0;
109
+ }
110
+ catch (e) {
111
+ err(e.message);
112
+ return 1;
113
+ }
114
+ }
115
+ const isMain = (() => {
116
+ try {
117
+ return process.argv[1] !== undefined && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
118
+ }
119
+ catch {
120
+ return false;
121
+ }
122
+ })();
123
+ if (isMain)
124
+ process.exitCode = run(process.argv.slice(2));
@@ -0,0 +1,9 @@
1
+ import { type RosterConfig } from "./types.ts";
2
+ /** At most this many roles, cover rules a day, and closed days. */
3
+ export declare const MAX_ROLES = 30;
4
+ export declare const MAX_RULES = 10;
5
+ export declare const MAX_CLOSED = 400;
6
+ /** Every problem with a roster.json, or none. */
7
+ export declare function rosterProblems(value: unknown, where?: string): string[];
8
+ /** Checks workbench/roster.json and returns it typed, or throws bad_config naming every problem. */
9
+ export declare function checkRosterConfig(value: unknown): RosterConfig;
package/dist/config.js ADDED
@@ -0,0 +1,103 @@
1
+ // workbench/roster.json: checked here, by createRoster and by
2
+ // `npx workbench-roster generate`.
3
+ import { RosterError } from "./errors.js";
4
+ import { clockMinutes, durationMinutes, validDate, validZone } from "./time.js";
5
+ import { WEEKDAYS } from "./types.js";
6
+ const TOP = ["$schema", "format", "time_zone", "week_starts", "roles", "cover", "closed", "changes", "changes_after", "retention_months"];
7
+ const RULE = ["from", "to", "role", "people"];
8
+ const NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
9
+ /** At most this many roles, cover rules a day, and closed days. */
10
+ export const MAX_ROLES = 30;
11
+ export const MAX_RULES = 10;
12
+ export const MAX_CLOSED = 400;
13
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
14
+ /** Every problem with a roster.json, or none. */
15
+ export function rosterProblems(value, where = "roster.json") {
16
+ const p = [];
17
+ if (!isObj(value))
18
+ return [`${where}: not a JSON object`];
19
+ for (const k of Object.keys(value))
20
+ if (!TOP.includes(k))
21
+ p.push(`${k} isn't a roster setting`);
22
+ if (value.format !== 1)
23
+ p.push("format must be 1");
24
+ if (!validZone(value.time_zone))
25
+ p.push("time_zone must be an IANA time zone, such as Australia/Sydney");
26
+ if (value.week_starts !== undefined && !WEEKDAYS.includes(value.week_starts))
27
+ p.push(`week_starts must be one of ${WEEKDAYS.join(", ")}`);
28
+ const roles = value.roles;
29
+ const roleNames = new Set();
30
+ if (roles !== undefined) {
31
+ if (!isObj(roles) || Object.keys(roles).length === 0 || Object.keys(roles).length > MAX_ROLES)
32
+ p.push(`roles must name 1 to ${MAX_ROLES} roles`);
33
+ else {
34
+ for (const [name, r] of Object.entries(roles)) {
35
+ if (!NAME.test(name))
36
+ p.push(`roles.${name}: a role's name is lower case letters, digits and -, up to 40`);
37
+ if (!isObj(r) || typeof r.title !== "string" || !r.title.trim() || r.title.length > 60)
38
+ p.push(`roles.${name}.title must be text, 1 to 60 characters`);
39
+ else
40
+ for (const k of Object.keys(r))
41
+ if (k !== "title")
42
+ p.push(`roles.${name}.${k} isn't a role setting`);
43
+ roleNames.add(name);
44
+ }
45
+ }
46
+ }
47
+ const cover = value.cover;
48
+ if (cover !== undefined) {
49
+ if (!isObj(cover))
50
+ p.push("cover must be an object of days");
51
+ else {
52
+ for (const [day, rules] of Object.entries(cover)) {
53
+ if (!WEEKDAYS.includes(day)) {
54
+ p.push(`cover.${day} isn't a day (${WEEKDAYS.join(", ")})`);
55
+ continue;
56
+ }
57
+ if (!Array.isArray(rules) || rules.length > MAX_RULES) {
58
+ p.push(`cover.${day} must be a list of up to ${MAX_RULES} rules`);
59
+ continue;
60
+ }
61
+ rules.forEach((r, i) => {
62
+ const at = `cover.${day}[${i}]`;
63
+ if (!isObj(r))
64
+ return void p.push(`${at} must be { from, to, role?, people? }`);
65
+ for (const k of Object.keys(r))
66
+ if (!RULE.includes(k))
67
+ p.push(`${at}.${k} isn't a cover setting`);
68
+ const a = clockMinutes(r.from);
69
+ const b = clockMinutes(r.to);
70
+ if (a === null || b === null)
71
+ p.push(`${at}: from and to are times such as "09:00"`);
72
+ else if (a === b)
73
+ p.push(`${at}: from and to are the same time`);
74
+ if (r.role !== undefined && !roleNames.has(r.role))
75
+ p.push(`${at}.role ${JSON.stringify(r.role)} isn't in roles`);
76
+ if (r.people !== undefined && (!Number.isInteger(r.people) || r.people < 1 || r.people > 50))
77
+ p.push(`${at}.people must be a whole number from 1 to 50`);
78
+ });
79
+ }
80
+ }
81
+ }
82
+ const closed = value.closed;
83
+ if (closed !== undefined && (!Array.isArray(closed) || closed.length > MAX_CLOSED || !closed.every(validDate)))
84
+ p.push(`closed must be a list of up to ${MAX_CLOSED} days, YYYY-MM-DD`);
85
+ if (value.changes !== undefined && value.changes !== "auto" && value.changes !== "manual")
86
+ p.push('changes must be "auto" or "manual"');
87
+ if (value.changes_after !== undefined) {
88
+ const m = durationMinutes(value.changes_after);
89
+ if (m === null || m < 5 || m > 1440)
90
+ p.push('changes_after must be a length from 5m to 1d, such as "1h"');
91
+ }
92
+ const r = value.retention_months;
93
+ if (r !== undefined && (!Number.isInteger(r) || r < 1 || r > 84))
94
+ p.push("retention_months must be a whole number from 1 to 84");
95
+ return p.map((x) => `${where}: ${x}`);
96
+ }
97
+ /** Checks workbench/roster.json and returns it typed, or throws bad_config naming every problem. */
98
+ export function checkRosterConfig(value) {
99
+ const problems = rosterProblems(value);
100
+ if (problems.length)
101
+ throw new RosterError("bad_config", problems.join("; "));
102
+ return value;
103
+ }
package/dist/csv.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { Lang, RosterConfig, Shift } from "./types.ts";
2
+ /** One cell, quoted and defused. */
3
+ export declare function csvCell(v: unknown): string;
4
+ /** Paid hours of a shift: its length less its break, to 2 decimals. */
5
+ export declare function paidHours(s: Pick<Shift, "starts_at" | "ends_at" | "break_minutes">): number;
6
+ export declare function hoursCsv(shifts: readonly Shift[], o: {
7
+ lang: Lang;
8
+ config: RosterConfig;
9
+ }): string;
package/dist/csv.js ADDED
@@ -0,0 +1,35 @@
1
+ // The hours export for the owner's own payroll: one row a shift, UTF-8 with a
2
+ // byte order mark so Excel reads ñ and other letters, and every cell that a
3
+ // spreadsheet would run as a formula (=, +, -, @, tab, return) starts with an
4
+ // apostrophe. Hours are paid hours (the shift less its break) to 2 decimals.
5
+ // No pay rates: the roster never holds pay.
6
+ import { clockIn, todayIn } from "./time.js";
7
+ import { ROSTER_WORDS } from "./words.js";
8
+ /** One cell, quoted and defused. */
9
+ export function csvCell(v) {
10
+ let s = v === null || v === undefined ? "" : String(v);
11
+ if (/^[=+\-@\t\r]/.test(s))
12
+ s = `'${s}`;
13
+ return /[",\r\n]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s;
14
+ }
15
+ /** Paid hours of a shift: its length less its break, to 2 decimals. */
16
+ export function paidHours(s) {
17
+ const minutes = (Date.parse(s.ends_at) - Date.parse(s.starts_at)) / 60_000 - s.break_minutes;
18
+ return Math.round(Math.max(0, minutes) * (100 / 60)) / 100;
19
+ }
20
+ export function hoursCsv(shifts, o) {
21
+ const w = ROSTER_WORDS[o.lang] ?? ROSTER_WORDS.en;
22
+ const tz = o.config.time_zone;
23
+ const role = (r) => (r ? (o.config.roles?.[r]?.title ?? r) : "");
24
+ const cols = [
25
+ ["csv.date", (s) => todayIn(tz, new Date(s.starts_at))],
26
+ ["csv.name", (s) => s.staff_name],
27
+ ["csv.role", (s) => role(s.role)],
28
+ ["csv.start", (s) => clockIn(tz, new Date(s.starts_at))],
29
+ ["csv.end", (s) => clockIn(tz, new Date(s.ends_at))],
30
+ ["csv.break", (s) => s.break_minutes],
31
+ ["csv.hours", (s) => paidHours(s).toFixed(2)],
32
+ ];
33
+ const lines = [cols.map(([k]) => csvCell(w[k])).join(","), ...shifts.map((s) => cols.map(([, cell]) => csvCell(cell(s))).join(","))];
34
+ return `${lines.join("\r\n")}\r\n`;
35
+ }
@@ -0,0 +1,23 @@
1
+ export type RosterErrorCode =
2
+ /** workbench/roster.json is out of shape. */
3
+ "bad_config"
4
+ /** A call's arguments are out of shape. */
5
+ | "bad_input"
6
+ /** No such person on this account's roster (or they were removed). */
7
+ | "unknown_staff"
8
+ /** No such shift or leave in this account. */
9
+ | "unknown_shift"
10
+ /** The person already has a shift at that time. Nothing was changed. */
11
+ | "clash"
12
+ /** The person is on leave then. Nothing was changed. */
13
+ | "on_leave"
14
+ /** Someone on the roster already has that email or bookings resource. */
15
+ | "taken"
16
+ /** Copying a week: the week copied into already has shifts. */
17
+ | "not_empty"
18
+ /** The database refused or failed. */
19
+ | "store_failed";
20
+ export declare class RosterError extends Error {
21
+ readonly code: RosterErrorCode;
22
+ constructor(code: RosterErrorCode, message: string);
23
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,10 @@
1
+ // Every failure carries a permanent code, so an app can act on it without
2
+ // reading the words.
3
+ export class RosterError extends Error {
4
+ code;
5
+ constructor(code, message) {
6
+ super(message);
7
+ this.name = "RosterError";
8
+ this.code = code;
9
+ }
10
+ }
@@ -0,0 +1,19 @@
1
+ import type { Lang } from "./types.ts";
2
+ import { type RosterWordKey } from "./words.ts";
3
+ /** The project's strings lookup: `t('ui.wbroster.week.publish')`. Undefined falls back to the words of `lang`. */
4
+ export type Words = (key: string, params?: Readonly<Record<string, string | number>>) => string | undefined;
5
+ export type Say = (key: RosterWordKey, params?: Readonly<Record<string, string | number>>) => string;
6
+ export declare function words(o: {
7
+ t?: Words;
8
+ lang?: Lang;
9
+ }): Say;
10
+ /** en-AU for English, fil-PH for Tagalog and Taglish, unless the app says. */
11
+ export declare const localeFor: (lang: Lang | undefined, locale?: string) => string;
12
+ /** "Saturday 6 December". A day (YYYY-MM-DD) is read at noon UTC, so it never slips a day. */
13
+ export declare function dayText(date: string, locale: string): string;
14
+ /** "6 December 2026". */
15
+ export declare function dateText(date: string, locale: string): string;
16
+ /** "9:00 am". */
17
+ export declare function timeText(iso: string, timeZone: string, locale: string): string;
18
+ /** "Saturday 6 December, 9:00 am to 12:00 pm". */
19
+ export declare function spanText(start: string, end: string, timeZone: string, locale: string): string;
package/dist/format.js ADDED
@@ -0,0 +1,31 @@
1
+ // Words, dates and times for people: the project's strings lookup over the
2
+ // package's words in the page's language, and dates on the business's clock
3
+ // in the project's locale (en-AU unless the app passes its country pack's).
4
+ import { ROSTER_WORDS } from "./words.js";
5
+ function fill(text, params = {}) {
6
+ return text.replace(/\{(\w+)\}/g, (m, k) => (Object.hasOwn(params, k) ? String(params[k]) : m));
7
+ }
8
+ export function words(o) {
9
+ const base = ROSTER_WORDS[o.lang ?? "en"] ?? ROSTER_WORDS.en;
10
+ return (key, params = {}) => o.t?.(`ui.wbroster.${key}`, params) ?? fill(base[key], params);
11
+ }
12
+ /** en-AU for English, fil-PH for Tagalog and Taglish, unless the app says. */
13
+ export const localeFor = (lang, locale) => locale ?? (lang && lang !== "en" ? "fil-PH" : "en-AU");
14
+ const fmt = (locale, timeZone, o) => new Intl.DateTimeFormat(locale, { timeZone, ...o });
15
+ /** "Saturday 6 December". A day (YYYY-MM-DD) is read at noon UTC, so it never slips a day. */
16
+ export function dayText(date, locale) {
17
+ return fmt(locale, "UTC", { weekday: "long", day: "numeric", month: "long" }).format(new Date(`${date}T12:00:00Z`));
18
+ }
19
+ /** "6 December 2026". */
20
+ export function dateText(date, locale) {
21
+ return fmt(locale, "UTC", { day: "numeric", month: "long", year: "numeric" }).format(new Date(`${date}T12:00:00Z`));
22
+ }
23
+ /** "9:00 am". */
24
+ export function timeText(iso, timeZone, locale) {
25
+ return fmt(locale, timeZone, { hour: "numeric", minute: "2-digit" }).format(new Date(iso));
26
+ }
27
+ /** "Saturday 6 December, 9:00 am to 12:00 pm". */
28
+ export function spanText(start, end, timeZone, locale) {
29
+ const day = fmt(locale, timeZone, { weekday: "long", day: "numeric", month: "long" }).format(new Date(start));
30
+ return `${day}, ${timeText(start, timeZone, locale)} – ${timeText(end, timeZone, locale)}`;
31
+ }
package/dist/gaps.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { type Clash, type CoverNeed, type Gap, type Leave, type RosterConfig, type Shift, type Staff } from "./types.ts";
2
+ interface Need {
3
+ start: number;
4
+ end: number;
5
+ role: string | null;
6
+ people: number;
7
+ title?: string;
8
+ }
9
+ /** The cover rules of a week as dated needs, closed days left out. */
10
+ export declare function coverNeeds(config: RosterConfig, days: readonly string[], closed?: readonly string[]): Need[];
11
+ /** Shifts whose person is on leave then, or no longer on the roster. */
12
+ export declare function clashes(shifts: readonly Shift[], leave: readonly Leave[], staff: readonly Staff[]): Clash[];
13
+ /** Every stretch of the week with fewer people on than needed. */
14
+ export declare function findGaps(o: {
15
+ config: RosterConfig;
16
+ days: readonly string[];
17
+ shifts: readonly Shift[];
18
+ leave: readonly Leave[];
19
+ staff: readonly Staff[];
20
+ needs?: readonly CoverNeed[];
21
+ closed?: readonly string[];
22
+ }): Gap[];
23
+ export {};
package/dist/gaps.js ADDED
@@ -0,0 +1,89 @@
1
+ // The gaps check: a week's shifts against who must be on (roster.json's
2
+ // cover, on the business's clock, and any dated needs the app passes, such as
3
+ // bookings' sessions). Pure code, no database: the store hands it the week.
4
+ //
5
+ // A shift counts for a need when it overlaps it, its role matches (a shift
6
+ // with no role counts for any role its person can work), and its person isn't
7
+ // on leave then. Each stretch where fewer are on than needed is one gap;
8
+ // stretches next to each other with the same shortfall are joined.
9
+ import { addDays, clockMinutes, localInstant, weekdayIndex } from "./time.js";
10
+ import { WEEKDAYS } from "./types.js";
11
+ const ms = (v) => (v instanceof Date ? v.getTime() : Date.parse(v));
12
+ /** The cover rules of a week as dated needs, closed days left out. */
13
+ export function coverNeeds(config, days, closed = []) {
14
+ const shut = new Set([...(config.closed ?? []), ...closed]);
15
+ const out = [];
16
+ for (const day of days) {
17
+ if (shut.has(day))
18
+ continue;
19
+ for (const r of config.cover?.[WEEKDAYS[weekdayIndex(day)]] ?? []) {
20
+ const overnight = (clockMinutes(r.to) ?? 0) <= (clockMinutes(r.from) ?? 0);
21
+ out.push({
22
+ start: localInstant(day, r.from, config.time_zone).getTime(),
23
+ end: localInstant(overnight ? addDays(day, 1) : day, r.to, config.time_zone).getTime(),
24
+ role: r.role ?? null,
25
+ people: r.people ?? 1,
26
+ });
27
+ }
28
+ }
29
+ return out;
30
+ }
31
+ const onLeave = (s, leave) => leave.some((l) => l.staff === s.staff && Date.parse(l.starts_at) < Date.parse(s.ends_at) && Date.parse(l.ends_at) > Date.parse(s.starts_at));
32
+ /** Shifts whose person is on leave then, or no longer on the roster. */
33
+ export function clashes(shifts, leave, staff) {
34
+ const active = new Set(staff.filter((s) => s.active).map((s) => s.id));
35
+ const out = [];
36
+ for (const s of shifts) {
37
+ if (!active.has(s.staff))
38
+ out.push({ shift: s, reason: "removed" });
39
+ else if (onLeave(s, leave))
40
+ out.push({ shift: s, reason: "on_leave" });
41
+ }
42
+ return out;
43
+ }
44
+ /** Every stretch of the week with fewer people on than needed. */
45
+ export function findGaps(o) {
46
+ const roles = new Map(o.staff.filter((s) => s.active).map((s) => [s.id, s.roles]));
47
+ const working = o.shifts.filter((s) => roles.has(s.staff) && !onLeave(s, o.leave));
48
+ const extra = (o.needs ?? []).map((n) => {
49
+ const start = ms(n.start);
50
+ const end = ms(n.end);
51
+ if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start)
52
+ throw new Error("a cover need has a start before its end");
53
+ return { start, end, role: n.role ?? null, people: n.people ?? 1, ...(n.title ? { title: n.title } : {}) };
54
+ });
55
+ const gaps = [];
56
+ for (const need of [...coverNeeds(o.config, o.days, o.closed), ...extra]) {
57
+ const fits = working.filter((s) => {
58
+ if (Date.parse(s.starts_at) >= need.end || Date.parse(s.ends_at) <= need.start)
59
+ return false;
60
+ if (need.role === null)
61
+ return true;
62
+ return s.role === need.role || (s.role === null && (roles.get(s.staff) ?? []).includes(need.role));
63
+ });
64
+ const cuts = new Set([need.start, need.end]);
65
+ for (const s of fits)
66
+ for (const t of [Date.parse(s.starts_at), Date.parse(s.ends_at)])
67
+ if (t > need.start && t < need.end)
68
+ cuts.add(t);
69
+ const points = [...cuts].sort((a, b) => a - b);
70
+ let open = null;
71
+ for (let i = 0; i < points.length - 1; i++) {
72
+ const a = points[i];
73
+ const b = points[i + 1];
74
+ // People on for the whole stretch (each person once, however many shifts).
75
+ const on = new Set(fits.filter((s) => Date.parse(s.starts_at) <= a && Date.parse(s.ends_at) >= b).map((s) => s.staff)).size;
76
+ if (on >= need.people) {
77
+ open = null;
78
+ continue;
79
+ }
80
+ if (open && open.rostered === on && Date.parse(open.end) === a) {
81
+ open.end = new Date(b).toISOString();
82
+ continue;
83
+ }
84
+ open = { start: new Date(a).toISOString(), end: new Date(b).toISOString(), role: need.role, needed: need.people, rostered: on, ...(need.title ? { title: need.title } : {}) };
85
+ gaps.push(open);
86
+ }
87
+ }
88
+ return gaps.sort((x, y) => Date.parse(x.start) - Date.parse(y.start) || (x.role ?? "").localeCompare(y.role ?? ""));
89
+ }
package/dist/ical.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import type { Shift } from "./types.ts";
2
+ /** What a shift's event says: "Instructor · Riverside Swim School". */
3
+ export type ShiftTitle = (s: Shift) => string;
4
+ /** A person's shifts as one calendar file. */
5
+ export declare function shiftsIcs(shifts: readonly Shift[], title: ShiftTitle, now?: Date): string;
6
+ /** Shifts taken off a person, as a cancelling calendar file, so a calendar app that has them takes them off. */
7
+ export declare function cancelIcs(gone: readonly Pick<Shift, "id" | "starts_at" | "ends_at" | "sequence">[], summary: string, now?: Date): string;
8
+ /** A person's feed: every published shift from 30 days ago. */
9
+ export declare function feedIcs(shifts: readonly Shift[], title: ShiftTitle, name: string, now?: Date): string;
package/dist/ical.js ADDED
@@ -0,0 +1,57 @@
1
+ // Calendar files (RFC 5545): a person's shifts for a week, attached to the
2
+ // roster email, the shifts taken off them (METHOD:CANCEL), and their own
3
+ // read-only feed of published shifts, which they subscribe to in Google
4
+ // Calendar, Outlook or Apple Calendar. Only the role, the business and the
5
+ // owner's note go in: never anyone else's name.
6
+ /** RFC 5545 TEXT: backslash, semicolon and comma escaped, line breaks as \n. */
7
+ const text = (s) => s.replace(/[\\;,]/g, (c) => `\\${c}`).replace(/\r?\n|\r/g, "\\n");
8
+ const utc = (iso) => new Date(iso).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}/, "");
9
+ /** Folds a content line at 75 octets, as RFC 5545 asks, never inside a character. */
10
+ function fold(line) {
11
+ const enc = new TextEncoder();
12
+ const out = [];
13
+ let rest = line;
14
+ while (enc.encode(rest).length > 75) {
15
+ let cut = Math.min(rest.length, 75);
16
+ while (enc.encode(rest.slice(0, cut)).length > 75)
17
+ cut--;
18
+ if (/[\uD800-\uDBFF]/.test(rest[cut - 1] ?? ""))
19
+ cut--;
20
+ out.push(rest.slice(0, cut));
21
+ rest = ` ${rest.slice(cut)}`;
22
+ }
23
+ out.push(rest);
24
+ return out.join("\r\n");
25
+ }
26
+ function vevent(s, summary, stamp, cancelled) {
27
+ return [
28
+ "BEGIN:VEVENT",
29
+ `UID:${s.id}@workbench-roster`,
30
+ `DTSTAMP:${stamp}`,
31
+ `SEQUENCE:${s.sequence}`,
32
+ `DTSTART:${utc(s.starts_at)}`,
33
+ `DTEND:${utc(s.ends_at)}`,
34
+ `SUMMARY:${text(summary)}`,
35
+ ...(s.note ? [`DESCRIPTION:${text(s.note)}`] : []),
36
+ `STATUS:${cancelled ? "CANCELLED" : "CONFIRMED"}`,
37
+ "TRANSP:OPAQUE",
38
+ "END:VEVENT",
39
+ ];
40
+ }
41
+ const wrap = (lines) => `${lines.map(fold).join("\r\n")}\r\n`;
42
+ const head = (method, name) => ["BEGIN:VCALENDAR", "VERSION:2.0", "PRODID:-//Workbench//workbench-roster//EN", "CALSCALE:GREGORIAN", `METHOD:${method}`, ...(name ? [`X-WR-CALNAME:${text(name)}`] : [])];
43
+ /** A person's shifts as one calendar file. */
44
+ export function shiftsIcs(shifts, title, now = new Date()) {
45
+ const stamp = utc(now.toISOString());
46
+ return wrap([...head("PUBLISH"), ...shifts.flatMap((s) => vevent(s, title(s), stamp, false)), "END:VCALENDAR"]);
47
+ }
48
+ /** Shifts taken off a person, as a cancelling calendar file, so a calendar app that has them takes them off. */
49
+ export function cancelIcs(gone, summary, now = new Date()) {
50
+ const stamp = utc(now.toISOString());
51
+ return wrap([...head("CANCEL"), ...gone.flatMap((s) => vevent({ ...s, sequence: s.sequence + 1, note: null }, summary, stamp, true)), "END:VCALENDAR"]);
52
+ }
53
+ /** A person's feed: every published shift from 30 days ago. */
54
+ export function feedIcs(shifts, title, name, now = new Date()) {
55
+ const stamp = utc(now.toISOString());
56
+ return wrap([...head("PUBLISH", name), "REFRESH-INTERVAL;VALUE=DURATION:PT1H", "X-PUBLISHED-TTL:PT1H", ...shifts.flatMap((s) => vevent(s, title(s), stamp, false)), "END:VCALENDAR"]);
57
+ }
@@ -0,0 +1,14 @@
1
+ export { createRoster, type Roster, type RosterClient, type RosterMailer, type RosterOptions, type ShiftInput, type StaffInput } from "./roster.ts";
2
+ export { checkRosterConfig, MAX_CLOSED, MAX_ROLES, MAX_RULES, rosterProblems } from "./config.ts";
3
+ export { clashes, coverNeeds, findGaps } from "./gaps.ts";
4
+ export { cancelIcs, feedIcs, shiftsIcs, type ShiftTitle } from "./ical.ts";
5
+ export { csvCell, hoursCsv, paidHours } from "./csv.ts";
6
+ export { rosterMigration } from "./migration.ts";
7
+ export { STARTER_ROSTER } from "./starters.ts";
8
+ export { renderMyShifts, renderStaff, renderWeek, rosterAction, type ActionResult, type MineOptions, type RosterDone, type StaffOptions, type WeekOptions } from "./ui.ts";
9
+ export { type Words } from "./format.ts";
10
+ export { ROSTER_WORDS, ROSTER_WORD_KEYS, type RosterWordKey } from "./words.ts";
11
+ export { ROSTER_STYLES } from "./styles.ts";
12
+ export { RosterError, type RosterErrorCode } from "./errors.ts";
13
+ export { WEEKDAYS } from "./types.ts";
14
+ export type { Clash, CoverNeed, CoverRule, Duration, Gap, Lang, Leave, ResourceTimes, RosterConfig, RosterRole, Shift, Staff, TickResult, Weekday, WeekState, WeekView } from "./types.ts";