diff --git a/.changeset/35355-working-calendar-service.md b/.changeset/35355-working-calendar-service.md new file mode 100644 index 00000000000..7a695c8e35e --- /dev/null +++ b/.changeset/35355-working-calendar-service.md @@ -0,0 +1,19 @@ +--- +'@objectstack/spec': patch +'@objectstack/formula': patch +'@objectstack/objectql': patch +'@objectstack/core': patch +--- + +feat: the working-calendar service, its arithmetic and its refusal codes (ADR-0157, part one of two) + +Clause-②: yes (widening) +Metadata-protocol: none + +Not released alone; pair #35641/#35642. This ships in the same release as #35642 (the calendar objects and Setup pages, the second half of this change), the working-day formula functions (#35356) and the approval escalation's working-time clock (#35357), ADR-0157 D4. + +- **The arithmetic** (`@objectstack/formula`). `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` compute over a resolved calendar and its dated exceptions, as pure functions a formula can call synchronously, beside `parseWorkPeriods` (`HH:mm-HH:mm` periods; a period that crosses midnight is refused, `24:00` is a legal end), `buildWorkCalendar` (a frozen calendar) and the three error classes. A computation that needs a date outside the calendar's maintained span is refused rather than read from the weekly pattern. +- **The types, constants and time-zone rule** (`@objectstack/spec`). `WorkCalendar` and the column and code constants are in `@objectstack/spec/data`; the service contract is `IWorkCalendarService` in `@objectstack/spec/contracts`. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move to `@objectstack/spec/data` from `@objectstack/core`, unchanged; `@objectstack/core` re-exports all three, so no import changes. +- **Three error codes** in the ADR-0112 ledger: `ERR_WORK_CALENDAR_UNRESOLVED` (no calendar by that code, no organization default, two defaults, or no organization named outside the `single` posture), `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`, each a 400. +- **The calendar service** (`@objectstack/objectql`, registered as `work-calendar`). `resolve({ organizationId, calendar })` takes the named code, else the organization default, else refuses; it never falls back to wall-clock time. It reads in the organization the caller names, elevated, and caches until a calendar or exception row is written. Outside the `single` tenancy posture, a computation that names no organization is refused before any read. Until the calendar objects are registered it refuses every resolution. +- **The write door** (`@objectstack/objectql`). Once the calendar objects exist, a calendar or exception write is refused `400 VALIDATION_FAILED` when a period crosses midnight, is malformed or overlaps another, an `off` row carries periods or an `on` row carries none, `maintained_through` is before `maintained_from`, a second calendar is marked the default, or a calendar created in an organization other than the one being worked in is marked the default (create it there, or set the default by an update); a calendar created without `timezone` takes the organization's Localization time zone. The hooks take the organization from the session. diff --git a/content/docs/references/api/automation-api.mdx b/content/docs/references/api/automation-api.mdx index 596e2265f48..a26d4f41730 100644 --- a/content/docs/references/api/automation-api.mdx +++ b/content/docs/references/api/automation-api.mdx @@ -424,7 +424,7 @@ const result = AutomationApiErrorCode.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +372 more>` | ✅ | The inner refusal's code in its WIRE spelling - the ADR-0112 member a record save of the same write answers in `error.code` (e.g. `UNIQUE_VIOLATION`); the closed set `ApiErrorSchema.code` parses against | | **message** | `string` | ✅ | The inner refusal's own diagnostic text, verbatim, without the node and operation prefixes the run's failure text adds | ### Allowed Values: `FlowInnerRefusal.code` @@ -575,6 +575,9 @@ const result = AutomationApiErrorCode.parse(data); * `ERR_SUMMARY_RECOMPUTE` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` +* `ERR_WORK_CALENDAR_INVALID` +* `ERR_WORK_CALENDAR_NOT_MAINTAINED` +* `ERR_WORK_CALENDAR_UNRESOLVED` * `EXECUTION_ERROR` * `EXPIRED_OR_REVOKED` * `EXPIRY_IN_PAST` diff --git a/content/docs/references/api/contract.mdx b/content/docs/references/api/contract.mdx index 61383d13513..f7f33ec7bb1 100644 --- a/content/docs/references/api/contract.mdx +++ b/content/docs/references/api/contract.mdx @@ -28,7 +28,7 @@ const result = ApiErrorSchema.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +369 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | +| **code** | `Enum<'VALIDATION_ERROR' \| 'INVALID_FIELD' \| 'MISSING_REQUIRED_FIELD' \| 'INVALID_FORMAT' \| 'VALUE_TOO_LONG' \| 'VALUE_TOO_SHORT' \| 'VALUE_OUT_OF_RANGE' \| … +372 more>` | ✅ | Error code (e.g. VALIDATION_ERROR; StandardErrorCode ∪ the ledger the serving side registers — ERROR_CODE_LEDGER for framework packages) | | **declaredCode** | `string` | optional | The producer-declared code, verbatim, when it is not a member of the closed `code` vocabulary — the open, author-authored channel (app-specific spellings; ADR-0112) | | **message** | `string` | ✅ | Readable error message | | **userMessage** | `string` | optional | Producer-marked user-facing refusal text, verbatim, in the request's locale: platform-composed text falls back to the workspace default locale, then `en`; an app-authored refusal falls back to its declared wording. Present exactly when the producer opted in at throw time; consumers render it to end users as received and keep their generic substitution for anything unmarked. Status-agnostic; never replaces `message`. | @@ -186,6 +186,9 @@ const result = ApiErrorSchema.parse(data); * `ERR_SUMMARY_RECOMPUTE` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` +* `ERR_WORK_CALENDAR_INVALID` +* `ERR_WORK_CALENDAR_NOT_MAINTAINED` +* `ERR_WORK_CALENDAR_UNRESOLVED` * `EXECUTION_ERROR` * `EXPIRED_OR_REVOKED` * `EXPIRY_IN_PAST` diff --git a/content/docs/references/api/error-code-ledger.mdx b/content/docs/references/api/error-code-ledger.mdx index 60681acb4c1..a4bd1b42695 100644 --- a/content/docs/references/api/error-code-ledger.mdx +++ b/content/docs/references/api/error-code-ledger.mdx @@ -353,6 +353,9 @@ const result = ErrorCode.parse(data); * `ERR_SUMMARY_RECOMPUTE` * `ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED` * `ERR_TRANSACTION_UNSUPPORTED` +* `ERR_WORK_CALENDAR_INVALID` +* `ERR_WORK_CALENDAR_NOT_MAINTAINED` +* `ERR_WORK_CALENDAR_UNRESOLVED` * `EXECUTION_ERROR` * `EXPIRED_OR_REVOKED` * `EXPIRY_IN_PAST` diff --git a/packages/core/src/utils/datetime.ts b/packages/core/src/utils/datetime.ts index 323d3b5aa0a..e8843f00bfc 100644 --- a/packages/core/src/utils/datetime.ts +++ b/packages/core/src/utils/datetime.ts @@ -16,6 +16,19 @@ * to avoid a layering dependency on core.) */ +/** + * [ADR-0157 D11, open point 3] The wall-clock → instant pair and its parts + * type live in `@objectstack/spec/data` (`wall-clock.ts`) — the platform's one + * daylight-saving rule, moved below `@objectstack/formula` so the working-day + * formula functions read the same rule as everything here, as + * `nextUtcCalendarDay` moved before it. Re-exported so this package's + * published surface and every import site are unchanged; this file's own + * helpers below build on them. + */ +import { wallClockToUtcMs, zonedWallClockToUtcMs } from '@objectstack/spec/data'; +export { wallClockToUtcMs, zonedWallClockToUtcMs } from '@objectstack/spec/data'; +export type { WallClockParts } from '@objectstack/spec/data'; + /** Calendar-day parts in a reference timezone. `month` is 1-12. */ export interface CalendarParts { year: number; @@ -23,47 +36,6 @@ export interface CalendarParts { day: number; } -/** - * A wall clock as a human writes it — calendar day plus an optional - * time-of-day, with **no zone attached**. `2026-08-01 06:00:00` is this shape: - * it names a reading on a clock, and only a reference timezone turns it into an - * instant. Omitted time components default to 0, so {@link CalendarParts} alone - * is midnight. - */ -export interface WallClockParts extends CalendarParts { - /** 0-23. */ - hour?: number; - minute?: number; - second?: number; - millisecond?: number; -} - -/** - * [#20599] The epoch milliseconds of a wall clock read as **UTC**: `Date.UTC` - * without its two-digit-year remap. The zone-free sibling of - * {@link zonedWallClockToUtcMs}, and the one construction this package and its - * callers use to build a UTC instant from year / month / day / time parts. - * - * Not `Date.UTC(year, …)` and not `new Date(year, …)`: both read a year from 0 - * to 99 as 1900 + year (ECMA-262 `MakeFullYear`), so `0050-01-01` is built as - * 1950-01-01 — while 0001..9999 is a `date`'s supported range ([#20280] a - * `datetime`'s is 1000..9999; `isOutsideTemporalYearRange`). - * `setUTCFullYear` takes the year as written. - * - * Every component rolls over past its end exactly as `Date.UTC` rolls it, and - * callers rely on that: `month: 13` is January of the next year, `month: 0` is - * December of the previous one, `day: 0` is the previous month's last day, - * `day: 32` runs into the next month, and `hour: 24` is the next day's - * midnight. Omitted time components default to 0. A `NaN` or non-finite - * component, or an instant outside the `Date` range, gives `NaN`, as - * `Date.UTC` does. - */ -export function wallClockToUtcMs(parts: WallClockParts): number { - const dt = new Date(0); - dt.setUTCFullYear(parts.year, parts.month - 1, parts.day); - return dt.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0); -} - /** * The year/month/day an instant falls on in `tz`. Throws if `tz` is not a * valid IANA zone (callers treat that as a fall-through to UTC). @@ -126,98 +98,6 @@ export function zonedDateStartToUtcMs(ymd: string, tz?: string): number { ); } -/** - * The UTC instant (epoch ms) at which a **wall clock** reading happens in - * reference timezone `tz` — the general inverse of {@link calendarPartsInTz}, - * of which {@link zonedDateStartToUtcMs} is the midnight special case. - * - * `2026-08-01 06:00:00` in `Asia/Shanghai` is `2026-07-31T22:00:00Z`: a - * different day, month and quarter. That gap is why this direction exists as a - * shared primitive at all — bulk import (#8485) reads offset-free spreadsheet - * cells, which are wall clocks and nothing more, and `new Date(cell)` resolves - * them against the **process** `TZ`, i.e. a host setting rather than the - * tenant's configured zone. - * - * DST-safe: the zone offset is read from the platform tz database via - * `Intl.DateTimeFormat` (never hand-computed), and a two-pass resolution settles - * the case where the offset differs side-to-side of the target instant. Two - * wall clocks are not a bijection with instants, and this function resolves - * both degenerate cases to the **earlier candidate instant** — in both, the - * final pass reads the offset on the DST side of the transition (measured, not - * merely intended — `datetime.test.ts` pins both): - * - a clock reading the zone **skips** (spring forward: `02:30` on a US - * spring-forward day) settles on the *post*-transition offset (EDT, −04), - * which places the instant just **before** the gap: it reads `01:30` EST - * locally, not `03:30` EDT. Note this is the opposite of Temporal's - * `'compatible'` disambiguation, which pushes a gap reading forward; - * - a clock reading that happens **twice** (fall back: `01:30` on a US - * fall-back day) resolves to its first occurrence, the one still on the - * pre-transition DST offset (EDT, −04). - * - * A spreadsheet cell naming a wall clock that its zone never had is ambiguous - * by construction; what matters for an import is that the answer is - * deterministic and host-independent, which both branches above are. - * - * FALLBACK — an unset, `'UTC'`, or invalid `tz` reads the wall clock **as UTC**, - * never as the process-local clock. Every caller of this family already degrades - * that way ({@link zonedDateStartToUtcMs}, and the export renderer's cell path), - * and a host `TZ` fallback would reintroduce exactly the deployment-dependent - * instant this primitive exists to remove. A parts object that produces an - * invalid date (`NaN` components) returns `NaN`, as `Date.UTC` does. - * - * [#20599] A year from 0001 to 0099 is read as written, never as 1900 + year: - * both the wall clock and the offset read below go through - * {@link wallClockToUtcMs}, not `Date.UTC`. The offset read takes the zone's - * year with its era, because `Intl`'s `year` part is an ERA year — 1 BC reads - * `1` — and the first probe for a wall clock early on 0001-01-01 in a zone - * west of UTC lands in year 0. - */ -export function zonedWallClockToUtcMs(parts: WallClockParts, tz?: string): number { - const wallAsUtc = wallClockToUtcMs(parts); - if (!tz || tz === 'UTC' || Number.isNaN(wallAsUtc)) return wallAsUtc; - try { - // The tz offset (local − UTC, in ms) at instant `t`: read t's wall clock in - // `tz`, re-interpret those parts as UTC, and subtract t. `formatToParts` - // resolves no finer than a second, so `t` is truncated to a whole second - // first — otherwise a sub-second wall clock leaks its milliseconds into the - // "offset" and shifts the answer by them (a real defect while generalising - // this from the date-only form, where ms was always 0). - const offsetAt = (t: number): number => { - const whole = Math.floor(t / 1000) * 1000; - const p = new Intl.DateTimeFormat('en-US', { - timeZone: tz, - hourCycle: 'h23', - era: 'short', - year: 'numeric', - month: '2-digit', - day: '2-digit', - hour: '2-digit', - minute: '2-digit', - second: '2-digit', - }).formatToParts(new Date(whole)); - const g = (k: string) => Number(p.find((x) => x.type === k)?.value); - const eraYear = g('year'); - const year = p.find((x) => x.type === 'era')?.value === 'BC' ? 1 - eraYear : eraYear; - return ( - wallClockToUtcMs({ - year, - month: g('month'), - day: g('day'), - hour: g('hour'), - minute: g('minute'), - second: g('second'), - }) - whole - ); - }; - // Want U such that localParts(U) == the wall clock, i.e. U = wallAsUtc − offset(U). - // Iterate from the zero-offset guess; converges in ≤2 steps off a DST edge. - const off1 = offsetAt(wallAsUtc - offsetAt(wallAsUtc)); - return wallAsUtc - off1; - } catch { - return wallAsUtc; // unknown zone → the wall clock read as UTC - } -} - /** * Calendar-day bound semantics (ADR-0053 D-D) now live in `@objectstack/spec`, * beside the date-macro vocabulary they give meaning to — the fifth consumer diff --git a/packages/formula/src/index.ts b/packages/formula/src/index.ts index d6edef720c0..783f21cc353 100644 --- a/packages/formula/src/index.ts +++ b/packages/formula/src/index.ts @@ -195,6 +195,26 @@ export type { FormulaReturnDeclaration, FormulaSourceField } from './formula-ret // number the engine stores. export { toScaledDecimal, divideToPlaces, formatScaledDecimal, documentDateOf } from './home-amount-arithmetic'; export type { ScaledDecimal } from './home-amount-arithmetic'; +// ADR-0157 — the working-calendar arithmetic: the calendar service +// (`@objectstack/objectql`) and the working-day formula functions count with +// this one copy, through the one daylight-saving rule. The codes, the column +// names and the `WorkCalendar` shape are `@objectstack/spec/data`'s. +export { + WorkCalendarUnresolvedError, + WorkCalendarNotMaintainedError, + WorkCalendarInvalidError, + isWorkCalendarRefusal, + parseWorkPeriods, + buildWorkCalendar, + exceptionDayOf, + calendarDayOf, + workingPeriodsOn, + isWorkingDay, + isWorkingTime, + addWorkingDays, + workingDaysBetween, + addWorkingHours, +} from './work-calendar'; // The closed set of refusal codes `validateExpression` and // `collectCelRootIdentifiers` carry beside their English message, with the // typed params each message interpolates — so a localized author surface keys diff --git a/packages/formula/src/work-calendar.test.ts b/packages/formula/src/work-calendar.test.ts new file mode 100644 index 00000000000..258e2b4ac00 --- /dev/null +++ b/packages/formula/src/work-calendar.test.ts @@ -0,0 +1,177 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { + WORK_CALENDAR_INVALID_CODE, + WORK_CALENDAR_NOT_MAINTAINED_CODE, + type WorkCalendar, +} from '@objectstack/spec/data'; +import { + addWorkingDays, + addWorkingHours, + buildWorkCalendar, + isWorkingDay, + isWorkingTime, + parseWorkPeriods, + workingDaysBetween, +} from './work-calendar'; + +// ADR-0157: the arithmetic over one resolved calendar. 2026-10-01 is a Thursday. +const WEEKDAY = '09:00-12:00, 13:00-18:00'; +const cnRow = { + code: 'cn_standard', + timezone: 'Asia/Shanghai', + maintained_from: '2026-01-01', + maintained_through: '2026-12-31', + monday_periods: WEEKDAY, + tuesday_periods: WEEKDAY, + wednesday_periods: WEEKDAY, + thursday_periods: WEEKDAY, + friday_periods: WEEKDAY, + saturday_periods: '', + sunday_periods: null, +}; +// A National Day week (seven `off` rows) and a 调休 make-up Saturday (an `on` row). +const nationalDay = ['01', '02', '03', '04', '05', '06', '07'].map((d) => ({ date: `2026-10-${d}`, kind: 'off' })); +const makeUpSaturday = { date: '2026-10-10', kind: 'on', periods: WEEKDAY }; +const cn = buildWorkCalendar(cnRow, [...nationalDay, makeUpSaturday]); +// CONTROL: the same calendar with no exceptions entered. +const bare = buildWorkCalendar(cnRow, []); + +/** Shanghai wall clock → instant (UTC+8, no DST). */ +const sh = (day: string, hm: string) => Date.parse(`${day}T${hm}:00+08:00`); + +describe('working calendar — exceptions override the weekly pattern (ADR-0157 D1, D10)', () => { + it('a 调休 make-up Saturday works its own periods; a plain Saturday does not (CONTROL)', () => { + expect(isWorkingDay(cn, '2026-10-10')).toBe(true); + expect(isWorkingDay(cn, '2026-10-17')).toBe(false); + expect(isWorkingDay(bare, '2026-10-10')).toBe(false); + expect(isWorkingTime(cn, sh('2026-10-10', '10:00'))).toBe(true); + expect(isWorkingTime(cn, sh('2026-10-10', '12:30'))).toBe(false); + expect(isWorkingTime(cn, new Date(sh('2026-10-17', '10:00')))).toBe(false); + }); + + it('a National Day week is off on every weekday it covers; the weekday pattern answers without it (CONTROL)', () => { + expect(isWorkingDay(cn, '2026-10-01')).toBe(false); + expect(isWorkingTime(cn, sh('2026-10-05', '10:00'))).toBe(false); + expect(isWorkingDay(bare, '2026-10-01')).toBe(true); + }); + + it('addWorkingDays steps over the holiday week and onto the make-up Saturday', () => { + expect(addWorkingDays(cn, '2026-09-30', 1)).toBe('2026-10-08'); + expect(addWorkingDays(cn, '2026-09-30', 3)).toBe('2026-10-10'); + expect(addWorkingDays(bare, '2026-09-30', 1)).toBe('2026-10-01'); + expect(addWorkingDays(cn, '2026-10-10', -3)).toBe('2026-09-30'); + expect(addWorkingDays(cn, '2026-10-03', 0)).toBe('2026-10-03'); + }); + + it('workingDaysBetween excludes the start, includes the end, and inverts addWorkingDays', () => { + expect(workingDaysBetween(cn, '2026-09-30', '2026-10-10')).toBe(3); + expect(workingDaysBetween(cn, '2026-10-10', '2026-09-30')).toBe(-3); + expect(workingDaysBetween(bare, '2026-09-30', '2026-10-10')).toBe(7); + for (const n of [-4, -1, 0, 1, 2, 5]) { + expect(workingDaysBetween(cn, '2026-10-09', addWorkingDays(cn, '2026-10-09', n))).toBe(n); + } + }); + + it('addWorkingHours runs across both, forward and backward', () => { + expect(addWorkingHours(cn, sh('2026-09-30', '17:00'), 2)).toBe(sh('2026-10-08', '10:00')); + expect(addWorkingHours(cn, sh('2026-10-09', '17:00'), 2)).toBe(sh('2026-10-10', '10:00')); + expect(addWorkingHours(cn, sh('2026-10-16', '17:00'), 2)).toBe(sh('2026-10-19', '10:00')); + expect(addWorkingHours(cn, sh('2026-10-08', '10:00'), -2)).toBe(sh('2026-09-30', '17:00')); + // A start outside working time begins at the next period; an answer on a period end is that end. + expect(addWorkingHours(cn, sh('2026-10-03', '08:00'), 1)).toBe(sh('2026-10-08', '10:00')); + expect(addWorkingHours(cn, sh('2026-10-08', '09:00'), 3)).toBe(sh('2026-10-08', '12:00')); + }); +}); + +describe('working calendar — the maintained span refuses (ADR-0157 D8)', () => { + it('a span past maintained_through is refused, never read from the weekly pattern', () => { + const run = () => addWorkingDays(cn, '2026-12-30', 3); + expect(run).toThrow(expect.objectContaining({ code: WORK_CALENDAR_NOT_MAINTAINED_CODE, status: 400, date: '2027-01-01' })); + expect(addWorkingDays(cn, '2026-12-29', 2)).toBe('2026-12-31'); // CONTROL: inside the span + expect(() => addWorkingHours(cn, sh('2026-12-31', '17:00'), 2)) + .toThrow(expect.objectContaining({ code: WORK_CALENDAR_NOT_MAINTAINED_CODE })); + }); + + it('a span reaching before maintained_from is refused the same way', () => { + expect(() => workingDaysBetween(cn, '2025-12-31', '2026-01-05')) + .toThrow(expect.objectContaining({ code: WORK_CALENDAR_NOT_MAINTAINED_CODE, date: '2025-12-31' })); + expect(() => isWorkingTime(cn, sh('2025-12-31', '10:00'))) + .toThrow(expect.objectContaining({ code: WORK_CALENDAR_NOT_MAINTAINED_CODE })); + expect(workingDaysBetween(cn, '2026-01-01', '2026-01-05')).toBe(2); // CONTROL + }); +}); + +describe('working calendar — periods (ADR-0157 D7, D10)', () => { + it('refuses a period that crosses midnight, at parse and when a stored row carries one', () => { + expect(parseWorkPeriods('22:00-06:00')).toMatchObject({ ok: false, reason: 'crosses_midnight' }); + expect(() => buildWorkCalendar({ ...cnRow, monday_periods: '22:00-06:00' }, [])) + .toThrow(expect.objectContaining({ code: WORK_CALENDAR_INVALID_CODE, status: 400, field: 'monday_periods' })); + }); + + it('accepts 24:00 as an end, and only as an end', () => { + expect(parseWorkPeriods('18:00-24:00')).toEqual({ ok: true, periods: [{ start: 1080, end: 1440 }] }); + expect(parseWorkPeriods('24:00-24:00')).toMatchObject({ ok: false, reason: 'malformed' }); + expect(parseWorkPeriods('18:00-24:30')).toMatchObject({ ok: false, reason: 'malformed' }); + const late = buildWorkCalendar({ ...cnRow, monday_periods: '18:00-24:00' }, []); + expect(isWorkingTime(late, sh('2026-10-12', '23:59'))).toBe(true); + expect(isWorkingTime(late, sh('2026-10-13', '00:00'))).toBe(false); + }); + + it('refuses overlapping, empty and malformed periods; blank is a day off', () => { + expect(parseWorkPeriods('09:00-12:00, 11:00-13:00')).toMatchObject({ ok: false, reason: 'overlap' }); + expect(parseWorkPeriods('09:00-09:00')).toMatchObject({ ok: false, reason: 'empty_period' }); + expect(parseWorkPeriods('9:00-12:00')).toMatchObject({ ok: false, reason: 'malformed' }); + expect(parseWorkPeriods('09:00-12:00,12:00-13:00')).toMatchObject({ ok: true }); + expect(parseWorkPeriods(' ')).toEqual({ ok: true, periods: [] }); + }); + + it('refuses an off row with periods, an on row without them, a duplicate date and a zone that is not IANA', () => { + const bad = (rows: Record[], row: Record = cnRow) => () => buildWorkCalendar(row, rows); + const invalid = expect.objectContaining({ code: WORK_CALENDAR_INVALID_CODE }); + expect(bad([{ date: '2026-10-01', kind: 'off', periods: '09:00-12:00' }])).toThrow(invalid); + expect(bad([{ date: '2026-10-10', kind: 'on', periods: '' }])).toThrow(invalid); + expect(bad([{ date: '2026-10-01', kind: 'off' }, { date: '2026-10-01', kind: 'off' }])).toThrow(invalid); + expect(bad([], { ...cnRow, timezone: 'Mars/Olympus' })).toThrow(expect.objectContaining({ field: 'timezone' })); + expect(bad([], { ...cnRow, maintained_through: '' })).toThrow(expect.objectContaining({ field: 'maintained_through' })); + }); +}); + +describe('working calendar — a transition day counts elapsed time (ADR-0157 D11)', () => { + // Every day 01:00-04:00 New York time: a three-hour clock face. + const ny: WorkCalendar = buildWorkCalendar({ + code: 'us_night', timezone: 'America/New_York', maintained_from: '2026-01-01', maintained_through: '2026-12-31', + monday_periods: '01:00-04:00', tuesday_periods: '01:00-04:00', wednesday_periods: '01:00-04:00', + thursday_periods: '01:00-04:00', friday_periods: '01:00-04:00', saturday_periods: '01:00-04:00', + sunday_periods: '01:00-04:00', + }, []); + + it('spring forward (2026-03-08): the period holds two hours, so half an hour spills into the next day', () => { + expect(addWorkingHours(ny, Date.parse('2026-03-08T06:00:00Z'), 2.5)).toBe(Date.parse('2026-03-09T05:30:00Z')); + // CONTROL: a week earlier the same period holds three hours. + expect(addWorkingHours(ny, Date.parse('2026-03-01T06:00:00Z'), 2.5)).toBe(Date.parse('2026-03-01T08:30:00Z')); + }); + + it('fall back (2026-11-01): the period holds four hours', () => { + expect(addWorkingHours(ny, Date.parse('2026-11-01T05:00:00Z'), 3.5)).toBe(Date.parse('2026-11-01T08:30:00Z')); + // CONTROL: a week later the same period holds three hours. + expect(addWorkingHours(ny, Date.parse('2026-11-08T06:00:00Z'), 3.5)).toBe(Date.parse('2026-11-09T06:30:00Z')); + expect(isWorkingTime(ny, Date.parse('2026-11-01T08:30:00Z'))).toBe(true); + }); +}); + +describe('working calendar — a built calendar cannot be changed by a reader', () => { + it('is frozen down to its periods, so one cached calendar answers every caller alike', () => { + expect(Object.isFrozen(cn)).toBe(true); + expect(Object.isFrozen(cn.weekly)).toBe(true); + expect(Object.isFrozen(cn.weekly[0])).toBe(true); + expect(Object.isFrozen(cn.weekly[0]![0])).toBe(true); + expect(Object.isFrozen(cn.exceptions)).toBe(true); + expect(Object.isFrozen(cn.exceptions['2026-10-10'])).toBe(true); + expect(Object.isFrozen(cn.exceptions['2026-10-10']!.periods)).toBe(true); + const exceptions = cn.exceptions as Record; + expect(() => { exceptions['2026-10-12'] = { kind: 'off', periods: [] }; }).toThrow(TypeError); + expect(isWorkingDay(cn, '2026-10-12')).toBe(true); + }); +}); diff --git a/packages/formula/src/work-calendar.ts b/packages/formula/src/work-calendar.ts new file mode 100644 index 00000000000..765ea819c13 --- /dev/null +++ b/packages/formula/src/work-calendar.ts @@ -0,0 +1,469 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Working-calendar arithmetic (ADR-0157): what a calendar's rows MEAN, as pure + * synchronous functions over one resolved calendar. + * + * ## Why this lives in the formula package + * + * ADR-0157 open point 3: there is exactly one daylight-saving rule (D11), and + * two readers count with a calendar: the calendar service + * (`WorkCalendarService`, `@objectstack/objectql`, which the approval clock + * reads) and the working-day formula functions, which evaluate synchronously + * over data pinned before evaluation. Both already depend on this package, so + * the arithmetic sits here and neither keeps a copy. The contract package + * keeps what it may hold (Prime Directive #2: schemas, types and constants + * only): the refusal codes, the column names, the {@link WorkCalendar} shape + * and the wall-clock primitive this module converts through + * (`zonedWallClockToUtcMs`, `@objectstack/spec/data`). Nothing here reads a + * row, a clock or a host zone: the service resolves, refuses and caches; this + * module only counts, and states what a stored row MEANS. + * + * ## The rows, as this module reads them (ADR-0157 D1, D7, D10) + * + * - A calendar carries one period list per weekday (`monday_periods` … + * `sunday_periods`, `WORK_CALENDAR_WEEKDAY_FIELDS`), each local + * `HH:mm-HH:mm` periods separated by commas; a blank weekday is not worked. + * - A period's end is later than its start on the same local day: a period + * that crosses midnight is refused (D7). `24:00` is a legal end (D10). The + * platform's `time` value refuses it, so the calendar validates its own + * periods ({@link parseWorkPeriods}). + * - An exception row overrides one date: `off` carries no periods and means + * the whole date is off; `on` carries that date's FULL periods and never + * borrows a weekday's (D10). One row per calendar and date. + * - `maintained_from` .. `maintained_through` is the span the organization + * keeps the calendar's exceptions for. A computation that needs a date + * outside it is refused ({@link WorkCalendarNotMaintainedError}): past the + * end is D8 (a missing next year must not read as "no holidays"), and before + * the start is the same refusal on the other side. There is no fallback to + * the weekly pattern alone and none to wall-clock time (D2, D8). + * + * ## Elapsed time (D11) + * + * Each local period becomes two instants through `zonedWallClockToUtcMs` and + * counts its REAL duration, so on a transition day a period can be an hour + * shorter or longer than its clock face. A skipped or repeated reading + * resolves the way that primitive resolves it (the earlier candidate); a + * period whose end the primitive resolves at or before its start counts no + * time. + * + * ## The four counts, and their ends + * + * - {@link isWorkingTime}: the instant lies in `[start, end)` of a period of + * its own local date. + * - {@link addWorkingDays}: step `days` working days from a calendar day; the + * start day is never counted, so `0` answers the start day itself. + * - {@link workingDaysBetween}: the working days stepped through from `start` + * to `end`, excluding `start` and including `end`, negative when `end` is + * earlier, so `workingDaysBetween(d, addWorkingDays(d, n)) === n`. + * - {@link addWorkingHours}: consume working time from an instant, forward or + * (negative hours) backward; a start outside working time begins at the next + * (previous) period edge, and an answer that lands on a period's end is that + * end. + * + * These are the service's semantics. The working-day FORMULA functions' own + * argument semantics are their card's public contract (ADR-0157 D4); they are + * expressible over these primitives and {@link isWorkingDay}. + */ + +import { + WORK_CALENDAR_INVALID_CODE, + WORK_CALENDAR_NOT_MAINTAINED_CODE, + WORK_CALENDAR_UNRESOLVED_CODE, + WORK_CALENDAR_WEEKDAY_FIELDS, + nextUtcCalendarDay, + wallClockToUtcMs, + zonedWallClockToUtcMs, + type WorkCalendar, + type WorkCalendarDay, + type WorkCalendarUnresolvedReason, + type WorkPeriod, + type WorkPeriodsParse, + type WorkPeriodsRefusal, +} from '@objectstack/spec/data'; +import { isValueDomainMember } from '@objectstack/spec/shared'; + +// ── Refusals (codes: ADR-0112 ledger, defined in `@objectstack/spec/data`) ── + +/** + * ADR-0157 D2: the consumer named no calendar that exists, named none and the + * organization has no single default, or named no organization where one is + * required. Never answered with wall-clock time. + */ +export class WorkCalendarUnresolvedError extends Error { + readonly code = WORK_CALENDAR_UNRESOLVED_CODE; + readonly status = 400; + readonly reason: WorkCalendarUnresolvedReason; + /** The calendar code the consumer named, when it named one. */ + readonly calendar?: string; + constructor(reason: WorkCalendarUnresolvedReason, calendar?: string) { + super(unresolvedMessage(reason, calendar)); + this.name = 'WorkCalendarUnresolvedError'; + this.reason = reason; + if (calendar !== undefined) this.calendar = calendar; + } +} + +function unresolvedMessage(reason: WorkCalendarUnresolvedReason, calendar: string | undefined): string { + switch (reason) { + case 'not_found': + return `No working calendar has the code '${calendar}' in this organization. Create it, or name an existing calendar.`; + case 'no_default': + return 'No working calendar is marked as the default in this organization, and none was named. ' + + 'Mark one calendar as the default, or name a calendar code.'; + case 'no_organization': + return 'The computation names no organization, and this installation keeps organizations apart, ' + + 'so no working calendar can be chosen. Name the organization the computation belongs to.'; + case 'ambiguous': + return calendar === undefined + ? 'More than one working calendar is marked as the default in this organization. ' + + 'Clear the default flag on all but one of them.' + : `More than one working calendar answers the code '${calendar}'. ` + + 'Name the organization the computation belongs to.'; + } +} + +/** + * ADR-0157 D8: the computation needs `date`, which lies outside the span the + * calendar is maintained for. Fixed by entering the exceptions for that span + * and moving the bound, never by a weekly-pattern guess. + */ +export class WorkCalendarNotMaintainedError extends Error { + readonly code = WORK_CALENDAR_NOT_MAINTAINED_CODE; + readonly status = 400; + readonly calendar: string; + readonly date: string; + readonly maintainedFrom: string; + readonly maintainedThrough: string; + constructor(calendar: WorkCalendar, date: string) { + const after = date > calendar.maintainedThrough; + super( + `Working calendar '${calendar.code}' is maintained from ${calendar.maintainedFrom} through ` + + `${calendar.maintainedThrough}, and this computation needs ${date}. ` + + (after + ? 'Enter the holidays and make-up workdays after that date, then move "Maintained Through" forward.' + : 'Enter the holidays and make-up workdays before that date, then move "Maintained From" back.'), + ); + this.name = 'WorkCalendarNotMaintainedError'; + this.calendar = calendar.code; + this.date = date; + this.maintainedFrom = calendar.maintainedFrom; + this.maintainedThrough = calendar.maintainedThrough; + } +} + +/** ADR-0157 D7/D10: a stored row the calendar cannot read; `field` names the column. */ +export class WorkCalendarInvalidError extends Error { + readonly code = WORK_CALENDAR_INVALID_CODE; + readonly status = 400; + readonly calendar: string; + readonly field: string; + constructor(calendar: string, field: string, problem: string) { + super(`Working calendar '${calendar}' cannot be used: ${field} ${problem}. Correct the row in Setup.`); + this.name = 'WorkCalendarInvalidError'; + this.calendar = calendar; + this.field = field; + } +} + +/** The three codes above, read structurally so a duplicated module copy still classifies. */ +export function isWorkCalendarRefusal(err: unknown): err is + WorkCalendarUnresolvedError | WorkCalendarNotMaintainedError | WorkCalendarInvalidError { + const code = (err as { code?: unknown } | null | undefined)?.code; + return code === WORK_CALENDAR_UNRESOLVED_CODE + || code === WORK_CALENDAR_NOT_MAINTAINED_CODE + || code === WORK_CALENDAR_INVALID_CODE; +} + +// ── Periods ────────────────────────────────────────────────────────────── + +const PERIOD = /^(\d{2}):(\d{2})\s*-\s*(\d{2}):(\d{2})$/; + +/** + * Parse a period list: `HH:mm-HH:mm` periods separated by commas, ascending + * and not overlapping (two periods may touch). Blank (`''`, `null`, + * `undefined`) is the empty list, a day with no working time. ADR-0157 D7 + * refuses a period that crosses midnight; D10 admits `24:00` as an end, and + * only as an end. + */ +export function parseWorkPeriods(text: unknown): WorkPeriodsParse { + if (text === null || text === undefined) return { ok: true, periods: [] }; + if (typeof text !== 'string') return refuse('malformed', 'must be text such as "09:00-12:00, 13:00-18:00"'); + if (text.trim() === '') return { ok: true, periods: [] }; + const periods: WorkPeriod[] = []; + for (const token of text.split(',')) { + const m = PERIOD.exec(token.trim()); + if (!m) return refuse('malformed', `"${token.trim()}" is not a period written HH:mm-HH:mm, such as 09:00-12:00`); + const [sh, sm, eh, em] = [Number(m[1]), Number(m[2]), Number(m[3]), Number(m[4])]; + if (sh > 23 || sm > 59 || eh > 24 || em > 59 || (eh === 24 && em !== 0)) { + return refuse('malformed', `"${token.trim()}" names a time that does not exist (a start runs 00:00-23:59, an end 00:01-24:00)`); + } + const start = sh * 60 + sm; + const end = eh * 60 + em; + if (end < start) { + return refuse('crosses_midnight', `"${token.trim()}" crosses midnight; end a period by 24:00 and start the next day's at 00:00`); + } + if (end === start) return refuse('empty_period', `"${token.trim()}" has no length`); + const prev = periods[periods.length - 1]; + if (prev && start < prev.end) { + return refuse('overlap', `"${token.trim()}" starts before the period ahead of it ends; list periods in order, without overlap`); + } + periods.push({ start, end }); + } + return { ok: true, periods }; +} + +function refuse(reason: WorkPeriodsRefusal, message: string): WorkPeriodsParse { + return { ok: false, reason, message }; +} + +// ── The resolved calendar ──────────────────────────────────────────────── + +/** A frozen copy of one period list, its periods frozen too. */ +function frozenPeriods(periods: readonly WorkPeriod[]): readonly WorkPeriod[] { + return Object.freeze(periods.map((p) => Object.freeze({ start: p.start, end: p.end }))); +} + +/** + * Build a {@link WorkCalendar} from a `sys_work_calendar` row and its + * `sys_work_calendar_exception` rows, validating every value the arithmetic + * reads. A row that fails is refused with {@link WorkCalendarInvalidError} + * naming the column, never read leniently: a typo'd zone would otherwise + * count in UTC, and an unreadable period would silently drop working time. + * Exceptions outside the maintained span are left out (no computation can + * reach them). + * + * The answer is frozen to its periods, so the calendar service can hand one + * cached calendar to every caller and no caller can change what it answers. + */ +export function buildWorkCalendar( + row: Readonly>, + exceptionRows: readonly Readonly>[], +): WorkCalendar { + const code = typeof row.code === 'string' && row.code !== '' ? row.code : '(no code)'; + const timezone = row.timezone; + if (typeof timezone !== 'string' || !isValueDomainMember('iana_time_zone', timezone)) { + throw new WorkCalendarInvalidError(code, 'timezone', `'${String(timezone ?? '')}' is not an IANA time zone`); + } + const maintainedFrom = calendarDayOf(row.maintained_from); + if (!maintainedFrom) throw new WorkCalendarInvalidError(code, 'maintained_from', 'is blank or not a date'); + const maintainedThrough = calendarDayOf(row.maintained_through); + if (!maintainedThrough) throw new WorkCalendarInvalidError(code, 'maintained_through', 'is blank or not a date'); + if (maintainedFrom > maintainedThrough) { + throw new WorkCalendarInvalidError(code, 'maintained_through', `(${maintainedThrough}) is before maintained_from (${maintainedFrom})`); + } + const weekly = WORK_CALENDAR_WEEKDAY_FIELDS.map((field) => { + const parsed = parseWorkPeriods(row[field]); + if (!parsed.ok) throw new WorkCalendarInvalidError(code, field, parsed.message); + return frozenPeriods(parsed.periods); + }); + const exceptions: Record = {}; + for (const ex of exceptionRows) { + const date = calendarDayOf(ex.date); + if (!date) throw new WorkCalendarInvalidError(code, 'exception date', `'${String(ex.date ?? '')}' is not a date`); + const day = exceptionDayOf(ex); + if (typeof day === 'string') throw new WorkCalendarInvalidError(code, `the ${date} exception`, day); + if (date < maintainedFrom || date > maintainedThrough) continue; + if (Object.prototype.hasOwnProperty.call(exceptions, date)) { + throw new WorkCalendarInvalidError(code, `the ${date} exception`, 'appears twice; keep one row per date'); + } + exceptions[date] = Object.freeze({ kind: day.kind, periods: frozenPeriods(day.periods) }); + } + return Object.freeze({ + code, + timezone, + maintainedFrom, + maintainedThrough, + weekly: Object.freeze(weekly), + exceptions: Object.freeze(exceptions), + }); +} + +/** + * An exception row's day, or why it cannot be one (ADR-0157 D10): `off` with + * no periods, `on` with that date's full, valid periods. + */ +export function exceptionDayOf(row: Readonly>): WorkCalendarDay | string { + const parsed = parseWorkPeriods(row.periods); + if (row.kind === 'off') { + if (!parsed.ok || parsed.periods.length > 0) return 'is a day off and carries periods; an off day has none'; + return { kind: 'off', periods: [] }; + } + if (row.kind === 'on') { + if (!parsed.ok) return `has periods that ${parsed.message}`; + if (parsed.periods.length === 0) return "is a working day with no periods; write the date's full periods"; + return { kind: 'on', periods: parsed.periods }; + } + return `has kind '${String(row.kind ?? '')}'; it must be off or on`; +} + +/** + * A stored calendar-day value as `YYYY-MM-DD`, or `undefined`: a driver hands a + * `date` column back as that text or as a `Date` at UTC midnight. + */ +export function calendarDayOf(value: unknown): string | undefined { + let day: string | undefined; + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) return undefined; + day = formatDay(value.getTime()); + } else if (typeof value === 'string') { + day = /^(\d{4}-\d{2}-\d{2})(?:T00:00:00(?:\.0+)?Z)?$/.exec(value.trim())?.[1]; + } + return day !== undefined && nextUtcCalendarDay(day) !== null ? day : undefined; +} + +// ── Day arithmetic (calendar days are zone-free, ADR-0053) ────────────── + +function partsOf(day: string): { year: number; month: number; day: number } { + return { year: Number(day.slice(0, 4)), month: Number(day.slice(5, 7)), day: Number(day.slice(8, 10)) }; +} + +function formatDay(utcMs: number): string { + const d = new Date(utcMs); + return `${String(d.getUTCFullYear()).padStart(4, '0')}-${String(d.getUTCMonth() + 1).padStart(2, '0')}-${String(d.getUTCDate()).padStart(2, '0')}`; +} + +function addDays(day: string, n: number): string { + const p = partsOf(day); + return formatDay(wallClockToUtcMs({ ...p, day: p.day + n })); +} + +/** Index into {@link WorkCalendar.weekly}: Monday 0 … Sunday 6. */ +function weekdayIndex(day: string): number { + return (new Date(wallClockToUtcMs(partsOf(day))).getUTCDay() + 6) % 7; +} + +function requireDay(value: string, name: string): string { + const day = calendarDayOf(value); + if (!day) throw new RangeError(`${name} must be a calendar day written YYYY-MM-DD; got '${String(value)}'`); + return day; +} + +function requireMaintained(cal: WorkCalendar, day: string): void { + if (day < cal.maintainedFrom || day > cal.maintainedThrough) throw new WorkCalendarNotMaintainedError(cal, day); +} + +/** The instant a local minute-of-day of `day` happens at, through the one DST rule (D11). */ +function instantOf(cal: WorkCalendar, day: string, minute: number): number { + return zonedWallClockToUtcMs({ ...partsOf(day), hour: Math.floor(minute / 60), minute: minute % 60 }, cal.timezone); +} + +/** The local calendar day an instant falls on, found with the same primitive. */ +function localDayOf(cal: WorkCalendar, at: number): string { + const utcDay = formatDay(at); + for (const day of [addDays(utcDay, -1), utcDay, addDays(utcDay, 1)]) { + if (instantOf(cal, day, 0) <= at && at < instantOf(cal, addDays(day, 1), 0)) return day; + } + throw new RangeError(`no local day of '${cal.timezone}' holds the instant ${new Date(at).toISOString()}`); +} + +function instantArg(value: number | Date, name: string): number { + const t = value instanceof Date ? value.getTime() : value; + if (typeof t !== 'number' || !Number.isFinite(t)) throw new RangeError(`${name} must be a valid instant`); + return t; +} + +// ── The four counts ───────────────────────────────────────────────────── + +/** + * The working periods of `day`: its exception's periods when one is entered, + * else its weekday's. Refused outside the maintained span (D8). + */ +export function workingPeriodsOn(cal: WorkCalendar, day: string): readonly WorkPeriod[] { + const d = requireDay(day, 'day'); + requireMaintained(cal, d); + const exception = cal.exceptions[d]; + return exception ? exception.periods : (cal.weekly[weekdayIndex(d)] ?? []); +} + +/** Does `day` carry any working time? */ +export function isWorkingDay(cal: WorkCalendar, day: string): boolean { + return workingPeriodsOn(cal, day).length > 0; +} + +/** Is the instant inside a working period of its own local date (`[start, end)`)? */ +export function isWorkingTime(cal: WorkCalendar, at: number | Date): boolean { + const t = instantArg(at, 'at'); + const day = localDayOf(cal, t); + return workingPeriodsOn(cal, day).some((p) => instantOf(cal, day, p.start) <= t && t < instantOf(cal, day, p.end)); +} + +/** + * The calendar day `days` working days after `day` (before it, for a negative + * count). The start day is never counted; `0` answers `day`. Every day the + * walk reads, the start included, must lie in the maintained span (D8). + */ +export function addWorkingDays(cal: WorkCalendar, day: string, days: number): string { + if (!Number.isSafeInteger(days)) throw new RangeError(`days must be a whole number; got ${String(days)}`); + let d = requireDay(day, 'day'); + requireMaintained(cal, d); + const step = days < 0 ? -1 : 1; + for (let remaining = Math.abs(days); remaining > 0;) { + d = addDays(d, step); + if (isWorkingDay(cal, d)) remaining -= 1; + } + return d; +} + +/** + * The working days stepped through from `start` to `end`: `start` excluded, + * `end` included, negative when `end` is earlier. Both ends must lie in the + * maintained span (D8). The inverse of {@link addWorkingDays}. + */ +export function workingDaysBetween(cal: WorkCalendar, start: string, end: string): number { + const s = requireDay(start, 'start'); + const e = requireDay(end, 'end'); + requireMaintained(cal, s); + requireMaintained(cal, e); + const forward = e >= s; + let count = 0; + // Forward counts (s, e]; backward counts [e, s), so each direction steps + // over exactly the days `addWorkingDays` would. + for (let d = forward ? addDays(s, 1) : e; forward ? d <= e : d < s; d = addDays(d, 1)) { + if (isWorkingDay(cal, d)) count += 1; + } + return forward ? count : -count; +} + +/** + * The instant `hours` of working time after `start` (before it, for negative + * hours), counted as elapsed time (D11). A start outside working time begins + * at the next period's start (the previous one's end); an answer landing on a + * period's end is that end. Returns epoch milliseconds. Every day the walk + * reads must lie in the maintained span (D8). + */ +export function addWorkingHours(cal: WorkCalendar, start: number | Date, hours: number): number { + if (typeof hours !== 'number' || !Number.isFinite(hours)) throw new RangeError(`hours must be a finite number; got ${String(hours)}`); + const t0 = instantArg(start, 'start'); + let day = localDayOf(cal, t0); + requireMaintained(cal, day); + // Whole milliseconds, so a fractional hour (1/3) answers an instant a + // `Date` holds exactly and two evaluations compare equal. + let remaining = Math.round(Math.abs(hours) * 3_600_000); + if (remaining === 0) return t0; + const forward = hours > 0; + let t = t0; + for (;;) { + const periods = workingPeriodsOn(cal, day); + for (const p of forward ? periods : [...periods].reverse()) { + const ps = instantOf(cal, day, p.start); + const pe = instantOf(cal, day, p.end); + if (pe <= ps) continue; + if (forward) { + if (pe <= t) continue; + const from = Math.max(ps, t); + if (pe - from >= remaining) return from + remaining; + remaining -= pe - from; + t = pe; + } else { + if (ps >= t) continue; + const to = Math.min(pe, t); + if (to - ps >= remaining) return to - remaining; + remaining -= to - ps; + t = ps; + } + } + day = addDays(day, forward ? 1 : -1); + requireMaintained(cal, day); + } +} diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index 48f55df9025..7a23354e68c 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -735,6 +735,24 @@ export type { HookSkipReason, } from './hook-metrics.js'; +// [ADR-0157] The working-calendar service and the calendar objects' write +// hooks. Its contract is `IWorkCalendarService` (`@objectstack/spec/contracts`); +// its refusals and arithmetic are `@objectstack/formula`'s. +export { + WorkCalendarService, + installWorkCalendarHooks, + WORK_CALENDAR_OBJECT, + WORK_CALENDAR_EXCEPTION_OBJECT, + WORK_CALENDAR_CACHE_TTL_MS, + WORK_CALENDAR_HOOK_PACKAGE, +} from './work-calendar-service.js'; +export type { + WorkCalendarServiceOptions, + WorkCalendarHookOptions, + WorkCalendarReadEngine, + WorkCalendarHookEngine, +} from './work-calendar-service.js'; + // Export LifecycleService (ADR-0057 — declarative retention/rotation/archival) export { LifecycleService, diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index 479f04f65e7..161e6f23b09 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -42,6 +42,7 @@ import { wrapDeclarativeHook } from './hook-wrappers.js'; import { announceStoredExpressionHoles } from './stored-expression-backfill.js'; import { announceSummaryHoles } from './summary-hole-announce.js'; import { LifecycleService } from './lifecycle/lifecycle-service.js'; +import { WORK_CALENDAR_OBJECT, WorkCalendarService, installWorkCalendarHooks } from './work-calendar-service.js'; import { readRecycleBinRetentionEnv, type RecycleBinRetentionSettings } from './recycle-bin/retention.js'; import { lifecycleSettingsManifest } from './lifecycle/lifecycle-settings.js'; import { @@ -66,6 +67,7 @@ import { } from './action-activation.js'; import type { IMetadataService } from '@objectstack/spec/contracts'; import type { ServiceObject } from '@objectstack/spec/data'; +import { WORK_CALENDAR_SERVICE } from '@objectstack/spec/contracts'; import { collectManifestPicklistNames, collectManifestPicklistReferences, @@ -605,6 +607,8 @@ export class ObjectQLPlugin implements Plugin { private metadataUnsubscribes: Array<() => void> = []; /** ADR-0057 lifecycle enforcement (Reaper/Rotator/Archiver). */ private lifecycleService: LifecycleService | undefined; + /** [ADR-0157] The working-calendar service, registered as {@link WORK_CALENDAR_SERVICE}. */ + private workCalendarService: WorkCalendarService | undefined; private lifecycleOptions: ObjectQLPluginOptions['lifecycle']; /** [#30237] The host's recycle-bin retention seam, handed to the engine in `init()`. */ private recycleBinRetention: ObjectQLPluginOptions['recycleBinRetention']; @@ -1194,6 +1198,18 @@ export class ObjectQLPlugin implements Plugin { ...this.lifecycleOptions, }); ctx.registerService('lifecycle', this.lifecycleService); + + // [ADR-0157 D1, D2] The working-calendar service, beside the engine's + // other reader of organization reference data (the exchange-rate read of + // the home projection): registered from the engine plugin so every kernel + // that has data can count working time, and resolved by the formula + // functions and the approval sweep through `ctx.getService`. A kernel + // without `sys_work_calendar` registered holds no calendar, and refuses. + this.workCalendarService = new WorkCalendarService({ + getEngine: () => this.ql as never, + hasCalendarObject: () => Boolean(this.ql?.registry?.getObject?.(WORK_CALENDAR_OBJECT)), + }); + ctx.registerService(WORK_CALENDAR_SERVICE, this.workCalendarService); } start = async (ctx: PluginContext) => { @@ -1575,7 +1591,7 @@ export class ObjectQLPlugin implements Plugin { // UTC; a read that FAILS is the write's failure, not an unset setting. const isUnregisteredSetting = (e: any) => e?.code === 'SETTINGS_UNKNOWN_NAMESPACE' || e?.code === 'SETTINGS_UNKNOWN_KEY'; const settingText = (resolved: { value?: unknown } | undefined) => (typeof resolved?.value === 'string' ? resolved.value : undefined); - this.ql.setHomeLocalizationResolver(async (organizationId) => { + const readLocalization = async (organizationId: string | undefined) => { let settings: { get?: (ns: string, key: string, c?: Record) => Promise<{ value?: unknown } | undefined>; getMany?: (ns: string, keys: string[], c?: Record) => Promise>; @@ -1606,7 +1622,17 @@ export class ObjectQLPlugin implements Plugin { } }; return { currency: await one('currency'), timezone: await one('timezone') }; - }); + }; + this.ql.setHomeLocalizationResolver(readLocalization); + // [ADR-0157 D7, D10] The calendar objects' write door, and the drop of + // the calendar cache on every calendar or exception write. A create + // that leaves `timezone` out takes the organization's + // `localization.timezone` from the same read. + if (this.workCalendarService) { + installWorkCalendarHooks(this.ql as never, this.workCalendarService, { + timezoneOf: async (organizationId) => (await readLocalization(organizationId))?.timezone, + }, ctx.logger); + } } // Initialize drivers (calls driver.connect() which sets up persistence) diff --git a/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts new file mode 100644 index 00000000000..f134ccf8040 --- /dev/null +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -0,0 +1,426 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0157: the working-calendar service (resolution, organization, cache, + * the four computations) and the calendar objects' write hooks. + * + * The service half reads through a recording double, because what is pinned + * is WHAT it asks the engine (which object, which organization, how often). + * The hook half runs on a real `ObjectQL`, because what is pinned is what the + * engine's own write path answers: the refusal envelope of a real insert. + */ + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { resolveThrownHttpError } from '@objectstack/types'; +import { WORK_CALENDAR_NOT_MAINTAINED_CODE, WORK_CALENDAR_UNRESOLVED_CODE } from '@objectstack/spec/data'; +import { isWorkingDay } from '@objectstack/formula'; +import { ObjectQL } from './engine.js'; +import { + WORK_CALENDAR_CACHE_TTL_MS, + WORK_CALENDAR_EXCEPTION_OBJECT, + WORK_CALENDAR_OBJECT, + WorkCalendarService, + enginePostureOf, + installWorkCalendarHooks, +} from './work-calendar-service.js'; + +type Row = Record; + +// 2026-10-01 is a Thursday. A National Day week (seven `off` rows) and a 调休 +// make-up Saturday (an `on` row on 2026-10-10). +const WEEKDAY = '09:00-12:00, 13:00-18:00'; +const CN: Row = { + id: 'cal_cn', code: 'cn_standard', name: 'China', timezone: 'Asia/Shanghai', is_default: true, + maintained_from: '2026-01-01', maintained_through: '2026-12-31', + monday_periods: WEEKDAY, tuesday_periods: WEEKDAY, wednesday_periods: WEEKDAY, + thursday_periods: WEEKDAY, friday_periods: WEEKDAY, saturday_periods: '', sunday_periods: '', +}; +const HOLIDAYS: Row[] = [ + ...['01', '02', '03', '04', '05', '06', '07'].map((d) => ({ id: `ex_${d}`, calendar: 'cal_cn', date: `2026-10-${d}`, kind: 'off' })), + { id: 'ex_10', calendar: 'cal_cn', date: '2026-10-10', kind: 'on', periods: WEEKDAY }, +]; +const sh = (day: string, hm: string) => Date.parse(`${day}T${hm}:00+08:00`); +const ORG = { organizationId: 'org_a' } as const; + +/** + * A read double that answers equality `where`s and records every read. A read + * whose context names a tenant sees that organization's rows (and rows that + * carry none), as the engine scopes it; a read without one sees every row. + */ +function readDouble(calendars: Row[], exceptions: Row[]) { + const reads: Array<{ object: string; query: Row }> = []; + return { + reads, + async find(object: string, query: Row) { + reads.push({ object, query }); + const src = object === WORK_CALENDAR_OBJECT ? calendars : exceptions; + const tenant = query.context?.tenantId; + const scoped = tenant === undefined ? src : src.filter((r) => r.organization_id === undefined || r.organization_id === tenant); + const hits = scoped.filter((r) => + Object.entries(query.where ?? {}).every(([k, v]) => { + // Equality only: a combinator or an operator object is refused, never answered wrong. + if (k.startsWith('$') || (v !== null && typeof v === 'object')) throw new Error(`readDouble answers equality only, not ${k}`); + return r[k] === v; + }), + ); + const from = query.offset ?? 0; + return hits.slice(from, from + (query.limit ?? hits.length)); + }, + }; +} + +async function refusal(p: Promise): Promise { + try { + await p; + } catch (e) { + return e; + } + throw new Error('expected a refusal'); +} + +describe('WorkCalendarService — resolution (ADR-0157 D2)', () => { + it('takes the named code, else the organization default; refuses with no default, never wall-clock', async () => { + // adr0112-ok: D6b — a calendar's persisted `code` column, not an error code + const other = { ...CN, id: 'cal_x', code: 'plant_x', is_default: false }; + const svc = new WorkCalendarService({ getEngine: () => readDouble([CN, other], HOLIDAYS) }); + expect((await svc.resolve({ ...ORG, calendar: 'plant_x' })).code).toBe('plant_x'); + expect((await svc.resolve(ORG)).code).toBe('cn_standard'); // CONTROL: the default answers + + const none = new WorkCalendarService({ getEngine: () => readDouble([other], []) }); + const e = await refusal(none.resolve(ORG)); + expect(e).toMatchObject({ code: WORK_CALENDAR_UNRESOLVED_CODE, reason: 'no_default' }); + expect(resolveThrownHttpError(e)).toMatchObject({ status: 400, code: WORK_CALENDAR_UNRESOLVED_CODE }); + await expect(none.resolve({ ...ORG, calendar: 'nope' })).rejects.toMatchObject({ reason: 'not_found', calendar: 'nope' }); + }); + + it('refuses two defaults rather than picking one', async () => { + // adr0112-ok: D6b — a calendar's persisted `code` column, not an error code + const svc = new WorkCalendarService({ getEngine: () => readDouble([CN, { ...CN, id: 'cal_2', code: 'two' }], []) }); + await expect(svc.resolve(ORG)).rejects.toMatchObject({ code: WORK_CALENDAR_UNRESOLVED_CODE, reason: 'ambiguous' }); + }); + + it('never sends a name that is not a calendar code to the query layer', async () => { + const engine = readDouble([CN], HOLIDAYS); + const svc = new WorkCalendarService({ getEngine: () => engine }); + await expect(svc.resolve({ ...ORG, calendar: '{current_user_id}' })).rejects.toMatchObject({ reason: 'not_found' }); + expect(engine.reads).toHaveLength(0); + }); + + it('a kernel without the calendar object holds no calendar', async () => { + const svc = new WorkCalendarService({ getEngine: () => readDouble([CN], []), hasCalendarObject: () => false }); + await expect(svc.resolve(ORG)).rejects.toMatchObject({ reason: 'no_default' }); + }); +}); + +describe('WorkCalendarService — organization and authority (ADR-0157 open point 4)', () => { + it('reads elevated in the organization the caller names, for the calendar and its exceptions', async () => { + const engine = readDouble([CN], HOLIDAYS); + await new WorkCalendarService({ getEngine: () => engine }).resolve({ organizationId: 'org_b', calendar: 'cn_standard' }); + expect(engine.reads.map((r) => [r.object, r.query.context])).toEqual([ + [WORK_CALENDAR_OBJECT, { isSystem: true, tenantId: 'org_b' }], + [WORK_CALENDAR_EXCEPTION_OBJECT, { isSystem: true, tenantId: 'org_b' }], + ]); + expect(engine.reads[1]!.query.where).toEqual({ calendar: 'cal_cn' }); + }); +}); + +describe('WorkCalendarService — no organization, outside `single` (ADR-0157 open point 4)', () => { + // A calendar that only organization B holds, as its default and by code. + const B_ONLY: Row = { ...CN, id: 'cal_b', code: 'plant_b', organization_id: 'org_b' }; + + for (const posture of ['isolated', 'group'] as const) { + it(`${posture}: a code or a default only another organization holds is refused before any read`, async () => { + const engine = readDouble([B_ONLY], []); + const svc = new WorkCalendarService({ getEngine: () => engine, posture: () => posture }); + for (const ref of [{ organizationId: undefined, calendar: 'plant_b' }, { organizationId: undefined }, { organizationId: '' }]) { + const e = await refusal(svc.resolve(ref)); + expect(e).toMatchObject({ code: WORK_CALENDAR_UNRESOLVED_CODE, reason: 'no_organization' }); + expect(resolveThrownHttpError(e)).toMatchObject({ status: 400, code: WORK_CALENDAR_UNRESOLVED_CODE }); + } + await expect(svc.addWorkingDays({ organizationId: undefined }, '2026-09-30', 1)).rejects.toMatchObject({ reason: 'no_organization' }); + expect(engine.reads).toHaveLength(0); + // CONTROL: named, the organization that holds it resolves it. + expect((await svc.resolve({ organizationId: 'org_b', calendar: 'plant_b' })).code).toBe('plant_b'); + }); + } + + it('single: a computation without an organization reads unscoped, as before', async () => { + const engine = readDouble([B_ONLY], []); + const svc = new WorkCalendarService({ getEngine: () => engine, posture: () => 'single' }); + expect((await svc.resolve({ organizationId: undefined })).code).toBe('plant_b'); + expect(engine.reads[0]!.query.context).toEqual({ isSystem: true }); + }); + + it('reads the posture the engine enforces when none is passed', async () => { + const engine = new ObjectQL(); + engine.setTenancyPostureProvider(() => 'isolated'); + expect(enginePostureOf(engine)).toBe('isolated'); + const svc = new WorkCalendarService({ getEngine: () => engine as never }); + await expect(svc.resolve({ organizationId: undefined })).rejects.toMatchObject({ reason: 'no_organization' }); + engine.setTenancyPostureProvider(() => 'single'); + expect(enginePostureOf(engine)).toBe('single'); // CONTROL + }); +}); + +describe('WorkCalendarService — the cache', () => { + it('serves one read until a write invalidates it or the TTL runs out; a refusal is never cached', async () => { + let now = 1_000; + const calendars: Row[] = []; + const engine = readDouble(calendars, HOLIDAYS); + const svc = new WorkCalendarService({ getEngine: () => engine, now: () => now }); + await expect(svc.resolve(ORG)).rejects.toMatchObject({ reason: 'no_default' }); + calendars.push(CN); // the administrator fixes it + await svc.resolve(ORG); + const afterFix = engine.reads.length; + await svc.resolve(ORG); + expect(engine.reads.length).toBe(afterFix); // cached + svc.invalidate(); + await svc.resolve(ORG); + expect(engine.reads.length).toBe(afterFix + 2); + now += WORK_CALENDAR_CACHE_TTL_MS; + await svc.resolve(ORG); + expect(engine.reads.length).toBe(afterFix + 4); + }); +}); + +describe('WorkCalendarService — a 调休 Saturday and a National Day week (ADR-0157 D1, D10)', () => { + const svc = new WorkCalendarService({ getEngine: () => readDouble([CN], HOLIDAYS) }); + // CONTROL: the same calendar with no exceptions entered. + const bare = new WorkCalendarService({ getEngine: () => readDouble([CN], []) }); + + it('addWorkingDays and workingDaysBetween step over the week and onto the Saturday', async () => { + expect(await svc.addWorkingDays(ORG, '2026-09-30', 1)).toBe('2026-10-08'); + expect(await svc.addWorkingDays(ORG, '2026-09-30', 3)).toBe('2026-10-10'); + expect(await bare.addWorkingDays(ORG, '2026-09-30', 1)).toBe('2026-10-01'); + expect(await svc.workingDaysBetween(ORG, '2026-09-30', '2026-10-10')).toBe(3); + expect(await bare.workingDaysBetween(ORG, '2026-09-30', '2026-10-10')).toBe(7); + }); + + it('addWorkingHours and isWorkingTime count the same days', async () => { + expect(await svc.addWorkingHours(ORG, sh('2026-09-30', '17:00'), 2)).toBe(sh('2026-10-08', '10:00')); + expect(await svc.addWorkingHours(ORG, sh('2026-10-09', '17:00'), 2)).toBe(sh('2026-10-10', '10:00')); + expect(await bare.addWorkingHours(ORG, sh('2026-09-30', '17:00'), 2)).toBe(sh('2026-10-01', '10:00')); + expect(await svc.isWorkingTime(ORG, sh('2026-10-10', '10:00'))).toBe(true); + expect(await svc.isWorkingTime(ORG, sh('2026-10-05', '10:00'))).toBe(false); + expect(await bare.isWorkingTime(ORG, sh('2026-10-05', '10:00'))).toBe(true); + }); + + it('a span past maintained_through is refused (D8)', async () => { + const e = await refusal(svc.addWorkingDays(ORG, '2026-12-30', 3)); + expect(e).toMatchObject({ code: WORK_CALENDAR_NOT_MAINTAINED_CODE, date: '2027-01-01' }); + expect(resolveThrownHttpError(e)).toMatchObject({ status: 400, code: WORK_CALENDAR_NOT_MAINTAINED_CODE }); + expect(await svc.addWorkingDays(ORG, '2026-12-29', 2)).toBe('2026-12-31'); // CONTROL + }); +}); + +// ── The write hooks, on a real engine ────────────────────────────────── + +const text = { type: 'text' }; +const CALENDAR_SCHEMA = { + name: WORK_CALENDAR_OBJECT, + label: 'Working Calendar', + fields: { + code: text, name: text, timezone: text, is_default: { type: 'boolean' }, + maintained_from: { type: 'date' }, maintained_through: { type: 'date' }, + monday_periods: text, tuesday_periods: text, wednesday_periods: text, thursday_periods: text, + friday_periods: text, saturday_periods: text, sunday_periods: text, + }, +}; +const EXCEPTION_SCHEMA = { + name: WORK_CALENDAR_EXCEPTION_OBJECT, + label: 'Calendar Exception', + fields: { calendar: text, date: { type: 'date' }, kind: text, periods: text, note: text }, +}; + +function memoryDriver() { + const tables = new Map>(); + const table = (o: string) => tables.get(o) ?? tables.set(o, new Map()).get(o)!; + const matches = (r: Row, where: Row = {}) => + Object.entries(where).every(([k, v]) => (v && typeof v === 'object' ? true : r[k] === v)); + return { + name: 'com.objectstack.driver.memory.work-calendar', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async initObjects() {}, async checkHealth() { return true; }, + async find(o: string, q?: any) { + const rows = [...table(o).values()].filter((r) => matches(r, q?.where)); + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + }, + async findOne(o: string, q?: any) { return [...table(o).values()].find((r) => matches(r, q?.where)) ?? null; }, + async count(o: string, q?: any) { return [...table(o).values()].filter((r) => matches(r, q?.where)).length; }, + async create(o: string, data: Row) { table(o).set(String(data.id), { ...data }); return { ...data }; }, + async update(o: string, data: Row, q?: any) { + const id = String(q?.where?.id ?? data.id); + const next = { ...(table(o).get(id) ?? { id }), ...data }; + table(o).set(id, next); + return next; + }, + async delete(o: string, q?: any) { return table(o).delete(String(q?.where?.id)) ? { deleted: 1 } : false; }, + } as any; +} + +describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { + let engine: ObjectQL; + let svc: WorkCalendarService; + let zoneAsked: Array; + + beforeEach(async () => { + engine = new ObjectQL(); + engine.registerDriver(memoryDriver(), true); + await engine.init(); + engine.registry.registerObject(CALENDAR_SCHEMA as any, 'com.objectstack.test.work-calendar'); + engine.registry.registerObject(EXCEPTION_SCHEMA as any, 'com.objectstack.test.work-calendar'); + engine.setTenancyPostureProvider(() => 'single'); + svc = new WorkCalendarService({ getEngine: () => engine as never }); + zoneAsked = []; + installWorkCalendarHooks(engine as never, svc, { + timezoneOf: async (org) => { zoneAsked.push(org); return 'Asia/Shanghai'; }, + }); + }); + + afterEach(async () => { + try { await engine.destroy(); } catch { /* noop */ } + }); + + const insertCalendar = (row: Row) => engine.insert(WORK_CALENDAR_OBJECT, { ...CN, ...row }, { context: { isSystem: true } }); + + it('refuses a period that crosses midnight, on insert and on update; accepts 24:00 (D7, D10)', async () => { + const e = await refusal(insertCalendar({ id: 'c1', monday_periods: '22:00-06:00' })); + expect(resolveThrownHttpError(e)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + expect(e.fields).toEqual([expect.objectContaining({ field: 'monday_periods', code: 'invalid_value' })]); + await insertCalendar({ id: 'c2', monday_periods: '18:00-24:00' }); // CONTROL + const u = await refusal(engine.update(WORK_CALENDAR_OBJECT, { friday_periods: '23:00-01:00' }, { where: { id: 'c2' }, context: { isSystem: true } })); + expect(u.fields).toEqual([expect.objectContaining({ field: 'friday_periods', code: 'invalid_value' })]); + }); + + it('refuses a malformed period and a span that ends before it starts', async () => { + const e = await refusal(insertCalendar({ id: 'c1', tuesday_periods: '9:00-12:00' })); + expect(e.fields).toEqual([expect.objectContaining({ field: 'tuesday_periods', code: 'invalid_format' })]); + const span = await refusal(insertCalendar({ id: 'c2', maintained_from: '2027-01-01', maintained_through: '2026-12-31' })); + expect(span.fields).toEqual([expect.objectContaining({ field: 'maintained_through', code: 'invalid_value' })]); + }); + + it('refuses a second default in the organization (D2)', async () => { + await insertCalendar({ id: 'c1' }); + const e = await refusal(insertCalendar({ id: 'c2', code: 'second' })); + expect(e.fields).toEqual([expect.objectContaining({ field: 'is_default', code: 'invalid_value' })]); + await insertCalendar({ id: 'c3', code: 'third', is_default: false }); // CONTROL + }); + + it('a create that leaves the time zone out takes the organization\'s (D7)', async () => { + await engine.insert(WORK_CALENDAR_OBJECT, { ...CN, id: 'c1', timezone: undefined, organization_id: 'org_z' }, { context: { isSystem: true, tenantId: 'org_z' } }); + const [row] = await engine.find(WORK_CALENDAR_OBJECT, { where: { id: 'c1' }, context: { isSystem: true } }); + expect(row?.timezone).toBe('Asia/Shanghai'); + expect(zoneAsked).toEqual(['org_z']); + }); + + it('refuses an off row with periods and an on row without them (D10)', async () => { + const insertException = (row: Row) => engine.insert(WORK_CALENDAR_EXCEPTION_OBJECT, row, { context: { isSystem: true } }); + const off = await refusal(insertException({ id: 'x1', calendar: 'cal_cn', date: '2026-10-01', kind: 'off', periods: '09:00-12:00' })); + expect(resolveThrownHttpError(off)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + expect(off.fields).toEqual([expect.objectContaining({ field: 'periods', code: 'invalid_value' })]); + const on = await refusal(insertException({ id: 'x2', calendar: 'cal_cn', date: '2026-10-10', kind: 'on' })); + expect(on.fields).toEqual([expect.objectContaining({ field: 'periods', code: 'required' })]); + await insertException({ id: 'x3', calendar: 'cal_cn', date: '2026-10-10', kind: 'on', periods: '09:00-12:00' }); // CONTROL + }); + + it('a calendar or exception write drops the cached calendar', async () => { + await insertCalendar({ id: 'cal_cn' }); + expect(isWorkingDay(await svc.resolve(ORG), '2026-10-12')).toBe(true); + await engine.insert(WORK_CALENDAR_EXCEPTION_OBJECT, { id: 'x1', calendar: 'cal_cn', date: '2026-10-12', kind: 'off' }, { context: { isSystem: true } }); + expect(isWorkingDay(await svc.resolve(ORG), '2026-10-12')).toBe(false); + }); +}); + +describe('the calendar hooks take the organization from the session', () => { + const A_DEFAULT: Row = { ...CN, id: 'cal_a', code: 'plant_a', organization_id: 'org_a' }; + const B_DEFAULT: Row = { ...CN, id: 'cal_b', code: 'plant_b', organization_id: 'org_b' }; + const created = (organizationId?: string): Row => ({ + ...CN, id: 'cal_new', code: 'new_one', timezone: undefined, + ...(organizationId === undefined ? {} : { organization_id: organizationId }), + }); + + /** The hooks bound on a read double, with the time-zone reads they ask for. */ + function bound(posture: 'single' | 'isolated') { + const handlers = new Map unknown>(); + const engine = { + ...readDouble([A_DEFAULT, B_DEFAULT], []), + registerHook(event: string, handler: (ctx: any) => unknown, options?: Row) { + handlers.set(`${event}:${String(options?.object)}`, handler); + }, + }; + const zoneAsked: Array = []; + installWorkCalendarHooks(engine, { invalidate() {} }, { + posture: () => posture, + timezoneOf: async (org) => { zoneAsked.push(org); return 'Asia/Shanghai'; }, + }); + const insert = (session: Row, data: Row) => + handlers.get(`beforeInsert:${WORK_CALENDAR_OBJECT}`)!({ session, input: { data, options: {} } }); + const update = (session: Row, data: Row, previous: Row) => + handlers.get(`beforeUpdate:${WORK_CALENDAR_OBJECT}`)!({ session, input: { data, options: {} }, previous }); + return { reads: engine.reads, zoneAsked, insert, update }; + } + const member = { userId: 'usr_1', organizationId: 'org_a', isSystem: false }; + + for (const posture of ['single', 'isolated'] as const) { + it(`${posture}: a member's create reads in the session's organization`, async () => { + // A default on a create placed in another organization is refused at the door, before any read. + const h = bound(posture); + const placed = await refusal(Promise.resolve(h.insert(member, created('org_b')))); + expect(resolveThrownHttpError(placed)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + expect(placed.fields).toEqual([expect.objectContaining({ field: 'is_default', code: 'invalid_value' })]); + expect(placed.message).not.toContain('plant_b'); + expect(h.reads).toEqual([]); + expect(h.zoneAsked).toEqual([]); + // CONTROL: the same create without a default passes, with no read and no time-zone fill. + const row: Row = { ...created('org_b'), is_default: false }; + await h.insert(member, row); + expect(h.reads).toEqual([]); + expect(h.zoneAsked).toEqual([]); + expect(row.timezone).toBeUndefined(); + + // CONTROL: the session's own organization is read, and judged. + const own = bound(posture); + const e = await refusal(Promise.resolve(own.insert(member, created()))); + expect(e.fields).toEqual([expect.objectContaining({ field: 'is_default', code: 'invalid_value' })]); + expect(e.message).toContain('plant_a'); + expect(own.reads.map((r) => r.query.context?.tenantId)).toEqual(['org_a']); + expect(own.zoneAsked).toEqual(['org_a']); + }); + } + + it('a system writer reads in its session\'s organization too', async () => { + const h = bound('isolated'); + const e = await refusal(Promise.resolve(h.insert({ isSystem: true, organizationId: 'org_b' }, created('org_b')))); + expect(e.message).toContain('plant_b'); + expect(h.zoneAsked).toEqual(['org_b']); + // No organization of its own: a default is refused, a plain create passes, and neither reads. + const other = bound('isolated'); + const d = await refusal(Promise.resolve(other.insert({ isSystem: true }, created('org_b')))); + expect(d.fields).toEqual([expect.objectContaining({ field: 'is_default', code: 'invalid_value' })]); + await other.insert({ isSystem: true }, { ...created('org_b'), is_default: false }); + expect(other.reads).toEqual([]); + }); + + it('a default set by an update is judged in the stored row\'s organization', async () => { + const h = bound('isolated'); + const stored: Row = { ...created('org_b'), is_default: false }; + const e = await refusal(Promise.resolve(h.update({ ...member, organizationId: 'org_b' }, { is_default: true }, stored))); + expect(e.fields).toEqual([expect.objectContaining({ field: 'is_default', code: 'invalid_value' })]); + expect(e.message).toContain('plant_b'); + expect(h.reads.map((r) => r.query.context?.tenantId)).toEqual(['org_b']); + }); + + it('isolated: a write that names no organization reads nothing', async () => { + const stored: Row = { ...CN, id: 'cal_old', code: 'old_one', is_default: false }; + const h = bound('isolated'); + await h.insert({ isSystem: true }, created()); + await h.update({ isSystem: true }, { is_default: true }, stored); + expect(h.reads).toEqual([]); + expect(h.zoneAsked).toEqual([]); + // CONTROL: under `single` the same writes read, and are judged. + const single = bound('single'); + for (const write of [() => single.insert({ isSystem: true }, created()), () => single.update({ isSystem: true }, { is_default: true }, stored)]) { + const e = await refusal(Promise.resolve(write())); + expect(resolveThrownHttpError(e)).toMatchObject({ status: 400, code: 'VALIDATION_FAILED' }); + } + }); +}); diff --git a/packages/objectql/src/work-calendar-service.ts b/packages/objectql/src/work-calendar-service.ts new file mode 100644 index 00000000000..a38ad0325a4 --- /dev/null +++ b/packages/objectql/src/work-calendar-service.ts @@ -0,0 +1,450 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The working-calendar service (ADR-0157 D1, D2, D8; open point 4), and the + * write hooks that keep the two calendar objects readable. + * + * ## What it does, and what it leaves to the other packages + * + * It RESOLVES a calendar under D2 — the code the consumer names, else the + * organization's default (`is_default`), else a refusal, never wall-clock time + * — loads its exceptions, caches the result, and computes with the pure + * arithmetic in `@objectstack/formula` (`work-calendar.ts`), which also holds + * the three error classes. The arithmetic sits there so the working-day + * formula functions count with the same daylight-saving rule (D11, open point + * 3); a caller that must compute synchronously resolves here first and counts + * over the plain, frozen data it gets. The contract it implements is + * `IWorkCalendarService` (`@objectstack/spec/contracts`); the codes, column + * names and the `WorkCalendar` shape are `@objectstack/spec/data`'s. + * + * ## Which organization, under whose authority (open point 4) + * + * The exchange-rate reader's rule (`homeAmountServing.rateOn`, ADR-0144 D5): + * the read runs `{ isSystem: true, tenantId: }`, so a + * rank-and-file member — who cannot read the calendar tables — still has every + * deadline counted through them. The organization is the one the CALLER names + * (`WorkCalendarRef.organizationId`): the record's own, never the ambient + * active organization. A system-context caller across organizations (the + * approval sweep) names each request's `organization_id`. + * + * A computation that names NO organization is refused + * `ERR_WORK_CALENDAR_UNRESOLVED` (`no_organization`) before any read, the + * cache's included, in every tenancy posture but `single` (the engine's own + * reading, `resolveEnginePosture`). An elevated read without an organization + * carries no scope under a wall, so a code or a default would resolve in + * whichever organization happened to hold one; refusing it is what keeps one + * organization's calendar from counting another's. Under `single` there is one + * logical tenant and the read runs unscoped, as before. + * + * ## The cache + * + * One entry per (organization, code-or-default), kept until a calendar or + * exception row is written on this node (the `after*` hooks below drop every + * entry) and at most {@link WORK_CALENDAR_CACHE_TTL_MS} — the TTL is what + * bounds staleness on the OTHER replicas, which hear of no local write. + * A refusal is never cached: the next computation after an administrator's + * fix reads the rows again. + * + * ## The write hooks (ADR-0157 D2, D7, D10) + * + * `beforeInsert` / `beforeUpdate` on both objects refuse what the arithmetic + * could not read as written, at the door, with the engine's own + * `400 VALIDATION_FAILED` envelope and one `fields[]` entry from the closed + * ADR-0114 catalog — so an administrator meets the refusal when saving, not a + * consumer when counting. They judge every write, system writes included: a + * seeded calendar with a period crossing midnight is as unreadable as a typed + * one. Judged: the period columns (D7: no period crosses midnight; D10: + * `24:00` is a legal end; `off` carries none, `on` carries its date's full + * periods); `maintained_from` on or before `maintained_through`; one default + * per organization. A create that leaves `timezone` out takes the + * organization's `localization.timezone` (D7), stored as the calendar's own. + * + * The hooks take the organization from the session, every writer's alike: a + * seed or an import writes under its organization's tenant, so its session + * names it. An update reads in the stored row's own organization. Outside the + * `single` posture no hook reads without an organization, the service's rule. + * + * A create whose row names an organization other than the session's is not + * read for, so its one-default judgement cannot run where the row lands: when + * it sets `is_default` it is refused at the door, before any read — write it + * under that organization, or set the default afterwards by an update, which + * is judged in the stored row's own organization. A future seed that sets a + * calendar's default must therefore load pinned to its organization, or set + * the default by an update afterwards. Such a create without a default passes, + * and gets no time-zone fill. + */ + +import { + WORK_CALENDAR_CODE_PATTERN, + WORK_CALENDAR_WEEKDAY_FIELDS, + type WorkCalendar, +} from '@objectstack/spec/data'; +import type { IWorkCalendarService, WorkCalendarRef } from '@objectstack/spec/contracts'; +import type { FieldErrorCode } from '@objectstack/spec/api'; +import type { TenancyPosture } from '@objectstack/spec/security'; +import { + WorkCalendarUnresolvedError, + addWorkingDays, + addWorkingHours, + buildWorkCalendar, + calendarDayOf, + exceptionDayOf, + isWorkingTime, + parseWorkPeriods, + workingDaysBetween, +} from '@objectstack/formula'; +import { validationFailure } from '@objectstack/types'; +import { resolveEnginePosture } from './engine-driver-options.js'; + +/** The calendar object (`@objectstack/platform-objects`). */ +export const WORK_CALENDAR_OBJECT = 'sys_work_calendar'; +/** The dated-exception object (`@objectstack/platform-objects`). */ +export const WORK_CALENDAR_EXCEPTION_OBJECT = 'sys_work_calendar_exception'; +/** The longest a cached calendar is served without a local write dropping it. */ +export const WORK_CALENDAR_CACHE_TTL_MS = 60_000; +/** The `packageId` every hook below registers under, so they bind (and re-bind) as one. */ +export const WORK_CALENDAR_HOOK_PACKAGE = 'objectql:work-calendar'; + +/** Exception rows read per page while loading one calendar. */ +const EXCEPTION_PAGE = 1000; + +/** The engine surface the service reads through. */ +export interface WorkCalendarReadEngine { + find(object: string, query: Record): Promise; +} + +/** The engine surface the hooks register on. */ +export interface WorkCalendarHookEngine extends WorkCalendarReadEngine { + registerHook(event: string, handler: (ctx: any) => unknown, options?: Record): void; + unregisterHooksByPackage?(packageId: string): number; +} + +export interface WorkCalendarServiceOptions { + /** The engine, resolved per read so plugin order cannot leave the service without it. */ + getEngine: () => WorkCalendarReadEngine | undefined; + /** Is the calendar object registered on this kernel? Without it no calendar resolves. */ + hasCalendarObject?: () => boolean; + /** + * The tenancy posture, read per computation. Omitted, it is the posture the + * engine from `getEngine` enforces ({@link enginePostureOf}). + */ + posture?: () => TenancyPosture; + /** Milliseconds now — injectable for the TTL pin. */ + now?: () => number; + ttlMs?: number; +} + +type Row = Record; + +const isRow = (v: unknown): v is Row => !!v && typeof v === 'object' && !Array.isArray(v); + +/** A stored or carried organization id, or `undefined` for none. */ +function organizationOf(value: unknown): string | undefined { + return value === undefined || value === null || value === '' ? undefined : String(value); +} + +/** + * The tenancy posture an engine enforces, through the engine's own reader + * (`resolveEnginePosture`), read live: the posture SecurityPlugin injected on + * the engine, else the deployment's configuration, else `isolated` when that + * cannot be read. + */ +export function enginePostureOf(engine?: unknown): TenancyPosture { + const provider = (engine as { tenancyPostureProvider?: () => string | undefined } | null | undefined)?.tenancyPostureProvider; + return resolveEnginePosture.call({ tenancyPostureProvider: provider }); +} + +/** Where the hooks' elevated reads run; `read: false` when they make none. */ +interface ReadScope { + read: boolean; + organizationId?: string | undefined; + /** The create's row names an organization other than the session's. */ + elsewhere?: boolean; +} + +/** May an elevated calendar read run in `organizationId`? Not without one, outside `single`. */ +function mayReadIn(organizationId: string | undefined, posture: TenancyPosture): boolean { + return organizationId !== undefined || posture === 'single'; +} + +/** The elevated read context in the organization a computation belongs to (open point 4). */ +function readContext(organizationId: string | undefined, transaction?: unknown): Row { + const context: Row = { isSystem: true }; + if (organizationId !== undefined) context.tenantId = organizationId; + if (transaction !== undefined) context.transaction = transaction; + return context; +} + +function namedCode(ref: WorkCalendarRef): string | undefined { + const code = typeof ref.calendar === 'string' ? ref.calendar.trim() : ''; + return code === '' ? undefined : code; +} + +const CODE_RE = new RegExp(WORK_CALENDAR_CODE_PATTERN); + +/** ADR-0157: the calendar service. See the module note. */ +export class WorkCalendarService implements IWorkCalendarService { + private readonly cache = new Map }>(); + + constructor(private readonly options: WorkCalendarServiceOptions) {} + + resolve(ref: WorkCalendarRef): Promise { + // No organization, outside `single`: refused before any read, the cache's + // included, so a calendar resolved under another posture is never served. + const posture = this.options.posture?.() ?? enginePostureOf(this.options.getEngine()); + if (!mayReadIn(organizationOf(ref.organizationId), posture)) { + return Promise.reject(new WorkCalendarUnresolvedError('no_organization', namedCode(ref))); + } + const now = (this.options.now ?? Date.now)(); + const key = JSON.stringify([organizationOf(ref.organizationId) ?? null, namedCode(ref) ?? null]); + const hit = this.cache.get(key); + if (hit && now - hit.at < (this.options.ttlMs ?? WORK_CALENDAR_CACHE_TTL_MS)) return hit.calendar; + const calendar = this.load(ref); + this.cache.set(key, { at: now, calendar }); + // A refusal is never cached: the next computation reads the rows again. + calendar.catch(() => { + if (this.cache.get(key)?.calendar === calendar) this.cache.delete(key); + }); + return calendar; + } + + async isWorkingTime(ref: WorkCalendarRef, at: number | Date): Promise { + return isWorkingTime(await this.resolve(ref), at); + } + + async addWorkingDays(ref: WorkCalendarRef, day: string, days: number): Promise { + return addWorkingDays(await this.resolve(ref), day, days); + } + + async workingDaysBetween(ref: WorkCalendarRef, start: string, end: string): Promise { + return workingDaysBetween(await this.resolve(ref), start, end); + } + + async addWorkingHours(ref: WorkCalendarRef, start: number | Date, hours: number): Promise { + return addWorkingHours(await this.resolve(ref), start, hours); + } + + invalidate(): void { + this.cache.clear(); + } + + /** ADR-0157 D2: the named code, else the organization default, else refuse. */ + private async load(ref: WorkCalendarRef): Promise { + const code = namedCode(ref); + // A code that is not a calendar code names no calendar; it is never sent + // to the query layer, where a `{…}` spelling would read as a filter token. + if (code !== undefined && !CODE_RE.test(code)) throw new WorkCalendarUnresolvedError('not_found', code); + const engine = this.options.getEngine(); + // A kernel without the calendar object holds no calendar (the rate table's rule). + if (!engine || this.options.hasCalendarObject?.() === false) { + throw new WorkCalendarUnresolvedError(code === undefined ? 'no_default' : 'not_found', code); + } + const context = readContext(organizationOf(ref.organizationId)); + const rows = (await engine.find(WORK_CALENDAR_OBJECT, { + where: code === undefined ? { is_default: true } : { code }, + limit: 2, + context, + })).filter(isRow); + if (rows.length === 0) throw new WorkCalendarUnresolvedError(code === undefined ? 'no_default' : 'not_found', code); + if (rows.length > 1) throw new WorkCalendarUnresolvedError('ambiguous', code); + const calendar = rows[0]!; + const exceptions: Row[] = []; + for (let offset = 0; ; offset += EXCEPTION_PAGE) { + const page = (await engine.find(WORK_CALENDAR_EXCEPTION_OBJECT, { + where: { calendar: calendar.id }, + orderBy: [{ field: 'date', order: 'asc' }, { field: 'id', order: 'asc' }], + limit: EXCEPTION_PAGE, + offset, + fields: ['date', 'kind', 'periods'], + context, + })).filter(isRow); + exceptions.push(...page); + if (page.length < EXCEPTION_PAGE) break; + } + return buildWorkCalendar(calendar, exceptions); + } +} + +// ── The write hooks ───────────────────────────────────────────────────── + +interface FieldRefusal { + field: string; + code: FieldErrorCode; + message: string; + value?: unknown; +} + +function refuse(object: string, problems: FieldRefusal[]): never { + const noun = object === WORK_CALENDAR_OBJECT ? 'working calendar' : 'calendar exception'; + throw validationFailure(`The ${noun} cannot be saved: ${problems.map((p) => p.message).join(' ')}`, problems); +} + +function hasOwn(row: Row, key: string): boolean { + return Object.prototype.hasOwnProperty.call(row, key); +} + +/** One period column's refusal, or none (ADR-0157 D7, D10). */ +function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined { + const parsed = parseWorkPeriods(value); + if (parsed.ok) return undefined; + const message = `${field} ${parsed.message}.`; + // Two plain literals, one per branch: a field-level ADR-0114 code, never `error.code`. + if (parsed.reason === 'malformed') return { field, code: 'invalid_format', message, value }; + return { field, code: 'invalid_value', message, value }; +} + +/** + * Where an insert's elevated reads run: the session's organization (see the + * module note), `read: false` when the hooks make none. + */ +function insertReadOrganization(ctx: any, row: Row, posture: TenancyPosture): ReadScope { + const organizationId = organizationOf(ctx?.session?.organizationId); + const named = organizationOf(row.organization_id); + if (named !== undefined && named !== organizationId) return { read: false, elsewhere: true }; + return mayReadIn(organizationId, posture) ? { read: true, organizationId } : { read: false }; +} + +export interface WorkCalendarHookOptions { + /** The organization's `localization.timezone`, for a create that leaves `timezone` out (ADR-0157 D7). */ + timezoneOf?: (organizationId: string | undefined) => Promise; + /** The tenancy posture; omitted, the one the hooked engine enforces ({@link enginePostureOf}). */ + posture?: () => TenancyPosture; +} + +/** + * Judge a calendar row's post-image: the columns the write carries, and the + * pair they belong to. `scope.read` false skips the one-default judgement, + * which reads (see the module note). + */ +async function judgeCalendar( + engine: WorkCalendarReadEngine, + ctx: any, + data: Row, + previous: Row | undefined, + scope: ReadScope, +): Promise { + const problems: FieldRefusal[] = []; + for (const field of WORK_CALENDAR_WEEKDAY_FIELDS) { + if (!hasOwn(data, field)) continue; + const refusal = periodsRefusal(field, data[field]); + if (refusal) problems.push(refusal); + } + if (hasOwn(data, 'maintained_from') || hasOwn(data, 'maintained_through')) { + const pick = (k: string) => calendarDayOf(hasOwn(data, k) ? data[k] : previous?.[k]); + const from = pick('maintained_from'); + const through = pick('maintained_through'); + if (from !== undefined && through !== undefined && from > through) { + problems.push({ + field: 'maintained_through', + code: 'invalid_value', + message: `maintained_through (${through}) is before maintained_from (${from}).`, + value: through, + }); + } + } + // One default per organization (ADR-0157 D2): judged when the write makes + // this row a default, against every OTHER default the organization holds. + // A create placed in another organization cannot be judged there, so its + // default is refused, with no read (see the module note). + if (scope.elsewhere && data.is_default === true) { + problems.push({ + field: 'is_default', + code: 'invalid_value', + message: + 'This calendar is created in an organization other than the one you are working in, so it cannot be marked ' + + 'the default here. Create it while working in that organization, or create it without Default and set ' + + 'Default afterwards by editing it.', + value: true, + }); + } else if (scope.read && data.is_default === true && previous?.is_default !== true) { + const others = (await engine.find(WORK_CALENDAR_OBJECT, { + where: { is_default: true }, + fields: ['id', 'code'], + limit: 2, + context: readContext(scope.organizationId, ctx?.transaction), + })).filter(isRow).filter((r) => previous === undefined || String(r.id) !== String(previous.id)); + if (others.length > 0) { + problems.push({ + field: 'is_default', + code: 'invalid_value', + message: `The calendar '${String(others[0]!.code ?? others[0]!.id)}' is already the default in this organization; clear its Default flag first.`, + value: true, + }); + } + } + if (problems.length > 0) refuse(WORK_CALENDAR_OBJECT, problems); +} + +/** Judge an exception row's post-image (ADR-0157 D10) when the write carries its kind or periods. */ +function judgeException(data: Row, previous: Row | undefined): void { + if (!hasOwn(data, 'kind') && !hasOwn(data, 'periods')) return; + const post: Row = { ...(previous ?? {}), ...data }; + if (post.kind !== 'off' && post.kind !== 'on') return; // the select's own door answers it + const day = exceptionDayOf(post); + if (typeof day !== 'string') return; + const malformed = periodsRefusal('periods', post.periods); + const message = `This exception ${day}.`; + if (post.kind === 'off') { + refuse(WORK_CALENDAR_EXCEPTION_OBJECT, [{ field: 'periods', code: 'invalid_value', message, value: post.periods }]); + } + refuse(WORK_CALENDAR_EXCEPTION_OBJECT, [ + malformed ?? { field: 'periods', code: 'required', message, value: post.periods }, + ]); +} + +/** + * Bind the hooks on the engine — idempotently: a re-run replaces the binding. + * Returns `false`, after saying so at `warn`, when the engine has no hook + * registry (a test double): the refusals and the cache invalidation are then + * not in force. + */ +export function installWorkCalendarHooks( + engine: WorkCalendarHookEngine | null | undefined, + service: Pick, + options: WorkCalendarHookOptions = {}, + logger?: { warn?: (msg: string) => void }, +): boolean { + if (!engine || typeof engine.registerHook !== 'function') { + logger?.warn?.( + '[objectql] the engine exposes no hook registry — working-calendar rows are NOT validated at write, ' + + 'and the calendar cache is dropped only by its TTL', + ); + return false; + } + engine.unregisterHooksByPackage?.(WORK_CALENDAR_HOOK_PACKAGE); + const bind = (event: string, object: string | string[], handler: (ctx: any) => unknown) => + engine.registerHook(event, handler, { object, packageId: WORK_CALENDAR_HOOK_PACKAGE }); + const postureNow = () => options.posture?.() ?? enginePostureOf(engine); + + bind('beforeInsert', WORK_CALENDAR_OBJECT, async (ctx: any) => { + const row = ctx?.input?.data; + if (!isRow(row)) return; + const scope = insertReadOrganization(ctx, row, postureNow()); + const zone = row.timezone; + if ((zone === undefined || zone === null || zone === '') && options.timezoneOf && scope.read) { + const fallback = await options.timezoneOf(scope.organizationId); + if (fallback) row.timezone = fallback; + } + await judgeCalendar(engine, ctx, row, undefined, scope); + }); + bind('beforeUpdate', WORK_CALENDAR_OBJECT, async (ctx: any) => { + const data = ctx?.input?.data; + const previous = isRow(ctx?.previous) ? ctx.previous : undefined; + if (!isRow(data) || !previous) return; + // The stored row's own organization: the engine read it under the write's own scope. + const organizationId = organizationOf(previous.organization_id); + const scope: ReadScope = mayReadIn(organizationId, postureNow()) ? { read: true, organizationId } : { read: false }; + await judgeCalendar(engine, ctx, data, previous, scope); + }); + bind('beforeInsert', WORK_CALENDAR_EXCEPTION_OBJECT, (ctx: any) => { + const row = ctx?.input?.data; + if (isRow(row)) judgeException(row, undefined); + }); + bind('beforeUpdate', WORK_CALENDAR_EXCEPTION_OBJECT, (ctx: any) => { + const data = ctx?.input?.data; + if (isRow(data) && isRow(ctx?.previous)) judgeException(data, ctx.previous); + }); + const both = [WORK_CALENDAR_OBJECT, WORK_CALENDAR_EXCEPTION_OBJECT]; + for (const event of ['afterInsert', 'afterUpdate', 'afterDelete']) bind(event, both, () => service.invalidate()); + return true; +} diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 0ded343f094..e72653cf4a9 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -224,6 +224,7 @@ "ITeamGraphService (interface)", "ITriggerApiService (interface)", "IWebhookService (interface)", + "IWorkCalendarService (interface)", "ImportObjectOpts (interface)", "ImportObjectResult (interface)", "InboxListResult (interface)", @@ -386,6 +387,8 @@ "UploadArtifactResult (interface)", "UserModelMessage (type)", "ValidationResult (type)", + "WORK_CALENDAR_SERVICE (const)", + "WorkCalendarRef (interface)", "WriteObservabilityOptions (interface)", "decodeStorageListCursor (function)", "encodeStorageListCursor (function)", diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 58480a4a298..9fe1d348350 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -929,6 +929,19 @@ "ValueRoundTripCase (interface)", "ValueRoundTripColumn (type)", "ValueShapeFieldDef (interface)", + "WORK_CALENDAR_CODE_PATTERN (const)", + "WORK_CALENDAR_INVALID_CODE (const)", + "WORK_CALENDAR_MAINTENANCE_LEAD_DAYS (const)", + "WORK_CALENDAR_NOT_MAINTAINED_CODE (const)", + "WORK_CALENDAR_UNRESOLVED_CODE (const)", + "WORK_CALENDAR_WEEKDAY_FIELDS (const)", + "WallClockParts (interface)", + "WorkCalendar (interface)", + "WorkCalendarDay (interface)", + "WorkCalendarUnresolvedReason (type)", + "WorkPeriod (interface)", + "WorkPeriodsParse (type)", + "WorkPeriodsRefusal (type)", "ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody (function)", "actionTextsWithoutRunnableCode (function)", @@ -1170,6 +1183,8 @@ "validateDriverConfig (function)", "valueRoundTripDivergence (function)", "valueSchemaFor (function)", - "virtualFieldAggregateRemedy (function)" + "virtualFieldAggregateRemedy (function)", + "wallClockToUtcMs (function)", + "zonedWallClockToUtcMs (function)" ] } diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index 12555bd19c8..fc3930ed958 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -224,6 +224,7 @@ "ITeamGraphService": "src/contracts/sharing-service.ts#ITeamGraphService (interface)", "ITriggerApiService": "src/contracts/trigger-api-service.ts#ITriggerApiService (interface)", "IWebhookService": "src/contracts/webhook-service.ts#IWebhookService (interface)", + "IWorkCalendarService": "src/contracts/work-calendar-service.ts#IWorkCalendarService (interface)", "ImportObjectOpts": "src/contracts/external-datasource-service.ts#ImportObjectOpts (interface)", "ImportObjectResult": "src/contracts/external-datasource-service.ts#ImportObjectResult (interface)", "InboxListResult": "src/contracts/notification-service.ts#InboxListResult (interface)", @@ -386,6 +387,8 @@ "UploadArtifactResult": "src/contracts/package-service.ts#UploadArtifactResult (interface)", "UserModelMessage": "node_modules/@ai-sdk/provider-utils/dist/index.d.ts#UserModelMessage (type)", "ValidationResult": "src/kernel/plugin-validator.zod.ts#ValidationResult (type)", + "WORK_CALENDAR_SERVICE": "src/contracts/work-calendar-service.ts#WORK_CALENDAR_SERVICE (const)", + "WorkCalendarRef": "src/contracts/work-calendar-service.ts#WorkCalendarRef (interface)", "WriteObservabilityOptions": "src/contracts/data-engine.ts#WriteObservabilityOptions (interface)", "decodeStorageListCursor": "src/contracts/storage-service.ts#decodeStorageListCursor (function)", "encodeStorageListCursor": "src/contracts/storage-service.ts#encodeStorageListCursor (function)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index 101f17c2b33..c0bb460e591 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -915,6 +915,19 @@ "ValueRoundTripCase": "src/data/value-roundtrip-conformance.ts#ValueRoundTripCase (interface)", "ValueRoundTripColumn": "src/data/value-roundtrip-conformance.ts#ValueRoundTripColumn (type)", "ValueShapeFieldDef": "src/data/field-value.zod.ts#ValueShapeFieldDef (interface)", + "WORK_CALENDAR_CODE_PATTERN": "src/data/work-calendar.ts#WORK_CALENDAR_CODE_PATTERN (const)", + "WORK_CALENDAR_INVALID_CODE": "src/data/work-calendar.ts#WORK_CALENDAR_INVALID_CODE (const)", + "WORK_CALENDAR_MAINTENANCE_LEAD_DAYS": "src/data/work-calendar.ts#WORK_CALENDAR_MAINTENANCE_LEAD_DAYS (const)", + "WORK_CALENDAR_NOT_MAINTAINED_CODE": "src/data/work-calendar.ts#WORK_CALENDAR_NOT_MAINTAINED_CODE (const)", + "WORK_CALENDAR_UNRESOLVED_CODE": "src/data/work-calendar.ts#WORK_CALENDAR_UNRESOLVED_CODE (const)", + "WORK_CALENDAR_WEEKDAY_FIELDS": "src/data/work-calendar.ts#WORK_CALENDAR_WEEKDAY_FIELDS (const)", + "WallClockParts": "src/data/wall-clock.ts#WallClockParts (interface)", + "WorkCalendar": "src/data/work-calendar.ts#WorkCalendar (interface)", + "WorkCalendarDay": "src/data/work-calendar.ts#WorkCalendarDay (interface)", + "WorkCalendarUnresolvedReason": "src/data/work-calendar.ts#WorkCalendarUnresolvedReason (type)", + "WorkPeriod": "src/data/work-calendar.ts#WorkPeriod (interface)", + "WorkPeriodsParse": "src/data/work-calendar.ts#WorkPeriodsParse (type)", + "WorkPeriodsRefusal": "src/data/work-calendar.ts#WorkPeriodsRefusal (type)", "ZeroLimitConformanceCase": "src/data/pagination-conformance.ts#ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody": "src/data/hook-refusal-codes.ts#actionRefusalsWithoutSandboxedBody (function)", "actionTextsWithoutRunnableCode": "src/data/hook-refusal-codes.ts#actionTextsWithoutRunnableCode (function)", @@ -1156,6 +1169,8 @@ "validateDriverConfig": "src/data/driver/config-registry.zod.ts#validateDriverConfig (function)", "valueRoundTripDivergence": "src/data/value-roundtrip-conformance.ts#valueRoundTripDivergence (function)", "valueSchemaFor": "src/data/field-value.zod.ts#valueSchemaFor (function)", - "virtualFieldAggregateRemedy": "src/data/aggregate-field-type-compatibility.ts#virtualFieldAggregateRemedy (function)" + "virtualFieldAggregateRemedy": "src/data/aggregate-field-type-compatibility.ts#virtualFieldAggregateRemedy (function)", + "wallClockToUtcMs": "src/data/wall-clock.ts#wallClockToUtcMs (function)", + "zonedWallClockToUtcMs": "src/data/wall-clock.ts#zonedWallClockToUtcMs (function)" } } diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index adf3e8b2798..92f2b6a1ddf 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1943,6 +1943,18 @@ export const ERROR_CODE_LEDGER = { 'STACK_COMPOSE_FUNCTIONS_SHAPE_CONFLICT', // `functions` authored in the map form by one stack and the array form by another 'STACK_COMPOSE_KEY_CONFLICT', // a single-valued top-level key is declared with different values by two stacks 'STACK_COMPOSE_OBJECT_CONFLICT', // the same object name is defined by more than one stack under the default `objectConflict: 'error'` + // [ADR-0157 D2, D7, D8, D10] The working-calendar refusals, every one + // `status: 400`. The codes are this package's constants + // (`data/work-calendar.ts`, where the provenance scan reads them); the three + // error classes that carry them are `@objectstack/formula`'s + // (`work-calendar.ts`). The calendar service (`@objectstack/objectql`) and + // the working-day formula functions throw them; the thrown value is the + // boundary on this tree (no HTTP door answers with them yet — the approval + // sweep that reads them skips and retries, ADR-0157 D9). No wall-clock + // answer stands in for any. + 'ERR_WORK_CALENDAR_INVALID', // a stored calendar or exception row the arithmetic cannot read as written (a period crossing midnight, a zone that is not IANA, an `on` row without periods); `field` names the column + 'ERR_WORK_CALENDAR_NOT_MAINTAINED', // the computation needs a date outside the calendar's `maintained_from`..`maintained_through` span (D8); fixed by entering that span's holidays and moving the bound + 'ERR_WORK_CALENDAR_UNRESOLVED', // no calendar resolves under D2: the named code is absent, the organization has no default, more than one row answers, or no organization is named outside the `single` posture (`reason`) ], '@objectstack/lint': [ // [#20206] `packagesOf` (`object-graph.ts`) refuses a present non-array diff --git a/packages/spec/src/contracts/index.ts b/packages/spec/src/contracts/index.ts index d3282d16e11..49e930a2554 100644 --- a/packages/spec/src/contracts/index.ts +++ b/packages/spec/src/contracts/index.ts @@ -59,6 +59,8 @@ export * from './sharing-service.js'; export * from './rls-membership-resolver.js'; // [ADR-0142 D1/D2] The ownership-queue service (registered as `ownership-queue`, never `queue`). export * from './ownership-queue-service.js'; +// [ADR-0157 D1/D2] The working-calendar service (registered as `work-calendar`). +export * from './work-calendar-service.js'; export * from './share-link-service.js'; // './report-service.js' (the saved-report contract and its seven types) removed // (#20102): the saved-report stack it described had zero callers in any repo. diff --git a/packages/spec/src/contracts/work-calendar-service.ts b/packages/spec/src/contracts/work-calendar-service.ts new file mode 100644 index 00000000000..b35d8776d44 --- /dev/null +++ b/packages/spec/src/contracts/work-calendar-service.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * @objectstack/spec/contracts/work-calendar-service + * + * [ADR-0157 D1, D2, D8; open point 4] The working-calendar service: resolve a + * calendar under D2 (the named code, else the organization's default, else a + * refusal, never wall-clock time), load its exceptions, cache the result until + * a calendar or exception row is written, and count working time over it. + * `@objectstack/objectql` implements it (`WorkCalendarService`) and registers + * it under {@link WORK_CALENDAR_SERVICE}; the arithmetic it counts with is + * `@objectstack/formula`'s. + * + * Every method rejects with `ERR_WORK_CALENDAR_UNRESOLVED`, + * `ERR_WORK_CALENDAR_NOT_MAINTAINED` or `ERR_WORK_CALENDAR_INVALID` + * (`@objectstack/spec/data`; `isWorkCalendarRefusal` in + * `@objectstack/formula` classifies them); none answers wall-clock time. + */ + +import type { WorkCalendar } from '../data/work-calendar.js'; + +/** Kernel service name the working-calendar service registers under (`ctx.getService`). */ +export const WORK_CALENDAR_SERVICE = 'work-calendar' as const; + +/** + * Which calendar a computation reads (ADR-0157 D2, open point 4). + * + * `organizationId` is the organization the COMPUTATION belongs to: the + * record's own `organization_id` (for the approval sweep, the request's), + * never the caller's ambient active organization. A system context has none, + * and a package-seeded calendar carries the same code in every organization, + * so a code without an organization names nothing. + * + * The service reads in that organization elevated, as the exchange-rate + * reader does (ADR-0144 D5): a rank-and-file member cannot read the calendar + * tables, yet every deadline of theirs is counted through them. + * + * An absent `organizationId` is refused `ERR_WORK_CALENDAR_UNRESOLVED` + * (reason `no_organization`) before any read, in every tenancy posture but + * `single`. Under `single` there is one logical tenant and the read runs + * without an organization scope; a read that matches more than one row is + * refused `ambiguous`, never settled by picking one. + */ +export interface WorkCalendarRef { + readonly organizationId: string | undefined; + /** The code the consumer names (a formula argument, `escalation.calendar`); blank takes the organization default. */ + readonly calendar?: string | null; +} + +/** + * The working-calendar service contract. + * + * {@link IWorkCalendarService.resolve} hands back plain, frozen data, so a + * caller that must compute synchronously (a formula evaluated over pinned + * data) resolves first and then counts with `@objectstack/formula`'s + * `addWorkingDays` and its siblings itself. + */ +export interface IWorkCalendarService { + /** The calendar a computation reads, under D2. */ + resolve(ref: WorkCalendarRef): Promise; + /** Is the instant inside a working period of its own local date? */ + isWorkingTime(ref: WorkCalendarRef, at: number | Date): Promise; + /** The calendar day `days` working days after `day` (the start day is never counted). */ + addWorkingDays(ref: WorkCalendarRef, day: string, days: number): Promise; + /** The working days from `start` (excluded) to `end` (included); negative when `end` is earlier. */ + workingDaysBetween(ref: WorkCalendarRef, start: string, end: string): Promise; + /** The instant `hours` of working time after `start`, as epoch milliseconds (D11 elapsed time). */ + addWorkingHours(ref: WorkCalendarRef, start: number | Date, hours: number): Promise; + /** Drop every cached calendar; the next computation reads the rows again. */ + invalidate(): void; +} diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index cef95997016..71d204c25bf 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -173,6 +173,13 @@ export * from './date-macros.zod'; // rule (#8690 C half). `ui/dashboard.zod.ts` re-exports the vocabulary. export * from './date-range-presets'; export * from './calendar-day'; +// [ADR-0157 D11, open point 3] The wall-clock → instant primitive (the one +// daylight-saving rule), below `@objectstack/formula` so the working-calendar +// arithmetic there and every other reader convert through one rule; +// `@objectstack/core` re-exports it. Beside it, the working calendar's codes, +// column names and resolved-calendar types (the arithmetic is formula's). +export * from './wall-clock'; +export * from './work-calendar'; // [ADR-0053 D-D1, amended 2026-09-30 — #5930] The shared `FilterCondition → // FilterCondition` lowering the seams run once, after the comparand doors and // after filter-token resolution: the `$between` split, the whole-day upper diff --git a/packages/spec/src/data/wall-clock.ts b/packages/spec/src/data/wall-clock.ts new file mode 100644 index 00000000000..2d3f2c65686 --- /dev/null +++ b/packages/spec/src/data/wall-clock.ts @@ -0,0 +1,164 @@ +// Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Wall clock → instant: the platform's ONE daylight-saving rule (ADR-0053, + * ADR-0157 D11). + * + * A wall clock (`2026-08-01 06:00`) names a reading on a clock; only a + * reference timezone turns it into an instant, and on a daylight-saving + * transition day two readings are not a bijection with instants. How a + * skipped or repeated reading resolves is a RULE, and every consumer must apply + * the same one: bulk import's offset-free cells, the date-bucket drill ranges, + * the working calendar's periods (ADR-0157 D11) and the working-day formula + * functions all read through {@link zonedWallClockToUtcMs}. + * + * It lived in `@objectstack/core` (`utils/datetime.ts`) until ADR-0157 open + * point 3 moved it here, as `nextUtcCalendarDay` moved before it + * (`./calendar-day.ts`): `@objectstack/formula` depends on `@objectstack/spec` + * and never on core, and a private copy in formula would be the second DST rule + * D11 forbids. `@objectstack/core` re-exports both functions and the + * {@link WallClockParts} type from its own `utils/datetime.ts`, so its published + * surface and every caller's import site are unchanged. The bodies moved + * verbatim; core's `datetime.test.ts` keeps pinning them through that + * re-export. + * + * Pure: `Intl.DateTimeFormat` and `Date` only, no host clock and no host zone. + */ + +/** + * A wall clock as a human writes it — calendar day plus an optional + * time-of-day, with **no zone attached**. `2026-08-01 06:00:00` is this shape: + * it names a reading on a clock, and only a reference timezone turns it into an + * instant. Omitted time components default to 0, so a bare calendar day + * (`@objectstack/core`'s `CalendarParts`) is midnight. + */ +export interface WallClockParts { + year: number; + /** 1-12. */ + month: number; + day: number; + /** 0-23. */ + hour?: number; + minute?: number; + second?: number; + millisecond?: number; +} + +/** + * [#20599] The epoch milliseconds of a wall clock read as **UTC**: `Date.UTC` + * without its two-digit-year remap. The zone-free sibling of + * {@link zonedWallClockToUtcMs}, and the one construction this package and its + * callers use to build a UTC instant from year / month / day / time parts. + * + * Not `Date.UTC(year, …)` and not `new Date(year, …)`: both read a year from 0 + * to 99 as 1900 + year (ECMA-262 `MakeFullYear`), so `0050-01-01` is built as + * 1950-01-01 — while 0001..9999 is a `date`'s supported range ([#20280] a + * `datetime`'s is 1000..9999; `isOutsideTemporalYearRange`). + * `setUTCFullYear` takes the year as written. + * + * Every component rolls over past its end exactly as `Date.UTC` rolls it, and + * callers rely on that: `month: 13` is January of the next year, `month: 0` is + * December of the previous one, `day: 0` is the previous month's last day, + * `day: 32` runs into the next month, and `hour: 24` is the next day's + * midnight. Omitted time components default to 0. A `NaN` or non-finite + * component, or an instant outside the `Date` range, gives `NaN`, as + * `Date.UTC` does. + */ +export function wallClockToUtcMs(parts: WallClockParts): number { + const dt = new Date(0); + dt.setUTCFullYear(parts.year, parts.month - 1, parts.day); + return dt.setUTCHours(parts.hour ?? 0, parts.minute ?? 0, parts.second ?? 0, parts.millisecond ?? 0); +} + +/** + * The UTC instant (epoch ms) at which a **wall clock** reading happens in + * reference timezone `tz` — the general inverse of `@objectstack/core`'s + * `calendarPartsInTz`, of which its `zonedDateStartToUtcMs` is the midnight + * special case. + * + * `2026-08-01 06:00:00` in `Asia/Shanghai` is `2026-07-31T22:00:00Z`: a + * different day, month and quarter. That gap is why this direction exists as a + * shared primitive at all — bulk import (#8485) reads offset-free spreadsheet + * cells, which are wall clocks and nothing more, and `new Date(cell)` resolves + * them against the **process** `TZ`, i.e. a host setting rather than the + * tenant's configured zone. + * + * DST-safe: the zone offset is read from the platform tz database via + * `Intl.DateTimeFormat` (never hand-computed), and a two-pass resolution settles + * the case where the offset differs side-to-side of the target instant. Two + * wall clocks are not a bijection with instants, and this function resolves + * both degenerate cases to the **earlier candidate instant** — in both, the + * final pass reads the offset on the DST side of the transition (measured, not + * merely intended — `@objectstack/core`'s `datetime.test.ts` pins both): + * - a clock reading the zone **skips** (spring forward: `02:30` on a US + * spring-forward day) settles on the *post*-transition offset (EDT, −04), + * which places the instant just **before** the gap: it reads `01:30` EST + * locally, not `03:30` EDT. Note this is the opposite of Temporal's + * `'compatible'` disambiguation, which pushes a gap reading forward; + * - a clock reading that happens **twice** (fall back: `01:30` on a US + * fall-back day) resolves to its first occurrence, the one still on the + * pre-transition DST offset (EDT, −04). + * + * A spreadsheet cell naming a wall clock that its zone never had is ambiguous + * by construction; what matters for an import is that the answer is + * deterministic and host-independent, which both branches above are. + * + * FALLBACK — an unset, `'UTC'`, or invalid `tz` reads the wall clock **as UTC**, + * never as the process-local clock. Every caller of this family already degrades + * that way (`zonedDateStartToUtcMs`, and the export renderer's cell path), + * and a host `TZ` fallback would reintroduce exactly the deployment-dependent + * instant this primitive exists to remove. A parts object that produces an + * invalid date (`NaN` components) returns `NaN`, as `Date.UTC` does. + * + * [#20599] A year from 0001 to 0099 is read as written, never as 1900 + year: + * both the wall clock and the offset read below go through + * {@link wallClockToUtcMs}, not `Date.UTC`. The offset read takes the zone's + * year with its era, because `Intl`'s `year` part is an ERA year — 1 BC reads + * `1` — and the first probe for a wall clock early on 0001-01-01 in a zone + * west of UTC lands in year 0. + */ +export function zonedWallClockToUtcMs(parts: WallClockParts, tz?: string): number { + const wallAsUtc = wallClockToUtcMs(parts); + if (!tz || tz === 'UTC' || Number.isNaN(wallAsUtc)) return wallAsUtc; + try { + // The tz offset (local − UTC, in ms) at instant `t`: read t's wall clock in + // `tz`, re-interpret those parts as UTC, and subtract t. `formatToParts` + // resolves no finer than a second, so `t` is truncated to a whole second + // first — otherwise a sub-second wall clock leaks its milliseconds into the + // "offset" and shifts the answer by them (a real defect while generalising + // this from the date-only form, where ms was always 0). + const offsetAt = (t: number): number => { + const whole = Math.floor(t / 1000) * 1000; + const p = new Intl.DateTimeFormat('en-US', { + timeZone: tz, + hourCycle: 'h23', + era: 'short', + year: 'numeric', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit', + }).formatToParts(new Date(whole)); + const g = (k: string) => Number(p.find((x) => x.type === k)?.value); + const eraYear = g('year'); + const year = p.find((x) => x.type === 'era')?.value === 'BC' ? 1 - eraYear : eraYear; + return ( + wallClockToUtcMs({ + year, + month: g('month'), + day: g('day'), + hour: g('hour'), + minute: g('minute'), + second: g('second'), + }) - whole + ); + }; + // Want U such that localParts(U) == the wall clock, i.e. U = wallAsUtc − offset(U). + // Iterate from the zero-offset guess; converges in ≤2 steps off a DST edge. + const off1 = offsetAt(wallAsUtc - offsetAt(wallAsUtc)); + return wallAsUtc - off1; + } catch { + return wallAsUtc; // unknown zone → the wall clock read as UTC + } +} diff --git a/packages/spec/src/data/work-calendar.ts b/packages/spec/src/data/work-calendar.ts new file mode 100644 index 00000000000..a757c06dc42 --- /dev/null +++ b/packages/spec/src/data/work-calendar.ts @@ -0,0 +1,125 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Working calendars (ADR-0157): the refusal codes, the column names, the + * machine-code shape and the plain-data shape of one resolved calendar. + * + * Prime Directive #2: spec holds schemas, types and constants only. The + * arithmetic over these types — the period parser, `buildWorkCalendar`, the + * four counts and the three error classes that carry these codes — lives in + * `@objectstack/formula` (`work-calendar.ts`), where the working-day formula + * functions and the calendar service (`@objectstack/objectql`) both read it + * over a dependency edge they already have. The one daylight-saving rule it + * converts through stays here (`./wall-clock.ts`, D11). The service contract + * is `IWorkCalendarService` (`../contracts/work-calendar-service.ts`). + * + * ## The rows (ADR-0157 D1, D7, D10) + * + * - A calendar carries one period list per weekday + * ({@link WORK_CALENDAR_WEEKDAY_FIELDS}), each local `HH:mm-HH:mm` periods + * separated by commas; a blank weekday is not worked. A period that crosses + * midnight is refused (D7); `24:00` is a legal end (D10). + * - An exception row overrides one date: `off` carries no periods, `on` + * carries that date's FULL periods (D10). One row per calendar and date. + * - `maintained_from` .. `maintained_through` is the span the organization + * keeps the calendar's exceptions for; a computation that needs a date + * outside it is refused (D8), never read from the weekly pattern alone or + * from wall-clock time (D2). + */ + +// ── Refusal codes (ADR-0112 ledger, `@objectstack/spec`) ───────────────── + +/** ADR-0157 D2: no calendar resolves — the named code is absent, the organization has no single default, or no organization was named where one is required. */ +export const WORK_CALENDAR_UNRESOLVED_CODE = 'ERR_WORK_CALENDAR_UNRESOLVED' as const; + +/** ADR-0157 D3/D8: the computation needs a date outside the calendar's maintained span. */ +export const WORK_CALENDAR_NOT_MAINTAINED_CODE = 'ERR_WORK_CALENDAR_NOT_MAINTAINED' as const; + +/** ADR-0157 D7/D10: a stored calendar or exception row the arithmetic cannot read as written. */ +export const WORK_CALENDAR_INVALID_CODE = 'ERR_WORK_CALENDAR_INVALID' as const; + +/** + * ADR-0157 D2: why a calendar did not resolve. + * + * - `not_found`: the named code is no calendar of the organization. + * - `no_default`: no code was named and the organization marks no default. + * - `ambiguous`: more than one row answers (two defaults); refused, never + * settled by picking one. + * - `no_organization`: the computation names no organization outside the + * `single` tenancy posture, where a code or a default names nothing without + * one. Refused before any read. + */ +export type WorkCalendarUnresolvedReason = 'not_found' | 'no_default' | 'ambiguous' | 'no_organization'; + +// ── Periods ────────────────────────────────────────────────────────────── + +/** One working period, in minutes from local midnight: `0 <= start < end <= 1440`. */ +export interface WorkPeriod { + readonly start: number; + readonly end: number; +} + +/** Why a period list was refused. */ +export type WorkPeriodsRefusal = 'malformed' | 'crosses_midnight' | 'empty_period' | 'overlap'; + +/** A period list read as written, or why it cannot be. */ +export type WorkPeriodsParse = + | { readonly ok: true; readonly periods: readonly WorkPeriod[] } + | { readonly ok: false; readonly reason: WorkPeriodsRefusal; readonly message: string }; + +/** The weekday period columns, Monday first (ISO order); index 0 is Monday. */ +export const WORK_CALENDAR_WEEKDAY_FIELDS = [ + 'monday_periods', + 'tuesday_periods', + 'wednesday_periods', + 'thursday_periods', + 'friday_periods', + 'saturday_periods', + 'sunday_periods', +] as const; + +// ── The resolved calendar ──────────────────────────────────────────────── + +/** One exception date: `off` (no periods) or `on` (the date's full periods). */ +export interface WorkCalendarDay { + readonly kind: 'off' | 'on'; + readonly periods: readonly WorkPeriod[]; +} + +/** + * One resolved calendar with its exceptions, as plain data: what the calendar + * service hands a consumer and what every count computes over. Built frozen, + * so a consumer cannot change what a cached calendar answers. + */ +export interface WorkCalendar { + readonly code: string; + /** IANA zone the periods are local to (ADR-0157 D7). */ + readonly timezone: string; + /** First calendar day the exceptions are maintained for (`YYYY-MM-DD`). */ + readonly maintainedFrom: string; + /** Last calendar day the exceptions are maintained for (`YYYY-MM-DD`). */ + readonly maintainedThrough: string; + /** Seven period lists, Monday first ({@link WORK_CALENDAR_WEEKDAY_FIELDS}). */ + readonly weekly: readonly (readonly WorkPeriod[])[]; + /** Exception dates (`YYYY-MM-DD`) inside the maintained span. */ + readonly exceptions: Readonly>; +} + +// ── Names ──────────────────────────────────────────────────────────────── + +/** + * The machine-code shape a calendar is named by (`sys_work_calendar.code`): + * snake_case, as every machine name in the platform. A consumer's code that + * does not match names no calendar, and is never read as a filter token. + */ +export const WORK_CALENDAR_CODE_PATTERN = '^[a-z][a-z0-9_]*$'; + +/** + * ADR-0157 D8: how many days before a calendar's `maintained_through` Setup + * lists it as needing maintenance, before refusals start. Sixty days opens the + * notice around the window in which the next year's public holidays and 调休 + * days are usually published (around or after November), and leaves weeks to + * enter them; a longer lead would flag a calendar before the data to extend + * it exists. + */ +export const WORK_CALENDAR_MAINTENANCE_LEAD_DAYS = 60; diff --git a/scripts/adr-anchors/packages__formula__src__work-calendar.ts.json b/scripts/adr-anchors/packages__formula__src__work-calendar.ts.json new file mode 100644 index 00000000000..e69fbe16def --- /dev/null +++ b/scripts/adr-anchors/packages__formula__src__work-calendar.ts.json @@ -0,0 +1,5 @@ +{ + "file": "packages/formula/src/work-calendar.ts", + "adrs": ["ADR-0157"], + "invariant": "ADR-0157: the working-calendar arithmetic is one copy, in @objectstack/formula, so the calendar service and the working-day formula functions count with one daylight-saving rule (D11, open point 3); it converts only through zonedWallClockToUtcMs. A computation that needs a date outside the calendar's maintained span is refused, never read from the weekly pattern alone or from wall-clock time (D2, D8); a period crossing midnight is refused, 24:00 is a legal end, and an `on` exception carries its date's full periods (D7, D10)." +} diff --git a/scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json b/scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json new file mode 100644 index 00000000000..c5d04e30dd1 --- /dev/null +++ b/scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json @@ -0,0 +1,5 @@ +{ + "file": "packages/objectql/src/work-calendar-service.ts", + "adrs": ["ADR-0157", "ADR-0144"], + "invariant": "ADR-0157 D2: a calendar resolves by the named code, else the organization default, else a refusal with a ledger code, never wall-clock time. Open point 4 follows the ADR-0144 exchange-rate reader: the read is elevated and scoped to the organization the caller names (the record's own), so a member's deadlines are counted through tables the member cannot read. Outside the single tenancy posture (resolveEnginePosture), a computation that names no organization is refused ERR_WORK_CALENDAR_UNRESOLVED before any read, so one organization's calendar never counts another's; the write hooks take the organization from the session and read nothing without one." +} diff --git a/scripts/adr-anchors/packages__spec__src__data__wall-clock.ts.json b/scripts/adr-anchors/packages__spec__src__data__wall-clock.ts.json new file mode 100644 index 00000000000..966a193a628 --- /dev/null +++ b/scripts/adr-anchors/packages__spec__src__data__wall-clock.ts.json @@ -0,0 +1,5 @@ +{ + "file": "packages/spec/src/data/wall-clock.ts", + "adrs": ["ADR-0053", "ADR-0157"], + "invariant": "The platform's one daylight-saving rule (ADR-0053): a wall clock becomes an instant only through zonedWallClockToUtcMs, and a skipped or repeated reading resolves to the earlier candidate. ADR-0157 D11 moved it below @objectstack/formula so the working-day functions read the same rule; a private copy anywhere is a second DST rule." +}