Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .changeset/35355-working-calendar-service.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
---
'@objectstack/spec': patch
'@objectstack/formula': patch
'@objectstack/objectql': patch
'@objectstack/core': patch
---

feat: the working-calendar service, its arithmetic and its refusal codes (ADR-0157, part one of two)

Clause-②: yes (widening)
Metadata-protocol: none

Not released alone; pair #35641/#35642. This ships in the same release as #35642 (the calendar objects and Setup pages, the second half of this change), the working-day formula functions (#35356) and the approval escalation's working-time clock (#35357), ADR-0157 D4.

- **The arithmetic** (`@objectstack/formula`). `isWorkingTime`, `addWorkingDays`, `workingDaysBetween` and `addWorkingHours` compute over a resolved calendar and its dated exceptions, as pure functions a formula can call synchronously, beside `parseWorkPeriods` (`HH:mm-HH:mm` periods; a period that crosses midnight is refused, `24:00` is a legal end), `buildWorkCalendar` (a frozen calendar) and the three error classes. A computation that needs a date outside the calendar's maintained span is refused rather than read from the weekly pattern.
- **The types, constants and time-zone rule** (`@objectstack/spec`). `WorkCalendar` and the column and code constants are in `@objectstack/spec/data`; the service contract is `IWorkCalendarService` in `@objectstack/spec/contracts`. `zonedWallClockToUtcMs`, `wallClockToUtcMs` and `WallClockParts` move to `@objectstack/spec/data` from `@objectstack/core`, unchanged; `@objectstack/core` re-exports all three, so no import changes.
- **Three error codes** in the ADR-0112 ledger: `ERR_WORK_CALENDAR_UNRESOLVED` (no calendar by that code, no organization default, two defaults, or no organization named outside the `single` posture), `ERR_WORK_CALENDAR_NOT_MAINTAINED` and `ERR_WORK_CALENDAR_INVALID`, each a 400.
- **The calendar service** (`@objectstack/objectql`, registered as `work-calendar`). `resolve({ organizationId, calendar })` takes the named code, else the organization default, else refuses; it never falls back to wall-clock time. It reads in the organization the caller names, elevated, and caches until a calendar or exception row is written. Outside the `single` tenancy posture, a computation that names no organization is refused before any read. Until the calendar objects are registered it refuses every resolution.
- **The write door** (`@objectstack/objectql`). Once the calendar objects exist, a calendar or exception write is refused `400 VALIDATION_FAILED` when a period crosses midnight, is malformed or overlaps another, an `off` row carries periods or an `on` row carries none, `maintained_through` is before `maintained_from`, a second calendar is marked the default, or a calendar created in an organization other than the one being worked in is marked the default (create it there, or set the default by an update); a calendar created without `timezone` takes the organization's Localization time zone. The hooks take the organization from the session.
5 changes: 4 additions & 1 deletion content/docs/references/api/automation-api.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -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`
Expand Down
5 changes: 4 additions & 1 deletion content/docs/references/api/contract.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`. |
Expand Down Expand Up @@ -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`
Expand Down
3 changes: 3 additions & 0 deletions content/docs/references/api/error-code-ledger.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
146 changes: 13 additions & 133 deletions packages/core/src/utils/datetime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,54 +16,26 @@
* 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;
month: number;
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).
Expand Down Expand Up @@ -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
Expand Down
20 changes: 20 additions & 0 deletions packages/formula/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading
Loading