@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/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,15 @@
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 { confirmed, renderConfirm, type ConfirmOptions } from "./confirm.ts";
10
+ export { type Words } from "./format.ts";
11
+ export { ROSTER_WORDS, ROSTER_WORD_KEYS, type RosterWordKey } from "./words.ts";
12
+ export { ROSTER_STYLES } from "./styles.ts";
13
+ export { RosterError, type RosterErrorCode } from "./errors.ts";
14
+ export { WEEKDAYS } from "./types.ts";
15
+ export type { Clash, CoverNeed, CoverRule, Duration, Gap, Lang, Leave, ResourceTimes, RosterConfig, RosterRole, Shift, Staff, TickResult, Weekday, WeekState, WeekView } from "./types.ts";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ // @mccaskie-labs/workbench-roster: a staff roster. Staff, shifts and leave in
2
+ // the app's own database (rosterMigration). The owner builds a week and
3
+ // publishes it; each person is emailed their shifts with a calendar file and
4
+ // has their own page and feed; later changes are emailed to the people they
5
+ // touch. A gaps check compares the week with who must be on. hoursFor() is
6
+ // what the app passes to workbench-bookings' settings option, so nobody is
7
+ // booked outside a shift; exportHours() is a spreadsheet for the owner's own
8
+ // payroll. tick() from the app's cron; no AI and no pay.
9
+ export { createRoster } from "./roster.js";
10
+ export { checkRosterConfig, MAX_CLOSED, MAX_ROLES, MAX_RULES, rosterProblems } from "./config.js";
11
+ export { clashes, coverNeeds, findGaps } from "./gaps.js";
12
+ export { cancelIcs, feedIcs, shiftsIcs } from "./ical.js";
13
+ export { csvCell, hoursCsv, paidHours } from "./csv.js";
14
+ export { rosterMigration } from "./migration.js";
15
+ export { STARTER_ROSTER } from "./starters.js";
16
+ export { renderMyShifts, renderStaff, renderWeek, rosterAction } from "./ui.js";
17
+ export { confirmed, renderConfirm } from "./confirm.js";
18
+ export {} from "./format.js";
19
+ export { ROSTER_WORDS, ROSTER_WORD_KEYS } from "./words.js";
20
+ export { ROSTER_STYLES } from "./styles.js";
21
+ export { RosterError } from "./errors.js";
22
+ export { WEEKDAYS } from "./types.js";
@@ -0,0 +1,4 @@
1
+ export declare const rosterMigration: {
2
+ up: string;
3
+ down: string;
4
+ };