From 92974593888c171b3ca20d80bcdd74656ea32b88 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:35:46 +0000 Subject: [PATCH 01/13] feat(spec): move the wall-clock primitive below formula and add working-calendar arithmetic ADR-0157 open point 3: zonedWallClockToUtcMs and wallClockToUtcMs move from @objectstack/core to @objectstack/spec/data (bodies byte-identical; core re-exports them), and the pure working-time arithmetic over one resolved calendar lands beside them, so the calendar service and the working-day formula functions count with one daylight-saving rule (D11). The three refusal codes are registered in the ADR-0112 ledger. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- packages/core/src/utils/datetime.ts | 146 +---- .../spec/src/api/error-code-ledger.zod.ts | 9 + packages/spec/src/data/index.ts | 6 + packages/spec/src/data/wall-clock.ts | 164 ++++++ packages/spec/src/data/work-calendar.test.ts | 160 +++++ packages/spec/src/data/work-calendar.ts | 553 ++++++++++++++++++ 6 files changed, 905 insertions(+), 133 deletions(-) create mode 100644 packages/spec/src/data/wall-clock.ts create mode 100644 packages/spec/src/data/work-calendar.test.ts create mode 100644 packages/spec/src/data/work-calendar.ts 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/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index adf3e8b2798..c87b076acec 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1943,6 +1943,15 @@ 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, stamped by the + // error classes in `data/work-calendar.ts`, every one `status: 400`. 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, or more than one row answers (`reason`) ], '@objectstack/lint': [ // [#20206] `packagesOf` (`object-graph.ts`) refuses a present non-array diff --git a/packages/spec/src/data/index.ts b/packages/spec/src/data/index.ts index b32ed5b7492..83651d413be 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -173,6 +173,12 @@ 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) and the working-calendar arithmetic built on it, below +// `@objectstack/formula` so the working-day formula functions and the calendar +// service count with one rule. `@objectstack/core` re-exports the primitive. +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.test.ts b/packages/spec/src/data/work-calendar.test.ts new file mode 100644 index 00000000000..c14261ed88e --- /dev/null +++ b/packages/spec/src/data/work-calendar.test.ts @@ -0,0 +1,160 @@ +// 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, + addWorkingDays, + addWorkingHours, + buildWorkCalendar, + isWorkingDay, + isWorkingTime, + parseWorkPeriods, + workingDaysBetween, + type WorkCalendar, +} 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); + }); +}); diff --git a/packages/spec/src/data/work-calendar.ts b/packages/spec/src/data/work-calendar.ts new file mode 100644 index 00000000000..0dfc5edae6a --- /dev/null +++ b/packages/spec/src/data/work-calendar.ts @@ -0,0 +1,553 @@ +// 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 contract package + * + * ADR-0157 open point 3: there is exactly one daylight-saving rule (D11), and + * two readers compute with a calendar — the calendar service + * (`WorkCalendarService`, `@objectstack/objectql`, which the approval clock + * reads) and the working-day formula functions, which evaluate synchronously + * inside `@objectstack/formula` over data pinned before evaluation. Formula + * depends on `@objectstack/spec` and never on a service, so the arithmetic + * sits here, beside the wall-clock primitive it reads (`./wall-clock.ts`), as + * `nextUtcCalendarDay` sits in `./calendar-day.ts`. 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 — protocol, which is + * why it is the contract package's (Prime Directive #2 keeps I/O out of it, + * and there is none here). + * + * ## The rows, as this module reads them (ADR-0157 D1, D7, D10) + * + * - A calendar carries one period list per weekday (`monday_periods` … + * `sunday_periods`, {@link 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 {@link 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 { isValueDomainMember } from '../shared/value-domain.zod'; +import { nextUtcCalendarDay } from './calendar-day'; +import { wallClockToUtcMs, zonedWallClockToUtcMs } from './wall-clock'; + +// ── Refusal codes (ADR-0112 ledger, `@objectstack/spec`) ───────────────── + +/** ADR-0157 D2: no calendar resolves — the named code is absent, or the organization has no single default. */ +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 this module 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. `ambiguous` is more than one + * row answering — two defaults, or a code read without an organization on an + * install that holds several; it is refused, never settled by picking one. + */ +export type WorkCalendarUnresolvedReason = 'not_found' | 'no_default' | 'ambiguous'; + +/** + * ADR-0157 D2: the consumer named no calendar that exists, or named none and + * the organization has no single default. 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( + reason === 'not_found' + ? `No working calendar has the code '${calendar}' in this organization. Create it, or name an existing calendar.` + : reason === 'no_default' + ? '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.' + : 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.', + ); + this.name = 'WorkCalendarUnresolvedError'; + this.reason = reason; + if (calendar !== undefined) this.calendar = calendar; + } +} + +/** + * 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 ────────────────────────────────────────────────────────────── + +/** 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'; + +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; + +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 ──────────────────────────────────────────────── + +/** 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 service + * hands a consumer and what every function below computes over. + */ +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>; +} + +/** + * 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). + */ +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 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] = day; + } + return { code, timezone, maintainedFrom, maintainedThrough, weekly, 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); + } +} + +// ── The service contract (ADR-0157 D2, D8, open point 4) ──────────────── + +/** The kernel service the calendar service registers under (`ctx.getService`). */ +export const WORK_CALENDAR_SERVICE = 'work-calendar' as const; + +/** + * ADR-0157 D8: how many days before a calendar's `maintained_through` Setup + * lists it as needing maintenance — before refusals start. Sixty days: the + * Setup list `needs_maintenance` filters on it, and a CN calendar maintained + * through December 31 is flagged from November 1, by which time next year's + * public holidays and 调休 days are normally published; a longer lead would + * flag a calendar before the data to extend it exists. + */ +export const WORK_CALENDAR_MAINTENANCE_LEAD_DAYS = 60; + +/** + * 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. + * 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. `undefined` + * reads without an organization scope — right only where rows carry none; if + * that read matches more than one row it 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 calendar service (ADR-0157 D1, D2): resolves a calendar under D2 — + * the named code, else the organization default, else refuse — loads its + * exceptions, caches the result until a calendar or exception row is + * written, and computes with the functions of this module. Every method + * rejects with {@link WorkCalendarUnresolvedError}, + * {@link WorkCalendarNotMaintainedError} or {@link WorkCalendarInvalidError} + * ({@link isWorkCalendarRefusal}); none answers wall-clock time. + * + * {@link WorkCalendarService.resolve} hands back plain data, so a caller that + * must compute synchronously (a formula evaluated over pinned data) resolves + * first and then calls {@link addWorkingDays} and its siblings itself. + */ +export interface WorkCalendarService { + resolve(ref: WorkCalendarRef): Promise; + isWorkingTime(ref: WorkCalendarRef, at: number | Date): Promise; + addWorkingDays(ref: WorkCalendarRef, day: string, days: number): Promise; + workingDaysBetween(ref: WorkCalendarRef, start: string, end: string): Promise; + addWorkingHours(ref: WorkCalendarRef, start: number | Date, hours: number): Promise; + /** Drop every cached calendar; the next computation reads the rows again. */ + invalidate(): void; +} From be23d9090b16813c018829d7d98042d683a9ef2e Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:44:30 +0000 Subject: [PATCH 02/13] wip(platform-objects,objectql): working-calendar objects, service, hooks and Setup entries Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- packages/objectql/src/index.ts | 17 + packages/objectql/src/plugin.ts | 30 +- .../objectql/src/work-calendar-service.ts | 364 ++++++++++++++++++ .../scripts/i18n-extract.config.ts | 4 + .../src/apps/setup-nav.contributions.ts | 7 + .../src/apps/translations/ar.ts | 2 + .../src/apps/translations/de.ts | 2 + .../src/apps/translations/en.ts | 2 + .../src/apps/translations/es-ES.ts | 2 + .../src/apps/translations/fr.ts | 2 + .../src/apps/translations/ja-JP.ts | 2 + .../src/apps/translations/ko.ts | 2 + .../src/apps/translations/pt-BR.ts | 2 + .../src/apps/translations/ru.ts | 2 + .../src/apps/translations/zh-CN.ts | 2 + .../src/apps/translations/zh-Hant.ts | 2 + packages/platform-objects/src/plugin.ts | 10 +- packages/platform-objects/src/system/index.ts | 7 + .../sys-work-calendar-exception.object.ts | 125 ++++++ .../src/system/sys-work-calendar.object.ts | 185 +++++++++ packages/spec/src/data/work-calendar.ts | 7 + .../system/constants/platform-object-names.ts | 2 + 22 files changed, 777 insertions(+), 3 deletions(-) create mode 100644 packages/objectql/src/work-calendar-service.ts create mode 100644 packages/platform-objects/src/system/sys-work-calendar-exception.object.ts create mode 100644 packages/platform-objects/src/system/sys-work-calendar.object.ts diff --git a/packages/objectql/src/index.ts b/packages/objectql/src/index.ts index fbc3478d7d7..a79e3ee1581 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -731,6 +731,23 @@ export type { HookSkipReason, } from './hook-metrics.js'; +// [ADR-0157] The working-calendar service and the calendar objects' write +// hooks. Its contract, refusals and arithmetic are `@objectstack/spec/data`'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..afc35bb509a 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/data'; 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.ts b/packages/objectql/src/work-calendar-service.ts new file mode 100644 index 00000000000..4f3d87ffbda --- /dev/null +++ b/packages/objectql/src/work-calendar-service.ts @@ -0,0 +1,364 @@ +// 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 contract package + * + * 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/spec/data` (`work-calendar.ts`), which also + * holds the refusal codes and the service contract it implements. 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 data it gets. + * + * ## 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, and one organization's calendar never counts + * another's. 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`. + * + * ## 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. + */ + +import { + WORK_CALENDAR_CODE_PATTERN, + WORK_CALENDAR_WEEKDAY_FIELDS, + WorkCalendarUnresolvedError, + addWorkingDays, + addWorkingHours, + buildWorkCalendar, + calendarDayOf, + exceptionDayOf, + isWorkingTime, + parseWorkPeriods, + workingDaysBetween, + type WorkCalendar, + type WorkCalendarRef, + type WorkCalendarService as WorkCalendarServiceContract, +} from '@objectstack/spec/data'; +import type { FieldErrorCode } from '@objectstack/spec/api'; +import { validationFailure } from '@objectstack/types'; + +/** 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; + /** 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); + +/** 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 WorkCalendarServiceContract { + private readonly cache = new Map }>(); + + constructor(private readonly options: WorkCalendarServiceOptions) {} + + resolve(ref: WorkCalendarRef): Promise { + const now = (this.options.now ?? Date.now)(); + const key = JSON.stringify([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(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; + return { + field, + code: parsed.reason === 'malformed' ? 'invalid_format' : 'invalid_value', + message: `${field} ${parsed.message}.`, + value, + }; +} + +/** The organization an insert row is stored in: its own, else the call's tenant, else the writer's. */ +function insertOrganization(ctx: any, row: Row): string | undefined { + for (const candidate of [row.organization_id, ctx?.input?.options?.tenantId, ctx?.session?.organizationId]) { + if (candidate !== undefined && candidate !== null && candidate !== '') return String(candidate); + } + return undefined; +} + +export interface WorkCalendarHookOptions { + /** The organization's `localization.timezone`, for a create that leaves `timezone` out (ADR-0157 D7). */ + timezoneOf?: (organizationId: string | undefined) => Promise; +} + +/** Judge a calendar row's post-image: the columns the write carries, and the pair they belong to. */ +async function judgeCalendar( + engine: WorkCalendarReadEngine, + ctx: any, + data: Row, + previous: Row | undefined, + organizationId: string | undefined, +): 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. + if (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(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); + refuse(WORK_CALENDAR_EXCEPTION_OBJECT, [ + malformed && post.kind === 'on' + ? malformed + : { + field: 'periods', + code: post.kind === 'on' ? 'required' : 'invalid_value', + message: `This exception ${day}.`, + 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 }); + + bind('beforeInsert', WORK_CALENDAR_OBJECT, async (ctx: any) => { + const row = ctx?.input?.data; + if (!isRow(row)) return; + const organizationId = insertOrganization(ctx, row); + const zone = row.timezone; + if ((zone === undefined || zone === null || zone === '') && options.timezoneOf) { + const fallback = await options.timezoneOf(organizationId); + if (fallback) row.timezone = fallback; + } + await judgeCalendar(engine, ctx, row, undefined, organizationId); + }); + 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; + const org = previous.organization_id; + await judgeCalendar(engine, ctx, data, previous, org === undefined || org === null || org === '' ? undefined : String(org)); + }); + 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/platform-objects/scripts/i18n-extract.config.ts b/packages/platform-objects/scripts/i18n-extract.config.ts index 3d59bc05744..8b73a529c76 100644 --- a/packages/platform-objects/scripts/i18n-extract.config.ts +++ b/packages/platform-objects/scripts/i18n-extract.config.ts @@ -203,6 +203,8 @@ import { SysPlatformSettingAudit, SysMigration, SysExchangeRate, + SysWorkCalendar, + SysWorkCalendarException, } from '../src/system/index.js'; // ── Existing Setup app + dashboards + translations ──────────────────────── @@ -360,6 +362,8 @@ const config: ObjectStackDefinition = defineStack({ SysPlatformSettingAudit, SysMigration, SysExchangeRate, + SysWorkCalendar, + SysWorkCalendarException, ] as any, apps: [SETUP_APP, STUDIO_APP, ACCOUNT_APP] as any, diff --git a/packages/platform-objects/src/apps/setup-nav.contributions.ts b/packages/platform-objects/src/apps/setup-nav.contributions.ts index a7d13fe83b4..f0102abebda 100644 --- a/packages/platform-objects/src/apps/setup-nav.contributions.ts +++ b/packages/platform-objects/src/apps/setup-nav.contributions.ts @@ -134,6 +134,13 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [ // `requiredPermissions`: the object grant decides who reads and writes // (organization admins), and Setup itself already needs `setup.access`. { id: 'nav_exchange_rates', type: 'object', label: 'Exchange Rates', objectName: 'sys_exchange_rate', viewName: 'all_rates', icon: 'arrow-right-left' }, + // [ADR-0157 D1, D3] Working calendars and their holidays, beside the + // other organization reference data Localization governs. The exceptions + // get their own entry because their list page is the import door for a + // year of holidays; the calendar list's `needs_maintenance` view is the + // D8 notice. Access as Exchange Rates: the object grant decides. + { id: 'nav_work_calendars', type: 'object', label: 'Working Calendars', objectName: 'sys_work_calendar', viewName: 'all_calendars', icon: 'calendar-clock' }, + { id: 'nav_work_calendar_exceptions', type: 'object', label: 'Calendar Exceptions', objectName: 'sys_work_calendar_exception', viewName: 'all_exceptions', icon: 'calendar-x' }, { id: 'nav_settings_company', type: 'url', label: 'Company', url: '/apps/setup/system/settings/company', icon: 'building-2' }, // `nav_settings_branding` is contributed by `@objectstack/service-settings` // with the `branding` namespace, which is offered only where no diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index b5576f775e0..87c04baf12c 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -94,6 +94,8 @@ export const ar: TranslationData = { nav_settings_hub: { label: 'جميع الإعدادات' }, nav_settings_localization: { label: 'الترجمة والإعدادات المحلية' }, nav_exchange_rates: { label: 'أسعار الصرف' }, + nav_work_calendars: { label: 'تقويمات العمل' }, + nav_work_calendar_exceptions: { label: 'استثناءات التقويم' }, nav_settings_company: { label: 'الشركة' }, nav_settings_mail: { label: 'إرسال البريد' }, nav_settings_sms: { label: 'إرسال الرسائل النصية' }, diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index a90ba6d2117..f0c97065ef1 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -96,6 +96,8 @@ export const de: TranslationData = { nav_settings_hub: { label: 'Alle Einstellungen' }, nav_settings_localization: { label: 'Lokalisierung' }, nav_exchange_rates: { label: 'Wechselkurse' }, + nav_work_calendars: { label: 'Arbeitskalender' }, + nav_work_calendar_exceptions: { label: 'Kalenderausnahmen' }, nav_settings_company: { label: 'Unternehmen' }, nav_settings_mail: { label: 'E-Mail-Versand' }, nav_settings_sms: { label: 'SMS-Versand' }, diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index 0d94a1f54d2..d90a7e1fcb9 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -130,6 +130,8 @@ export const en: TranslationData = { nav_settings_hub: { label: 'All Settings' }, nav_settings_localization: { label: 'Localization' }, nav_exchange_rates: { label: 'Exchange Rates' }, + nav_work_calendars: { label: 'Working Calendars' }, + nav_work_calendar_exceptions: { label: 'Calendar Exceptions' }, nav_settings_company: { label: 'Company' }, nav_settings_mail: { label: 'Mail Delivery' }, nav_settings_sms: { label: 'SMS Delivery' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index 414d4372176..f476bee4962 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -85,6 +85,8 @@ export const esES: TranslationData = { nav_settings_hub: { label: 'Todos los Ajustes' }, nav_settings_localization: { label: 'Localización' }, nav_exchange_rates: { label: 'Tipos de cambio' }, + nav_work_calendars: { label: 'Calendarios laborales' }, + nav_work_calendar_exceptions: { label: 'Excepciones de calendario' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envío de correo' }, nav_settings_sms: { label: 'Envío de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index 8512a22f91a..fea45b80ee3 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -96,6 +96,8 @@ export const fr: TranslationData = { nav_settings_hub: { label: 'Tous les paramètres' }, nav_settings_localization: { label: 'Localisation' }, nav_exchange_rates: { label: 'Taux de change' }, + nav_work_calendars: { label: 'Calendriers de travail' }, + nav_work_calendar_exceptions: { label: 'Exceptions de calendrier' }, nav_settings_company: { label: 'Entreprise' }, nav_settings_mail: { label: 'Envoi des e-mails' }, nav_settings_sms: { label: 'Envoi des SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 39eabfd756e..20b02b2e2e6 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -85,6 +85,8 @@ export const jaJP: TranslationData = { nav_settings_hub: { label: 'すべての設定' }, nav_settings_localization: { label: 'ローカリゼーション' }, nav_exchange_rates: { label: '為替レート' }, + nav_work_calendars: { label: '稼働カレンダー' }, + nav_work_calendar_exceptions: { label: 'カレンダー例外' }, nav_settings_company: { label: '会社' }, nav_settings_mail: { label: 'メール配信' }, nav_settings_sms: { label: 'SMS 配信' }, diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index 98c3ccc6ee0..499cb9fb693 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -95,6 +95,8 @@ export const ko: TranslationData = { nav_settings_hub: { label: '전체 설정' }, nav_settings_localization: { label: '현지화' }, nav_exchange_rates: { label: '환율' }, + nav_work_calendars: { label: '근무 캘린더' }, + nav_work_calendar_exceptions: { label: '캘린더 예외' }, nav_settings_company: { label: '회사' }, nav_settings_mail: { label: '메일 전송' }, nav_settings_sms: { label: 'SMS 전송' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 4869a68d45b..7e95bea6884 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -96,6 +96,8 @@ export const ptBR: TranslationData = { nav_settings_hub: { label: 'Todas as configurações' }, nav_settings_localization: { label: 'Localização' }, nav_exchange_rates: { label: 'Taxas de câmbio' }, + nav_work_calendars: { label: 'Calendários de trabalho' }, + nav_work_calendar_exceptions: { label: 'Exceções de calendário' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envio de e-mail' }, nav_settings_sms: { label: 'Envio de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index 26a165608d7..175eb27ec92 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -96,6 +96,8 @@ export const ru: TranslationData = { nav_settings_hub: { label: 'Все настройки' }, nav_settings_localization: { label: 'Локализация' }, nav_exchange_rates: { label: 'Курсы валют' }, + nav_work_calendars: { label: 'Рабочие календари' }, + nav_work_calendar_exceptions: { label: 'Исключения календаря' }, nav_settings_company: { label: 'Компания' }, nav_settings_mail: { label: 'Доставка почты' }, nav_settings_sms: { label: 'Доставка SMS' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index 0ab64b2e61b..3ed6f3432f2 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -89,6 +89,8 @@ export const zhCN: TranslationData = { nav_settings_hub: { label: '全部设置' }, nav_settings_localization: { label: '本地化' }, nav_exchange_rates: { label: '汇率' }, + nav_work_calendars: { label: '工作日历' }, + nav_work_calendar_exceptions: { label: '日历例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '邮件投递' }, nav_settings_sms: { label: '短信投递' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index 876aec38241..6a19d05cd96 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -94,6 +94,8 @@ export const zhHant: TranslationData = { nav_settings_hub: { label: '全部設定' }, nav_settings_localization: { label: '在地化' }, nav_exchange_rates: { label: '匯率' }, + nav_work_calendars: { label: '工作日曆' }, + nav_work_calendar_exceptions: { label: '日曆例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '郵件投遞' }, nav_settings_sms: { label: '簡訊投遞' }, diff --git a/packages/platform-objects/src/plugin.ts b/packages/platform-objects/src/plugin.ts index b2838397578..f42c6229b20 100644 --- a/packages/platform-objects/src/plugin.ts +++ b/packages/platform-objects/src/plugin.ts @@ -7,6 +7,8 @@ import { SysMigration } from './system/sys-migration.object.js'; import { SysMigrationJournal } from './system/sys-migration-journal.object.js'; import { SysSecret } from './system/sys-secret.object.js'; import { SysExchangeRate } from './system/sys-exchange-rate.object.js'; +import { SysWorkCalendar } from './system/sys-work-calendar.object.js'; +import { SysWorkCalendarException } from './system/sys-work-calendar-exception.object.js'; import { SysTrustedKey } from './system/sys-trusted-key.object.js'; import { SysLifecycleState } from './system/sys-lifecycle-state.object.js'; import { SysRecycleBin } from './system/sys-recycle-bin.object.js'; @@ -113,6 +115,12 @@ import { SEED_SETTLEMENT_SERVICE } from '@objectstack/spec/contracts'; * engine-facing infrastructure above, not with an optional service. Rides * the first manifest (the project database), like every per-organization * table here. + * - **`sys_work_calendar`** / **`sys_work_calendar_exception`** — the + * organization's working calendars and their dated holidays and make-up + * workdays (ADR-0157 D1). Registered here for the reason the rate table + * is: their readers are the ObjectQL engine's calendar service and what it + * serves — the working-day formula functions and the approval sweep's + * working-time clock — not one optional service. Same manifest. * - **Fresh-datastore attestation** (#3438, ADR-0104 2026-07-30) — * travels with the ledger registration: a store this boot created from * empty is attested once that boot's own data has settled @@ -222,7 +230,7 @@ export class PlatformObjectsPlugin { version: this.version, type: 'plugin', scope: 'system', - objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], + objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], }); ctx?.getService?.('manifest')?.register?.({ ...ACTIVATION_LEDGER_MANIFEST, diff --git a/packages/platform-objects/src/system/index.ts b/packages/platform-objects/src/system/index.ts index 3957ce32118..78af040ff38 100644 --- a/packages/platform-objects/src/system/index.ts +++ b/packages/platform-objects/src/system/index.ts @@ -37,6 +37,13 @@ export { EXCHANGE_RATE_SCALE, EXCHANGE_RATE_PRECISION, } from './sys-exchange-rate.object.js'; +// [ADR-0157 D1] Working calendars and their dated exceptions, read by the +// calendar service (`@objectstack/objectql`). +export { + SysWorkCalendar, + WORK_CALENDAR_PERIODS_HELP, +} from './sys-work-calendar.object.js'; +export { SysWorkCalendarException } from './sys-work-calendar-exception.object.js'; export { readDataMigrationFlag, isDataMigrationVerified, diff --git a/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts b/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts new file mode 100644 index 00000000000..0c39539b9a2 --- /dev/null +++ b/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts @@ -0,0 +1,125 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field } from '@objectstack/spec/data'; + +/** + * sys_work_calendar_exception — Calendar Exception (ADR-0157 D1, D10) + * + * One dated override of a working calendar's weekly pattern. One table holds + * public holidays, 调休 make-up workdays and plant shutdowns: + * + * - **`off`** — the whole date is off, and the row carries no periods. + * - **`on`** — the date is worked, and the row carries that date's FULL + * periods (a half day is shortened periods). It never borrows its weekday's: + * with borrowing, a later edit to the weekday would silently rewrite every + * past make-up day (D10, 「每条写全时段」). + * + * One row per calendar and date (the unique key below). The date is a calendar + * day, never an instant (ADR-0053). The period format and its validation are + * the calendar's ({@link import('./sys-work-calendar.object.js').WORK_CALENDAR_PERIODS_HELP}), + * refused at write by the calendar service's hooks (`@objectstack/objectql`). + * Tenancy, write grant and audit as `sys_work_calendar`. Deleting a calendar + * deletes its exceptions. + * + * **Import** — opt-in on `system-data`, as `sys_exchange_rate` opts in: an + * administrator loads a year of holidays in one file through the generic + * import door (`sys_import_job`). The `calendar` column names the calendar by + * its code or its name; a line repeating a (calendar, date) on file is refused + * for that row alone by the unique key. + * + * @namespace sys + */ +export const SysWorkCalendarException = ObjectSchema.create({ + name: 'sys_work_calendar_exception', + label: 'Calendar Exception', + pluralLabel: 'Calendar Exceptions', + icon: 'calendar-x', + isSystem: true, + // Platform-defined schema, organization-administered data. + managedBy: 'system-data', + userActions: { import: true }, + description: + 'Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. ' + + 'A working day carries its full working periods.', + displayNameField: 'date', + nameField: 'date', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) + highlightFields: ['calendar', 'date', 'kind', 'periods'], + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + calendar: Field.lookup('sys_work_calendar', { + label: 'Calendar', + required: true, + // A calendar's exceptions mean nothing without it. + deleteBehavior: 'cascade', + trackHistory: true, + group: 'Exception', + }), + + date: Field.date({ + label: 'Date', + required: true, + trackHistory: true, + group: 'Exception', + }), + + kind: Field.select( + [ + { value: 'off', label: 'Day Off' }, + { value: 'on', label: 'Working Day' }, + ], + { + label: 'Kind', + required: true, + trackHistory: true, + description: 'Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.', + group: 'Exception', + }, + ), + + periods: Field.text({ + label: 'Periods', + maxLength: 255, + trackHistory: true, + description: + "For a working day, that date's full working periods, HH:mm-HH:mm separated by commas (09:00-12:00, 13:00-18:00); they are never taken from the weekday. Leave blank for a day off.", + group: 'Exception', + }), + + note: Field.text({ + label: 'Note', + maxLength: 255, + trackHistory: true, + description: 'What the date is, such as National Day or a make-up workday for Spring Festival.', + group: 'Exception', + }), + }, + + indexes: [ + { fields: ['calendar', 'date'], unique: 'organization' }, + ], + + listViews: { + all_exceptions: { + type: 'grid', + name: 'all_exceptions', + label: 'All', + data: { provider: 'object', object: 'sys_work_calendar_exception' }, + columns: ['calendar', 'date', 'kind', 'periods', 'note'], + sort: [{ field: 'date', order: 'desc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'No calendar exceptions yet', + message: 'Add one row per holiday or make-up workday, or import a year of them from a file.', + }, + }, + }, + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + feeds: false, + }, +}); diff --git a/packages/platform-objects/src/system/sys-work-calendar.object.ts b/packages/platform-objects/src/system/sys-work-calendar.object.ts new file mode 100644 index 00000000000..57b0da9b37a --- /dev/null +++ b/packages/platform-objects/src/system/sys-work-calendar.object.ts @@ -0,0 +1,185 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { ObjectSchema, Field, WORK_CALENDAR_CODE_PATTERN, WORK_CALENDAR_MAINTENANCE_LEAD_DAYS } from '@objectstack/spec/data'; + +/** + * The help every weekday's period column carries, stated once so the seven + * columns can never disagree about the format (ADR-0157 D1, D7, D10). + */ +export const WORK_CALENDAR_PERIODS_HELP = + 'Working periods that day in the calendar\'s time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. ' + + 'A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off.'; + +const weekday = (label: string) => + Field.text({ label, maxLength: 255, description: WORK_CALENDAR_PERIODS_HELP, group: 'Weekly Hours' }); + +/** + * sys_work_calendar — Working Calendar (ADR-0157 D1) + * + * One row per working calendar per organization: a weekly pattern of local + * working periods, the zone they are local to, and the span its exceptions + * (`sys_work_calendar_exception`) are maintained for. Runtime data an + * organization administrator keeps, never package metadata: holidays change + * every year, and a holiday is a row, not a release (D1). The precedent is + * `sys_exchange_rate` (ADR-0144), and every bullet of its tenancy, write-grant + * and audit note holds here unchanged — organization-scoped through the + * Layer 0 wall, written by organization administrators, every change audited. + * + * - **Code** — what a consumer names (a formula argument, the approval + * escalation's `calendar`), and what a package seeds a row under (D13: the + * existing seed contract, create-only unless the package declares a mode). + * Unique per organization, so a seeded code means one calendar in each. + * - **Default** — the calendar a computation takes when it names none (D2). + * One per organization: a second is refused at write by the calendar + * service's hooks (`@objectstack/objectql`), and a read that still meets two + * refuses rather than picking one. + * - **Time zone** — required (D7); the periods are local to it and the + * computation reads only it. A create that leaves it out takes the + * organization's `localization.timezone`, stored as the calendar's own. + * - **Periods** — one column per weekday, validated by the calendar itself + * (D10: `24:00` is a legal end, which the platform's `time` value refuses); + * a period crossing midnight is refused (D7). + * - **Maintained span** — `maintained_from` .. `maintained_through`, both + * required (open point 2): a blank must not read as "no holidays from here + * on". A computation needing a date outside the span is refused (D8, and the + * same refusal on the past side), and the `needs_maintenance` list marks a + * calendar {@link WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days ahead (D8). + * + * @namespace sys + */ +export const SysWorkCalendar = ObjectSchema.create({ + name: 'sys_work_calendar', + label: 'Working Calendar', + pluralLabel: 'Working Calendars', + icon: 'calendar-clock', + isSystem: true, + // Platform-defined schema, organization-administered data. + managedBy: 'system-data', + description: + 'Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. ' + + 'Due dates counted in working time read them.', + displayNameField: 'name', + nameField: 'name', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) + highlightFields: ['code', 'timezone', 'is_default', 'maintained_through'], + + fields: { + id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), + + code: Field.text({ + label: 'Code', + required: true, + searchable: true, + maxLength: 64, + unique: 'organization', + trackHistory: true, + description: + 'Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores.', + group: 'Calendar', + }), + + name: Field.text({ + label: 'Name', + required: true, + searchable: true, + maxLength: 255, + trackHistory: true, + group: 'Calendar', + }), + + timezone: Field.text({ + label: 'Time Zone', + required: true, + maxLength: 64, + valueDomain: 'iana_time_zone', + trackHistory: true, + description: + "IANA time zone the working periods are local to, such as Asia/Shanghai. Left out on create, it takes the organization's default time zone (Settings → Localization).", + group: 'Calendar', + }), + + is_default: Field.boolean({ + label: 'Default', + defaultValue: false, + trackHistory: true, + description: 'The calendar a due date uses when it names none. One per organization.', + group: 'Calendar', + }), + + maintained_from: Field.date({ + label: 'Maintained From', + required: true, + trackHistory: true, + description: + 'First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused.', + group: 'Maintenance', + }), + + maintained_through: Field.date({ + label: 'Maintained Through', + required: true, + trackHistory: true, + description: + "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date.", + group: 'Maintenance', + }), + + monday_periods: weekday('Monday'), + tuesday_periods: weekday('Tuesday'), + wednesday_periods: weekday('Wednesday'), + thursday_periods: weekday('Thursday'), + friday_periods: weekday('Friday'), + saturday_periods: weekday('Saturday'), + sunday_periods: weekday('Sunday'), + }, + + listViews: { + all_calendars: { + type: 'grid', + name: 'all_calendars', + label: 'All', + data: { provider: 'object', object: 'sys_work_calendar' }, + columns: ['name', 'code', 'timezone', 'is_default', 'maintained_through'], + sort: [{ field: 'name', order: 'asc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'No working calendars yet', + message: 'Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays.', + }, + }, + // [ADR-0157 D8] The notice ahead of the refusals: every calendar whose + // maintained span ends within the lead time. + needs_maintenance: { + type: 'grid', + name: 'needs_maintenance', + label: 'Needs Maintenance', + data: { provider: 'object', object: 'sys_work_calendar' }, + columns: ['name', 'code', 'maintained_through'], + filter: [{ field: 'maintained_through', operator: 'lte', value: `{${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS}_days_from_now}` }], + sort: [{ field: 'maintained_through', order: 'asc' }], + pagination: { pageSize: 50 }, + emptyState: { + title: 'Every calendar is maintained ahead', + message: `A calendar appears here when its holidays run out within the next ${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days; due dates past that date are refused.`, + }, + }, + }, + + validations: [ + { + type: 'format', + name: 'work_calendar_code_shape', + field: 'code', + regex: WORK_CALENDAR_CODE_PATTERN, + severity: 'error', + message: 'Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard.', + }, + ], + + enable: { + trackHistory: true, + searchable: false, + apiEnabled: true, + // A calendar is reference data, not a discussion surface. + feeds: false, + }, +}); diff --git a/packages/spec/src/data/work-calendar.ts b/packages/spec/src/data/work-calendar.ts index 0dfc5edae6a..43ffb37ceaa 100644 --- a/packages/spec/src/data/work-calendar.ts +++ b/packages/spec/src/data/work-calendar.ts @@ -496,6 +496,13 @@ export function addWorkingHours(cal: WorkCalendar, start: number | Date, hours: // ── The service contract (ADR-0157 D2, D8, open point 4) ──────────────── +/** + * 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_]*$'; + /** The kernel service the calendar service registers under (`ctx.getService`). */ export const WORK_CALENDAR_SERVICE = 'work-calendar' as const; diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index b66cf6552ab..083c19681b0 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -102,6 +102,8 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly Date: Thu, 19 Nov 2026 15:50:26 +0000 Subject: [PATCH 03/13] wip(objectql): calendar service tests Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../src/work-calendar-service.test.ts | 277 ++++++++++++++++++ .../src/system/sys-work-calendar.object.ts | 2 +- 2 files changed, 278 insertions(+), 1 deletion(-) create mode 100644 packages/objectql/src/work-calendar-service.test.ts 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..9070d8ae47a --- /dev/null +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -0,0 +1,277 @@ +// 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, + isWorkingDay, +} from '@objectstack/spec/data'; +import { ObjectQL } from './engine.js'; +import { + WORK_CALENDAR_CACHE_TTL_MS, + WORK_CALENDAR_EXCEPTION_OBJECT, + WORK_CALENDAR_OBJECT, + WorkCalendarService, + 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. */ +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 hits = src.filter((r) => Object.entries(query.where ?? {}).every(([k, v]) => 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 () => { + 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 () => { + 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 — 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) { return [...table(o).values()].filter((r) => matches(r, q?.where)); }, + 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'); + 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 } } as any); + + 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 } } as any)); + 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 } } as any); + const [row] = await engine.find(WORK_CALENDAR_OBJECT, { where: { id: 'c1' }, context: { isSystem: true } } as any); + 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 } } as any); + 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 } } as any); + expect(isWorkingDay(await svc.resolve(ORG), '2026-10-12')).toBe(false); + }); +}); diff --git a/packages/platform-objects/src/system/sys-work-calendar.object.ts b/packages/platform-objects/src/system/sys-work-calendar.object.ts index 57b0da9b37a..3794ffd8d4d 100644 --- a/packages/platform-objects/src/system/sys-work-calendar.object.ts +++ b/packages/platform-objects/src/system/sys-work-calendar.object.ts @@ -154,7 +154,7 @@ export const SysWorkCalendar = ObjectSchema.create({ label: 'Needs Maintenance', data: { provider: 'object', object: 'sys_work_calendar' }, columns: ['name', 'code', 'maintained_through'], - filter: [{ field: 'maintained_through', operator: 'lte', value: `{${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS}_days_from_now}` }], + filter: [{ field: 'maintained_through', operator: 'less_than_or_equal', value: `{${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS}_days_from_now}` }], sort: [{ field: 'maintained_through', order: 'asc' }], pagination: { pageSize: 50 }, emptyState: { From 91823473626ffcaf42a17ff9f26ac51c5e04a0be Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 15:54:56 +0000 Subject: [PATCH 04/13] wip(platform-objects): register the calendar objects in the nav and plugin pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- packages/platform-objects/src/platform-objects.test.ts | 4 +++- packages/platform-objects/src/plugin.test.ts | 10 +++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/packages/platform-objects/src/platform-objects.test.ts b/packages/platform-objects/src/platform-objects.test.ts index a9c80336b27..173bea85716 100644 --- a/packages/platform-objects/src/platform-objects.test.ts +++ b/packages/platform-objects/src/platform-objects.test.ts @@ -37,7 +37,7 @@ import { SysMetadata, SysMetadataHistoryObject, } from './metadata/index.js'; -import { SysExchangeRate, SysSecret, SysSetting } from './system/index.js'; +import { SysExchangeRate, SysSecret, SysSetting, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; import { ACCOUNT_APP, SETUP_APP, SETUP_NAV_CONTRIBUTIONS, STUDIO_APP } from './apps/index.js'; import { AppSchema } from '@objectstack/spec/ui'; import { resolveEffectiveApiMethods, isApiOperationAllowed, canServeApiOperation } from '@objectstack/spec/data'; @@ -609,6 +609,8 @@ describe('@objectstack/platform-objects', () => { sys_team: SysTeam, sys_user: SysUser, sys_user_preference: SysUserPreference, + sys_work_calendar: SysWorkCalendar, + sys_work_calendar_exception: SysWorkCalendarException, }; // Targets owned by another package (contributed there, gated by // `requiresObject`), so nothing here can read their `enable`. Named diff --git a/packages/platform-objects/src/plugin.test.ts b/packages/platform-objects/src/plugin.test.ts index a3cb50e646c..53d7f1a8ba4 100644 --- a/packages/platform-objects/src/plugin.test.ts +++ b/packages/platform-objects/src/plugin.test.ts @@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest'; import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { ObjectSchema, RECYCLE_BIN_ENTRY_FIELDS, RECYCLE_BIN_OBJECT } from '@objectstack/spec/data'; import { PlatformObjectsPlugin } from './plugin.js'; -import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey } from './system/index.js'; +import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; /** * Hand-rolled fake PluginContext (mirrors the service-plugin tests) — this @@ -47,7 +47,7 @@ function makeCtx() { } describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4243, #4270)', () => { - it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { + it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { const ctx = makeCtx(); const manifests: any[] = []; ctx.registerService('manifest', { register: (m: any) => manifests.push(m) }); @@ -57,7 +57,7 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 const infra = manifests.find((m) => m.id === 'com.objectstack.platform-objects'); expect(infra).toBeDefined(); expect(infra.scope).toBe('system'); - expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); + expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); expect(infra.objects.map((o: any) => o.name)).toEqual([ 'sys_migration', // ADR-0119 D2 (#4617). Registered UNCONDITIONALLY, alongside the flag @@ -70,6 +70,10 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 // home-currency projection, so it registers with the engine-facing // infrastructure, on the project database. 'sys_exchange_rate', + // [ADR-0157 D1] Working calendars and their exceptions, read by the + // engine's calendar service; organization data on the project database. + 'sys_work_calendar', + 'sys_work_calendar_exception', // [ADR-0025 §3.5 M1, #27123] The environment's trusted plugin-publisher // keys, read by `os plugin install` from a one-shot boot that composes // this plugin and nothing that would register it otherwise. From affaa83aeeda33b7dbe63093bda0ebc705999e73 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 16:26:33 +0000 Subject: [PATCH 05/13] feat(platform-objects): translate the calendar objects, register their bundles, and record the baselines they need The ten translated locales carry hand translations for every new key of sys_work_calendar and sys_work_calendar_exception; the ownership list, the organization-ownership inventory, the tenancy census, the ADR anchors, the spec API surface and the changeset follow the two new objects. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../35355-working-calendar-objects-service.md | 20 +++ .../utils/organization-ownership-inventory.ts | 5 + .../apps/translations/ar.objects.generated.ts | 123 ++++++++++++++++++ .../translations/bundle-ownership.test.ts | 1 + .../apps/translations/de.objects.generated.ts | 123 ++++++++++++++++++ .../de.source-hashes.generated.ts | 4 + .../apps/translations/en.objects.generated.ts | 123 ++++++++++++++++++ .../translations/es-ES.objects.generated.ts | 123 ++++++++++++++++++ .../es-ES.source-hashes.generated.ts | 2 + .../apps/translations/fr.objects.generated.ts | 123 ++++++++++++++++++ .../fr.source-hashes.generated.ts | 5 + .../translations/ja-JP.objects.generated.ts | 123 ++++++++++++++++++ .../ja-JP.source-hashes.generated.ts | 2 + .../apps/translations/ko.objects.generated.ts | 123 ++++++++++++++++++ .../ko.source-hashes.generated.ts | 2 + .../translations/pt-BR.objects.generated.ts | 123 ++++++++++++++++++ .../pt-BR.source-hashes.generated.ts | 2 + .../apps/translations/ru.objects.generated.ts | 123 ++++++++++++++++++ .../ru.source-hashes.generated.ts | 2 + .../translations/zh-CN.objects.generated.ts | 123 ++++++++++++++++++ .../zh-CN.source-hashes.generated.ts | 2 + .../translations/zh-Hant.objects.generated.ts | 123 ++++++++++++++++++ .../zh-Hant.source-hashes.generated.ts | 2 + packages/spec/api-surface/data.json | 34 ++++- ...jectql__src__work-calendar-service.ts.json | 5 + ...kages__spec__src__data__wall-clock.ts.json | 5 + ...es__spec__src__data__work-calendar.ts.json | 5 + scripts/platform-object-tenancy-census.json | 18 ++- 28 files changed, 1466 insertions(+), 3 deletions(-) create mode 100644 .changeset/35355-working-calendar-objects-service.md create mode 100644 scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json create mode 100644 scripts/adr-anchors/packages__spec__src__data__wall-clock.ts.json create mode 100644 scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json diff --git a/.changeset/35355-working-calendar-objects-service.md b/.changeset/35355-working-calendar-objects-service.md new file mode 100644 index 00000000000..be950360856 --- /dev/null +++ b/.changeset/35355-working-calendar-objects-service.md @@ -0,0 +1,20 @@ +--- +'@objectstack/spec': minor +'@objectstack/platform-objects': minor +'@objectstack/objectql': minor +'@objectstack/core': patch +'@objectstack/cli': patch +--- + +feat: working calendars — `sys_work_calendar` and `sys_work_calendar_exception`, the calendar service and the Setup pages (ADR-0157) + +Clause-②: yes (widening) +Metadata-protocol: added + +Not released alone: this ships in the same release as the working-day formula functions and the approval escalation's working-time clock (ADR-0157 D4). + +- **Two platform objects** (`@objectstack/platform-objects`). `sys_work_calendar` holds a calendar's `code` (unique per organization, snake_case), `name`, required IANA `timezone`, `is_default` (one per organization), the required `maintained_from` .. `maintained_through` span its holidays are entered for, and one period column per weekday (`monday_periods` … `sunday_periods`, `HH:mm-HH:mm` periods separated by commas, blank for a day off). `sys_work_calendar_exception` holds dated overrides: `calendar`, `date`, `kind` (`off`, no periods; `on`, that date's full periods), `periods` and `note`, one row per calendar and date. Both are organization data an administrator keeps, audited, like `sys_exchange_rate`; a package may seed rows under the existing seed contract and name a calendar by code. +- **Setup.** Two entries under Exchange Rates: Working Calendars (with a Needs Maintenance list of every calendar whose maintained span ends within 60 days) and Calendar Exceptions, whose list page imports a year of holidays from a file; the `calendar` column names a calendar by its code or name. +- **The write door** (`@objectstack/objectql`). A calendar or exception write is refused `400 VALIDATION_FAILED` when a period crosses midnight, is malformed or overlaps another (`24:00` is a legal end), an `off` row carries periods or an `on` row carries none, `maintained_through` is before `maintained_from`, or a second calendar is marked the default. A create that leaves `timezone` out takes the organization's Localization time zone. +- **The calendar service** (`@objectstack/objectql`, registered as `work-calendar`). `resolve({ organizationId, calendar })` takes the named code, else the organization default, else refuses `ERR_WORK_CALENDAR_UNRESOLVED`; it never falls back to wall-clock time. `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` compute over the resolved calendar, and a computation that needs a date outside the maintained span is refused `ERR_WORK_CALENDAR_NOT_MAINTAINED`. It reads in the organization the caller names, elevated, and caches until a calendar or exception row is written. +- **The arithmetic and the time-zone rule** (`@objectstack/spec/data`). The four computations, the period parser and the refusal classes are exported as pure functions over a resolved calendar, so a formula can count synchronously. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move here from `@objectstack/core`, unchanged; `@objectstack/core` re-exports all three, so no import changes. Three codes are registered in the error-code ledger: `ERR_WORK_CALENDAR_UNRESOLVED`, `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`. diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 953ac18b4ce..16a6cc8e58f 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -851,6 +851,11 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ // Exchange rates (`@objectstack/platform-objects`, #27185): an organization's // administrators author its own rate table; no parent row anchors a rate. { object: 'sys_exchange_rate', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, + // Working calendars (`@objectstack/platform-objects`, ADR-0157 D1): an + // organization's administrators author its calendars, and an exception's + // calendar carries the organization. + { object: 'sys_work_calendar', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, + { object: 'sys_work_calendar_exception', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); the exception's calendar carries the organization`, anchors: [parent('calendar', 'sys_work_calendar')] }, // The recycle bin (`@objectstack/platform-objects`, ADR-0148, #30237): the // engine writes each entry with the organization of the record it holds, // else the deleting context's. A NULL row comes only from a delete with diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index 1df359ee862..71b3f33249b 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4422,5 +4422,128 @@ export const arObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "تقويم العمل", + pluralLabel: "تقويمات العمل", + description: "تقويمات العمل: ساعات العمل الأسبوعية، والمنطقة الزمنية التي تُحسب بها، وإلى أي تاريخ أُدخلت العطلات. تقرؤها تواريخ الاستحقاق المحسوبة بوقت العمل.", + fields: { + id: { + label: "المعرّف" + }, + code: { + label: "الرمز", + help: "الرمز الآلي الذي تُسمّي به الصيغ وتصعيدات الموافقة والحزم هذا التقويم، مثل cn_standard: أحرف صغيرة وأرقام وشرطات سفلية." + }, + name: { + label: "الاسم" + }, + timezone: { + label: "المنطقة الزمنية", + help: "منطقة IANA الزمنية التي تُحسب بها فترات العمل، مثل Asia/Shanghai. إذا تُركت فارغة عند الإنشاء، تُؤخذ المنطقة الزمنية الافتراضية للمؤسسة (الإعدادات ← الترجمة والإعدادات المحلية)." + }, + is_default: { + label: "افتراضي", + help: "التقويم الذي يستخدمه تاريخ الاستحقاق عندما لا يحدد تقويمًا. واحد لكل مؤسسة." + }, + maintained_from: { + label: "مُحدَّث من", + help: "أول تاريخ أُدخلت منه العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ أسبق." + }, + maintained_through: { + label: "مُحدَّث حتى", + help: "آخر تاريخ أُدخلت حتى نهايته العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ لاحق: أدخل عطلات العام التالي، ثم انقل هذا التاريخ." + }, + monday_periods: { + label: "الاثنين", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + tuesday_periods: { + label: "الثلاثاء", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + wednesday_periods: { + label: "الأربعاء", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + thursday_periods: { + label: "الخميس", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + friday_periods: { + label: "الجمعة", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + saturday_periods: { + label: "السبت", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + }, + sunday_periods: { + label: "الأحد", + help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." + } + }, + _views: { + all_calendars: { + label: "الكل", + emptyState: { + title: "لا توجد تقويمات عمل بعد", + message: "أضف تقويمًا بساعات عمله الأسبوعية وحدّد أحدها تقويمًا افتراضيًا، ثم أدخل عطلاته وأيام العمل التعويضية." + } + }, + needs_maintenance: { + label: "بحاجة إلى تحديث", + emptyState: { + title: "جميع التقويمات محدَّثة مسبقًا", + message: "يظهر التقويم هنا عندما تنتهي عطلاته المُدخلة خلال الـ 60 يومًا القادمة؛ وتُرفض تواريخ الاستحقاق التي تتجاوز ذلك التاريخ." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "يجب أن يبدأ الرمز بحرف صغير وأن يحتوي فقط على أحرف صغيرة وأرقام وشرطات سفلية، مثل cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "استثناء تقويم", + pluralLabel: "استثناءات التقويم", + description: "استثناءات مؤرّخة لتقويم العمل: العطلات الرسمية وأيام العمل التعويضية وأيام الإغلاق. يحمل يوم العمل فترات عمله كاملة.", + fields: { + id: { + label: "المعرّف" + }, + calendar: { + label: "التقويم" + }, + date: { + label: "التاريخ" + }, + kind: { + label: "النوع", + help: "يوم إجازة: التاريخ كله إجازة. يوم عمل: يُعمل في التاريخ وفق الفترات أدناه، مثل يوم عمل تعويضي.", + options: { + off: "يوم إجازة", + on: "يوم عمل" + } + }, + periods: { + label: "الفترات", + help: "ليوم العمل، فترات العمل الكاملة لذلك التاريخ بصيغة HH:mm-HH:mm مفصولة بفواصل (09:00-12:00, 13:00-18:00)؛ ولا تُؤخذ أبدًا من يوم الأسبوع. اتركها فارغة ليوم الإجازة." + }, + note: { + label: "ملاحظة", + help: "ما هو هذا التاريخ، مثل العيد الوطني أو يوم عمل تعويضي لعيد الربيع." + } + }, + _views: { + all_exceptions: { + label: "الكل", + emptyState: { + title: "لا توجد استثناءات تقويم بعد", + message: "أضف صفًا لكل عطلة أو يوم عمل تعويضي، أو استورد سنة كاملة منها من ملف." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts index 648ef7e731a..4a0608f81bc 100644 --- a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts +++ b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts @@ -56,6 +56,7 @@ const OWNED_OBJECTS = new Set([ 'sys_metadata', 'sys_metadata_history', 'sys_metadata_audit', 'sys_metadata_commit', // system 'sys_setting', 'sys_platform_setting', 'sys_secret', 'sys_setting_audit', 'sys_platform_setting_audit', 'sys_migration', 'sys_exchange_rate', + 'sys_work_calendar', 'sys_work_calendar_exception', ]); describe('objects translation bundle ownership (ADR-0029 D8)', () => { diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index a83e2630d8e..0b98fbcb401 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4422,5 +4422,128 @@ export const deObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Arbeitskalender", + pluralLabel: "Arbeitskalender", + description: "Arbeitskalender: die wöchentlichen Arbeitszeiten, die Zeitzone, in der sie gelten, und bis wann die Feiertage gepflegt sind. Fälligkeitsdaten, die in Arbeitszeit gezählt werden, lesen sie.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Maschinencode, mit dem Formeln, Genehmigungseskalationen und Pakete diesen Kalender benennen, z. B. cn_standard: Kleinbuchstaben, Ziffern und Unterstriche." + }, + name: { + label: "Name" + }, + timezone: { + label: "Zeitzone", + help: "IANA-Zeitzone, in der die Arbeitszeiten gelten, z. B. Asia/Shanghai. Beim Anlegen leer gelassen, wird die Standardzeitzone der Organisation übernommen (Einstellungen → Lokalisierung)." + }, + is_default: { + label: "Standard", + help: "Der Kalender, den ein Fälligkeitsdatum verwendet, wenn es keinen nennt. Einer pro Organisation." + }, + maintained_from: { + label: "Gepflegt ab", + help: "Erstes Datum, ab dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein früheres Datum braucht, wird abgelehnt." + }, + maintained_through: { + label: "Gepflegt bis", + help: "Letztes Datum, bis zu dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein späteres Datum braucht, wird abgelehnt: Erfassen Sie die Feiertage des nächsten Jahres und verschieben Sie dann dieses Datum." + }, + monday_periods: { + label: "Montag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + tuesday_periods: { + label: "Dienstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + wednesday_periods: { + label: "Mittwoch", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + thursday_periods: { + label: "Donnerstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + friday_periods: { + label: "Freitag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + saturday_periods: { + label: "Samstag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + }, + sunday_periods: { + label: "Sonntag", + help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." + } + }, + _views: { + all_calendars: { + label: "Alle", + emptyState: { + title: "Noch keine Arbeitskalender", + message: "Fügen Sie einen Kalender mit seinen wöchentlichen Arbeitszeiten hinzu, markieren Sie einen als Standard und erfassen Sie dann seine Feiertage und Ersatzarbeitstage." + } + }, + needs_maintenance: { + label: "Pflege erforderlich", + emptyState: { + title: "Alle Kalender sind vorausschauend gepflegt", + message: "Ein Kalender erscheint hier, wenn seine Feiertage innerhalb der nächsten 60 Tage enden; Fälligkeitsdaten nach diesem Datum werden abgelehnt." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Der Code muss mit einem Kleinbuchstaben beginnen und darf nur Kleinbuchstaben, Ziffern und Unterstriche enthalten, z. B. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Kalenderausnahme", + pluralLabel: "Kalenderausnahmen", + description: "Datierte Abweichungen von einem Arbeitskalender: Feiertage, Ersatzarbeitstage und Betriebsruhen. Ein Arbeitstag trägt seine vollständigen Arbeitszeiten.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Kalender" + }, + date: { + label: "Datum" + }, + kind: { + label: "Art", + help: "Frei: Der ganze Tag ist frei. Arbeitstag: An dem Datum wird mit den Zeiträumen unten gearbeitet, z. B. an einem Ersatzarbeitstag.", + options: { + off: "Frei", + on: "Arbeitstag" + } + }, + periods: { + label: "Zeiträume", + help: "Für einen Arbeitstag die vollständigen Arbeitszeiten dieses Datums, HH:mm-HH:mm durch Kommas getrennt (09:00-12:00, 13:00-18:00); sie werden nie vom Wochentag übernommen. Für einen freien Tag leer lassen." + }, + note: { + label: "Notiz", + help: "Was das Datum ist, z. B. Nationalfeiertag oder ein Ersatzarbeitstag zum Frühlingsfest." + } + }, + _views: { + all_exceptions: { + label: "Alle", + emptyState: { + title: "Noch keine Kalenderausnahmen", + message: "Fügen Sie pro Feiertag oder Ersatzarbeitstag eine Zeile hinzu oder importieren Sie ein Jahr davon aus einer Datei." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 628a3fca820..4d0c80cb908 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -232,4 +232,8 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_user.fields.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar.fields.name.label": "5274417ff1ccaf01", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index 64f13a0d72b..df9fd29adf3 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4422,5 +4422,128 @@ export const enObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Working Calendar", + pluralLabel: "Working Calendars", + description: "Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. Due dates counted in working time read them.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores." + }, + name: { + label: "Name" + }, + timezone: { + label: "Time Zone", + help: "IANA time zone the working periods are local to, such as Asia/Shanghai. Left out on create, it takes the organization's default time zone (Settings → Localization)." + }, + is_default: { + label: "Default", + help: "The calendar a due date uses when it names none. One per organization." + }, + maintained_from: { + label: "Maintained From", + help: "First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused." + }, + maintained_through: { + label: "Maintained Through", + help: "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date." + }, + monday_periods: { + label: "Monday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + tuesday_periods: { + label: "Tuesday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + wednesday_periods: { + label: "Wednesday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + thursday_periods: { + label: "Thursday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + friday_periods: { + label: "Friday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + saturday_periods: { + label: "Saturday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + }, + sunday_periods: { + label: "Sunday", + help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." + } + }, + _views: { + all_calendars: { + label: "All", + emptyState: { + title: "No working calendars yet", + message: "Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays." + } + }, + needs_maintenance: { + label: "Needs Maintenance", + emptyState: { + title: "Every calendar is maintained ahead", + message: "A calendar appears here when its holidays run out within the next 60 days; due dates past that date are refused." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Calendar Exception", + pluralLabel: "Calendar Exceptions", + description: "Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. A working day carries its full working periods.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendar" + }, + date: { + label: "Date" + }, + kind: { + label: "Kind", + help: "Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.", + options: { + off: "Day Off", + on: "Working Day" + } + }, + periods: { + label: "Periods", + help: "For a working day, that date's full working periods, HH:mm-HH:mm separated by commas (09:00-12:00, 13:00-18:00); they are never taken from the weekday. Leave blank for a day off." + }, + note: { + label: "Note", + help: "What the date is, such as National Day or a make-up workday for Spring Festival." + } + }, + _views: { + all_exceptions: { + label: "All", + emptyState: { + title: "No calendar exceptions yet", + message: "Add one row per holiday or make-up workday, or import a year of them from a file." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index 4a7ef584e34..bf7e2c9027a 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -4422,5 +4422,128 @@ export const esESObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Calendario laboral", + pluralLabel: "Calendarios laborales", + description: "Calendarios laborales: el horario semanal, la zona horaria en la que se aplica y hasta cuándo están mantenidos los festivos. Las fechas de vencimiento contadas en tiempo laborable los leen.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Código", + help: "Código de máquina con el que las fórmulas, las escalaciones de aprobación y los paquetes nombran este calendario, p. ej. cn_standard: letras minúsculas, dígitos y guiones bajos." + }, + name: { + label: "Nombre" + }, + timezone: { + label: "Zona horaria", + help: "Zona horaria IANA en la que se aplican las franjas de trabajo, p. ej. Asia/Shanghai. Si se deja vacía al crear, toma la zona horaria predeterminada de la organización (Ajustes → Localización)." + }, + is_default: { + label: "Predeterminado", + help: "El calendario que usa una fecha de vencimiento cuando no indica ninguno. Uno por organización." + }, + maintained_from: { + label: "Mantenido desde", + help: "Primera fecha desde la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha anterior." + }, + maintained_through: { + label: "Mantenido hasta", + help: "Última fecha hasta la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha posterior: registra los festivos del año siguiente y luego mueve esta fecha." + }, + monday_periods: { + label: "Lunes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + tuesday_periods: { + label: "Martes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + wednesday_periods: { + label: "Miércoles", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + thursday_periods: { + label: "Jueves", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + friday_periods: { + label: "Viernes", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + saturday_periods: { + label: "Sábado", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + }, + sunday_periods: { + label: "Domingo", + help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." + } + }, + _views: { + all_calendars: { + label: "Todos", + emptyState: { + title: "Aún no hay calendarios laborales", + message: "Añade un calendario con su horario semanal y marca uno como predeterminado; después registra sus festivos y días laborables de recuperación." + } + }, + needs_maintenance: { + label: "Requiere mantenimiento", + emptyState: { + title: "Todos los calendarios están mantenidos con antelación", + message: "Un calendario aparece aquí cuando sus festivos se acaban en los próximos 60 días; se rechazan las fechas de vencimiento posteriores a esa fecha." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "El código debe empezar por una letra minúscula y usar solo letras minúsculas, dígitos y guiones bajos, p. ej. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Excepción de calendario", + pluralLabel: "Excepciones de calendario", + description: "Excepciones fechadas a un calendario laboral: festivos, días laborables de recuperación y cierres. Un día laborable lleva sus franjas de trabajo completas.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendario" + }, + date: { + label: "Fecha" + }, + kind: { + label: "Clase", + help: "Día libre: la fecha entera es libre. Día laborable: la fecha se trabaja con las franjas de abajo, p. ej. un día laborable de recuperación.", + options: { + off: "Día libre", + on: "Día laborable" + } + }, + periods: { + label: "Franjas", + help: "Para un día laborable, las franjas de trabajo completas de esa fecha, HH:mm-HH:mm separadas por comas (09:00-12:00, 13:00-18:00); nunca se toman del día de la semana. Déjalo vacío para un día libre." + }, + note: { + label: "Nota", + help: "Qué es la fecha, p. ej. la Fiesta Nacional o un día laborable de recuperación por el Festival de Primavera." + } + }, + _views: { + all_exceptions: { + label: "Todos", + emptyState: { + title: "Aún no hay excepciones de calendario", + message: "Añade una fila por cada festivo o día laborable de recuperación, o importa un año de ellos desde un archivo." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 99c0176fec9..2f42fc6c006 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -161,4 +161,6 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 8a974a89c8d..29843f40098 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4422,5 +4422,128 @@ export const frObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Calendrier de travail", + pluralLabel: "Calendriers de travail", + description: "Calendriers de travail : les horaires hebdomadaires, le fuseau horaire dans lequel ils s’appliquent et jusqu’à quand les jours fériés sont tenus à jour. Les échéances comptées en temps ouvré les lisent.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Code", + help: "Code machine par lequel les formules, les escalades d’approbation et les packages désignent ce calendrier, par ex. cn_standard : lettres minuscules, chiffres et traits de soulignement." + }, + name: { + label: "Nom" + }, + timezone: { + label: "Fuseau horaire", + help: "Fuseau horaire IANA dans lequel s’appliquent les plages de travail, par ex. Asia/Shanghai. Laissé vide à la création, il reprend le fuseau horaire par défaut de l’organisation (Paramètres → Localisation)." + }, + is_default: { + label: "Par défaut", + help: "Le calendrier utilisé par une échéance qui n’en désigne aucun. Un par organisation." + }, + maintained_from: { + label: "Tenu à jour depuis", + help: "Première date à partir de laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date antérieure est refusé." + }, + maintained_through: { + label: "Tenu à jour jusqu’au", + help: "Dernière date jusqu’à laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date ultérieure est refusé : saisissez les jours fériés de l’année suivante, puis reportez cette date." + }, + monday_periods: { + label: "Lundi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + tuesday_periods: { + label: "Mardi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + wednesday_periods: { + label: "Mercredi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + thursday_periods: { + label: "Jeudi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + friday_periods: { + label: "Vendredi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + saturday_periods: { + label: "Samedi", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + }, + sunday_periods: { + label: "Dimanche", + help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." + } + }, + _views: { + all_calendars: { + label: "Tous", + emptyState: { + title: "Aucun calendrier de travail pour le moment", + message: "Ajoutez un calendrier avec ses horaires hebdomadaires et marquez-en un comme calendrier par défaut, puis saisissez ses jours fériés et ses jours de récupération." + } + }, + needs_maintenance: { + label: "À mettre à jour", + emptyState: { + title: "Tous les calendriers sont tenus à jour à l’avance", + message: "Un calendrier apparaît ici lorsque ses jours fériés s’arrêtent dans les 60 prochains jours ; les échéances au-delà de cette date sont refusées." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Le code doit commencer par une lettre minuscule et ne contenir que des lettres minuscules, des chiffres et des traits de soulignement, par ex. cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Exception de calendrier", + pluralLabel: "Exceptions de calendrier", + description: "Dérogations datées à un calendrier de travail : jours fériés, jours de récupération et fermetures. Un jour travaillé porte ses plages de travail complètes.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendrier" + }, + date: { + label: "Date" + }, + kind: { + label: "Type", + help: "Jour chômé : toute la date est chômée. Jour travaillé : la date est travaillée selon les plages ci-dessous, par ex. un jour de récupération.", + options: { + off: "Jour chômé", + on: "Jour travaillé" + } + }, + periods: { + label: "Plages", + help: "Pour un jour travaillé, les plages de travail complètes de cette date, au format HH:mm-HH:mm séparées par des virgules (09:00-12:00, 13:00-18:00) ; elles ne sont jamais reprises du jour de la semaine. Laissez vide pour un jour chômé." + }, + note: { + label: "Note", + help: "Ce qu’est la date, par ex. la fête nationale ou un jour de récupération pour la fête du Printemps." + } + }, + _views: { + all_exceptions: { + label: "Tous", + emptyState: { + title: "Aucune exception de calendrier pour le moment", + message: "Ajoutez une ligne par jour férié ou jour de récupération, ou importez-en une année depuis un fichier." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 19e26f7989d..f7dcf2220c2 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -257,4 +257,9 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.date.label": "767cabc93ccbdaa0", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.note.label": "f78f61778f71bf68", }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index 5cd6eb158c0..8e2b44f3eb4 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -4422,5 +4422,128 @@ export const jaJPObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "稼働カレンダー", + pluralLabel: "稼働カレンダー", + description: "稼働カレンダー:週ごとの稼働時間、その時間帯の基準となるタイムゾーン、祝日をどこまで登録済みか。稼働時間で数える期日はこれを参照します。", + fields: { + id: { + label: "ID" + }, + code: { + label: "コード", + help: "数式、承認エスカレーション、パッケージがこのカレンダーを指すときの機械コード(例: cn_standard)。英小文字、数字、アンダースコアのみ使用できます。" + }, + name: { + label: "名前" + }, + timezone: { + label: "タイムゾーン", + help: "稼働時間帯の基準となる IANA タイムゾーン(例: Asia/Shanghai)。作成時に省略すると、組織の既定のタイムゾーン(設定 → ローカリゼーション)を使用します。" + }, + is_default: { + label: "既定", + help: "期日がカレンダーを指定しないときに使うカレンダー。組織ごとに 1 つです。" + }, + maintained_from: { + label: "登録開始日", + help: "祝日と振替出勤日を登録している最初の日付。これより前の日付を必要とする計算は拒否されます。" + }, + maintained_through: { + label: "登録終了日", + help: "祝日と振替出勤日を登録している最後の日付。これより後の日付を必要とする計算は拒否されます。翌年の祝日を登録してから、この日付を延ばしてください。" + }, + monday_periods: { + label: "月曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + tuesday_periods: { + label: "火曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + wednesday_periods: { + label: "水曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + thursday_periods: { + label: "木曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + friday_periods: { + label: "金曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + saturday_periods: { + label: "土曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + }, + sunday_periods: { + label: "日曜日", + help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" + } + }, + _views: { + all_calendars: { + label: "すべて", + emptyState: { + title: "稼働カレンダーはまだありません", + message: "週ごとの稼働時間を入れてカレンダーを追加し、1 つを既定に設定してから、祝日と振替出勤日を登録します。" + } + }, + needs_maintenance: { + label: "要メンテナンス", + emptyState: { + title: "すべてのカレンダーが先まで登録済みです", + message: "祝日の登録が 60 日以内に切れるカレンダーがここに表示されます。その日付を過ぎる期日の計算は拒否されます。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "コードは英小文字で始め、英小文字、数字、アンダースコアのみを使用してください(例: cn_standard)。" + } + } + }, + sys_work_calendar_exception: { + label: "カレンダー例外", + pluralLabel: "カレンダー例外", + description: "稼働カレンダーの日付ごとの上書き:祝日、振替出勤日、休業日。稼働日にはその日の稼働時間帯をすべて入力します。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "カレンダー" + }, + date: { + label: "日付" + }, + kind: { + label: "種類", + help: "休日:終日休みです。稼働日:下の時間帯で稼働する日です(振替出勤日など)。", + options: { + off: "休日", + on: "稼働日" + } + }, + periods: { + label: "稼働時間帯", + help: "稼働日の場合、その日の稼働時間帯をすべて HH:mm-HH:mm 形式のカンマ区切りで入力します(09:00-12:00, 13:00-18:00)。曜日の設定は引き継がれません。休日は空欄にします。" + }, + note: { + label: "メモ", + help: "その日付の内容(例: 国慶節、春節の振替出勤日)。" + } + }, + _views: { + all_exceptions: { + label: "すべて", + emptyState: { + title: "カレンダー例外はまだありません", + message: "祝日または振替出勤日ごとに 1 行追加するか、ファイルから 1 年分をインポートします。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index c539c773da5..d1257f1d385 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -151,4 +151,6 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index c9c54c6edd0..89c5bb48056 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4422,5 +4422,128 @@ export const koObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "근무 캘린더", + pluralLabel: "근무 캘린더", + description: "근무 캘린더: 주간 근무 시간, 그 시간의 기준 시간대, 공휴일이 어디까지 관리되었는지를 담습니다. 근무 시간으로 계산하는 기한이 이를 참조합니다.", + fields: { + id: { + label: "ID" + }, + code: { + label: "코드", + help: "수식, 승인 에스컬레이션, 패키지가 이 캘린더를 가리킬 때 쓰는 기계 코드(예: cn_standard)로, 영문 소문자, 숫자, 밑줄만 사용합니다." + }, + name: { + label: "이름" + }, + timezone: { + label: "시간대", + help: "근무 시간대의 기준이 되는 IANA 시간대(예: Asia/Shanghai). 생성할 때 비워 두면 조직의 기본 시간대(설정 → 현지화)를 사용합니다." + }, + is_default: { + label: "기본값", + help: "기한이 캘린더를 지정하지 않을 때 사용하는 캘린더입니다. 조직당 하나입니다." + }, + maintained_from: { + label: "관리 시작일", + help: "공휴일과 대체 근무일이 입력되기 시작한 날짜입니다. 이보다 이른 날짜가 필요한 계산은 거부됩니다." + }, + maintained_through: { + label: "관리 종료일", + help: "공휴일과 대체 근무일이 입력된 마지막 날짜입니다. 이보다 늦은 날짜가 필요한 계산은 거부됩니다. 다음 해 공휴일을 입력한 뒤 이 날짜를 옮기세요." + }, + monday_periods: { + label: "월요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + tuesday_periods: { + label: "화요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + wednesday_periods: { + label: "수요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + thursday_periods: { + label: "목요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + friday_periods: { + label: "금요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + saturday_periods: { + label: "토요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + }, + sunday_periods: { + label: "일요일", + help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." + } + }, + _views: { + all_calendars: { + label: "전체", + emptyState: { + title: "아직 근무 캘린더 없음", + message: "주간 근무 시간과 함께 캘린더를 추가하고 하나를 기본값으로 지정한 다음, 공휴일과 대체 근무일을 입력하세요." + } + }, + needs_maintenance: { + label: "관리 필요", + emptyState: { + title: "모든 캘린더가 미리 관리되어 있음", + message: "공휴일 입력이 60일 이내에 끝나는 캘린더가 여기에 표시됩니다. 그 날짜를 넘는 기한 계산은 거부됩니다." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "코드는 영문 소문자로 시작하고 영문 소문자, 숫자, 밑줄만 사용해야 합니다(예: cn_standard)." + } + } + }, + sys_work_calendar_exception: { + label: "캘린더 예외", + pluralLabel: "캘린더 예외", + description: "근무 캘린더의 날짜별 재정의: 공휴일, 대체 근무일, 휴업일. 근무일에는 그날의 전체 근무 시간대를 입력합니다.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "캘린더" + }, + date: { + label: "날짜" + }, + kind: { + label: "종류", + help: "휴무일: 하루 종일 쉽니다. 근무일: 아래 시간대로 근무하는 날입니다(예: 대체 근무일).", + options: { + off: "휴무일", + on: "근무일" + } + }, + periods: { + label: "근무 시간대", + help: "근무일이면 그날의 전체 근무 시간대를 HH:mm-HH:mm 형식으로 쉼표로 구분해 입력합니다(09:00-12:00, 13:00-18:00). 요일 설정을 이어받지 않습니다. 휴무일은 비워 두세요." + }, + note: { + label: "메모", + help: "해당 날짜가 무엇인지(예: 국경절, 춘절 대체 근무일)." + } + }, + _views: { + all_exceptions: { + label: "전체", + emptyState: { + title: "아직 캘린더 예외 없음", + message: "공휴일이나 대체 근무일마다 한 행을 추가하거나, 파일에서 1년 치를 가져오세요." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index f70c7e7adb7..cd4dc42ae97 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -119,4 +119,6 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index b9beef7b7b0..e7329e488b1 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -4422,5 +4422,128 @@ export const ptBRObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Calendário de trabalho", + pluralLabel: "Calendários de trabalho", + description: "Calendários de trabalho: o horário semanal, o fuso horário em que ele vale e até quando os feriados estão mantidos. Prazos contados em tempo útil os leem.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Código", + help: "Código de máquina pelo qual fórmulas, escalonamentos de aprovação e pacotes nomeiam este calendário, por exemplo cn_standard: letras minúsculas, dígitos e sublinhados." + }, + name: { + label: "Nome" + }, + timezone: { + label: "Fuso horário", + help: "Fuso horário IANA em que os períodos de trabalho valem, por exemplo Asia/Shanghai. Se omitido na criação, usa o fuso horário padrão da organização (Configurações → Localização)." + }, + is_default: { + label: "Padrão", + help: "O calendário que um prazo usa quando não indica nenhum. Um por organização." + }, + maintained_from: { + label: "Mantido desde", + help: "Primeira data a partir da qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data anterior é recusado." + }, + maintained_through: { + label: "Mantido até", + help: "Última data até a qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data posterior é recusado: cadastre os feriados do próximo ano e depois mova esta data." + }, + monday_periods: { + label: "Segunda-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + tuesday_periods: { + label: "Terça-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + wednesday_periods: { + label: "Quarta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + thursday_periods: { + label: "Quinta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + friday_periods: { + label: "Sexta-feira", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + saturday_periods: { + label: "Sábado", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + }, + sunday_periods: { + label: "Domingo", + help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." + } + }, + _views: { + all_calendars: { + label: "Todas", + emptyState: { + title: "Nenhum calendário de trabalho ainda", + message: "Adicione um calendário com seu horário semanal e marque um como padrão; depois cadastre seus feriados e dias úteis de compensação." + } + }, + needs_maintenance: { + label: "Precisa de manutenção", + emptyState: { + title: "Todos os calendários estão mantidos com antecedência", + message: "Um calendário aparece aqui quando seus feriados acabam nos próximos 60 dias; prazos além dessa data são recusados." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "O código deve começar com uma letra minúscula e usar apenas letras minúsculas, dígitos e sublinhados, por exemplo cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Exceção de calendário", + pluralLabel: "Exceções de calendário", + description: "Exceções datadas de um calendário de trabalho: feriados, dias úteis de compensação e paralisações. Um dia útil traz seus períodos de trabalho completos.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Calendário" + }, + date: { + label: "Data" + }, + kind: { + label: "Tipo", + help: "Folga: a data inteira é de folga. Dia útil: a data é trabalhada com os períodos abaixo, por exemplo um dia útil de compensação.", + options: { + off: "Folga", + on: "Dia útil" + } + }, + periods: { + label: "Períodos", + help: "Para um dia útil, os períodos de trabalho completos dessa data, HH:mm-HH:mm separados por vírgulas (09:00-12:00, 13:00-18:00); nunca são herdados do dia da semana. Deixe em branco para uma folga." + }, + note: { + label: "Observação", + help: "O que é a data, por exemplo o Dia Nacional ou um dia útil de compensação do Festival da Primavera." + } + }, + _views: { + all_exceptions: { + label: "Todas", + emptyState: { + title: "Nenhuma exceção de calendário ainda", + message: "Adicione uma linha por feriado ou dia útil de compensação, ou importe um ano deles de um arquivo." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index c86d9109f75..3d7d12167ed 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -162,4 +162,6 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index a831dc63a37..bdd27299261 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4422,5 +4422,128 @@ export const ruObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "Рабочий календарь", + pluralLabel: "Рабочие календари", + description: "Рабочие календари: еженедельный график работы, часовой пояс, в котором он действует, и дата, до которой внесены праздники. Сроки, отсчитываемые в рабочем времени, берутся из них.", + fields: { + id: { + label: "ID" + }, + code: { + label: "Код", + help: "Машинный код, по которому формулы, эскалации согласований и пакеты ссылаются на этот календарь, например cn_standard: строчные латинские буквы, цифры и подчёркивания." + }, + name: { + label: "Название" + }, + timezone: { + label: "Часовой пояс", + help: "Часовой пояс IANA, в котором действуют рабочие интервалы, например Asia/Shanghai. Если не указан при создании, берётся часовой пояс организации по умолчанию (Настройки → Локализация)." + }, + is_default: { + label: "По умолчанию", + help: "Календарь, который используется для срока, если календарь не указан. Один на организацию." + }, + maintained_from: { + label: "Ведётся с", + help: "Первая дата, начиная с которой внесены праздники и рабочие дни переноса. Расчёт, которому нужна более ранняя дата, отклоняется." + }, + maintained_through: { + label: "Ведётся по", + help: "Последняя дата, по которую внесены праздники и рабочие дни переноса. Расчёт, которому нужна более поздняя дата, отклоняется: внесите праздники следующего года, затем передвиньте эту дату." + }, + monday_periods: { + label: "Понедельник", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + tuesday_periods: { + label: "Вторник", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + wednesday_periods: { + label: "Среда", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + thursday_periods: { + label: "Четверг", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + friday_periods: { + label: "Пятница", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + saturday_periods: { + label: "Суббота", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + }, + sunday_periods: { + label: "Воскресенье", + help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." + } + }, + _views: { + all_calendars: { + label: "Все", + emptyState: { + title: "Рабочих календарей пока нет", + message: "Добавьте календарь с еженедельным графиком и отметьте один как календарь по умолчанию, затем внесите его праздники и рабочие дни переноса." + } + }, + needs_maintenance: { + label: "Требует обновления", + emptyState: { + title: "Все календари заполнены наперёд", + message: "Календарь появляется здесь, когда его праздники заканчиваются в ближайшие 60 дней; сроки после этой даты отклоняются." + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "Код должен начинаться со строчной латинской буквы и содержать только строчные латинские буквы, цифры и подчёркивания, например cn_standard." + } + } + }, + sys_work_calendar_exception: { + label: "Исключение календаря", + pluralLabel: "Исключения календаря", + description: "Датированные исключения из рабочего календаря: праздники, рабочие дни переноса и простои. Рабочий день содержит полный набор рабочих интервалов.", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "Календарь" + }, + date: { + label: "Дата" + }, + kind: { + label: "Тип", + help: "Выходной: вся дата нерабочая. Рабочий день: в эту дату работают по интервалам ниже, например рабочий день переноса.", + options: { + off: "Выходной", + on: "Рабочий день" + } + }, + periods: { + label: "Интервалы", + help: "Для рабочего дня — полный набор рабочих интервалов этой даты, HH:mm-HH:mm через запятую (09:00-12:00, 13:00-18:00); они никогда не берутся из дня недели. Оставьте пустым для выходного." + }, + note: { + label: "Примечание", + help: "Что это за дата, например Национальный день или рабочий день переноса к Празднику весны." + } + }, + _views: { + all_exceptions: { + label: "Все", + emptyState: { + title: "Исключений календаря пока нет", + message: "Добавьте по строке на каждый праздник или рабочий день переноса либо импортируйте их за год из файла." + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index c5c1bc306f5..5ae275ddf33 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -118,4 +118,6 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index 314ed4ba79b..8d278e0958a 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -4422,5 +4422,128 @@ export const zhCNObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "工作日历", + pluralLabel: "工作日历", + description: "工作日历:每周的工作时段、时段所在的时区,以及节假日维护到哪一天。按工作时间计算的到期日读取它们。", + fields: { + id: { + label: "ID" + }, + code: { + label: "代码", + help: "公式、审批升级和软件包用来指称此日历的机器代码,如 cn_standard:仅限小写字母、数字和下划线。" + }, + name: { + label: "名称" + }, + timezone: { + label: "时区", + help: "工作时段所在的 IANA 时区,如 Asia/Shanghai。创建时留空则取组织的默认时区(设置 → 本地化)。" + }, + is_default: { + label: "默认", + help: "到期日未指定日历时使用的日历。每个组织一个。" + }, + maintained_from: { + label: "维护起始日", + help: "节假日和调休工作日从这一天开始录入。需要更早日期的计算会被拒绝。" + }, + maintained_through: { + label: "维护截止日", + help: "节假日和调休工作日录入到这一天为止。需要更晚日期的计算会被拒绝:请录入下一年的节假日,再顺延此日期。" + }, + monday_periods: { + label: "星期一", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + tuesday_periods: { + label: "星期二", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + wednesday_periods: { + label: "星期三", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + thursday_periods: { + label: "星期四", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + friday_periods: { + label: "星期五", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + saturday_periods: { + label: "星期六", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + }, + sunday_periods: { + label: "星期日", + help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" + } + }, + _views: { + all_calendars: { + label: "全部", + emptyState: { + title: "还没有工作日历", + message: "添加一个日历并填写每周工作时段,将其中一个设为默认,然后录入它的节假日和调休工作日。" + } + }, + needs_maintenance: { + label: "待维护", + emptyState: { + title: "所有日历都已提前维护", + message: "节假日将在 60 天内用完的日历会出现在这里;超出该日期的到期日计算会被拒绝。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "代码须以小写字母开头,且只能包含小写字母、数字和下划线,如 cn_standard。" + } + } + }, + sys_work_calendar_exception: { + label: "日历例外", + pluralLabel: "日历例外", + description: "工作日历的按日期覆盖:法定节假日、调休工作日和停工日。工作日须带上当天完整的工作时段。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "日历" + }, + date: { + label: "日期" + }, + kind: { + label: "类型", + help: "休息日:整天休息。工作日:当天按下方时段上班,如调休工作日。", + options: { + off: "休息日", + on: "工作日" + } + }, + periods: { + label: "工作时段", + help: "工作日须填写当天完整的工作时段,格式为 HH:mm-HH:mm,多个时段用逗号分隔(09:00-12:00, 13:00-18:00);不会从对应星期的时段继承。休息日留空。" + }, + note: { + label: "备注", + help: "该日期是什么,如国庆节或春节调休工作日。" + } + }, + _views: { + all_exceptions: { + label: "全部", + emptyState: { + title: "还没有日历例外", + message: "每个节假日或调休工作日录一行,或从文件导入一整年的数据。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts index 5fc27e139ad..0d41f54578b 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts @@ -91,4 +91,6 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index 891c35c6a8f..d6e684b47d4 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -4422,5 +4422,128 @@ export const zhHantObjects: NonNullable = { } } } + }, + sys_work_calendar: { + label: "工作日曆", + pluralLabel: "工作日曆", + description: "工作日曆:每週的工作時段、時段所在的時區,以及假日維護到哪一天。依工作時間計算的到期日會讀取它們。", + fields: { + id: { + label: "ID" + }, + code: { + label: "代碼", + help: "公式、審批升級與套件用來指稱此日曆的機器代碼,如 cn_standard:僅限小寫字母、數字和底線。" + }, + name: { + label: "名稱" + }, + timezone: { + label: "時區", + help: "工作時段所在的 IANA 時區,如 Asia/Shanghai。建立時留空則取組織的預設時區(設定 → 在地化)。" + }, + is_default: { + label: "預設", + help: "到期日未指定日曆時使用的日曆。每個組織一個。" + }, + maintained_from: { + label: "維護起始日", + help: "假日與補班日從這一天開始登錄。需要更早日期的計算會被拒絕。" + }, + maintained_through: { + label: "維護截止日", + help: "假日與補班日登錄到這一天為止。需要更晚日期的計算會被拒絕:請登錄下一年的假日,再順延此日期。" + }, + monday_periods: { + label: "星期一", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + tuesday_periods: { + label: "星期二", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + wednesday_periods: { + label: "星期三", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + thursday_periods: { + label: "星期四", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + friday_periods: { + label: "星期五", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + saturday_periods: { + label: "星期六", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + }, + sunday_periods: { + label: "星期日", + help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" + } + }, + _views: { + all_calendars: { + label: "全部", + emptyState: { + title: "還沒有工作日曆", + message: "新增一個日曆並填寫每週工作時段,將其中一個設為預設,然後登錄它的假日與補班日。" + } + }, + needs_maintenance: { + label: "待維護", + emptyState: { + title: "所有日曆都已提前維護", + message: "假日將在 60 天內用完的日曆會出現在這裡;超出該日期的到期日計算會被拒絕。" + } + } + }, + _validations: { + work_calendar_code_shape: { + message: "代碼須以小寫字母開頭,且只能包含小寫字母、數字和底線,如 cn_standard。" + } + } + }, + sys_work_calendar_exception: { + label: "日曆例外", + pluralLabel: "日曆例外", + description: "工作日曆的依日期覆寫:國定假日、補班日與停工日。工作日須帶上當天完整的工作時段。", + fields: { + id: { + label: "ID" + }, + calendar: { + label: "日曆" + }, + date: { + label: "日期" + }, + kind: { + label: "類型", + help: "休息日:整天休息。工作日:當天依下方時段上班,如補班日。", + options: { + off: "休息日", + on: "工作日" + } + }, + periods: { + label: "工作時段", + help: "工作日須填寫當天完整的工作時段,格式為 HH:mm-HH:mm,多個時段以逗號分隔(09:00-12:00, 13:00-18:00);不會從對應星期的時段繼承。休息日留空。" + }, + note: { + label: "備註", + help: "該日期是什麼,如國慶日或春節補班日。" + } + }, + _views: { + all_exceptions: { + label: "全部", + emptyState: { + title: "還沒有日曆例外", + message: "每個假日或補班日登錄一列,或從檔案匯入一整年的資料。" + } + } + } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index cedbb33ccf7..d88745f71e4 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -112,4 +112,6 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", + "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", + "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index d69183d4b25..48273f9afa4 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -920,9 +920,30 @@ "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_SERVICE (const)", + "WORK_CALENDAR_UNRESOLVED_CODE (const)", + "WORK_CALENDAR_WEEKDAY_FIELDS (const)", + "WallClockParts (interface)", + "WorkCalendar (interface)", + "WorkCalendarDay (interface)", + "WorkCalendarInvalidError (class)", + "WorkCalendarNotMaintainedError (class)", + "WorkCalendarRef (interface)", + "WorkCalendarService (interface)", + "WorkCalendarUnresolvedError (class)", + "WorkCalendarUnresolvedReason (type)", + "WorkPeriod (interface)", + "WorkPeriodsParse (type)", + "WorkPeriodsRefusal (type)", "ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody (function)", "actionTextsWithoutRunnableCode (function)", + "addWorkingDays (function)", + "addWorkingHours (function)", "aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason (function)", @@ -933,6 +954,8 @@ "booleanComparandDoorVerdict (function)", "booleanComparandFieldVerdict (function)", "booleanComparandRefusalMessage (function)", + "buildWorkCalendar (function)", + "calendarDayOf (function)", "canServeApiOperation (function)", "canonicalAstOperator (function)", "canonicalizeSqlType (function)", @@ -973,6 +996,7 @@ "driverSupportsTransactions (function)", "effectiveOperationsArray (function)", "emptyGroupValueFor (function)", + "exceptionDayOf (function)", "expandEmptyOperator (function)", "externalBindingDatasourceRefusal (function)", "externalColumnMapTargets (function)", @@ -1057,6 +1081,9 @@ "isUnboundedAbove (function)", "isUniqueDeclared (function)", "isVirtualSearchField (function)", + "isWorkCalendarRefusal (function)", + "isWorkingDay (function)", + "isWorkingTime (function)", "judgeImportMappingTarget (function)", "likePatternToGlobPattern (function)", "likePatternToRegExp (function)", @@ -1081,6 +1108,7 @@ "parseDateMacroParam (function)", "parseFilterAST (function)", "parseNumericString (function)", + "parseWorkPeriods (function)", "passthroughSecretPaths (function)", "percentScaleOf (function)", "placeholderFree (function)", @@ -1158,6 +1186,10 @@ "validateDriverConfig (function)", "valueRoundTripDivergence (function)", "valueSchemaFor (function)", - "virtualFieldAggregateRemedy (function)" + "virtualFieldAggregateRemedy (function)", + "wallClockToUtcMs (function)", + "workingDaysBetween (function)", + "workingPeriodsOn (function)", + "zonedWallClockToUtcMs (function)" ] } 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..ec656a14603 --- /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 and one organization's calendar never counts another's." +} 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." +} diff --git a/scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json b/scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json new file mode 100644 index 00000000000..5e26ffab6e5 --- /dev/null +++ b/scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json @@ -0,0 +1,5 @@ +{ + "file": "packages/spec/src/data/work-calendar.ts", + "adrs": ["ADR-0157"], + "invariant": "ADR-0157: the working-calendar arithmetic is the contract package's so the calendar service and the working-day formula functions count with one daylight-saving rule (D11, open point 3). 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/platform-object-tenancy-census.json b/scripts/platform-object-tenancy-census.json index 1342fb8979b..4b168a0eadf 100644 --- a/scripts/platform-object-tenancy-census.json +++ b/scripts/platform-object-tenancy-census.json @@ -26,8 +26,8 @@ "predicate": "resolveTenantFieldName(registered schema) !== null, where the registered schema is the authored schema plus the columns resolveInjectedSystemColumns says the registration injects (the applySystemFields pass). Both functions are loaded from source and executed; neither is re-spelled here.", "population": "every object registered by a tracked packages/**/*.object.ts module whose name carries a platform prefix (sys_ / cloud_ / ai_). The cloud repository's own cloud_ objects are not in this tree and so not in this census.", "totals": { - "registered": 103, - "inReach": 52, + "registered": 105, + "inReach": 54, "outOfReach": 51 }, "reasonTotals": { @@ -867,6 +867,20 @@ "reach": "in", "tenantField": "organization_id", "reasons": [] + }, + { + "name": "sys_work_calendar", + "file": "packages/platform-objects/src/system/sys-work-calendar.object.ts", + "reach": "in", + "tenantField": "organization_id", + "reasons": [] + }, + { + "name": "sys_work_calendar_exception", + "file": "packages/platform-objects/src/system/sys-work-calendar-exception.object.ts", + "reach": "in", + "tenantField": "organization_id", + "reasons": [] } ] } From ec6245d8c1bbeedb42703196a0fb533029d1c04c Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 17:43:45 +0000 Subject: [PATCH 06/13] fix(objectql,spec): field codes as plain literals, honest test doubles, and the regenerated references The calendar write door stamps its ADR-0114 field codes as plain literals, one per branch. The service test's read double refuses an operator it does not implement, its memory driver honours the caller's limit, and its engine calls carry typed options. The spec export origins and the API references now list the working-calendar exports and the three ledger codes. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../docs/references/api/automation-api.mdx | 5 ++- content/docs/references/api/contract.mdx | 5 ++- .../docs/references/api/error-code-ledger.mdx | 3 ++ .../src/work-calendar-service.test.ts | 27 ++++++++++----- .../objectql/src/work-calendar-service.ts | 23 +++++-------- packages/spec/export-origins/data.json | 34 ++++++++++++++++++- 6 files changed, 72 insertions(+), 25 deletions(-) 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/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index 9070d8ae47a..258d3882f7a 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -52,7 +52,13 @@ function readDouble(calendars: Row[], exceptions: Row[]) { async find(object: string, query: Row) { reads.push({ object, query }); const src = object === WORK_CALENDAR_OBJECT ? calendars : exceptions; - const hits = src.filter((r) => Object.entries(query.where ?? {}).every(([k, v]) => r[k] === v)); + const hits = src.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)); }, @@ -70,6 +76,7 @@ async function refusal(p: Promise): Promise { 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'); @@ -83,6 +90,7 @@ describe('WorkCalendarService — resolution (ADR-0157 D2)', () => { }); 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' }); }); @@ -190,7 +198,10 @@ function memoryDriver() { 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) { return [...table(o).values()].filter((r) => matches(r, q?.where)); }, + 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 }; }, @@ -226,14 +237,14 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { try { await engine.destroy(); } catch { /* noop */ } }); - const insertCalendar = (row: Row) => engine.insert(WORK_CALENDAR_OBJECT, { ...CN, ...row }, { context: { isSystem: true } } as any); + 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 } } as any)); + 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' })]); }); @@ -252,14 +263,14 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { }); 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 } } as any); - const [row] = await engine.find(WORK_CALENDAR_OBJECT, { where: { id: 'c1' }, context: { isSystem: true } } as any); + await engine.insert(WORK_CALENDAR_OBJECT, { ...CN, id: 'c1', timezone: undefined, organization_id: 'org_z' }, { context: { isSystem: true } }); + 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 } } as any); + 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' })]); @@ -271,7 +282,7 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { 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 } } as any); + 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); }); }); diff --git a/packages/objectql/src/work-calendar-service.ts b/packages/objectql/src/work-calendar-service.ts index 4f3d87ffbda..224551c0926 100644 --- a/packages/objectql/src/work-calendar-service.ts +++ b/packages/objectql/src/work-calendar-service.ts @@ -220,12 +220,10 @@ function hasOwn(row: Row, key: string): boolean { function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined { const parsed = parseWorkPeriods(value); if (parsed.ok) return undefined; - return { - field, - code: parsed.reason === 'malformed' ? 'invalid_format' : 'invalid_value', - message: `${field} ${parsed.message}.`, - value, - }; + 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 }; } /** The organization an insert row is stored in: its own, else the call's tenant, else the writer's. */ @@ -297,15 +295,12 @@ function judgeException(data: Row, previous: Row | undefined): void { 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 && post.kind === 'on' - ? malformed - : { - field: 'periods', - code: post.kind === 'on' ? 'required' : 'invalid_value', - message: `This exception ${day}.`, - value: post.periods, - }, + malformed ?? { field: 'periods', code: 'required', message, value: post.periods }, ]); } diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index aabb17a6b31..e103462c202 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -906,9 +906,30 @@ "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_SERVICE": "src/data/work-calendar.ts#WORK_CALENDAR_SERVICE (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)", + "WorkCalendarInvalidError": "src/data/work-calendar.ts#WorkCalendarInvalidError (class)", + "WorkCalendarNotMaintainedError": "src/data/work-calendar.ts#WorkCalendarNotMaintainedError (class)", + "WorkCalendarRef": "src/data/work-calendar.ts#WorkCalendarRef (interface)", + "WorkCalendarService": "src/data/work-calendar.ts#WorkCalendarService (interface)", + "WorkCalendarUnresolvedError": "src/data/work-calendar.ts#WorkCalendarUnresolvedError (class)", + "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)", + "addWorkingDays": "src/data/work-calendar.ts#addWorkingDays (function)", + "addWorkingHours": "src/data/work-calendar.ts#addWorkingHours (function)", "aiReadExposureRefusal": "src/data/ai-read-exposure.ts#aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage": "src/data/analytics.zod.ts#analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason": "src/data/api-derivation.ts#apiExposureDenialReason (function)", @@ -919,6 +940,8 @@ "booleanComparandDoorVerdict": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandDoorVerdict (function)", "booleanComparandFieldVerdict": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandFieldVerdict (function)", "booleanComparandRefusalMessage": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandRefusalMessage (function)", + "buildWorkCalendar": "src/data/work-calendar.ts#buildWorkCalendar (function)", + "calendarDayOf": "src/data/work-calendar.ts#calendarDayOf (function)", "canServeApiOperation": "src/data/api-derivation.ts#canServeApiOperation (function)", "canonicalAstOperator": "src/data/filter.zod.ts#canonicalAstOperator (function)", "canonicalizeSqlType": "src/data/type-compat.ts#canonicalizeSqlType (function)", @@ -959,6 +982,7 @@ "driverSupportsTransactions": "src/data/driver.zod.ts#driverSupportsTransactions (function)", "effectiveOperationsArray": "src/data/api-derivation.ts#effectiveOperationsArray (function)", "emptyGroupValueFor": "src/data/aggregation-policy.ts#emptyGroupValueFor (function)", + "exceptionDayOf": "src/data/work-calendar.ts#exceptionDayOf (function)", "expandEmptyOperator": "src/data/filter-empty-operator.ts#expandEmptyOperator (function)", "externalBindingDatasourceRefusal": "src/data/external-binding-datasource.ts#externalBindingDatasourceRefusal (function)", "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", @@ -1043,6 +1067,9 @@ "isUnboundedAbove": "src/data/calendar-day.ts#isUnboundedAbove (function)", "isUniqueDeclared": "src/data/field.zod.ts#isUniqueDeclared (function)", "isVirtualSearchField": "src/data/search-fields.ts#isVirtualSearchField (function)", + "isWorkCalendarRefusal": "src/data/work-calendar.ts#isWorkCalendarRefusal (function)", + "isWorkingDay": "src/data/work-calendar.ts#isWorkingDay (function)", + "isWorkingTime": "src/data/work-calendar.ts#isWorkingTime (function)", "judgeImportMappingTarget": "src/data/import-mapping-target.ts#judgeImportMappingTarget (function)", "likePatternToGlobPattern": "src/data/filter.zod.ts#likePatternToGlobPattern (function)", "likePatternToRegExp": "src/data/filter.zod.ts#likePatternToRegExp (function)", @@ -1067,6 +1094,7 @@ "parseDateMacroParam": "src/data/date-macros.zod.ts#parseDateMacroParam (function)", "parseFilterAST": "src/data/filter.zod.ts#parseFilterAST (function)", "parseNumericString": "src/data/filter-number-comparand-declared-type.ts#parseNumericString (function)", + "parseWorkPeriods": "src/data/work-calendar.ts#parseWorkPeriods (function)", "passthroughSecretPaths": "src/data/datasource-credential-redaction.ts#passthroughSecretPaths (function)", "percentScaleOf": "src/data/percent-scale.ts#percentScaleOf (function)", "placeholderFree": "src/data/driver/common.zod.ts#placeholderFree (function)", @@ -1144,6 +1172,10 @@ "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)", + "workingDaysBetween": "src/data/work-calendar.ts#workingDaysBetween (function)", + "workingPeriodsOn": "src/data/work-calendar.ts#workingPeriodsOn (function)", + "zonedWallClockToUtcMs": "src/data/wall-clock.ts#zonedWallClockToUtcMs (function)" } } From 0122d6de883e9480c9c1004561ae1082f87228f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 18:15:16 +0000 Subject: [PATCH 07/13] test(cli): the Setup tree pin counts the two working-calendar entries The admin Setup composition grows from 31 to 33 entries with Working Calendars and Calendar Exceptions under Configuration; the pin names both. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../connect-agent-both-halves-wire.pin.test.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index abd6b9c0770..a2dcc93cb5c 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -264,7 +264,7 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // The Setup tree the platform admin is served BY THIS COMPOSITION: 9 // authored groups less `group_approvals`, `group_integrations` and // `group_apps`, which nothing in it contributes into and the filter - // collapses, plus the 24 entries `SETUP_NAV_CONTRIBUTIONS` carries, + // collapses, plus the 26 entries `SETUP_NAV_CONTRIBUTIONS` carries, // plus the MCP one. // (25 until #25098 moved the unfiltered Packages entry to Studio; 24 // until #30204 removed the Feature Flags entry with its namespace; 32 @@ -274,13 +274,17 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // Configuration; 32 until the recycle bin entry, `nav_recycle_bin`, // joined Configuration (#30239); 33 until objectstack#34724 retired // the Packaged Actions entry, `nav_packaged_actions`, the one entry - // `group_apps` held here, so that group collapses too.) + // `group_apps` held here, so that group collapses too; 31 until the + // working-calendar pair, `nav_work_calendars` and + // `nav_work_calendar_exceptions`, joined Configuration, ADR-0157.) // `nav_settings_branding` is not among them, and not because of a // tenancy wall (this harness boots none): since #24766 it is // contributed by `@objectstack/service-settings` together with the // `branding` namespace, offered only where no organization wall stands, // and this harness composes platform-objects and the MCP bundle alone. - expect(allowedIds).toHaveLength(31); + expect(allowedIds).toHaveLength(33); + expect(allowedIds).toContain('nav_work_calendars'); + expect(allowedIds).toContain('nav_work_calendar_exceptions'); expect(allowedIds).not.toContain('nav_packaged_actions'); expect(allowedIds).toContain('nav_settings_access_policy'); expect(allowedIds).toContain('nav_recycle_bin'); @@ -306,8 +310,8 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( expect(withAccountHalf.statusCode).toBe(200); expect(withoutAccountHalf.statusCode).toBe(200); expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item)); - // 31: the composition the count in the test above states. - expect(navIds(withAccountHalf.body?.item)).toHaveLength(31); + // 33: the composition the count in the test above states. + expect(navIds(withAccountHalf.body?.item)).toHaveLength(33); // The mechanism behind the invariance, asserted rather than assumed: // the bundle aims exactly one contribution at `setup` and one at From 0d042101815ac405e447d89681c5c0eb284fabec Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 19:09:33 +0000 Subject: [PATCH 08/13] refactor: keep the service, arithmetic and codes here; the objects and Setup move to a sibling branch This branch now carries the first half of the working-calendar change: the pure arithmetic and the wall-clock primitive in @objectstack/spec/data, the three ledger codes, the calendar service and its write hooks in @objectstack/objectql, and the regenerated references. The two calendar objects, their translations, the Setup entries, the import door, the tenancy census, the ownership inventory and the Setup-tree pin return to main here and land on claude/issue-35355-work-calendar-objects-setup. The spec API surface and export origins are regenerated from the merged tree. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../35355-working-calendar-objects-service.md | 20 -- .changeset/35355-working-calendar-service.md | 17 ++ .../utils/organization-ownership-inventory.ts | 5 - ...connect-agent-both-halves-wire.pin.test.ts | 14 +- .../scripts/i18n-extract.config.ts | 4 - .../src/apps/setup-nav.contributions.ts | 7 - .../apps/translations/ar.objects.generated.ts | 123 ------------ .../src/apps/translations/ar.ts | 2 - .../translations/bundle-ownership.test.ts | 1 - .../apps/translations/de.objects.generated.ts | 123 ------------ .../de.source-hashes.generated.ts | 4 - .../src/apps/translations/de.ts | 2 - .../apps/translations/en.objects.generated.ts | 123 ------------ .../src/apps/translations/en.ts | 2 - .../translations/es-ES.objects.generated.ts | 123 ------------ .../es-ES.source-hashes.generated.ts | 2 - .../src/apps/translations/es-ES.ts | 2 - .../apps/translations/fr.objects.generated.ts | 123 ------------ .../fr.source-hashes.generated.ts | 5 - .../src/apps/translations/fr.ts | 2 - .../translations/ja-JP.objects.generated.ts | 123 ------------ .../ja-JP.source-hashes.generated.ts | 2 - .../src/apps/translations/ja-JP.ts | 2 - .../apps/translations/ko.objects.generated.ts | 123 ------------ .../ko.source-hashes.generated.ts | 2 - .../src/apps/translations/ko.ts | 2 - .../translations/pt-BR.objects.generated.ts | 123 ------------ .../pt-BR.source-hashes.generated.ts | 2 - .../src/apps/translations/pt-BR.ts | 2 - .../apps/translations/ru.objects.generated.ts | 123 ------------ .../ru.source-hashes.generated.ts | 2 - .../src/apps/translations/ru.ts | 2 - .../translations/zh-CN.objects.generated.ts | 123 ------------ .../zh-CN.source-hashes.generated.ts | 2 - .../src/apps/translations/zh-CN.ts | 2 - .../translations/zh-Hant.objects.generated.ts | 123 ------------ .../zh-Hant.source-hashes.generated.ts | 2 - .../src/apps/translations/zh-Hant.ts | 2 - .../src/platform-objects.test.ts | 4 +- packages/platform-objects/src/plugin.test.ts | 10 +- packages/platform-objects/src/plugin.ts | 10 +- packages/platform-objects/src/system/index.ts | 7 - .../sys-work-calendar-exception.object.ts | 125 ------------ .../src/system/sys-work-calendar.object.ts | 185 ------------------ packages/spec/api-surface/data.json | 1 + packages/spec/export-origins/data.json | 1 + .../system/constants/platform-object-names.ts | 2 - scripts/platform-object-tenancy-census.json | 18 +- 48 files changed, 31 insertions(+), 1798 deletions(-) delete mode 100644 .changeset/35355-working-calendar-objects-service.md create mode 100644 .changeset/35355-working-calendar-service.md delete mode 100644 packages/platform-objects/src/system/sys-work-calendar-exception.object.ts delete mode 100644 packages/platform-objects/src/system/sys-work-calendar.object.ts diff --git a/.changeset/35355-working-calendar-objects-service.md b/.changeset/35355-working-calendar-objects-service.md deleted file mode 100644 index be950360856..00000000000 --- a/.changeset/35355-working-calendar-objects-service.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -'@objectstack/spec': minor -'@objectstack/platform-objects': minor -'@objectstack/objectql': minor -'@objectstack/core': patch -'@objectstack/cli': patch ---- - -feat: working calendars — `sys_work_calendar` and `sys_work_calendar_exception`, the calendar service and the Setup pages (ADR-0157) - -Clause-②: yes (widening) -Metadata-protocol: added - -Not released alone: this ships in the same release as the working-day formula functions and the approval escalation's working-time clock (ADR-0157 D4). - -- **Two platform objects** (`@objectstack/platform-objects`). `sys_work_calendar` holds a calendar's `code` (unique per organization, snake_case), `name`, required IANA `timezone`, `is_default` (one per organization), the required `maintained_from` .. `maintained_through` span its holidays are entered for, and one period column per weekday (`monday_periods` … `sunday_periods`, `HH:mm-HH:mm` periods separated by commas, blank for a day off). `sys_work_calendar_exception` holds dated overrides: `calendar`, `date`, `kind` (`off`, no periods; `on`, that date's full periods), `periods` and `note`, one row per calendar and date. Both are organization data an administrator keeps, audited, like `sys_exchange_rate`; a package may seed rows under the existing seed contract and name a calendar by code. -- **Setup.** Two entries under Exchange Rates: Working Calendars (with a Needs Maintenance list of every calendar whose maintained span ends within 60 days) and Calendar Exceptions, whose list page imports a year of holidays from a file; the `calendar` column names a calendar by its code or name. -- **The write door** (`@objectstack/objectql`). A calendar or exception write is refused `400 VALIDATION_FAILED` when a period crosses midnight, is malformed or overlaps another (`24:00` is a legal end), an `off` row carries periods or an `on` row carries none, `maintained_through` is before `maintained_from`, or a second calendar is marked the default. A create that leaves `timezone` out takes the organization's Localization time zone. -- **The calendar service** (`@objectstack/objectql`, registered as `work-calendar`). `resolve({ organizationId, calendar })` takes the named code, else the organization default, else refuses `ERR_WORK_CALENDAR_UNRESOLVED`; it never falls back to wall-clock time. `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` compute over the resolved calendar, and a computation that needs a date outside the maintained span is refused `ERR_WORK_CALENDAR_NOT_MAINTAINED`. It reads in the organization the caller names, elevated, and caches until a calendar or exception row is written. -- **The arithmetic and the time-zone rule** (`@objectstack/spec/data`). The four computations, the period parser and the refusal classes are exported as pure functions over a resolved calendar, so a formula can count synchronously. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move here from `@objectstack/core`, unchanged; `@objectstack/core` re-exports all three, so no import changes. Three codes are registered in the error-code ledger: `ERR_WORK_CALENDAR_UNRESOLVED`, `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`. diff --git a/.changeset/35355-working-calendar-service.md b/.changeset/35355-working-calendar-service.md new file mode 100644 index 00000000000..7aab6c6500f --- /dev/null +++ b/.changeset/35355-working-calendar-service.md @@ -0,0 +1,17 @@ +--- +'@objectstack/spec': 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: this ships in the same release as 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 and the time-zone rule** (`@objectstack/spec/data`). `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) and `buildWorkCalendar`. A computation that needs a date outside the calendar's maintained span is refused rather than read from the weekly pattern. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move here 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, or two defaults), `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. 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`, or a second calendar is marked the default; a calendar created without `timezone` takes the organization's Localization time zone. diff --git a/packages/cli/src/utils/organization-ownership-inventory.ts b/packages/cli/src/utils/organization-ownership-inventory.ts index 16a6cc8e58f..953ac18b4ce 100644 --- a/packages/cli/src/utils/organization-ownership-inventory.ts +++ b/packages/cli/src/utils/organization-ownership-inventory.ts @@ -851,11 +851,6 @@ export const ORGANIZATION_OWNERSHIP_INVENTORY: readonly InventoryEntry[] = [ // Exchange rates (`@objectstack/platform-objects`, #27185): an organization's // administrators author its own rate table; no parent row anchors a rate. { object: 'sys_exchange_rate', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, - // Working calendars (`@objectstack/platform-objects`, ADR-0157 D1): an - // organization's administrators author its calendars, and an exception's - // calendar carries the organization. - { object: 'sys_work_calendar', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); ${D10_SINGLE}`, anchors: [] }, - { object: 'sys_work_calendar_exception', census: PMAIN, fate: 'attribution', citation: `${CENSUS_MAIN} (in reach, added since the first census); the exception's calendar carries the organization`, anchors: [parent('calendar', 'sys_work_calendar')] }, // The recycle bin (`@objectstack/platform-objects`, ADR-0148, #30237): the // engine writes each entry with the organization of the record it holds, // else the deleting context's. A NULL row comes only from a delete with diff --git a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts index a2dcc93cb5c..abd6b9c0770 100644 --- a/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts +++ b/packages/cli/test/connect-agent-both-halves-wire.pin.test.ts @@ -264,7 +264,7 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // The Setup tree the platform admin is served BY THIS COMPOSITION: 9 // authored groups less `group_approvals`, `group_integrations` and // `group_apps`, which nothing in it contributes into and the filter - // collapses, plus the 26 entries `SETUP_NAV_CONTRIBUTIONS` carries, + // collapses, plus the 24 entries `SETUP_NAV_CONTRIBUTIONS` carries, // plus the MCP one. // (25 until #25098 moved the unfiltered Packages entry to Studio; 24 // until #30204 removed the Feature Flags entry with its namespace; 32 @@ -274,17 +274,13 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( // Configuration; 32 until the recycle bin entry, `nav_recycle_bin`, // joined Configuration (#30239); 33 until objectstack#34724 retired // the Packaged Actions entry, `nav_packaged_actions`, the one entry - // `group_apps` held here, so that group collapses too; 31 until the - // working-calendar pair, `nav_work_calendars` and - // `nav_work_calendar_exceptions`, joined Configuration, ADR-0157.) + // `group_apps` held here, so that group collapses too.) // `nav_settings_branding` is not among them, and not because of a // tenancy wall (this harness boots none): since #24766 it is // contributed by `@objectstack/service-settings` together with the // `branding` namespace, offered only where no organization wall stands, // and this harness composes platform-objects and the MCP bundle alone. - expect(allowedIds).toHaveLength(33); - expect(allowedIds).toContain('nav_work_calendars'); - expect(allowedIds).toContain('nav_work_calendar_exceptions'); + expect(allowedIds).toHaveLength(31); expect(allowedIds).not.toContain('nav_packaged_actions'); expect(allowedIds).toContain('nav_settings_access_policy'); expect(allowedIds).toContain('nav_recycle_bin'); @@ -310,8 +306,8 @@ describe('#17647 — Connect-an-Agent visibility: BOTH halves, over the wire', ( expect(withAccountHalf.statusCode).toBe(200); expect(withoutAccountHalf.statusCode).toBe(200); expect(navIds(withAccountHalf.body?.item)).toEqual(navIds(withoutAccountHalf.body?.item)); - // 33: the composition the count in the test above states. - expect(navIds(withAccountHalf.body?.item)).toHaveLength(33); + // 31: the composition the count in the test above states. + expect(navIds(withAccountHalf.body?.item)).toHaveLength(31); // The mechanism behind the invariance, asserted rather than assumed: // the bundle aims exactly one contribution at `setup` and one at diff --git a/packages/platform-objects/scripts/i18n-extract.config.ts b/packages/platform-objects/scripts/i18n-extract.config.ts index 8b73a529c76..3d59bc05744 100644 --- a/packages/platform-objects/scripts/i18n-extract.config.ts +++ b/packages/platform-objects/scripts/i18n-extract.config.ts @@ -203,8 +203,6 @@ import { SysPlatformSettingAudit, SysMigration, SysExchangeRate, - SysWorkCalendar, - SysWorkCalendarException, } from '../src/system/index.js'; // ── Existing Setup app + dashboards + translations ──────────────────────── @@ -362,8 +360,6 @@ const config: ObjectStackDefinition = defineStack({ SysPlatformSettingAudit, SysMigration, SysExchangeRate, - SysWorkCalendar, - SysWorkCalendarException, ] as any, apps: [SETUP_APP, STUDIO_APP, ACCOUNT_APP] as any, diff --git a/packages/platform-objects/src/apps/setup-nav.contributions.ts b/packages/platform-objects/src/apps/setup-nav.contributions.ts index f0102abebda..a7d13fe83b4 100644 --- a/packages/platform-objects/src/apps/setup-nav.contributions.ts +++ b/packages/platform-objects/src/apps/setup-nav.contributions.ts @@ -134,13 +134,6 @@ export const SETUP_NAV_CONTRIBUTIONS: NavigationContribution[] = [ // `requiredPermissions`: the object grant decides who reads and writes // (organization admins), and Setup itself already needs `setup.access`. { id: 'nav_exchange_rates', type: 'object', label: 'Exchange Rates', objectName: 'sys_exchange_rate', viewName: 'all_rates', icon: 'arrow-right-left' }, - // [ADR-0157 D1, D3] Working calendars and their holidays, beside the - // other organization reference data Localization governs. The exceptions - // get their own entry because their list page is the import door for a - // year of holidays; the calendar list's `needs_maintenance` view is the - // D8 notice. Access as Exchange Rates: the object grant decides. - { id: 'nav_work_calendars', type: 'object', label: 'Working Calendars', objectName: 'sys_work_calendar', viewName: 'all_calendars', icon: 'calendar-clock' }, - { id: 'nav_work_calendar_exceptions', type: 'object', label: 'Calendar Exceptions', objectName: 'sys_work_calendar_exception', viewName: 'all_exceptions', icon: 'calendar-x' }, { id: 'nav_settings_company', type: 'url', label: 'Company', url: '/apps/setup/system/settings/company', icon: 'building-2' }, // `nav_settings_branding` is contributed by `@objectstack/service-settings` // with the `branding` namespace, which is offered only where no diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index 71b3f33249b..1df359ee862 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -4422,128 +4422,5 @@ export const arObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "تقويم العمل", - pluralLabel: "تقويمات العمل", - description: "تقويمات العمل: ساعات العمل الأسبوعية، والمنطقة الزمنية التي تُحسب بها، وإلى أي تاريخ أُدخلت العطلات. تقرؤها تواريخ الاستحقاق المحسوبة بوقت العمل.", - fields: { - id: { - label: "المعرّف" - }, - code: { - label: "الرمز", - help: "الرمز الآلي الذي تُسمّي به الصيغ وتصعيدات الموافقة والحزم هذا التقويم، مثل cn_standard: أحرف صغيرة وأرقام وشرطات سفلية." - }, - name: { - label: "الاسم" - }, - timezone: { - label: "المنطقة الزمنية", - help: "منطقة IANA الزمنية التي تُحسب بها فترات العمل، مثل Asia/Shanghai. إذا تُركت فارغة عند الإنشاء، تُؤخذ المنطقة الزمنية الافتراضية للمؤسسة (الإعدادات ← الترجمة والإعدادات المحلية)." - }, - is_default: { - label: "افتراضي", - help: "التقويم الذي يستخدمه تاريخ الاستحقاق عندما لا يحدد تقويمًا. واحد لكل مؤسسة." - }, - maintained_from: { - label: "مُحدَّث من", - help: "أول تاريخ أُدخلت منه العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ أسبق." - }, - maintained_through: { - label: "مُحدَّث حتى", - help: "آخر تاريخ أُدخلت حتى نهايته العطلات وأيام العمل التعويضية. يُرفض أي حساب يحتاج إلى تاريخ لاحق: أدخل عطلات العام التالي، ثم انقل هذا التاريخ." - }, - monday_periods: { - label: "الاثنين", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - tuesday_periods: { - label: "الثلاثاء", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - wednesday_periods: { - label: "الأربعاء", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - thursday_periods: { - label: "الخميس", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - friday_periods: { - label: "الجمعة", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - saturday_periods: { - label: "السبت", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - }, - sunday_periods: { - label: "الأحد", - help: "فترات العمل في ذلك اليوم بالمنطقة الزمنية للتقويم، بصيغة HH:mm-HH:mm مفصولة بفواصل، مثل 09:00-12:00, 13:00-18:00. تنتهي الفترة بعد بدايتها في اليوم نفسه؛ وآخر نهاية ممكنة هي 24:00. اتركها فارغة ليوم الإجازة." - } - }, - _views: { - all_calendars: { - label: "الكل", - emptyState: { - title: "لا توجد تقويمات عمل بعد", - message: "أضف تقويمًا بساعات عمله الأسبوعية وحدّد أحدها تقويمًا افتراضيًا، ثم أدخل عطلاته وأيام العمل التعويضية." - } - }, - needs_maintenance: { - label: "بحاجة إلى تحديث", - emptyState: { - title: "جميع التقويمات محدَّثة مسبقًا", - message: "يظهر التقويم هنا عندما تنتهي عطلاته المُدخلة خلال الـ 60 يومًا القادمة؛ وتُرفض تواريخ الاستحقاق التي تتجاوز ذلك التاريخ." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "يجب أن يبدأ الرمز بحرف صغير وأن يحتوي فقط على أحرف صغيرة وأرقام وشرطات سفلية، مثل cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "استثناء تقويم", - pluralLabel: "استثناءات التقويم", - description: "استثناءات مؤرّخة لتقويم العمل: العطلات الرسمية وأيام العمل التعويضية وأيام الإغلاق. يحمل يوم العمل فترات عمله كاملة.", - fields: { - id: { - label: "المعرّف" - }, - calendar: { - label: "التقويم" - }, - date: { - label: "التاريخ" - }, - kind: { - label: "النوع", - help: "يوم إجازة: التاريخ كله إجازة. يوم عمل: يُعمل في التاريخ وفق الفترات أدناه، مثل يوم عمل تعويضي.", - options: { - off: "يوم إجازة", - on: "يوم عمل" - } - }, - periods: { - label: "الفترات", - help: "ليوم العمل، فترات العمل الكاملة لذلك التاريخ بصيغة HH:mm-HH:mm مفصولة بفواصل (09:00-12:00, 13:00-18:00)؛ ولا تُؤخذ أبدًا من يوم الأسبوع. اتركها فارغة ليوم الإجازة." - }, - note: { - label: "ملاحظة", - help: "ما هو هذا التاريخ، مثل العيد الوطني أو يوم عمل تعويضي لعيد الربيع." - } - }, - _views: { - all_exceptions: { - label: "الكل", - emptyState: { - title: "لا توجد استثناءات تقويم بعد", - message: "أضف صفًا لكل عطلة أو يوم عمل تعويضي، أو استورد سنة كاملة منها من ملف." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/ar.ts b/packages/platform-objects/src/apps/translations/ar.ts index 87c04baf12c..b5576f775e0 100644 --- a/packages/platform-objects/src/apps/translations/ar.ts +++ b/packages/platform-objects/src/apps/translations/ar.ts @@ -94,8 +94,6 @@ export const ar: TranslationData = { nav_settings_hub: { label: 'جميع الإعدادات' }, nav_settings_localization: { label: 'الترجمة والإعدادات المحلية' }, nav_exchange_rates: { label: 'أسعار الصرف' }, - nav_work_calendars: { label: 'تقويمات العمل' }, - nav_work_calendar_exceptions: { label: 'استثناءات التقويم' }, nav_settings_company: { label: 'الشركة' }, nav_settings_mail: { label: 'إرسال البريد' }, nav_settings_sms: { label: 'إرسال الرسائل النصية' }, diff --git a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts index 4a0608f81bc..648ef7e731a 100644 --- a/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts +++ b/packages/platform-objects/src/apps/translations/bundle-ownership.test.ts @@ -56,7 +56,6 @@ const OWNED_OBJECTS = new Set([ 'sys_metadata', 'sys_metadata_history', 'sys_metadata_audit', 'sys_metadata_commit', // system 'sys_setting', 'sys_platform_setting', 'sys_secret', 'sys_setting_audit', 'sys_platform_setting_audit', 'sys_migration', 'sys_exchange_rate', - 'sys_work_calendar', 'sys_work_calendar_exception', ]); describe('objects translation bundle ownership (ADR-0029 D8)', () => { diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index 0b98fbcb401..a83e2630d8e 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -4422,128 +4422,5 @@ export const deObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Arbeitskalender", - pluralLabel: "Arbeitskalender", - description: "Arbeitskalender: die wöchentlichen Arbeitszeiten, die Zeitzone, in der sie gelten, und bis wann die Feiertage gepflegt sind. Fälligkeitsdaten, die in Arbeitszeit gezählt werden, lesen sie.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Code", - help: "Maschinencode, mit dem Formeln, Genehmigungseskalationen und Pakete diesen Kalender benennen, z. B. cn_standard: Kleinbuchstaben, Ziffern und Unterstriche." - }, - name: { - label: "Name" - }, - timezone: { - label: "Zeitzone", - help: "IANA-Zeitzone, in der die Arbeitszeiten gelten, z. B. Asia/Shanghai. Beim Anlegen leer gelassen, wird die Standardzeitzone der Organisation übernommen (Einstellungen → Lokalisierung)." - }, - is_default: { - label: "Standard", - help: "Der Kalender, den ein Fälligkeitsdatum verwendet, wenn es keinen nennt. Einer pro Organisation." - }, - maintained_from: { - label: "Gepflegt ab", - help: "Erstes Datum, ab dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein früheres Datum braucht, wird abgelehnt." - }, - maintained_through: { - label: "Gepflegt bis", - help: "Letztes Datum, bis zu dem Feiertage und Ersatzarbeitstage erfasst sind. Eine Berechnung, die ein späteres Datum braucht, wird abgelehnt: Erfassen Sie die Feiertage des nächsten Jahres und verschieben Sie dann dieses Datum." - }, - monday_periods: { - label: "Montag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - tuesday_periods: { - label: "Dienstag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - wednesday_periods: { - label: "Mittwoch", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - thursday_periods: { - label: "Donnerstag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - friday_periods: { - label: "Freitag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - saturday_periods: { - label: "Samstag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - }, - sunday_periods: { - label: "Sonntag", - help: "Arbeitszeiten an diesem Tag in der Zeitzone des Kalenders, HH:mm-HH:mm durch Kommas getrennt, z. B. 09:00-12:00, 13:00-18:00. Ein Zeitraum endet am selben Tag später, als er beginnt; 24:00 ist das späteste Ende. Für einen freien Tag leer lassen." - } - }, - _views: { - all_calendars: { - label: "Alle", - emptyState: { - title: "Noch keine Arbeitskalender", - message: "Fügen Sie einen Kalender mit seinen wöchentlichen Arbeitszeiten hinzu, markieren Sie einen als Standard und erfassen Sie dann seine Feiertage und Ersatzarbeitstage." - } - }, - needs_maintenance: { - label: "Pflege erforderlich", - emptyState: { - title: "Alle Kalender sind vorausschauend gepflegt", - message: "Ein Kalender erscheint hier, wenn seine Feiertage innerhalb der nächsten 60 Tage enden; Fälligkeitsdaten nach diesem Datum werden abgelehnt." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "Der Code muss mit einem Kleinbuchstaben beginnen und darf nur Kleinbuchstaben, Ziffern und Unterstriche enthalten, z. B. cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Kalenderausnahme", - pluralLabel: "Kalenderausnahmen", - description: "Datierte Abweichungen von einem Arbeitskalender: Feiertage, Ersatzarbeitstage und Betriebsruhen. Ein Arbeitstag trägt seine vollständigen Arbeitszeiten.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Kalender" - }, - date: { - label: "Datum" - }, - kind: { - label: "Art", - help: "Frei: Der ganze Tag ist frei. Arbeitstag: An dem Datum wird mit den Zeiträumen unten gearbeitet, z. B. an einem Ersatzarbeitstag.", - options: { - off: "Frei", - on: "Arbeitstag" - } - }, - periods: { - label: "Zeiträume", - help: "Für einen Arbeitstag die vollständigen Arbeitszeiten dieses Datums, HH:mm-HH:mm durch Kommas getrennt (09:00-12:00, 13:00-18:00); sie werden nie vom Wochentag übernommen. Für einen freien Tag leer lassen." - }, - note: { - label: "Notiz", - help: "Was das Datum ist, z. B. Nationalfeiertag oder ein Ersatzarbeitstag zum Frühlingsfest." - } - }, - _views: { - all_exceptions: { - label: "Alle", - emptyState: { - title: "Noch keine Kalenderausnahmen", - message: "Fügen Sie pro Feiertag oder Ersatzarbeitstag eine Zeile hinzu oder importieren Sie ein Jahr davon aus einer Datei." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index 4d0c80cb908..628a3fca820 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -232,8 +232,4 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_user.fields.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar.fields.name.label": "5274417ff1ccaf01", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/de.ts b/packages/platform-objects/src/apps/translations/de.ts index f0c97065ef1..a90ba6d2117 100644 --- a/packages/platform-objects/src/apps/translations/de.ts +++ b/packages/platform-objects/src/apps/translations/de.ts @@ -96,8 +96,6 @@ export const de: TranslationData = { nav_settings_hub: { label: 'Alle Einstellungen' }, nav_settings_localization: { label: 'Lokalisierung' }, nav_exchange_rates: { label: 'Wechselkurse' }, - nav_work_calendars: { label: 'Arbeitskalender' }, - nav_work_calendar_exceptions: { label: 'Kalenderausnahmen' }, nav_settings_company: { label: 'Unternehmen' }, nav_settings_mail: { label: 'E-Mail-Versand' }, nav_settings_sms: { label: 'SMS-Versand' }, diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index df9fd29adf3..64f13a0d72b 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -4422,128 +4422,5 @@ export const enObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Working Calendar", - pluralLabel: "Working Calendars", - description: "Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. Due dates counted in working time read them.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Code", - help: "Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores." - }, - name: { - label: "Name" - }, - timezone: { - label: "Time Zone", - help: "IANA time zone the working periods are local to, such as Asia/Shanghai. Left out on create, it takes the organization's default time zone (Settings → Localization)." - }, - is_default: { - label: "Default", - help: "The calendar a due date uses when it names none. One per organization." - }, - maintained_from: { - label: "Maintained From", - help: "First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused." - }, - maintained_through: { - label: "Maintained Through", - help: "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date." - }, - monday_periods: { - label: "Monday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - tuesday_periods: { - label: "Tuesday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - wednesday_periods: { - label: "Wednesday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - thursday_periods: { - label: "Thursday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - friday_periods: { - label: "Friday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - saturday_periods: { - label: "Saturday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - }, - sunday_periods: { - label: "Sunday", - help: "Working periods that day in the calendar's time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off." - } - }, - _views: { - all_calendars: { - label: "All", - emptyState: { - title: "No working calendars yet", - message: "Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays." - } - }, - needs_maintenance: { - label: "Needs Maintenance", - emptyState: { - title: "Every calendar is maintained ahead", - message: "A calendar appears here when its holidays run out within the next 60 days; due dates past that date are refused." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Calendar Exception", - pluralLabel: "Calendar Exceptions", - description: "Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. A working day carries its full working periods.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Calendar" - }, - date: { - label: "Date" - }, - kind: { - label: "Kind", - help: "Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.", - options: { - off: "Day Off", - on: "Working Day" - } - }, - periods: { - label: "Periods", - help: "For a working day, that date's full working periods, HH:mm-HH:mm separated by commas (09:00-12:00, 13:00-18:00); they are never taken from the weekday. Leave blank for a day off." - }, - note: { - label: "Note", - help: "What the date is, such as National Day or a make-up workday for Spring Festival." - } - }, - _views: { - all_exceptions: { - label: "All", - emptyState: { - title: "No calendar exceptions yet", - message: "Add one row per holiday or make-up workday, or import a year of them from a file." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/en.ts b/packages/platform-objects/src/apps/translations/en.ts index d90a7e1fcb9..0d94a1f54d2 100644 --- a/packages/platform-objects/src/apps/translations/en.ts +++ b/packages/platform-objects/src/apps/translations/en.ts @@ -130,8 +130,6 @@ export const en: TranslationData = { nav_settings_hub: { label: 'All Settings' }, nav_settings_localization: { label: 'Localization' }, nav_exchange_rates: { label: 'Exchange Rates' }, - nav_work_calendars: { label: 'Working Calendars' }, - nav_work_calendar_exceptions: { label: 'Calendar Exceptions' }, nav_settings_company: { label: 'Company' }, nav_settings_mail: { label: 'Mail Delivery' }, nav_settings_sms: { label: 'SMS Delivery' }, diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index bf7e2c9027a..4a7ef584e34 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -4422,128 +4422,5 @@ export const esESObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Calendario laboral", - pluralLabel: "Calendarios laborales", - description: "Calendarios laborales: el horario semanal, la zona horaria en la que se aplica y hasta cuándo están mantenidos los festivos. Las fechas de vencimiento contadas en tiempo laborable los leen.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Código", - help: "Código de máquina con el que las fórmulas, las escalaciones de aprobación y los paquetes nombran este calendario, p. ej. cn_standard: letras minúsculas, dígitos y guiones bajos." - }, - name: { - label: "Nombre" - }, - timezone: { - label: "Zona horaria", - help: "Zona horaria IANA en la que se aplican las franjas de trabajo, p. ej. Asia/Shanghai. Si se deja vacía al crear, toma la zona horaria predeterminada de la organización (Ajustes → Localización)." - }, - is_default: { - label: "Predeterminado", - help: "El calendario que usa una fecha de vencimiento cuando no indica ninguno. Uno por organización." - }, - maintained_from: { - label: "Mantenido desde", - help: "Primera fecha desde la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha anterior." - }, - maintained_through: { - label: "Mantenido hasta", - help: "Última fecha hasta la que se registran los festivos y los días laborables de recuperación. Se rechaza un cálculo que necesite una fecha posterior: registra los festivos del año siguiente y luego mueve esta fecha." - }, - monday_periods: { - label: "Lunes", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - tuesday_periods: { - label: "Martes", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - wednesday_periods: { - label: "Miércoles", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - thursday_periods: { - label: "Jueves", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - friday_periods: { - label: "Viernes", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - saturday_periods: { - label: "Sábado", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - }, - sunday_periods: { - label: "Domingo", - help: "Franjas de trabajo de ese día en la zona horaria del calendario, HH:mm-HH:mm separadas por comas, p. ej. 09:00-12:00, 13:00-18:00. Una franja termina después de empezar, el mismo día; 24:00 es el final más tardío. Déjalo vacío para un día libre." - } - }, - _views: { - all_calendars: { - label: "Todos", - emptyState: { - title: "Aún no hay calendarios laborales", - message: "Añade un calendario con su horario semanal y marca uno como predeterminado; después registra sus festivos y días laborables de recuperación." - } - }, - needs_maintenance: { - label: "Requiere mantenimiento", - emptyState: { - title: "Todos los calendarios están mantenidos con antelación", - message: "Un calendario aparece aquí cuando sus festivos se acaban en los próximos 60 días; se rechazan las fechas de vencimiento posteriores a esa fecha." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "El código debe empezar por una letra minúscula y usar solo letras minúsculas, dígitos y guiones bajos, p. ej. cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Excepción de calendario", - pluralLabel: "Excepciones de calendario", - description: "Excepciones fechadas a un calendario laboral: festivos, días laborables de recuperación y cierres. Un día laborable lleva sus franjas de trabajo completas.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Calendario" - }, - date: { - label: "Fecha" - }, - kind: { - label: "Clase", - help: "Día libre: la fecha entera es libre. Día laborable: la fecha se trabaja con las franjas de abajo, p. ej. un día laborable de recuperación.", - options: { - off: "Día libre", - on: "Día laborable" - } - }, - periods: { - label: "Franjas", - help: "Para un día laborable, las franjas de trabajo completas de esa fecha, HH:mm-HH:mm separadas por comas (09:00-12:00, 13:00-18:00); nunca se toman del día de la semana. Déjalo vacío para un día libre." - }, - note: { - label: "Nota", - help: "Qué es la fecha, p. ej. la Fiesta Nacional o un día laborable de recuperación por el Festival de Primavera." - } - }, - _views: { - all_exceptions: { - label: "Todos", - emptyState: { - title: "Aún no hay excepciones de calendario", - message: "Añade una fila por cada festivo o día laborable de recuperación, o importa un año de ellos desde un archivo." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts index 2f42fc6c006..99c0176fec9 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.source-hashes.generated.ts @@ -161,6 +161,4 @@ export const esESGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/es-ES.ts b/packages/platform-objects/src/apps/translations/es-ES.ts index f476bee4962..414d4372176 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.ts @@ -85,8 +85,6 @@ export const esES: TranslationData = { nav_settings_hub: { label: 'Todos los Ajustes' }, nav_settings_localization: { label: 'Localización' }, nav_exchange_rates: { label: 'Tipos de cambio' }, - nav_work_calendars: { label: 'Calendarios laborales' }, - nav_work_calendar_exceptions: { label: 'Excepciones de calendario' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envío de correo' }, nav_settings_sms: { label: 'Envío de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 29843f40098..8a974a89c8d 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -4422,128 +4422,5 @@ export const frObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Calendrier de travail", - pluralLabel: "Calendriers de travail", - description: "Calendriers de travail : les horaires hebdomadaires, le fuseau horaire dans lequel ils s’appliquent et jusqu’à quand les jours fériés sont tenus à jour. Les échéances comptées en temps ouvré les lisent.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Code", - help: "Code machine par lequel les formules, les escalades d’approbation et les packages désignent ce calendrier, par ex. cn_standard : lettres minuscules, chiffres et traits de soulignement." - }, - name: { - label: "Nom" - }, - timezone: { - label: "Fuseau horaire", - help: "Fuseau horaire IANA dans lequel s’appliquent les plages de travail, par ex. Asia/Shanghai. Laissé vide à la création, il reprend le fuseau horaire par défaut de l’organisation (Paramètres → Localisation)." - }, - is_default: { - label: "Par défaut", - help: "Le calendrier utilisé par une échéance qui n’en désigne aucun. Un par organisation." - }, - maintained_from: { - label: "Tenu à jour depuis", - help: "Première date à partir de laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date antérieure est refusé." - }, - maintained_through: { - label: "Tenu à jour jusqu’au", - help: "Dernière date jusqu’à laquelle les jours fériés et les jours de récupération sont saisis. Un calcul qui exige une date ultérieure est refusé : saisissez les jours fériés de l’année suivante, puis reportez cette date." - }, - monday_periods: { - label: "Lundi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - tuesday_periods: { - label: "Mardi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - wednesday_periods: { - label: "Mercredi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - thursday_periods: { - label: "Jeudi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - friday_periods: { - label: "Vendredi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - saturday_periods: { - label: "Samedi", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - }, - sunday_periods: { - label: "Dimanche", - help: "Plages de travail ce jour-là dans le fuseau horaire du calendrier, au format HH:mm-HH:mm séparées par des virgules, par ex. 09:00-12:00, 13:00-18:00. Une plage se termine après son début, le même jour ; 24:00 est la fin la plus tardive. Laissez vide pour un jour non travaillé." - } - }, - _views: { - all_calendars: { - label: "Tous", - emptyState: { - title: "Aucun calendrier de travail pour le moment", - message: "Ajoutez un calendrier avec ses horaires hebdomadaires et marquez-en un comme calendrier par défaut, puis saisissez ses jours fériés et ses jours de récupération." - } - }, - needs_maintenance: { - label: "À mettre à jour", - emptyState: { - title: "Tous les calendriers sont tenus à jour à l’avance", - message: "Un calendrier apparaît ici lorsque ses jours fériés s’arrêtent dans les 60 prochains jours ; les échéances au-delà de cette date sont refusées." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "Le code doit commencer par une lettre minuscule et ne contenir que des lettres minuscules, des chiffres et des traits de soulignement, par ex. cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Exception de calendrier", - pluralLabel: "Exceptions de calendrier", - description: "Dérogations datées à un calendrier de travail : jours fériés, jours de récupération et fermetures. Un jour travaillé porte ses plages de travail complètes.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Calendrier" - }, - date: { - label: "Date" - }, - kind: { - label: "Type", - help: "Jour chômé : toute la date est chômée. Jour travaillé : la date est travaillée selon les plages ci-dessous, par ex. un jour de récupération.", - options: { - off: "Jour chômé", - on: "Jour travaillé" - } - }, - periods: { - label: "Plages", - help: "Pour un jour travaillé, les plages de travail complètes de cette date, au format HH:mm-HH:mm séparées par des virgules (09:00-12:00, 13:00-18:00) ; elles ne sont jamais reprises du jour de la semaine. Laissez vide pour un jour chômé." - }, - note: { - label: "Note", - help: "Ce qu’est la date, par ex. la fête nationale ou un jour de récupération pour la fête du Printemps." - } - }, - _views: { - all_exceptions: { - label: "Tous", - emptyState: { - title: "Aucune exception de calendrier pour le moment", - message: "Ajoutez une ligne par jour férié ou jour de récupération, ou importez-en une année depuis un fichier." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts index 5fd8e60ae06..8399fd2d550 100644 --- a/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.source-hashes.generated.ts @@ -258,9 +258,4 @@ export const frGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.code.label": "083180bdf83435b3", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.date.label": "767cabc93ccbdaa0", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.note.label": "f78f61778f71bf68", }; diff --git a/packages/platform-objects/src/apps/translations/fr.ts b/packages/platform-objects/src/apps/translations/fr.ts index fea45b80ee3..8512a22f91a 100644 --- a/packages/platform-objects/src/apps/translations/fr.ts +++ b/packages/platform-objects/src/apps/translations/fr.ts @@ -96,8 +96,6 @@ export const fr: TranslationData = { nav_settings_hub: { label: 'Tous les paramètres' }, nav_settings_localization: { label: 'Localisation' }, nav_exchange_rates: { label: 'Taux de change' }, - nav_work_calendars: { label: 'Calendriers de travail' }, - nav_work_calendar_exceptions: { label: 'Exceptions de calendrier' }, nav_settings_company: { label: 'Entreprise' }, nav_settings_mail: { label: 'Envoi des e-mails' }, nav_settings_sms: { label: 'Envoi des SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index 8e2b44f3eb4..5cd6eb158c0 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -4422,128 +4422,5 @@ export const jaJPObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "稼働カレンダー", - pluralLabel: "稼働カレンダー", - description: "稼働カレンダー:週ごとの稼働時間、その時間帯の基準となるタイムゾーン、祝日をどこまで登録済みか。稼働時間で数える期日はこれを参照します。", - fields: { - id: { - label: "ID" - }, - code: { - label: "コード", - help: "数式、承認エスカレーション、パッケージがこのカレンダーを指すときの機械コード(例: cn_standard)。英小文字、数字、アンダースコアのみ使用できます。" - }, - name: { - label: "名前" - }, - timezone: { - label: "タイムゾーン", - help: "稼働時間帯の基準となる IANA タイムゾーン(例: Asia/Shanghai)。作成時に省略すると、組織の既定のタイムゾーン(設定 → ローカリゼーション)を使用します。" - }, - is_default: { - label: "既定", - help: "期日がカレンダーを指定しないときに使うカレンダー。組織ごとに 1 つです。" - }, - maintained_from: { - label: "登録開始日", - help: "祝日と振替出勤日を登録している最初の日付。これより前の日付を必要とする計算は拒否されます。" - }, - maintained_through: { - label: "登録終了日", - help: "祝日と振替出勤日を登録している最後の日付。これより後の日付を必要とする計算は拒否されます。翌年の祝日を登録してから、この日付を延ばしてください。" - }, - monday_periods: { - label: "月曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - tuesday_periods: { - label: "火曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - wednesday_periods: { - label: "水曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - thursday_periods: { - label: "木曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - friday_periods: { - label: "金曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - saturday_periods: { - label: "土曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - }, - sunday_periods: { - label: "日曜日", - help: "その日の稼働時間帯(カレンダーのタイムゾーン基準)。HH:mm-HH:mm 形式をカンマで区切ります。例: 09:00-12:00, 13:00-18:00。時間帯は同じ日の中で開始より後に終わる必要があり、最も遅い終了は 24:00 です。休みの日は空欄にします。" - } - }, - _views: { - all_calendars: { - label: "すべて", - emptyState: { - title: "稼働カレンダーはまだありません", - message: "週ごとの稼働時間を入れてカレンダーを追加し、1 つを既定に設定してから、祝日と振替出勤日を登録します。" - } - }, - needs_maintenance: { - label: "要メンテナンス", - emptyState: { - title: "すべてのカレンダーが先まで登録済みです", - message: "祝日の登録が 60 日以内に切れるカレンダーがここに表示されます。その日付を過ぎる期日の計算は拒否されます。" - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "コードは英小文字で始め、英小文字、数字、アンダースコアのみを使用してください(例: cn_standard)。" - } - } - }, - sys_work_calendar_exception: { - label: "カレンダー例外", - pluralLabel: "カレンダー例外", - description: "稼働カレンダーの日付ごとの上書き:祝日、振替出勤日、休業日。稼働日にはその日の稼働時間帯をすべて入力します。", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "カレンダー" - }, - date: { - label: "日付" - }, - kind: { - label: "種類", - help: "休日:終日休みです。稼働日:下の時間帯で稼働する日です(振替出勤日など)。", - options: { - off: "休日", - on: "稼働日" - } - }, - periods: { - label: "稼働時間帯", - help: "稼働日の場合、その日の稼働時間帯をすべて HH:mm-HH:mm 形式のカンマ区切りで入力します(09:00-12:00, 13:00-18:00)。曜日の設定は引き継がれません。休日は空欄にします。" - }, - note: { - label: "メモ", - help: "その日付の内容(例: 国慶節、春節の振替出勤日)。" - } - }, - _views: { - all_exceptions: { - label: "すべて", - emptyState: { - title: "カレンダー例外はまだありません", - message: "祝日または振替出勤日ごとに 1 行追加するか、ファイルから 1 年分をインポートします。" - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts index d1257f1d385..c539c773da5 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.source-hashes.generated.ts @@ -151,6 +151,4 @@ export const jaJPGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ja-JP.ts b/packages/platform-objects/src/apps/translations/ja-JP.ts index 20b02b2e2e6..39eabfd756e 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.ts @@ -85,8 +85,6 @@ export const jaJP: TranslationData = { nav_settings_hub: { label: 'すべての設定' }, nav_settings_localization: { label: 'ローカリゼーション' }, nav_exchange_rates: { label: '為替レート' }, - nav_work_calendars: { label: '稼働カレンダー' }, - nav_work_calendar_exceptions: { label: 'カレンダー例外' }, nav_settings_company: { label: '会社' }, nav_settings_mail: { label: 'メール配信' }, nav_settings_sms: { label: 'SMS 配信' }, diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index 89c5bb48056..c9c54c6edd0 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -4422,128 +4422,5 @@ export const koObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "근무 캘린더", - pluralLabel: "근무 캘린더", - description: "근무 캘린더: 주간 근무 시간, 그 시간의 기준 시간대, 공휴일이 어디까지 관리되었는지를 담습니다. 근무 시간으로 계산하는 기한이 이를 참조합니다.", - fields: { - id: { - label: "ID" - }, - code: { - label: "코드", - help: "수식, 승인 에스컬레이션, 패키지가 이 캘린더를 가리킬 때 쓰는 기계 코드(예: cn_standard)로, 영문 소문자, 숫자, 밑줄만 사용합니다." - }, - name: { - label: "이름" - }, - timezone: { - label: "시간대", - help: "근무 시간대의 기준이 되는 IANA 시간대(예: Asia/Shanghai). 생성할 때 비워 두면 조직의 기본 시간대(설정 → 현지화)를 사용합니다." - }, - is_default: { - label: "기본값", - help: "기한이 캘린더를 지정하지 않을 때 사용하는 캘린더입니다. 조직당 하나입니다." - }, - maintained_from: { - label: "관리 시작일", - help: "공휴일과 대체 근무일이 입력되기 시작한 날짜입니다. 이보다 이른 날짜가 필요한 계산은 거부됩니다." - }, - maintained_through: { - label: "관리 종료일", - help: "공휴일과 대체 근무일이 입력된 마지막 날짜입니다. 이보다 늦은 날짜가 필요한 계산은 거부됩니다. 다음 해 공휴일을 입력한 뒤 이 날짜를 옮기세요." - }, - monday_periods: { - label: "월요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - tuesday_periods: { - label: "화요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - wednesday_periods: { - label: "수요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - thursday_periods: { - label: "목요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - friday_periods: { - label: "금요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - saturday_periods: { - label: "토요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - }, - sunday_periods: { - label: "일요일", - help: "캘린더 시간대 기준 그날의 근무 시간대로, HH:mm-HH:mm 형식을 쉼표로 구분합니다(예: 09:00-12:00, 13:00-18:00). 시간대는 같은 날 안에서 시작보다 늦게 끝나야 하며, 가장 늦은 종료는 24:00입니다. 쉬는 날은 비워 두세요." - } - }, - _views: { - all_calendars: { - label: "전체", - emptyState: { - title: "아직 근무 캘린더 없음", - message: "주간 근무 시간과 함께 캘린더를 추가하고 하나를 기본값으로 지정한 다음, 공휴일과 대체 근무일을 입력하세요." - } - }, - needs_maintenance: { - label: "관리 필요", - emptyState: { - title: "모든 캘린더가 미리 관리되어 있음", - message: "공휴일 입력이 60일 이내에 끝나는 캘린더가 여기에 표시됩니다. 그 날짜를 넘는 기한 계산은 거부됩니다." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "코드는 영문 소문자로 시작하고 영문 소문자, 숫자, 밑줄만 사용해야 합니다(예: cn_standard)." - } - } - }, - sys_work_calendar_exception: { - label: "캘린더 예외", - pluralLabel: "캘린더 예외", - description: "근무 캘린더의 날짜별 재정의: 공휴일, 대체 근무일, 휴업일. 근무일에는 그날의 전체 근무 시간대를 입력합니다.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "캘린더" - }, - date: { - label: "날짜" - }, - kind: { - label: "종류", - help: "휴무일: 하루 종일 쉽니다. 근무일: 아래 시간대로 근무하는 날입니다(예: 대체 근무일).", - options: { - off: "휴무일", - on: "근무일" - } - }, - periods: { - label: "근무 시간대", - help: "근무일이면 그날의 전체 근무 시간대를 HH:mm-HH:mm 형식으로 쉼표로 구분해 입력합니다(09:00-12:00, 13:00-18:00). 요일 설정을 이어받지 않습니다. 휴무일은 비워 두세요." - }, - note: { - label: "메모", - help: "해당 날짜가 무엇인지(예: 국경절, 춘절 대체 근무일)." - } - }, - _views: { - all_exceptions: { - label: "전체", - emptyState: { - title: "아직 캘린더 예외 없음", - message: "공휴일이나 대체 근무일마다 한 행을 추가하거나, 파일에서 1년 치를 가져오세요." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts index cd4dc42ae97..f70c7e7adb7 100644 --- a/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.source-hashes.generated.ts @@ -119,6 +119,4 @@ export const koGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ko.ts b/packages/platform-objects/src/apps/translations/ko.ts index 499cb9fb693..98c3ccc6ee0 100644 --- a/packages/platform-objects/src/apps/translations/ko.ts +++ b/packages/platform-objects/src/apps/translations/ko.ts @@ -95,8 +95,6 @@ export const ko: TranslationData = { nav_settings_hub: { label: '전체 설정' }, nav_settings_localization: { label: '현지화' }, nav_exchange_rates: { label: '환율' }, - nav_work_calendars: { label: '근무 캘린더' }, - nav_work_calendar_exceptions: { label: '캘린더 예외' }, nav_settings_company: { label: '회사' }, nav_settings_mail: { label: '메일 전송' }, nav_settings_sms: { label: 'SMS 전송' }, diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index e7329e488b1..b9beef7b7b0 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -4422,128 +4422,5 @@ export const ptBRObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Calendário de trabalho", - pluralLabel: "Calendários de trabalho", - description: "Calendários de trabalho: o horário semanal, o fuso horário em que ele vale e até quando os feriados estão mantidos. Prazos contados em tempo útil os leem.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Código", - help: "Código de máquina pelo qual fórmulas, escalonamentos de aprovação e pacotes nomeiam este calendário, por exemplo cn_standard: letras minúsculas, dígitos e sublinhados." - }, - name: { - label: "Nome" - }, - timezone: { - label: "Fuso horário", - help: "Fuso horário IANA em que os períodos de trabalho valem, por exemplo Asia/Shanghai. Se omitido na criação, usa o fuso horário padrão da organização (Configurações → Localização)." - }, - is_default: { - label: "Padrão", - help: "O calendário que um prazo usa quando não indica nenhum. Um por organização." - }, - maintained_from: { - label: "Mantido desde", - help: "Primeira data a partir da qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data anterior é recusado." - }, - maintained_through: { - label: "Mantido até", - help: "Última data até a qual feriados e dias úteis de compensação estão cadastrados. Um cálculo que precise de uma data posterior é recusado: cadastre os feriados do próximo ano e depois mova esta data." - }, - monday_periods: { - label: "Segunda-feira", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - tuesday_periods: { - label: "Terça-feira", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - wednesday_periods: { - label: "Quarta-feira", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - thursday_periods: { - label: "Quinta-feira", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - friday_periods: { - label: "Sexta-feira", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - saturday_periods: { - label: "Sábado", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - }, - sunday_periods: { - label: "Domingo", - help: "Períodos de trabalho nesse dia no fuso horário do calendário, HH:mm-HH:mm separados por vírgulas, por exemplo 09:00-12:00, 13:00-18:00. Um período termina depois de começar, no mesmo dia; 24:00 é o término mais tardio. Deixe em branco para um dia de folga." - } - }, - _views: { - all_calendars: { - label: "Todas", - emptyState: { - title: "Nenhum calendário de trabalho ainda", - message: "Adicione um calendário com seu horário semanal e marque um como padrão; depois cadastre seus feriados e dias úteis de compensação." - } - }, - needs_maintenance: { - label: "Precisa de manutenção", - emptyState: { - title: "Todos os calendários estão mantidos com antecedência", - message: "Um calendário aparece aqui quando seus feriados acabam nos próximos 60 dias; prazos além dessa data são recusados." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "O código deve começar com uma letra minúscula e usar apenas letras minúsculas, dígitos e sublinhados, por exemplo cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Exceção de calendário", - pluralLabel: "Exceções de calendário", - description: "Exceções datadas de um calendário de trabalho: feriados, dias úteis de compensação e paralisações. Um dia útil traz seus períodos de trabalho completos.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Calendário" - }, - date: { - label: "Data" - }, - kind: { - label: "Tipo", - help: "Folga: a data inteira é de folga. Dia útil: a data é trabalhada com os períodos abaixo, por exemplo um dia útil de compensação.", - options: { - off: "Folga", - on: "Dia útil" - } - }, - periods: { - label: "Períodos", - help: "Para um dia útil, os períodos de trabalho completos dessa data, HH:mm-HH:mm separados por vírgulas (09:00-12:00, 13:00-18:00); nunca são herdados do dia da semana. Deixe em branco para uma folga." - }, - note: { - label: "Observação", - help: "O que é a data, por exemplo o Dia Nacional ou um dia útil de compensação do Festival da Primavera." - } - }, - _views: { - all_exceptions: { - label: "Todas", - emptyState: { - title: "Nenhuma exceção de calendário ainda", - message: "Adicione uma linha por feriado ou dia útil de compensação, ou importe um ano deles de um arquivo." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts index 3d7d12167ed..c86d9109f75 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.source-hashes.generated.ts @@ -162,6 +162,4 @@ export const ptBRGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/pt-BR.ts b/packages/platform-objects/src/apps/translations/pt-BR.ts index 7e95bea6884..4869a68d45b 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.ts @@ -96,8 +96,6 @@ export const ptBR: TranslationData = { nav_settings_hub: { label: 'Todas as configurações' }, nav_settings_localization: { label: 'Localização' }, nav_exchange_rates: { label: 'Taxas de câmbio' }, - nav_work_calendars: { label: 'Calendários de trabalho' }, - nav_work_calendar_exceptions: { label: 'Exceções de calendário' }, nav_settings_company: { label: 'Empresa' }, nav_settings_mail: { label: 'Envio de e-mail' }, nav_settings_sms: { label: 'Envio de SMS' }, diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index bdd27299261..a831dc63a37 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -4422,128 +4422,5 @@ export const ruObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "Рабочий календарь", - pluralLabel: "Рабочие календари", - description: "Рабочие календари: еженедельный график работы, часовой пояс, в котором он действует, и дата, до которой внесены праздники. Сроки, отсчитываемые в рабочем времени, берутся из них.", - fields: { - id: { - label: "ID" - }, - code: { - label: "Код", - help: "Машинный код, по которому формулы, эскалации согласований и пакеты ссылаются на этот календарь, например cn_standard: строчные латинские буквы, цифры и подчёркивания." - }, - name: { - label: "Название" - }, - timezone: { - label: "Часовой пояс", - help: "Часовой пояс IANA, в котором действуют рабочие интервалы, например Asia/Shanghai. Если не указан при создании, берётся часовой пояс организации по умолчанию (Настройки → Локализация)." - }, - is_default: { - label: "По умолчанию", - help: "Календарь, который используется для срока, если календарь не указан. Один на организацию." - }, - maintained_from: { - label: "Ведётся с", - help: "Первая дата, начиная с которой внесены праздники и рабочие дни переноса. Расчёт, которому нужна более ранняя дата, отклоняется." - }, - maintained_through: { - label: "Ведётся по", - help: "Последняя дата, по которую внесены праздники и рабочие дни переноса. Расчёт, которому нужна более поздняя дата, отклоняется: внесите праздники следующего года, затем передвиньте эту дату." - }, - monday_periods: { - label: "Понедельник", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - tuesday_periods: { - label: "Вторник", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - wednesday_periods: { - label: "Среда", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - thursday_periods: { - label: "Четверг", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - friday_periods: { - label: "Пятница", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - saturday_periods: { - label: "Суббота", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - }, - sunday_periods: { - label: "Воскресенье", - help: "Рабочие интервалы в этот день в часовом поясе календаря, HH:mm-HH:mm через запятую, например 09:00-12:00, 13:00-18:00. Интервал заканчивается позже, чем начинается, в тот же день; самое позднее окончание — 24:00. Оставьте пустым для выходного." - } - }, - _views: { - all_calendars: { - label: "Все", - emptyState: { - title: "Рабочих календарей пока нет", - message: "Добавьте календарь с еженедельным графиком и отметьте один как календарь по умолчанию, затем внесите его праздники и рабочие дни переноса." - } - }, - needs_maintenance: { - label: "Требует обновления", - emptyState: { - title: "Все календари заполнены наперёд", - message: "Календарь появляется здесь, когда его праздники заканчиваются в ближайшие 60 дней; сроки после этой даты отклоняются." - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "Код должен начинаться со строчной латинской буквы и содержать только строчные латинские буквы, цифры и подчёркивания, например cn_standard." - } - } - }, - sys_work_calendar_exception: { - label: "Исключение календаря", - pluralLabel: "Исключения календаря", - description: "Датированные исключения из рабочего календаря: праздники, рабочие дни переноса и простои. Рабочий день содержит полный набор рабочих интервалов.", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "Календарь" - }, - date: { - label: "Дата" - }, - kind: { - label: "Тип", - help: "Выходной: вся дата нерабочая. Рабочий день: в эту дату работают по интервалам ниже, например рабочий день переноса.", - options: { - off: "Выходной", - on: "Рабочий день" - } - }, - periods: { - label: "Интервалы", - help: "Для рабочего дня — полный набор рабочих интервалов этой даты, HH:mm-HH:mm через запятую (09:00-12:00, 13:00-18:00); они никогда не берутся из дня недели. Оставьте пустым для выходного." - }, - note: { - label: "Примечание", - help: "Что это за дата, например Национальный день или рабочий день переноса к Празднику весны." - } - }, - _views: { - all_exceptions: { - label: "Все", - emptyState: { - title: "Исключений календаря пока нет", - message: "Добавьте по строке на каждый праздник или рабочий день переноса либо импортируйте их за год из файла." - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts index 5ae275ddf33..c5c1bc306f5 100644 --- a/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.source-hashes.generated.ts @@ -118,6 +118,4 @@ export const ruGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/ru.ts b/packages/platform-objects/src/apps/translations/ru.ts index 175eb27ec92..26a165608d7 100644 --- a/packages/platform-objects/src/apps/translations/ru.ts +++ b/packages/platform-objects/src/apps/translations/ru.ts @@ -96,8 +96,6 @@ export const ru: TranslationData = { nav_settings_hub: { label: 'Все настройки' }, nav_settings_localization: { label: 'Локализация' }, nav_exchange_rates: { label: 'Курсы валют' }, - nav_work_calendars: { label: 'Рабочие календари' }, - nav_work_calendar_exceptions: { label: 'Исключения календаря' }, nav_settings_company: { label: 'Компания' }, nav_settings_mail: { label: 'Доставка почты' }, nav_settings_sms: { label: 'Доставка SMS' }, diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index 8d278e0958a..314ed4ba79b 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -4422,128 +4422,5 @@ export const zhCNObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "工作日历", - pluralLabel: "工作日历", - description: "工作日历:每周的工作时段、时段所在的时区,以及节假日维护到哪一天。按工作时间计算的到期日读取它们。", - fields: { - id: { - label: "ID" - }, - code: { - label: "代码", - help: "公式、审批升级和软件包用来指称此日历的机器代码,如 cn_standard:仅限小写字母、数字和下划线。" - }, - name: { - label: "名称" - }, - timezone: { - label: "时区", - help: "工作时段所在的 IANA 时区,如 Asia/Shanghai。创建时留空则取组织的默认时区(设置 → 本地化)。" - }, - is_default: { - label: "默认", - help: "到期日未指定日历时使用的日历。每个组织一个。" - }, - maintained_from: { - label: "维护起始日", - help: "节假日和调休工作日从这一天开始录入。需要更早日期的计算会被拒绝。" - }, - maintained_through: { - label: "维护截止日", - help: "节假日和调休工作日录入到这一天为止。需要更晚日期的计算会被拒绝:请录入下一年的节假日,再顺延此日期。" - }, - monday_periods: { - label: "星期一", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - tuesday_periods: { - label: "星期二", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - wednesday_periods: { - label: "星期三", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - thursday_periods: { - label: "星期四", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - friday_periods: { - label: "星期五", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - saturday_periods: { - label: "星期六", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - }, - sunday_periods: { - label: "星期日", - help: "当天的工作时段,按日历的时区计,格式为 HH:mm-HH:mm,多个时段用逗号分隔,如 09:00-12:00, 13:00-18:00。时段须在同一天内且结束晚于开始;最晚结束为 24:00。留空表示当天休息。" - } - }, - _views: { - all_calendars: { - label: "全部", - emptyState: { - title: "还没有工作日历", - message: "添加一个日历并填写每周工作时段,将其中一个设为默认,然后录入它的节假日和调休工作日。" - } - }, - needs_maintenance: { - label: "待维护", - emptyState: { - title: "所有日历都已提前维护", - message: "节假日将在 60 天内用完的日历会出现在这里;超出该日期的到期日计算会被拒绝。" - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "代码须以小写字母开头,且只能包含小写字母、数字和下划线,如 cn_standard。" - } - } - }, - sys_work_calendar_exception: { - label: "日历例外", - pluralLabel: "日历例外", - description: "工作日历的按日期覆盖:法定节假日、调休工作日和停工日。工作日须带上当天完整的工作时段。", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "日历" - }, - date: { - label: "日期" - }, - kind: { - label: "类型", - help: "休息日:整天休息。工作日:当天按下方时段上班,如调休工作日。", - options: { - off: "休息日", - on: "工作日" - } - }, - periods: { - label: "工作时段", - help: "工作日须填写当天完整的工作时段,格式为 HH:mm-HH:mm,多个时段用逗号分隔(09:00-12:00, 13:00-18:00);不会从对应星期的时段继承。休息日留空。" - }, - note: { - label: "备注", - help: "该日期是什么,如国庆节或春节调休工作日。" - } - }, - _views: { - all_exceptions: { - label: "全部", - emptyState: { - title: "还没有日历例外", - message: "每个节假日或调休工作日录一行,或从文件导入一整年的数据。" - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts index 0d41f54578b..5fc27e139ad 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.source-hashes.generated.ts @@ -91,6 +91,4 @@ export const zhCNGeneratedSourceHashes: Readonly> = { "objects.sys_sso_provider.fields.sign_out_of_idp.label": "212587b8191bb91b", "objects.sys_user._actions.import_sso_users.params.csv.label": "bfb77802b66a9222", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-CN.ts b/packages/platform-objects/src/apps/translations/zh-CN.ts index 3ed6f3432f2..0ab64b2e61b 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.ts @@ -89,8 +89,6 @@ export const zhCN: TranslationData = { nav_settings_hub: { label: '全部设置' }, nav_settings_localization: { label: '本地化' }, nav_exchange_rates: { label: '汇率' }, - nav_work_calendars: { label: '工作日历' }, - nav_work_calendar_exceptions: { label: '日历例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '邮件投递' }, nav_settings_sms: { label: '短信投递' }, diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index d6e684b47d4..891c35c6a8f 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -4422,128 +4422,5 @@ export const zhHantObjects: NonNullable = { } } } - }, - sys_work_calendar: { - label: "工作日曆", - pluralLabel: "工作日曆", - description: "工作日曆:每週的工作時段、時段所在的時區,以及假日維護到哪一天。依工作時間計算的到期日會讀取它們。", - fields: { - id: { - label: "ID" - }, - code: { - label: "代碼", - help: "公式、審批升級與套件用來指稱此日曆的機器代碼,如 cn_standard:僅限小寫字母、數字和底線。" - }, - name: { - label: "名稱" - }, - timezone: { - label: "時區", - help: "工作時段所在的 IANA 時區,如 Asia/Shanghai。建立時留空則取組織的預設時區(設定 → 在地化)。" - }, - is_default: { - label: "預設", - help: "到期日未指定日曆時使用的日曆。每個組織一個。" - }, - maintained_from: { - label: "維護起始日", - help: "假日與補班日從這一天開始登錄。需要更早日期的計算會被拒絕。" - }, - maintained_through: { - label: "維護截止日", - help: "假日與補班日登錄到這一天為止。需要更晚日期的計算會被拒絕:請登錄下一年的假日,再順延此日期。" - }, - monday_periods: { - label: "星期一", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - tuesday_periods: { - label: "星期二", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - wednesday_periods: { - label: "星期三", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - thursday_periods: { - label: "星期四", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - friday_periods: { - label: "星期五", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - saturday_periods: { - label: "星期六", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - }, - sunday_periods: { - label: "星期日", - help: "當天的工作時段,依日曆的時區計,格式為 HH:mm-HH:mm,多個時段以逗號分隔,如 09:00-12:00, 13:00-18:00。時段須在同一天內且結束晚於開始;最晚結束為 24:00。留空表示當天休息。" - } - }, - _views: { - all_calendars: { - label: "全部", - emptyState: { - title: "還沒有工作日曆", - message: "新增一個日曆並填寫每週工作時段,將其中一個設為預設,然後登錄它的假日與補班日。" - } - }, - needs_maintenance: { - label: "待維護", - emptyState: { - title: "所有日曆都已提前維護", - message: "假日將在 60 天內用完的日曆會出現在這裡;超出該日期的到期日計算會被拒絕。" - } - } - }, - _validations: { - work_calendar_code_shape: { - message: "代碼須以小寫字母開頭,且只能包含小寫字母、數字和底線,如 cn_standard。" - } - } - }, - sys_work_calendar_exception: { - label: "日曆例外", - pluralLabel: "日曆例外", - description: "工作日曆的依日期覆寫:國定假日、補班日與停工日。工作日須帶上當天完整的工作時段。", - fields: { - id: { - label: "ID" - }, - calendar: { - label: "日曆" - }, - date: { - label: "日期" - }, - kind: { - label: "類型", - help: "休息日:整天休息。工作日:當天依下方時段上班,如補班日。", - options: { - off: "休息日", - on: "工作日" - } - }, - periods: { - label: "工作時段", - help: "工作日須填寫當天完整的工作時段,格式為 HH:mm-HH:mm,多個時段以逗號分隔(09:00-12:00, 13:00-18:00);不會從對應星期的時段繼承。休息日留空。" - }, - note: { - label: "備註", - help: "該日期是什麼,如國慶日或春節補班日。" - } - }, - _views: { - all_exceptions: { - label: "全部", - emptyState: { - title: "還沒有日曆例外", - message: "每個假日或補班日登錄一列,或從檔案匯入一整年的資料。" - } - } - } } }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts index d88745f71e4..cedbb33ccf7 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.source-hashes.generated.ts @@ -112,6 +112,4 @@ export const zhHantGeneratedSourceHashes: Readonly> = { "objects.sys_user._actions.remove_sso_user.label": "27e40f055ed9dc98", "objects.sys_user._actions.remove_sso_user.successMessage": "45facf16a8b5ebc7", "objects.sys_user.fields.source.options.idp_pending": "3751093c5b65b072", - "objects.sys_work_calendar.fields.id.label": "00b0385c9c152888", - "objects.sys_work_calendar_exception.fields.id.label": "00b0385c9c152888", }; diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.ts b/packages/platform-objects/src/apps/translations/zh-Hant.ts index 6a19d05cd96..876aec38241 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.ts @@ -94,8 +94,6 @@ export const zhHant: TranslationData = { nav_settings_hub: { label: '全部設定' }, nav_settings_localization: { label: '在地化' }, nav_exchange_rates: { label: '匯率' }, - nav_work_calendars: { label: '工作日曆' }, - nav_work_calendar_exceptions: { label: '日曆例外' }, nav_settings_company: { label: '公司' }, nav_settings_mail: { label: '郵件投遞' }, nav_settings_sms: { label: '簡訊投遞' }, diff --git a/packages/platform-objects/src/platform-objects.test.ts b/packages/platform-objects/src/platform-objects.test.ts index 173bea85716..a9c80336b27 100644 --- a/packages/platform-objects/src/platform-objects.test.ts +++ b/packages/platform-objects/src/platform-objects.test.ts @@ -37,7 +37,7 @@ import { SysMetadata, SysMetadataHistoryObject, } from './metadata/index.js'; -import { SysExchangeRate, SysSecret, SysSetting, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; +import { SysExchangeRate, SysSecret, SysSetting } from './system/index.js'; import { ACCOUNT_APP, SETUP_APP, SETUP_NAV_CONTRIBUTIONS, STUDIO_APP } from './apps/index.js'; import { AppSchema } from '@objectstack/spec/ui'; import { resolveEffectiveApiMethods, isApiOperationAllowed, canServeApiOperation } from '@objectstack/spec/data'; @@ -609,8 +609,6 @@ describe('@objectstack/platform-objects', () => { sys_team: SysTeam, sys_user: SysUser, sys_user_preference: SysUserPreference, - sys_work_calendar: SysWorkCalendar, - sys_work_calendar_exception: SysWorkCalendarException, }; // Targets owned by another package (contributed there, gated by // `requiresObject`), so nothing here can read their `enable`. Named diff --git a/packages/platform-objects/src/plugin.test.ts b/packages/platform-objects/src/plugin.test.ts index 53d7f1a8ba4..a3cb50e646c 100644 --- a/packages/platform-objects/src/plugin.test.ts +++ b/packages/platform-objects/src/plugin.test.ts @@ -11,7 +11,7 @@ import { describe, it, expect } from 'vitest'; import { assertEngineFindOnePredicate, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { ObjectSchema, RECYCLE_BIN_ENTRY_FIELDS, RECYCLE_BIN_OBJECT } from '@objectstack/spec/data'; import { PlatformObjectsPlugin } from './plugin.js'; -import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey, SysWorkCalendar, SysWorkCalendarException } from './system/index.js'; +import { SysExchangeRate, SysLifecycleState, SysMetadataActivation, SysMigration, SysMigrationJournal, SysRecycleBin, SysSecret, SysSeedLandedKey, SysTrustedKey } from './system/index.js'; /** * Hand-rolled fake PluginContext (mirrors the service-plugin tests) — this @@ -47,7 +47,7 @@ function makeCtx() { } describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4243, #4270)', () => { - it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { + it('registers SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin and SysSeedLandedKey through the manifest service', async () => { const ctx = makeCtx(); const manifests: any[] = []; ctx.registerService('manifest', { register: (m: any) => manifests.push(m) }); @@ -57,7 +57,7 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 const infra = manifests.find((m) => m.id === 'com.objectstack.platform-objects'); expect(infra).toBeDefined(); expect(infra.scope).toBe('system'); - expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); + expect(infra.objects).toEqual([SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey]); expect(infra.objects.map((o: any) => o.name)).toEqual([ 'sys_migration', // ADR-0119 D2 (#4617). Registered UNCONDITIONALLY, alongside the flag @@ -70,10 +70,6 @@ describe('PlatformObjectsPlugin: platform-infrastructure object registration (#4 // home-currency projection, so it registers with the engine-facing // infrastructure, on the project database. 'sys_exchange_rate', - // [ADR-0157 D1] Working calendars and their exceptions, read by the - // engine's calendar service; organization data on the project database. - 'sys_work_calendar', - 'sys_work_calendar_exception', // [ADR-0025 §3.5 M1, #27123] The environment's trusted plugin-publisher // keys, read by `os plugin install` from a one-shot boot that composes // this plugin and nothing that would register it otherwise. diff --git a/packages/platform-objects/src/plugin.ts b/packages/platform-objects/src/plugin.ts index f42c6229b20..b2838397578 100644 --- a/packages/platform-objects/src/plugin.ts +++ b/packages/platform-objects/src/plugin.ts @@ -7,8 +7,6 @@ import { SysMigration } from './system/sys-migration.object.js'; import { SysMigrationJournal } from './system/sys-migration-journal.object.js'; import { SysSecret } from './system/sys-secret.object.js'; import { SysExchangeRate } from './system/sys-exchange-rate.object.js'; -import { SysWorkCalendar } from './system/sys-work-calendar.object.js'; -import { SysWorkCalendarException } from './system/sys-work-calendar-exception.object.js'; import { SysTrustedKey } from './system/sys-trusted-key.object.js'; import { SysLifecycleState } from './system/sys-lifecycle-state.object.js'; import { SysRecycleBin } from './system/sys-recycle-bin.object.js'; @@ -115,12 +113,6 @@ import { SEED_SETTLEMENT_SERVICE } from '@objectstack/spec/contracts'; * engine-facing infrastructure above, not with an optional service. Rides * the first manifest (the project database), like every per-organization * table here. - * - **`sys_work_calendar`** / **`sys_work_calendar_exception`** — the - * organization's working calendars and their dated holidays and make-up - * workdays (ADR-0157 D1). Registered here for the reason the rate table - * is: their readers are the ObjectQL engine's calendar service and what it - * serves — the working-day formula functions and the approval sweep's - * working-time clock — not one optional service. Same manifest. * - **Fresh-datastore attestation** (#3438, ADR-0104 2026-07-30) — * travels with the ledger registration: a store this boot created from * empty is attested once that boot's own data has settled @@ -230,7 +222,7 @@ export class PlatformObjectsPlugin { version: this.version, type: 'plugin', scope: 'system', - objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysWorkCalendar, SysWorkCalendarException, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], + objects: [SysMigration, SysMigrationJournal, SysSecret, SysExchangeRate, SysTrustedKey, SysLifecycleState, SysRecycleBin, SysSeedLandedKey], }); ctx?.getService?.('manifest')?.register?.({ ...ACTIVATION_LEDGER_MANIFEST, diff --git a/packages/platform-objects/src/system/index.ts b/packages/platform-objects/src/system/index.ts index 78af040ff38..3957ce32118 100644 --- a/packages/platform-objects/src/system/index.ts +++ b/packages/platform-objects/src/system/index.ts @@ -37,13 +37,6 @@ export { EXCHANGE_RATE_SCALE, EXCHANGE_RATE_PRECISION, } from './sys-exchange-rate.object.js'; -// [ADR-0157 D1] Working calendars and their dated exceptions, read by the -// calendar service (`@objectstack/objectql`). -export { - SysWorkCalendar, - WORK_CALENDAR_PERIODS_HELP, -} from './sys-work-calendar.object.js'; -export { SysWorkCalendarException } from './sys-work-calendar-exception.object.js'; export { readDataMigrationFlag, isDataMigrationVerified, diff --git a/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts b/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts deleted file mode 100644 index 0c39539b9a2..00000000000 --- a/packages/platform-objects/src/system/sys-work-calendar-exception.object.ts +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import { ObjectSchema, Field } from '@objectstack/spec/data'; - -/** - * sys_work_calendar_exception — Calendar Exception (ADR-0157 D1, D10) - * - * One dated override of a working calendar's weekly pattern. One table holds - * public holidays, 调休 make-up workdays and plant shutdowns: - * - * - **`off`** — the whole date is off, and the row carries no periods. - * - **`on`** — the date is worked, and the row carries that date's FULL - * periods (a half day is shortened periods). It never borrows its weekday's: - * with borrowing, a later edit to the weekday would silently rewrite every - * past make-up day (D10, 「每条写全时段」). - * - * One row per calendar and date (the unique key below). The date is a calendar - * day, never an instant (ADR-0053). The period format and its validation are - * the calendar's ({@link import('./sys-work-calendar.object.js').WORK_CALENDAR_PERIODS_HELP}), - * refused at write by the calendar service's hooks (`@objectstack/objectql`). - * Tenancy, write grant and audit as `sys_work_calendar`. Deleting a calendar - * deletes its exceptions. - * - * **Import** — opt-in on `system-data`, as `sys_exchange_rate` opts in: an - * administrator loads a year of holidays in one file through the generic - * import door (`sys_import_job`). The `calendar` column names the calendar by - * its code or its name; a line repeating a (calendar, date) on file is refused - * for that row alone by the unique key. - * - * @namespace sys - */ -export const SysWorkCalendarException = ObjectSchema.create({ - name: 'sys_work_calendar_exception', - label: 'Calendar Exception', - pluralLabel: 'Calendar Exceptions', - icon: 'calendar-x', - isSystem: true, - // Platform-defined schema, organization-administered data. - managedBy: 'system-data', - userActions: { import: true }, - description: - 'Dated overrides of a working calendar: public holidays, make-up workdays and shutdowns. ' + - 'A working day carries its full working periods.', - displayNameField: 'date', - nameField: 'date', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) - highlightFields: ['calendar', 'date', 'kind', 'periods'], - - fields: { - id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), - - calendar: Field.lookup('sys_work_calendar', { - label: 'Calendar', - required: true, - // A calendar's exceptions mean nothing without it. - deleteBehavior: 'cascade', - trackHistory: true, - group: 'Exception', - }), - - date: Field.date({ - label: 'Date', - required: true, - trackHistory: true, - group: 'Exception', - }), - - kind: Field.select( - [ - { value: 'off', label: 'Day Off' }, - { value: 'on', label: 'Working Day' }, - ], - { - label: 'Kind', - required: true, - trackHistory: true, - description: 'Day Off: the whole date is off. Working Day: the date is worked with the periods below, such as a make-up workday.', - group: 'Exception', - }, - ), - - periods: Field.text({ - label: 'Periods', - maxLength: 255, - trackHistory: true, - description: - "For a working day, that date's full working periods, HH:mm-HH:mm separated by commas (09:00-12:00, 13:00-18:00); they are never taken from the weekday. Leave blank for a day off.", - group: 'Exception', - }), - - note: Field.text({ - label: 'Note', - maxLength: 255, - trackHistory: true, - description: 'What the date is, such as National Day or a make-up workday for Spring Festival.', - group: 'Exception', - }), - }, - - indexes: [ - { fields: ['calendar', 'date'], unique: 'organization' }, - ], - - listViews: { - all_exceptions: { - type: 'grid', - name: 'all_exceptions', - label: 'All', - data: { provider: 'object', object: 'sys_work_calendar_exception' }, - columns: ['calendar', 'date', 'kind', 'periods', 'note'], - sort: [{ field: 'date', order: 'desc' }], - pagination: { pageSize: 50 }, - emptyState: { - title: 'No calendar exceptions yet', - message: 'Add one row per holiday or make-up workday, or import a year of them from a file.', - }, - }, - }, - - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - feeds: false, - }, -}); diff --git a/packages/platform-objects/src/system/sys-work-calendar.object.ts b/packages/platform-objects/src/system/sys-work-calendar.object.ts deleted file mode 100644 index 3794ffd8d4d..00000000000 --- a/packages/platform-objects/src/system/sys-work-calendar.object.ts +++ /dev/null @@ -1,185 +0,0 @@ -// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. - -import { ObjectSchema, Field, WORK_CALENDAR_CODE_PATTERN, WORK_CALENDAR_MAINTENANCE_LEAD_DAYS } from '@objectstack/spec/data'; - -/** - * The help every weekday's period column carries, stated once so the seven - * columns can never disagree about the format (ADR-0157 D1, D7, D10). - */ -export const WORK_CALENDAR_PERIODS_HELP = - 'Working periods that day in the calendar\'s time zone, HH:mm-HH:mm separated by commas, such as 09:00-12:00, 13:00-18:00. ' + - 'A period ends later than it starts on the same day; 24:00 is the latest end. Leave blank for a day off.'; - -const weekday = (label: string) => - Field.text({ label, maxLength: 255, description: WORK_CALENDAR_PERIODS_HELP, group: 'Weekly Hours' }); - -/** - * sys_work_calendar — Working Calendar (ADR-0157 D1) - * - * One row per working calendar per organization: a weekly pattern of local - * working periods, the zone they are local to, and the span its exceptions - * (`sys_work_calendar_exception`) are maintained for. Runtime data an - * organization administrator keeps, never package metadata: holidays change - * every year, and a holiday is a row, not a release (D1). The precedent is - * `sys_exchange_rate` (ADR-0144), and every bullet of its tenancy, write-grant - * and audit note holds here unchanged — organization-scoped through the - * Layer 0 wall, written by organization administrators, every change audited. - * - * - **Code** — what a consumer names (a formula argument, the approval - * escalation's `calendar`), and what a package seeds a row under (D13: the - * existing seed contract, create-only unless the package declares a mode). - * Unique per organization, so a seeded code means one calendar in each. - * - **Default** — the calendar a computation takes when it names none (D2). - * One per organization: a second is refused at write by the calendar - * service's hooks (`@objectstack/objectql`), and a read that still meets two - * refuses rather than picking one. - * - **Time zone** — required (D7); the periods are local to it and the - * computation reads only it. A create that leaves it out takes the - * organization's `localization.timezone`, stored as the calendar's own. - * - **Periods** — one column per weekday, validated by the calendar itself - * (D10: `24:00` is a legal end, which the platform's `time` value refuses); - * a period crossing midnight is refused (D7). - * - **Maintained span** — `maintained_from` .. `maintained_through`, both - * required (open point 2): a blank must not read as "no holidays from here - * on". A computation needing a date outside the span is refused (D8, and the - * same refusal on the past side), and the `needs_maintenance` list marks a - * calendar {@link WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days ahead (D8). - * - * @namespace sys - */ -export const SysWorkCalendar = ObjectSchema.create({ - name: 'sys_work_calendar', - label: 'Working Calendar', - pluralLabel: 'Working Calendars', - icon: 'calendar-clock', - isSystem: true, - // Platform-defined schema, organization-administered data. - managedBy: 'system-data', - description: - 'Working calendars: the weekly working hours, the time zone they are local to, and how far the holidays are maintained. ' + - 'Due dates counted in working time read them.', - displayNameField: 'name', - nameField: 'name', // [ADR-0079] canonical primary-title pointer (mirrors deprecated displayNameField) - highlightFields: ['code', 'timezone', 'is_default', 'maintained_through'], - - fields: { - id: Field.text({ label: 'ID', required: true, readonly: true, group: 'System' }), - - code: Field.text({ - label: 'Code', - required: true, - searchable: true, - maxLength: 64, - unique: 'organization', - trackHistory: true, - description: - 'Machine code formulas, approval escalations and packages name this calendar by, such as cn_standard: lowercase letters, digits and underscores.', - group: 'Calendar', - }), - - name: Field.text({ - label: 'Name', - required: true, - searchable: true, - maxLength: 255, - trackHistory: true, - group: 'Calendar', - }), - - timezone: Field.text({ - label: 'Time Zone', - required: true, - maxLength: 64, - valueDomain: 'iana_time_zone', - trackHistory: true, - description: - "IANA time zone the working periods are local to, such as Asia/Shanghai. Left out on create, it takes the organization's default time zone (Settings → Localization).", - group: 'Calendar', - }), - - is_default: Field.boolean({ - label: 'Default', - defaultValue: false, - trackHistory: true, - description: 'The calendar a due date uses when it names none. One per organization.', - group: 'Calendar', - }), - - maintained_from: Field.date({ - label: 'Maintained From', - required: true, - trackHistory: true, - description: - 'First date the holidays and make-up workdays are entered from. A computation that needs an earlier date is refused.', - group: 'Maintenance', - }), - - maintained_through: Field.date({ - label: 'Maintained Through', - required: true, - trackHistory: true, - description: - "Last date the holidays and make-up workdays are entered through. A computation that needs a later date is refused: enter next year's holidays, then move this date.", - group: 'Maintenance', - }), - - monday_periods: weekday('Monday'), - tuesday_periods: weekday('Tuesday'), - wednesday_periods: weekday('Wednesday'), - thursday_periods: weekday('Thursday'), - friday_periods: weekday('Friday'), - saturday_periods: weekday('Saturday'), - sunday_periods: weekday('Sunday'), - }, - - listViews: { - all_calendars: { - type: 'grid', - name: 'all_calendars', - label: 'All', - data: { provider: 'object', object: 'sys_work_calendar' }, - columns: ['name', 'code', 'timezone', 'is_default', 'maintained_through'], - sort: [{ field: 'name', order: 'asc' }], - pagination: { pageSize: 50 }, - emptyState: { - title: 'No working calendars yet', - message: 'Add a calendar with its weekly hours and mark one as the default, then enter its holidays and make-up workdays.', - }, - }, - // [ADR-0157 D8] The notice ahead of the refusals: every calendar whose - // maintained span ends within the lead time. - needs_maintenance: { - type: 'grid', - name: 'needs_maintenance', - label: 'Needs Maintenance', - data: { provider: 'object', object: 'sys_work_calendar' }, - columns: ['name', 'code', 'maintained_through'], - filter: [{ field: 'maintained_through', operator: 'less_than_or_equal', value: `{${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS}_days_from_now}` }], - sort: [{ field: 'maintained_through', order: 'asc' }], - pagination: { pageSize: 50 }, - emptyState: { - title: 'Every calendar is maintained ahead', - message: `A calendar appears here when its holidays run out within the next ${WORK_CALENDAR_MAINTENANCE_LEAD_DAYS} days; due dates past that date are refused.`, - }, - }, - }, - - validations: [ - { - type: 'format', - name: 'work_calendar_code_shape', - field: 'code', - regex: WORK_CALENDAR_CODE_PATTERN, - severity: 'error', - message: 'Code must start with a lowercase letter and use only lowercase letters, digits and underscores, such as cn_standard.', - }, - ], - - enable: { - trackHistory: true, - searchable: false, - apiEnabled: true, - // A calendar is reference data, not a discussion surface. - feeds: false, - }, -}); diff --git a/packages/spec/api-surface/data.json b/packages/spec/api-surface/data.json index 48273f9afa4..16fb8e04eb5 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -419,6 +419,7 @@ "HookRefusalSchema (const)", "HookSchema (const)", "HookText (type)", + "HookTextReader (type)", "HookTextSchema (const)", "HookUpdateDoc (type)", "HookUpdateOptions (type)", diff --git a/packages/spec/export-origins/data.json b/packages/spec/export-origins/data.json index e103462c202..d766ac292d5 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -409,6 +409,7 @@ "HookRefusalSchema": "src/data/hook.zod.ts#HookRefusalSchema (const)", "HookSchema": "src/data/hook.zod.ts#HookSchema (const)", "HookText": "src/data/hook.zod.ts#HookText (type)", + "HookTextReader": "src/data/hook.zod.ts#HookTextReader (type)", "HookTextSchema": "src/data/hook.zod.ts#HookTextSchema (const)", "HookUpdateDoc": "src/data/hook-api.ts#HookUpdateDoc (type)", "HookUpdateOptions": "src/data/hook-api.ts#HookUpdateOptions (type)", diff --git a/packages/spec/src/system/constants/platform-object-names.ts b/packages/spec/src/system/constants/platform-object-names.ts index 083c19681b0..b66cf6552ab 100644 --- a/packages/spec/src/system/constants/platform-object-names.ts +++ b/packages/spec/src/system/constants/platform-object-names.ts @@ -102,8 +102,6 @@ export const PLATFORM_OBJECTS_BY_PACKAGE: Readonly Date: Thu, 19 Nov 2026 20:56:07 +0000 Subject: [PATCH 09/13] fix(ui): allow the gantt scheduler's own isWorkingDay and addWorkingDays beside the spec's @objectstack/spec/data now exports isWorkingDay and addWorkingDays, the platform working-calendar arithmetic. The gantt scheduler's module-local helpers carry the same two names over the view's own skipWeekends and holidays calendar, which ADR-0157 keeps until its Follow-up switches the gantt to the platform calendar. Two reasoned ALLOW entries in the spec-symbol derivation gate; no gantt behaviour changes. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- ui/scripts/check-spec-symbol-derivation.mjs | 35 +++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/ui/scripts/check-spec-symbol-derivation.mjs b/ui/scripts/check-spec-symbol-derivation.mjs index c3295007bc8..4269ded856e 100644 --- a/ui/scripts/check-spec-symbol-derivation.mjs +++ b/ui/scripts/check-spec-symbol-derivation.mjs @@ -839,6 +839,41 @@ const ALLOW = { // page-nav-misc-spec-parity.test.ts asserts all three names ABSENT from the // spec export set, so an upstream re-publish is a loud collision, not an // inherited exemption. + // ── The gantt's own working calendar, ADR-0157 (objectstack#35355) ──────── + // `@objectstack/spec/data` began exporting the platform's working-calendar + // arithmetic, and two of its names are names the gantt scheduler's + // module-local helpers already carried. Both are kept ON PURPOSE until + // ADR-0157's Follow-up "The gantt view's own calendar" switches the gantt to + // the platform calendar; that switch deletes the helpers, and ratchet 3 then + // fails these entries so they cannot outlive it. + "@object-ui/plugin-gantt:isWorkingDay": { + reason: + "Same name, a different calendar, kept on purpose. The spec's `isWorkingDay(cal, day)` reads " + + "an org's stored working calendar (`WorkCalendar`: weekly working periods, dated exceptions, " + + "a maintained span it refuses outside of) for a `YYYY-MM-DD` key. The gantt scheduler's " + + "module-local helper takes a local `Date` and the view's own authored `WorkingCalendar` " + + "(`skipWeekends`, `holidays`). ADR-0157 records the gantt's calendar as a second source of truth " + + "and names switching it to the platform calendar as a Follow-up, not as part of the record " + + "that added the spec function, so binding here would change what the gantt draws and " + + "schedules ahead of that ruling. Module-local, so no published name is involved; when the " + + "Follow-up lands, the helper goes and this entry goes stale.", + issue: 35355, + }, + "@object-ui/plugin-gantt:addWorkingDays": { + reason: + "Same name, a different calendar and a different count, kept on purpose. The spec's " + + "`addWorkingDays(cal, day, days)` answers a `YYYY-MM-DD` day from an org's stored " + + "`WorkCalendar` and never counts the start day. The gantt scheduler's module-local helper " + + "answers an exclusive end INSTANT (local midnight after the n-th consumed working day, the start " + + "day counted when it works) over the view's own `skipWeekends` / `holidays`, the duration " + + "arithmetic `computeProjectReschedule` preserves. The two answers part whenever a span ends " + + "before a non-working day (Thursday plus two working days with weekends off: the gantt answers " + + "Saturday midnight, the spec Monday), and the spec's needs a stored calendar the gantt view " + + "does not have. Kept until ADR-0157's " + + "Follow-up \"The gantt view's own calendar\" switches the gantt to the platform calendar, the " + + "`isWorkingDay` entry's judgement.", + issue: 35355, + }, }; // ── Untriaged collisions (the ledger) ──────────────────────────────────────── From e6e77b623d156c142fe67d7b46c6c73833ad81d7 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:32:01 +0000 Subject: [PATCH 10/13] fix(spec, formula, objectql): working-calendar arithmetic in formula, IWorkCalendarService, no-organization refusal Fix round 1 on the contract review of the first half of #35355 (ADR-0157). - The arithmetic, the period parser, buildWorkCalendar and the three error classes move to @objectstack/formula (an edge objectql already has); spec keeps zonedWallClockToUtcMs, the types, the constants and the ledger codes, and its module header states Prime Directive #2 as schemas/types/constants only. buildWorkCalendar returns a frozen calendar. - The service contract becomes IWorkCalendarService in @objectstack/spec/contracts; the objectql class keeps its name. - Outside the single tenancy posture (resolveEnginePosture), a computation that names no organization is refused ERR_WORK_CALENDAR_UNRESOLVED (no_organization) before any read; single is unchanged. The hooks take the organization from the session and read nothing without one outside single. - The 60-day lead's note no longer asserts a publication date. - The gantt's two ALLOW entries go: the spec no longer exports those names. - The changeset names the pair, #35641/#35642, and adds @objectstack/formula. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .changeset/35355-working-calendar-service.md | 12 +- packages/formula/src/index.ts | 20 + .../src}/work-calendar.test.ts | 19 +- packages/formula/src/work-calendar.ts | 469 ++++++++++++++++ packages/objectql/src/index.ts | 3 +- packages/objectql/src/plugin.ts | 2 +- .../src/work-calendar-service.test.ts | 127 ++++- .../objectql/src/work-calendar-service.ts | 140 +++-- packages/spec/api-surface/contracts.json | 3 + packages/spec/api-surface/data.json | 17 - packages/spec/export-origins/contracts.json | 3 + packages/spec/export-origins/data.json | 17 - .../spec/src/api/error-code-ledger.zod.ts | 17 +- packages/spec/src/contracts/index.ts | 2 + .../src/contracts/work-calendar-service.ts | 71 +++ packages/spec/src/data/index.ts | 7 +- packages/spec/src/data/work-calendar.ts | 519 ++---------------- ...kages__formula__src__work-calendar.ts.json | 5 + ...jectql__src__work-calendar-service.ts.json | 2 +- ...es__spec__src__data__work-calendar.ts.json | 5 - ui/scripts/check-spec-symbol-derivation.mjs | 35 -- 21 files changed, 888 insertions(+), 607 deletions(-) rename packages/{spec/src/data => formula/src}/work-calendar.test.ts (91%) create mode 100644 packages/formula/src/work-calendar.ts create mode 100644 packages/spec/src/contracts/work-calendar-service.ts create mode 100644 scripts/adr-anchors/packages__formula__src__work-calendar.ts.json delete mode 100644 scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json diff --git a/.changeset/35355-working-calendar-service.md b/.changeset/35355-working-calendar-service.md index 7aab6c6500f..52b84630356 100644 --- a/.changeset/35355-working-calendar-service.md +++ b/.changeset/35355-working-calendar-service.md @@ -1,5 +1,6 @@ --- '@objectstack/spec': patch +'@objectstack/formula': patch '@objectstack/objectql': patch '@objectstack/core': patch --- @@ -9,9 +10,10 @@ feat: the working-calendar service, its arithmetic and its refusal codes (ADR-01 Clause-②: yes (widening) Metadata-protocol: none -Not released alone: this ships in the same release as 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. +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 and the time-zone rule** (`@objectstack/spec/data`). `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) and `buildWorkCalendar`. A computation that needs a date outside the calendar's maintained span is refused rather than read from the weekly pattern. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move here 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, or two defaults), `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. 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`, or a second calendar is marked the default; a calendar created without `timezone` takes the organization's Localization time zone. +- **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`, or a second calendar is marked the default; a calendar created without `timezone` takes the organization's Localization time zone. The hooks take the organization from the session. 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/spec/src/data/work-calendar.test.ts b/packages/formula/src/work-calendar.test.ts similarity index 91% rename from packages/spec/src/data/work-calendar.test.ts rename to packages/formula/src/work-calendar.test.ts index c14261ed88e..258e2b4ac00 100644 --- a/packages/spec/src/data/work-calendar.test.ts +++ b/packages/formula/src/work-calendar.test.ts @@ -4,6 +4,9 @@ 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, @@ -11,7 +14,6 @@ import { isWorkingTime, parseWorkPeriods, workingDaysBetween, - type WorkCalendar, } from './work-calendar'; // ADR-0157: the arithmetic over one resolved calendar. 2026-10-01 is a Thursday. @@ -158,3 +160,18 @@ describe('working calendar — a transition day counts elapsed time (ADR-0157 D1 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 29480e19b0b..7a23354e68c 100644 --- a/packages/objectql/src/index.ts +++ b/packages/objectql/src/index.ts @@ -736,7 +736,8 @@ export type { } from './hook-metrics.js'; // [ADR-0157] The working-calendar service and the calendar objects' write -// hooks. Its contract, refusals and arithmetic are `@objectstack/spec/data`'s. +// hooks. Its contract is `IWorkCalendarService` (`@objectstack/spec/contracts`); +// its refusals and arithmetic are `@objectstack/formula`'s. export { WorkCalendarService, installWorkCalendarHooks, diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index afc35bb509a..161e6f23b09 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -67,7 +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/data'; +import { WORK_CALENDAR_SERVICE } from '@objectstack/spec/contracts'; import { collectManifestPicklistNames, collectManifestPicklistReferences, diff --git a/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index 258d3882f7a..4ca9594addc 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -12,17 +12,15 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { resolveThrownHttpError } from '@objectstack/types'; -import { - WORK_CALENDAR_NOT_MAINTAINED_CODE, - WORK_CALENDAR_UNRESOLVED_CODE, - isWorkingDay, -} from '@objectstack/spec/data'; +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'; @@ -44,7 +42,11 @@ const HOLIDAYS: Row[] = [ 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 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 { @@ -52,7 +54,9 @@ function readDouble(calendars: Row[], exceptions: Row[]) { async find(object: string, query: Row) { reads.push({ object, query }); const src = object === WORK_CALENDAR_OBJECT ? calendars : exceptions; + const tenant = query.context?.tenantId; const hits = src.filter((r) => + (tenant === undefined || r.organization_id === undefined || r.organization_id === tenant) && 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}`); @@ -120,6 +124,44 @@ describe('WorkCalendarService — organization and authority (ADR-0157 open poin }); }); +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; @@ -226,6 +268,7 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { 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, { @@ -286,3 +329,75 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { 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, not one its row names`, async () => { + const h = bound(posture); + const row = created('org_b'); + 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 writes where its row names', async () => { + const h = bound('isolated'); + const e = await refusal(Promise.resolve(h.insert({ isSystem: true }, created('org_b')))); + expect(e.message).toContain('plant_b'); + expect(h.zoneAsked).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 index 224551c0926..cc6253504f7 100644 --- a/packages/objectql/src/work-calendar-service.ts +++ b/packages/objectql/src/work-calendar-service.ts @@ -4,28 +4,38 @@ * 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 contract package + * ## 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/spec/data` (`work-calendar.ts`), which also - * holds the refusal codes and the service contract it implements. 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 data it gets. + * 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, and one organization's calendar never counts - * another's. The organization is the one the CALLER names + * 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 @@ -48,11 +58,23 @@ * 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. A system writer (a seed, + * a package install, the import engine) writes where it names: its row's own + * `organization_id`, else the call's tenant, else the session's. An update + * reads in the stored row's own organization. Outside the `single` posture no + * hook reads without an organization, the service's rule. */ 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, @@ -62,12 +84,9 @@ import { isWorkingTime, parseWorkPeriods, workingDaysBetween, - type WorkCalendar, - type WorkCalendarRef, - type WorkCalendarService as WorkCalendarServiceContract, -} from '@objectstack/spec/data'; -import type { FieldErrorCode } from '@objectstack/spec/api'; +} 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'; @@ -97,6 +116,11 @@ export interface WorkCalendarServiceOptions { 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; @@ -106,6 +130,33 @@ 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; +} + +/** 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 }; @@ -122,14 +173,20 @@ function namedCode(ref: WorkCalendarRef): string | undefined { const CODE_RE = new RegExp(WORK_CALENDAR_CODE_PATTERN); /** ADR-0157: the calendar service. See the module note. */ -export class WorkCalendarService implements WorkCalendarServiceContract { +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([ref.organizationId ?? null, namedCode(ref) ?? null]); + 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); @@ -172,7 +229,7 @@ export class WorkCalendarService implements WorkCalendarServiceContract { if (!engine || this.options.hasCalendarObject?.() === false) { throw new WorkCalendarUnresolvedError(code === undefined ? 'no_default' : 'not_found', code); } - const context = readContext(ref.organizationId); + const context = readContext(organizationOf(ref.organizationId)); const rows = (await engine.find(WORK_CALENDAR_OBJECT, { where: code === undefined ? { is_default: true } : { code }, limit: 2, @@ -226,26 +283,44 @@ function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined return { field, code: 'invalid_value', message, value }; } -/** The organization an insert row is stored in: its own, else the call's tenant, else the writer's. */ -function insertOrganization(ctx: any, row: Row): string | undefined { - for (const candidate of [row.organization_id, ctx?.input?.options?.tenantId, ctx?.session?.organizationId]) { - if (candidate !== undefined && candidate !== null && candidate !== '') return String(candidate); +/** + * Where an insert's elevated reads run (see the module note): `read: false` + * when the hooks make none. + */ +function insertReadOrganization(ctx: any, row: Row, posture: TenancyPosture): ReadScope { + let organizationId: string | undefined; + if (ctx?.session?.isSystem === true) { + // A system writer writes where it names. + organizationId = organizationOf(row.organization_id) + ?? organizationOf(ctx?.input?.options?.tenantId) + ?? organizationOf(ctx?.session?.organizationId); + } else { + // Any other writer: the session's organization only. + organizationId = organizationOf(ctx?.session?.organizationId); + const named = organizationOf(row.organization_id); + if (named !== undefined && named !== organizationId) return { read: false }; } - return undefined; + 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. */ +/** + * 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, - organizationId: string | undefined, + scope: ReadScope, ): Promise { const problems: FieldRefusal[] = []; for (const field of WORK_CALENDAR_WEEKDAY_FIELDS) { @@ -268,12 +343,12 @@ async function judgeCalendar( } // One default per organization (ADR-0157 D2): judged when the write makes // this row a default, against every OTHER default the organization holds. - if (data.is_default === true && previous?.is_default !== true) { + 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(organizationId, ctx?.transaction), + context: readContext(scope.organizationId, ctx?.transaction), })).filter(isRow).filter((r) => previous === undefined || String(r.id) !== String(previous.id)); if (others.length > 0) { problems.push({ @@ -326,24 +401,27 @@ export function installWorkCalendarHooks( 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 organizationId = insertOrganization(ctx, row); + const scope = insertReadOrganization(ctx, row, postureNow()); const zone = row.timezone; - if ((zone === undefined || zone === null || zone === '') && options.timezoneOf) { - const fallback = await options.timezoneOf(organizationId); + 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, organizationId); + 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; - const org = previous.organization_id; - await judgeCalendar(engine, ctx, data, previous, org === undefined || org === null || org === '' ? undefined : String(org)); + // 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; 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 16fb8e04eb5..8322cfa7dcc 100644 --- a/packages/spec/api-surface/data.json +++ b/packages/spec/api-surface/data.json @@ -925,17 +925,11 @@ "WORK_CALENDAR_INVALID_CODE (const)", "WORK_CALENDAR_MAINTENANCE_LEAD_DAYS (const)", "WORK_CALENDAR_NOT_MAINTAINED_CODE (const)", - "WORK_CALENDAR_SERVICE (const)", "WORK_CALENDAR_UNRESOLVED_CODE (const)", "WORK_CALENDAR_WEEKDAY_FIELDS (const)", "WallClockParts (interface)", "WorkCalendar (interface)", "WorkCalendarDay (interface)", - "WorkCalendarInvalidError (class)", - "WorkCalendarNotMaintainedError (class)", - "WorkCalendarRef (interface)", - "WorkCalendarService (interface)", - "WorkCalendarUnresolvedError (class)", "WorkCalendarUnresolvedReason (type)", "WorkPeriod (interface)", "WorkPeriodsParse (type)", @@ -943,8 +937,6 @@ "ZeroLimitConformanceCase (interface)", "actionRefusalsWithoutSandboxedBody (function)", "actionTextsWithoutRunnableCode (function)", - "addWorkingDays (function)", - "addWorkingHours (function)", "aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason (function)", @@ -955,8 +947,6 @@ "booleanComparandDoorVerdict (function)", "booleanComparandFieldVerdict (function)", "booleanComparandRefusalMessage (function)", - "buildWorkCalendar (function)", - "calendarDayOf (function)", "canServeApiOperation (function)", "canonicalAstOperator (function)", "canonicalizeSqlType (function)", @@ -997,7 +987,6 @@ "driverSupportsTransactions (function)", "effectiveOperationsArray (function)", "emptyGroupValueFor (function)", - "exceptionDayOf (function)", "expandEmptyOperator (function)", "externalBindingDatasourceRefusal (function)", "externalColumnMapTargets (function)", @@ -1082,9 +1071,6 @@ "isUnboundedAbove (function)", "isUniqueDeclared (function)", "isVirtualSearchField (function)", - "isWorkCalendarRefusal (function)", - "isWorkingDay (function)", - "isWorkingTime (function)", "judgeImportMappingTarget (function)", "likePatternToGlobPattern (function)", "likePatternToRegExp (function)", @@ -1109,7 +1095,6 @@ "parseDateMacroParam (function)", "parseFilterAST (function)", "parseNumericString (function)", - "parseWorkPeriods (function)", "passthroughSecretPaths (function)", "percentScaleOf (function)", "placeholderFree (function)", @@ -1189,8 +1174,6 @@ "valueSchemaFor (function)", "virtualFieldAggregateRemedy (function)", "wallClockToUtcMs (function)", - "workingDaysBetween (function)", - "workingPeriodsOn (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 d766ac292d5..e8ed857ec4e 100644 --- a/packages/spec/export-origins/data.json +++ b/packages/spec/export-origins/data.json @@ -911,17 +911,11 @@ "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_SERVICE": "src/data/work-calendar.ts#WORK_CALENDAR_SERVICE (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)", - "WorkCalendarInvalidError": "src/data/work-calendar.ts#WorkCalendarInvalidError (class)", - "WorkCalendarNotMaintainedError": "src/data/work-calendar.ts#WorkCalendarNotMaintainedError (class)", - "WorkCalendarRef": "src/data/work-calendar.ts#WorkCalendarRef (interface)", - "WorkCalendarService": "src/data/work-calendar.ts#WorkCalendarService (interface)", - "WorkCalendarUnresolvedError": "src/data/work-calendar.ts#WorkCalendarUnresolvedError (class)", "WorkCalendarUnresolvedReason": "src/data/work-calendar.ts#WorkCalendarUnresolvedReason (type)", "WorkPeriod": "src/data/work-calendar.ts#WorkPeriod (interface)", "WorkPeriodsParse": "src/data/work-calendar.ts#WorkPeriodsParse (type)", @@ -929,8 +923,6 @@ "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)", - "addWorkingDays": "src/data/work-calendar.ts#addWorkingDays (function)", - "addWorkingHours": "src/data/work-calendar.ts#addWorkingHours (function)", "aiReadExposureRefusal": "src/data/ai-read-exposure.ts#aiReadExposureRefusal (function)", "analyticsDateRangeRefusalMessage": "src/data/analytics.zod.ts#analyticsDateRangeRefusalMessage (function)", "apiExposureDenialReason": "src/data/api-derivation.ts#apiExposureDenialReason (function)", @@ -941,8 +933,6 @@ "booleanComparandDoorVerdict": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandDoorVerdict (function)", "booleanComparandFieldVerdict": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandFieldVerdict (function)", "booleanComparandRefusalMessage": "src/data/filter-boolean-comparand-declared-type.ts#booleanComparandRefusalMessage (function)", - "buildWorkCalendar": "src/data/work-calendar.ts#buildWorkCalendar (function)", - "calendarDayOf": "src/data/work-calendar.ts#calendarDayOf (function)", "canServeApiOperation": "src/data/api-derivation.ts#canServeApiOperation (function)", "canonicalAstOperator": "src/data/filter.zod.ts#canonicalAstOperator (function)", "canonicalizeSqlType": "src/data/type-compat.ts#canonicalizeSqlType (function)", @@ -983,7 +973,6 @@ "driverSupportsTransactions": "src/data/driver.zod.ts#driverSupportsTransactions (function)", "effectiveOperationsArray": "src/data/api-derivation.ts#effectiveOperationsArray (function)", "emptyGroupValueFor": "src/data/aggregation-policy.ts#emptyGroupValueFor (function)", - "exceptionDayOf": "src/data/work-calendar.ts#exceptionDayOf (function)", "expandEmptyOperator": "src/data/filter-empty-operator.ts#expandEmptyOperator (function)", "externalBindingDatasourceRefusal": "src/data/external-binding-datasource.ts#externalBindingDatasourceRefusal (function)", "externalColumnMapTargets": "src/data/injected-system-column-provenance.ts#externalColumnMapTargets (function)", @@ -1068,9 +1057,6 @@ "isUnboundedAbove": "src/data/calendar-day.ts#isUnboundedAbove (function)", "isUniqueDeclared": "src/data/field.zod.ts#isUniqueDeclared (function)", "isVirtualSearchField": "src/data/search-fields.ts#isVirtualSearchField (function)", - "isWorkCalendarRefusal": "src/data/work-calendar.ts#isWorkCalendarRefusal (function)", - "isWorkingDay": "src/data/work-calendar.ts#isWorkingDay (function)", - "isWorkingTime": "src/data/work-calendar.ts#isWorkingTime (function)", "judgeImportMappingTarget": "src/data/import-mapping-target.ts#judgeImportMappingTarget (function)", "likePatternToGlobPattern": "src/data/filter.zod.ts#likePatternToGlobPattern (function)", "likePatternToRegExp": "src/data/filter.zod.ts#likePatternToRegExp (function)", @@ -1095,7 +1081,6 @@ "parseDateMacroParam": "src/data/date-macros.zod.ts#parseDateMacroParam (function)", "parseFilterAST": "src/data/filter.zod.ts#parseFilterAST (function)", "parseNumericString": "src/data/filter-number-comparand-declared-type.ts#parseNumericString (function)", - "parseWorkPeriods": "src/data/work-calendar.ts#parseWorkPeriods (function)", "passthroughSecretPaths": "src/data/datasource-credential-redaction.ts#passthroughSecretPaths (function)", "percentScaleOf": "src/data/percent-scale.ts#percentScaleOf (function)", "placeholderFree": "src/data/driver/common.zod.ts#placeholderFree (function)", @@ -1175,8 +1160,6 @@ "valueSchemaFor": "src/data/field-value.zod.ts#valueSchemaFor (function)", "virtualFieldAggregateRemedy": "src/data/aggregate-field-type-compatibility.ts#virtualFieldAggregateRemedy (function)", "wallClockToUtcMs": "src/data/wall-clock.ts#wallClockToUtcMs (function)", - "workingDaysBetween": "src/data/work-calendar.ts#workingDaysBetween (function)", - "workingPeriodsOn": "src/data/work-calendar.ts#workingPeriodsOn (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 c87b076acec..92f2b6a1ddf 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -1943,15 +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, stamped by the - // error classes in `data/work-calendar.ts`, every one `status: 400`. 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. + // [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, or more than one row answers (`reason`) + '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 83651d413be..370f58109dd 100644 --- a/packages/spec/src/data/index.ts +++ b/packages/spec/src/data/index.ts @@ -174,9 +174,10 @@ export * from './date-macros.zod'; 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) and the working-calendar arithmetic built on it, below -// `@objectstack/formula` so the working-day formula functions and the calendar -// service count with one rule. `@objectstack/core` re-exports the primitive. +// 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 → diff --git a/packages/spec/src/data/work-calendar.ts b/packages/spec/src/data/work-calendar.ts index 43ffb37ceaa..a757c06dc42 100644 --- a/packages/spec/src/data/work-calendar.ts +++ b/packages/spec/src/data/work-calendar.ts @@ -1,172 +1,55 @@ // 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. + * Working calendars (ADR-0157): the refusal codes, the column names, the + * machine-code shape and the plain-data shape of one resolved calendar. * - * ## Why this lives in the contract package + * 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`). * - * ADR-0157 open point 3: there is exactly one daylight-saving rule (D11), and - * two readers compute with a calendar — the calendar service - * (`WorkCalendarService`, `@objectstack/objectql`, which the approval clock - * reads) and the working-day formula functions, which evaluate synchronously - * inside `@objectstack/formula` over data pinned before evaluation. Formula - * depends on `@objectstack/spec` and never on a service, so the arithmetic - * sits here, beside the wall-clock primitive it reads (`./wall-clock.ts`), as - * `nextUtcCalendarDay` sits in `./calendar-day.ts`. 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 — protocol, which is - * why it is the contract package's (Prime Directive #2 keeps I/O out of it, - * and there is none here). + * ## The rows (ADR-0157 D1, D7, D10) * - * ## The rows, as this module reads them (ADR-0157 D1, D7, D10) - * - * - A calendar carries one period list per weekday (`monday_periods` … - * `sunday_periods`, {@link 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. + * - 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 ({@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 {@link 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}. + * 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). */ -import { isValueDomainMember } from '../shared/value-domain.zod'; -import { nextUtcCalendarDay } from './calendar-day'; -import { wallClockToUtcMs, zonedWallClockToUtcMs } from './wall-clock'; - // ── Refusal codes (ADR-0112 ledger, `@objectstack/spec`) ───────────────── -/** ADR-0157 D2: no calendar resolves — the named code is absent, or the organization has no single default. */ +/** 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 this module cannot read as written. */ +/** 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. `ambiguous` is more than one - * row answering — two defaults, or a code read without an organization on an - * install that holds several; it is refused, never settled by picking one. - */ -export type WorkCalendarUnresolvedReason = 'not_found' | 'no_default' | 'ambiguous'; - -/** - * ADR-0157 D2: the consumer named no calendar that exists, or named none and - * the organization has no single default. 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( - reason === 'not_found' - ? `No working calendar has the code '${calendar}' in this organization. Create it, or name an existing calendar.` - : reason === 'no_default' - ? '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.' - : 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.', - ); - this.name = 'WorkCalendarUnresolvedError'; - this.reason = reason; - if (calendar !== undefined) this.calendar = calendar; - } -} - -/** - * 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. + * 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 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; -} +export type WorkCalendarUnresolvedReason = 'not_found' | 'no_default' | 'ambiguous' | 'no_organization'; // ── Periods ────────────────────────────────────────────────────────────── @@ -179,6 +62,7 @@ export interface WorkPeriod { /** 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 }; @@ -194,46 +78,6 @@ export const WORK_CALENDAR_WEEKDAY_FIELDS = [ 'sunday_periods', ] as const; -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 ──────────────────────────────────────────────── /** One exception date: `off` (no periods) or `on` (the date's full periods). */ @@ -243,8 +87,9 @@ export interface WorkCalendarDay { } /** - * One resolved calendar with its exceptions, as plain data: what the service - * hands a consumer and what every function below computes over. + * 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; @@ -260,241 +105,7 @@ export interface WorkCalendar { readonly exceptions: Readonly>; } -/** - * 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). - */ -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 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] = day; - } - return { code, timezone, maintainedFrom, maintainedThrough, weekly, 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); - } -} - -// ── The service contract (ADR-0157 D2, D8, open point 4) ──────────────── +// ── Names ──────────────────────────────────────────────────────────────── /** * The machine-code shape a calendar is named by (`sys_work_calendar.code`): @@ -503,58 +114,12 @@ export function addWorkingHours(cal: WorkCalendar, start: number | Date, hours: */ export const WORK_CALENDAR_CODE_PATTERN = '^[a-z][a-z0-9_]*$'; -/** The kernel service the calendar service registers under (`ctx.getService`). */ -export const WORK_CALENDAR_SERVICE = 'work-calendar' as const; - /** * ADR-0157 D8: how many days before a calendar's `maintained_through` Setup - * lists it as needing maintenance — before refusals start. Sixty days: the - * Setup list `needs_maintenance` filters on it, and a CN calendar maintained - * through December 31 is flagged from November 1, by which time next year's - * public holidays and 调休 days are normally published; a longer lead would - * flag a calendar before the data to extend it exists. + * 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; - -/** - * 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. - * 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. `undefined` - * reads without an organization scope — right only where rows carry none; if - * that read matches more than one row it 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 calendar service (ADR-0157 D1, D2): resolves a calendar under D2 — - * the named code, else the organization default, else refuse — loads its - * exceptions, caches the result until a calendar or exception row is - * written, and computes with the functions of this module. Every method - * rejects with {@link WorkCalendarUnresolvedError}, - * {@link WorkCalendarNotMaintainedError} or {@link WorkCalendarInvalidError} - * ({@link isWorkCalendarRefusal}); none answers wall-clock time. - * - * {@link WorkCalendarService.resolve} hands back plain data, so a caller that - * must compute synchronously (a formula evaluated over pinned data) resolves - * first and then calls {@link addWorkingDays} and its siblings itself. - */ -export interface WorkCalendarService { - resolve(ref: WorkCalendarRef): Promise; - isWorkingTime(ref: WorkCalendarRef, at: number | Date): Promise; - addWorkingDays(ref: WorkCalendarRef, day: string, days: number): Promise; - workingDaysBetween(ref: WorkCalendarRef, start: string, end: string): Promise; - 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/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 index ec656a14603..c5d04e30dd1 100644 --- a/scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json +++ b/scripts/adr-anchors/packages__objectql__src__work-calendar-service.ts.json @@ -1,5 +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 and one organization's calendar never counts another's." + "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__work-calendar.ts.json b/scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json deleted file mode 100644 index 5e26ffab6e5..00000000000 --- a/scripts/adr-anchors/packages__spec__src__data__work-calendar.ts.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "file": "packages/spec/src/data/work-calendar.ts", - "adrs": ["ADR-0157"], - "invariant": "ADR-0157: the working-calendar arithmetic is the contract package's so the calendar service and the working-day formula functions count with one daylight-saving rule (D11, open point 3). 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/ui/scripts/check-spec-symbol-derivation.mjs b/ui/scripts/check-spec-symbol-derivation.mjs index 4269ded856e..c3295007bc8 100644 --- a/ui/scripts/check-spec-symbol-derivation.mjs +++ b/ui/scripts/check-spec-symbol-derivation.mjs @@ -839,41 +839,6 @@ const ALLOW = { // page-nav-misc-spec-parity.test.ts asserts all three names ABSENT from the // spec export set, so an upstream re-publish is a loud collision, not an // inherited exemption. - // ── The gantt's own working calendar, ADR-0157 (objectstack#35355) ──────── - // `@objectstack/spec/data` began exporting the platform's working-calendar - // arithmetic, and two of its names are names the gantt scheduler's - // module-local helpers already carried. Both are kept ON PURPOSE until - // ADR-0157's Follow-up "The gantt view's own calendar" switches the gantt to - // the platform calendar; that switch deletes the helpers, and ratchet 3 then - // fails these entries so they cannot outlive it. - "@object-ui/plugin-gantt:isWorkingDay": { - reason: - "Same name, a different calendar, kept on purpose. The spec's `isWorkingDay(cal, day)` reads " + - "an org's stored working calendar (`WorkCalendar`: weekly working periods, dated exceptions, " + - "a maintained span it refuses outside of) for a `YYYY-MM-DD` key. The gantt scheduler's " + - "module-local helper takes a local `Date` and the view's own authored `WorkingCalendar` " + - "(`skipWeekends`, `holidays`). ADR-0157 records the gantt's calendar as a second source of truth " + - "and names switching it to the platform calendar as a Follow-up, not as part of the record " + - "that added the spec function, so binding here would change what the gantt draws and " + - "schedules ahead of that ruling. Module-local, so no published name is involved; when the " + - "Follow-up lands, the helper goes and this entry goes stale.", - issue: 35355, - }, - "@object-ui/plugin-gantt:addWorkingDays": { - reason: - "Same name, a different calendar and a different count, kept on purpose. The spec's " + - "`addWorkingDays(cal, day, days)` answers a `YYYY-MM-DD` day from an org's stored " + - "`WorkCalendar` and never counts the start day. The gantt scheduler's module-local helper " + - "answers an exclusive end INSTANT (local midnight after the n-th consumed working day, the start " + - "day counted when it works) over the view's own `skipWeekends` / `holidays`, the duration " + - "arithmetic `computeProjectReschedule` preserves. The two answers part whenever a span ends " + - "before a non-working day (Thursday plus two working days with weekends off: the gantt answers " + - "Saturday midnight, the spec Monday), and the spec's needs a stored calendar the gantt view " + - "does not have. Kept until ADR-0157's " + - "Follow-up \"The gantt view's own calendar\" switches the gantt to the platform calendar, the " + - "`isWorkingDay` entry's judgement.", - issue: 35355, - }, }; // ── Untriaged collisions (the ledger) ──────────────────────────────────────── From 743be6587f0dea5668a1d3534bac8881b82ad175 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 22:35:50 +0000 Subject: [PATCH 11/13] test(objectql): name the session pin by what it asserts Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- packages/objectql/src/work-calendar-service.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index 4ca9594addc..57d27717417 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -361,7 +361,7 @@ describe('the calendar hooks take the organization from the session', () => { 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, not one its row names`, async () => { + it(`${posture}: a member's create reads in the session's organization`, async () => { const h = bound(posture); const row = created('org_b'); await h.insert(member, row); From e8af40289106e5f37f73c64a18ee48254d982d5f Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 19 Nov 2026 23:07:05 +0000 Subject: [PATCH 12/13] fix(objectql): the calendar hooks take every writer's organization from the session A seed or an import writes under its organization's tenant, so its session names it; the hooks no longer branch on the caller. The test read double scopes by tenant in a step of its own, so the where-matcher gate judges its matcher as before. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .../src/work-calendar-service.test.ts | 13 +++++---- .../objectql/src/work-calendar-service.ts | 28 ++++++------------- 2 files changed, 17 insertions(+), 24 deletions(-) diff --git a/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index 57d27717417..7f7671d5955 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -55,8 +55,8 @@ function readDouble(calendars: Row[], exceptions: Row[]) { reads.push({ object, query }); const src = object === WORK_CALENDAR_OBJECT ? calendars : exceptions; const tenant = query.context?.tenantId; - const hits = src.filter((r) => - (tenant === undefined || r.organization_id === undefined || r.organization_id === tenant) && + 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}`); @@ -306,7 +306,7 @@ describe('the calendar objects\' write door (ADR-0157 D2, D7, D10)', () => { }); 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 } }); + 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']); @@ -379,11 +379,14 @@ describe('the calendar hooks take the organization from the session', () => { }); } - it('a system writer writes where its row names', async () => { + 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 }, created('org_b')))); + 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']); + const other = bound('isolated'); + await other.insert({ isSystem: true }, created('org_b')); + expect(other.reads).toEqual([]); }); it('isolated: a write that names no organization reads nothing', async () => { diff --git a/packages/objectql/src/work-calendar-service.ts b/packages/objectql/src/work-calendar-service.ts index cc6253504f7..150cc67e5c0 100644 --- a/packages/objectql/src/work-calendar-service.ts +++ b/packages/objectql/src/work-calendar-service.ts @@ -59,11 +59,10 @@ * 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. A system writer (a seed, - * a package install, the import engine) writes where it names: its row's own - * `organization_id`, else the call's tenant, else the session's. An update - * reads in the stored row's own organization. Outside the `single` posture no - * hook reads without an organization, the service's rule. + * 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. */ import { @@ -284,22 +283,13 @@ function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined } /** - * Where an insert's elevated reads run (see the module note): `read: false` - * when the hooks make none. + * 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 { - let organizationId: string | undefined; - if (ctx?.session?.isSystem === true) { - // A system writer writes where it names. - organizationId = organizationOf(row.organization_id) - ?? organizationOf(ctx?.input?.options?.tenantId) - ?? organizationOf(ctx?.session?.organizationId); - } else { - // Any other writer: the session's organization only. - organizationId = organizationOf(ctx?.session?.organizationId); - const named = organizationOf(row.organization_id); - if (named !== undefined && named !== organizationId) return { read: false }; - } + const organizationId = organizationOf(ctx?.session?.organizationId); + const named = organizationOf(row.organization_id); + if (named !== undefined && named !== organizationId) return { read: false }; return mayReadIn(organizationId, posture) ? { read: true, organizationId } : { read: false }; } From f502d9238ccaf3ceee589ee56b4858727a61c807 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 20 Nov 2026 00:42:31 +0000 Subject: [PATCH 13/13] fix(objectql): refuse a calendar default on a create placed in another organization 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 now refused at the door, before any read, with 400 VALIDATION_FAILED on is_default: write it under that organization, or set the default afterwards by an update, which is judged in the stored row's own organization. The same create without a default passes as before. The hook header says a seed that sets a calendar's default must load pinned to its organization or set the default by an update afterwards. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01Utp6Ca1jJvsA1dHsPwMiQb --- .changeset/35355-working-calendar-service.md | 2 +- .../src/work-calendar-service.test.ts | 24 +++++++++++++++-- .../objectql/src/work-calendar-service.ts | 27 +++++++++++++++++-- 3 files changed, 48 insertions(+), 5 deletions(-) diff --git a/.changeset/35355-working-calendar-service.md b/.changeset/35355-working-calendar-service.md index 52b84630356..7a695c8e35e 100644 --- a/.changeset/35355-working-calendar-service.md +++ b/.changeset/35355-working-calendar-service.md @@ -16,4 +16,4 @@ Not released alone; pair #35641/#35642. This ships in the same release as #35642 - **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`, or a second calendar is marked the default; a calendar created without `timezone` takes the organization's Localization time zone. The hooks take the organization from the session. +- **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/packages/objectql/src/work-calendar-service.test.ts b/packages/objectql/src/work-calendar-service.test.ts index 7f7671d5955..f134ccf8040 100644 --- a/packages/objectql/src/work-calendar-service.test.ts +++ b/packages/objectql/src/work-calendar-service.test.ts @@ -362,8 +362,16 @@ describe('the calendar hooks take the organization from the session', () => { 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 row = created('org_b'); + 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([]); @@ -384,11 +392,23 @@ describe('the calendar hooks take the organization from the session', () => { 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'); - await other.insert({ isSystem: true }, created('org_b')); + 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'); diff --git a/packages/objectql/src/work-calendar-service.ts b/packages/objectql/src/work-calendar-service.ts index 150cc67e5c0..a38ad0325a4 100644 --- a/packages/objectql/src/work-calendar-service.ts +++ b/packages/objectql/src/work-calendar-service.ts @@ -63,6 +63,15 @@ * 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 { @@ -149,6 +158,8 @@ export function enginePostureOf(engine?: unknown): TenancyPosture { 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`. */ @@ -289,7 +300,7 @@ function periodsRefusal(field: string, value: unknown): FieldRefusal | undefined 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 }; + if (named !== undefined && named !== organizationId) return { read: false, elsewhere: true }; return mayReadIn(organizationId, posture) ? { read: true, organizationId } : { read: false }; } @@ -333,7 +344,19 @@ async function judgeCalendar( } // One default per organization (ADR-0157 D2): judged when the write makes // this row a default, against every OTHER default the organization holds. - if (scope.read && data.is_default === true && previous?.is_default !== true) { + // 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'],