@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 ADDED
@@ -0,0 +1,15 @@
1
+ # @mccaskie-labs/workbench-roster
2
+
3
+ ## 0.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - The roster asks "Are you sure?" first. Take off the roster (`renderStaff`) no longer has a tick box: it opens a question that names the person and says their shifts from now on, their leave and their link go and that they're emailed, with "Yes, take {name} off" and "No, keep them on the roster". Email them their link asks first and says the old link and calendar feed stop; removing leave asks first and says the person is emailed; Publish and Send the changes (`renderWeek`) ask first and say how many people get the email; removing a shift asks first on a published week (one click on a draft). Each is a `<details>`, so it works with no script.
8
+ - **Breaking:** `rosterAction`'s `publish`, `remove_staff`, `send_link`, `remove_leave`, and `remove_shift` for a shift in a published week (or one it can't find in the posted `week`) refuse a post without `confirm=yes` with the new failure `confirm_needed` (409, "Please confirm first. Nothing has changed."). `remove_staff` without it was `bad_input` (400). A page that draws its own one-click button must ask first and post `confirm=yes`. The store methods are unchanged and need no flag.
9
+ - With a mailer, the person taken off the roster is now emailed (`roster.removed`): what happened, the shifts they lose with a cancelling calendar file, and that their page and feed stop. Removing leave emails the person which days are off the roster (`roster.leave_removed`). A failed email never fails the change.
10
+ - `roster.week()` answers `emailing`: how many people Publish or Send the changes would email now (0 without a mailer). `renderWeek` uses it in the question; a `WeekView` without it gets words with no number.
11
+ - `renderConfirm`, `confirmed` and `ConfirmOptions` are exported for an app's own pages. New words `confirm.no`, `error.confirm_needed`, `shift.remove.question`, `.consequence`, `.consequence_manual`, `.consequence_gone` and `.yes`, `week.publish.question`, `.consequence`, `.consequence_one`, `.consequence_none`, `.consequence_all`, `.yes` and `.no`, `week.send.question`, `.consequence`, `.consequence_one`, `.consequence_none`, `.consequence_all` and `.yes`, `staff.link.question`, `.consequence`, `.consequence_first`, `.yes` and `.no`, `staff.remove.question`, `.consequence`, `.yes` and `.no`, `leave.remove.question`, `.consequence` and `.yes`, and `email.removed.subject`, `.body` and `.next` and `email.leave_removed.subject`, `.body` and `.next`; `staff.remove_confirm` is gone. New classes `wb-roster-confirm` (now the question's `<details>`), `-confirm-open`, `-confirm-ask`, `-confirm-keep`, `-confirm-form`, `-confirm-question`, `-confirm-consequence` and `-confirm-yes`. The role tick boxes' label is now `wb-roster-tick` (it was `wb-roster-confirm`); `wb-roster-remove-form` is a `<div>`, and `wb-roster-danger`, `wb-roster-publish`, and `wb-roster-remove` and `wb-roster-secondary` where they ask first, are on the `<summary>` that opens the question.
12
+
13
+ ## 0.1.0
14
+
15
+ - 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,58 @@
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
+ // publish, remove_staff, send_link, remove_leave, and remove_shift on a published week need confirm=yes
36
+ // (the "Are you sure?" button sends it); without it the answer is confirm_needed (409) and nothing changes.
37
+
38
+ // A person's own page and feed, by their secret (sent with roster.sendLink):
39
+ html(renderMyShifts((await roster.mine(token))!, { config: roster.config, feedUrl: `webcal://${host}/roster/feed/${token}.ics` }))
40
+ new Response(await roster.feed(token), { headers: { 'content-type': 'text/calendar; charset=utf-8' } })
41
+
42
+ // Customers book a person only inside a published shift, never on leave:
43
+ createBookings({ ..., settings: async (account) => ({ resources: await roster.hoursFor(account) }) })
44
+
45
+ // The owner's payroll spreadsheet:
46
+ await roster.exportHours(account, { from: '2026-11-30', to: '2026-12-06' })
47
+
48
+ // scheduled(): tick() every 15 minutes, cleanup() once a day.
49
+ ctx.waitUntil(roster.tick())
50
+ ```
51
+
52
+ ## Restyling
53
+
54
+ 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`.
55
+
56
+ ## Words
57
+
58
+ `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
+ }
@@ -0,0 +1,60 @@
1
+ export interface ConfirmOptions {
2
+ /** The tool's class prefix, without the trailing dash: "wb-booking". */
3
+ prefix: string;
4
+ /** Where the form posts. */
5
+ endpoint: string;
6
+ /** The hidden fields that say what to do: action, the thing's id or token. */
7
+ fields: Readonly<Record<string, string>>;
8
+ /** The first button's words: "Cancel". */
9
+ ask: string;
10
+ /** The first button's class, so it keeps the look it has in the tool's styles. */
11
+ askClass: string;
12
+ /** The question, naming the thing: "Cancel Sam's booking for Yoga on Monday 7 December at 6:00 pm?" */
13
+ question: string;
14
+ /** What happens next and who is told: "We'll email Sam to say it's cancelled." */
15
+ consequence?: string;
16
+ /** The button that does it, in its own words: "Yes, cancel this booking". */
17
+ yes: string;
18
+ /** The words that close the question again: "No, keep it". */
19
+ no: string;
20
+ /** A reason to send with it, when the action takes one. */
21
+ reason?: {
22
+ label: string;
23
+ name?: string;
24
+ maxlength?: number;
25
+ required?: boolean;
26
+ };
27
+ /** For deleting a lot at once: a word the person must type before the button works. */
28
+ type?: {
29
+ label: string;
30
+ word: string;
31
+ };
32
+ /** More fields for the question's form, as HTML the tool has already escaped (a second box, a choice). Drawn above the button. */
33
+ extra?: string;
34
+ /** Draw the question already showing: the page was drawn again to ask it. */
35
+ open?: boolean;
36
+ }
37
+ /** The button and its question. */
38
+ export declare function renderConfirm(o: ConfirmOptions): string;
39
+ /** Whether a post answered the question: confirm=yes and, where a word had to be typed, that word. */
40
+ export declare function confirmed(body: Readonly<Record<string, unknown>>, word?: string): boolean;
41
+ interface ConfirmStyle {
42
+ name: string;
43
+ element: string;
44
+ about: string;
45
+ css: string;
46
+ states?: readonly {
47
+ selector: string;
48
+ about: string;
49
+ css: string;
50
+ }[];
51
+ }
52
+ /**
53
+ * The question's classes with their default rules, for the tool's styles.
54
+ * `v` reads one of the tool's own variables (text, muted, line, sunk, surface,
55
+ * radius, danger, on-danger, focus).
56
+ */
57
+ export declare function confirmStyles(prefix: string, v: (name: string) => string, o?: {
58
+ reason?: boolean;
59
+ }): ConfirmStyle[];
60
+ export {};
@@ -0,0 +1,85 @@
1
+ // "Are you sure?" for the actions that cancel, decline or delete
2
+ // (docs/critical-actions-audit.md, "The standard"). The button a person presses first only opens
3
+ // the question: what is about to happen, named in full, and who will be told.
4
+ // The second button does it. It is a <details>, so it works with no script,
5
+ // and the post carries confirm=yes, which the action helpers insist on: a page
6
+ // that draws its own one-click button is refused with `confirm_needed`.
7
+ //
8
+ // This file is the same in every tool that asks (only the prefix differs), so
9
+ // a project restyles each tool's question by that tool's own class names.
10
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
11
+ const pattern = (word) => word.replace(/[.*+?^${}()|[\]\\\/-]/g, "\\$&");
12
+ /** The button and its question. */
13
+ export function renderConfirm(o) {
14
+ const p = o.prefix;
15
+ const hidden = Object.entries({ ...o.fields, confirm: "yes" })
16
+ .map(([k, v]) => `<input type="hidden" name="${esc(k)}" value="${esc(v)}">`)
17
+ .join("");
18
+ const reason = o.reason
19
+ ? `<label class="${p}-confirm-field"><span class="${p}-confirm-label">${esc(o.reason.label)}</span><input class="${p}-confirm-input" type="text" name="${esc(o.reason.name ?? "reason")}" maxlength="${o.reason.maxlength ?? 200}"${o.reason.required ? " required" : ""}></label>`
20
+ : "";
21
+ const type = o.type
22
+ ? `<label class="${p}-confirm-field"><span class="${p}-confirm-label">${esc(o.type.label)}</span><input class="${p}-confirm-input" type="text" name="confirm_word" required pattern="${esc(pattern(o.type.word))}" autocomplete="off" autocapitalize="off" spellcheck="false"></label>`
23
+ : "";
24
+ return `<details class="${p}-confirm"${o.open ? " open" : ""}><summary class="${p}-confirm-open ${esc(o.askClass)}"><span class="${p}-confirm-ask">${esc(o.ask)}</span><span class="${p}-confirm-keep">${esc(o.no)}</span></summary><form class="${p}-confirm-form" method="post" action="${esc(o.endpoint)}">${hidden}<p class="${p}-confirm-question">${esc(o.question)}</p>${o.consequence ? `<p class="${p}-confirm-consequence">${esc(o.consequence)}</p>` : ""}${reason}${o.extra ?? ""}${type}<button class="${p}-confirm-yes" type="submit">${esc(o.yes)}</button></form></details>`;
25
+ }
26
+ /** Whether a post answered the question: confirm=yes and, where a word had to be typed, that word. */
27
+ export function confirmed(body, word) {
28
+ if (body.confirm !== "yes" && body.confirm !== true)
29
+ return false;
30
+ return word === undefined || (typeof body.confirm_word === "string" && body.confirm_word.trim() === word);
31
+ }
32
+ /**
33
+ * The question's classes with their default rules, for the tool's styles.
34
+ * `v` reads one of the tool's own variables (text, muted, line, sunk, surface,
35
+ * radius, danger, on-danger, focus).
36
+ */
37
+ export function confirmStyles(prefix, v, o = {}) {
38
+ const focus = { selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` };
39
+ return [
40
+ {
41
+ name: `${prefix}-confirm`,
42
+ element: "details",
43
+ about: "A button that asks \"Are you sure?\" before it cancels, declines or deletes",
44
+ css: "display:block",
45
+ states: [
46
+ { selector: `[open]`, about: "The question is showing", css: `display:flex;flex-direction:column;align-items:flex-start;gap:.75rem;box-sizing:border-box;width:100%;padding:1rem;background:${v("sunk")};border:1px solid ${v("line")};border-radius:${v("radius")}` },
47
+ { selector: `[open] > summary`, about: "\"No, keep it\" sits under the button that does it", css: "order:2" },
48
+ { selector: `[open] .${prefix}-confirm-ask`, about: "The first button's words, hidden while the question shows", css: "display:none" },
49
+ { selector: `[open] .${prefix}-confirm-keep`, about: "\"No, keep it\", shown while the question shows", css: "display:inline" },
50
+ ],
51
+ },
52
+ {
53
+ name: `${prefix}-confirm-open`,
54
+ element: "summary",
55
+ about: "The first button: it only opens the question",
56
+ css: "list-style:none",
57
+ states: [{ selector: "::-webkit-details-marker", about: "No arrow beside the button", css: "display:none" }],
58
+ },
59
+ { name: `${prefix}-confirm-ask`, element: "span", about: "The first button's words", css: "display:inline" },
60
+ { name: `${prefix}-confirm-keep`, element: "span", about: "\"No, keep it\": closes the question", css: `display:none;color:${v("text")}` },
61
+ { name: `${prefix}-confirm-form`, element: "form", about: "The question and the button that does it", css: "display:grid;gap:.75rem;justify-items:start;width:100%" },
62
+ { name: `${prefix}-confirm-question`, element: "p", about: "What is about to happen, naming the thing", css: `margin:0;font-weight:600;color:${v("text")}` },
63
+ { name: `${prefix}-confirm-consequence`, element: "p", about: "What happens next and who is told", css: `margin:0;color:${v("muted")}` },
64
+ ...(o.reason
65
+ ? [
66
+ { name: `${prefix}-confirm-field`, element: "label", about: "The reason, or the word to type", css: "display:grid;gap:.25rem;width:100%" },
67
+ { name: `${prefix}-confirm-label`, element: "span", about: "What to type there", css: `color:${v("muted")}` },
68
+ {
69
+ name: `${prefix}-confirm-input`,
70
+ element: "input",
71
+ about: "Where it is typed",
72
+ css: `box-sizing:border-box;width:100%;min-height:2.75rem;padding:.5rem .75rem;font:inherit;color:${v("text")};background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")}`,
73
+ states: [focus],
74
+ },
75
+ ]
76
+ : []),
77
+ {
78
+ name: `${prefix}-confirm-yes`,
79
+ element: "button",
80
+ about: "The button that does it",
81
+ css: `display:inline-flex;align-items:center;justify-content:center;min-height:2.75rem;padding:0 1rem;font:inherit;font-weight:600;border-radius:${v("radius")};cursor:pointer;color:${v("on-danger")};background:${v("danger")};border:1px solid ${v("danger")}`,
82
+ states: [focus],
83
+ },
84
+ ];
85
+ }
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,25 @@
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
+ /** Publishing, taking someone off, emailing a new link, removing leave, or removing a shift from a published week arrived without the answer to "Are you sure?" (confirm=yes). Nothing was changed. */
19
+ | "confirm_needed"
20
+ /** The database refused or failed. */
21
+ | "store_failed";
22
+ export declare class RosterError extends Error {
23
+ readonly code: RosterErrorCode;
24
+ constructor(code: RosterErrorCode, message: string);
25
+ }
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 {};