diff --git a/.changeset/35356-working-day-formula-functions.md b/.changeset/35356-working-day-formula-functions.md new file mode 100644 index 00000000000..9db7484aa90 --- /dev/null +++ b/.changeset/35356-working-day-formula-functions.md @@ -0,0 +1,23 @@ +--- +'@objectstack/formula': minor +'@objectstack/objectql': patch +'@objectstack/lint': patch +'@object-ui/core': patch +'@objectstack/skills': patch +--- + +feat(formula): `addWorkingDays()`, `workingDaysBetween()` and `addWorkingHours()` count with the organization's working calendar (ADR-0157 D4) + +Clause-②: yes (widening) +Metadata-protocol: added — a formula field's or a stored field's `expression` may now call `addWorkingDays(...)`, `workingDaysBetween(...)` and `addWorkingHours(...)` +Skills-docs: updated here — skills/objectstack-formula/SKILL.md teaches the three functions and eval 8 of skills/objectstack-project/evals/project-process.json exercises them (the card's order names both) + +Not released alone: it ships in the same release as the working calendar service and objects (#35355) and the approval escalation's working-time clock (#35357), ADR-0157 D4. + +- **Three formula functions** (`@objectstack/formula`). `addWorkingDays(day, n[, code])` answers the calendar day `n` working days after `day` (before it, for a negative `n`); `day` itself never counts and `0` answers `day`. `workingDaysBetween(start, end[, code])` counts the working days after `start` up to and including `end`, negative when `end` is earlier, and is the inverse of `addWorkingDays`. `addWorkingHours(start, hours[, code])` answers the instant `hours` of working time after `start`, counted as elapsed time in the calendar's time zone (D11); a start outside working time begins at the next working period. All three step over the calendar's weekends and holidays and onto its make-up working days. Without `code` a call counts with the organization's default calendar; `code` names a calendar and is written as a quoted literal. They join the advertised standard library (`CEL_STDLIB_FUNCTIONS`). +- **Where they count** (`@objectstack/objectql`). A `formula` field and a stored field's `expression` count with the record's own organization's calendars, which the engine loads through the calendar service before it evaluates them: only the calendars the expressions name, once per organization per read, from the service's cache. A formula field counts again on its next read after a calendar edit; a stored due time keeps the value of its last write. +- **When the calendar cannot answer** (D8). With no default calendar in the organization, a code the organization has no calendar for, or a count that reaches past the span the calendar is maintained for, the formula reads `null` and the server logs one line naming the object, the field and the reason. A stored field's `expression` stores blank and the write goes through; the blank stays until that record's next write, and a write made while the calendar refuses blanks a value that was valid before. Nothing counts on the weekly pattern or the wall clock instead. +- **No calendar arithmetic as a filter.** A query filter, a sharing rule's condition and every filter compiled from CEL refuse the three functions with a message that prescribes the stored due-time field (D6). +- **Build refusals** (`@objectstack/lint`). `os build` / `os validate` refuse the three functions at every expression site but a formula field's and a stored field's `expression` (validation rules, visibility, action conditions, flow conditions and values, sharing rules, a field's expression `defaultValue` and a seed value), and refuse a calendar code that is not a quoted literal, with a branch between literal calls as the way to pick a calendar per record. +- **Forms** (`@object-ui/core`). A form does not compute a formula that calls one of the three: its calendar is loaded for the server's read, never handed to the form, so the field is unservable there as on the server's write-path check. +- **Teaching** (`@objectstack/skills`). objectstack-formula documents the three functions; the platform catalog moves working-day formulas from Planned into what the platform ships; the project-process eval for business-hours SLAs now expects the functions. diff --git a/content/docs/data-modeling/formulas.mdx b/content/docs/data-modeling/formulas.mdx index a6257acc868..7b1742617ec 100644 --- a/content/docs/data-modeling/formulas.mdx +++ b/content/docs/data-modeling/formulas.mdx @@ -200,6 +200,9 @@ All functions are pure given a pinned `now`, which is what makes | `date(s)` / `datetime(s)` | timestamp | Parse an ISO date / date-time string (aliases) | | `isoDate(t)` / `isoDatetime(t)` | string | A timestamp as ISO text on the UTC calendar: `YYYY-MM-DD` / `YYYY-MM-DDTHH:mm:ss.sssZ`, the bytes a flow template's `{TODAY()}` / `{NOW()}` wrote. Refuses text, numbers and `null`: write `isoDate(date(s))` for ISO text | | `daysBetween(a, b)` | int | Whole days from `a` to `b` (negative when `b` is earlier) | +| `addWorkingDays(d, n[, code])` | timestamp | The calendar day `n` working days after `d` on the organization's working calendar (before it, for a negative `n`) — see [Working days](#working-days) | +| `workingDaysBetween(a, b[, code])` | int | Working days after `a` up to and including `b` (negative when `b` is earlier); the inverse of `addWorkingDays` | +| `addWorkingHours(t, h[, code])` | timestamp | The instant `h` working hours after `t`, counted as elapsed time in the calendar's time zone | | `isBlank(v)` | bool | True for `null`, `undefined`, `''`, `[]` | | `isEmpty(v)` | bool | True for `null` or zero-length string/list/map | | `coalesce(v, fallback)` | dyn | `v` when non-null, else `fallback` | @@ -573,6 +576,64 @@ counterpart to the date-arithmetic build error above — equality is rewritten a works; `+`/`-` arithmetic is rejected. +### Working days + +`addWorkingDays`, `workingDaysBetween` and `addWorkingHours` count with the +organization's **working calendar** (ADR-0157): its weekly working hours, its +holidays, and its make-up working days, such as a Saturday worked in exchange for +a holiday week. A due date "three working days later" steps over a weekend, a +National Day week, and onto a make-up Saturday. + +```typescript +// Response due three working days after the case opened (a calendar day) +Field.formula({ + label: 'Respond By', + returnType: 'date', + expression: 'addWorkingDays(record.opened_on, 3)', +}) + +// Working days left until the deadline, on a named calendar +Field.formula({ + label: 'Working Days Left', + returnType: 'number', + expression: "workingDaysBetween(today(), record.deadline, 'cn_mainland')", +}) + +// SLA due time, STORED: computed on each write, so a list view, a report +// or a flow can filter on it +Field.datetime({ + label: 'SLA Due', + expression: 'addWorkingHours(record.opened_at, 8)', +}) +``` + +- **Which calendar.** With two arguments, the organization's default calendar; + the third names a calendar by its code, and it must be a quoted literal: the + engine loads the calendars an expression names before it evaluates it. To pick + a calendar per record, branch between literal calls: + `record.region == 'us' ? addWorkingDays(record.start, 3, 'us') : addWorkingDays(record.start, 3, 'cn_mainland')`. +- **Days and instants.** `addWorkingDays` and `workingDaysBetween` take calendar + days (a `date` field, `today()`, or `YYYY-MM-DD` text) and the start day itself + never counts, so `0` answers the start. `addWorkingHours` takes an instant; a + start outside working time begins at the next working period. +- **Where they run.** Only in a `formula` field and in a stored field's + `expression`, evaluated on the server. No calendar arithmetic runs in SQL, so a + filter cannot call them; neither can a validation rule, a visibility rule, a + flow condition, a sharing rule, a field's expression `defaultValue` or a seed + value. `os build` refuses them there and points at the stored due-time field + above, which a filter compares with `{now}` and a CEL condition with `now()`. +- **When the calendar cannot answer.** With no default calendar in the + organization, or a count that reaches past the span the calendar is maintained + for, the formula reads `null` (a stored field stores blank and the write goes + through), and the server logs one line naming the object, the field and the + reason. It never falls back to counting the weekly pattern or the wall clock. +- **After a calendar edit.** A formula field counts again on its next read; a + stored due time keeps the value computed on its last write. So a stored due + time left blank by a refusal stays blank until that record is written again, + and a write made while the calendar refuses blanks a value that was valid + before. A filter such as "due before now" never matches a blank, so keep the + calendar's maintained span ahead of the records it counts for. + ### Financial Calculations ```typescript diff --git a/packages/formula/src/cel-engine.test.ts b/packages/formula/src/cel-engine.test.ts index 8b6b38a96be..68d101da688 100644 --- a/packages/formula/src/cel-engine.test.ts +++ b/packages/formula/src/cel-engine.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest'; import { celEngine, rewriteTemporalEquality, collectCelRootIdentifiers } from './cel-engine'; import { CEL_STDLIB_FUNCTIONS } from './validate'; +import { buildWorkCalendar } from './work-calendar'; import type { Expression } from '@objectstack/spec'; const cel = (source: string): Expression => ({ dialect: 'cel', source }); @@ -512,14 +513,24 @@ describe('celEngine', () => { size: 'size([1, 2])', has: 'has(record.a)', int: 'int("3")', string: 'string(3)', bool: 'bool("true")', double: 'double("3.5")', timestamp: 'timestamp("2026-01-01T00:00:00Z")', duration: 'duration("3600s")', label: 'label(record.a)', + addWorkingDays: 'addWorkingDays(today(), 2)', workingDaysBetween: 'workingDaysBetween(today(), daysFromNow(7))', + addWorkingHours: 'addWorkingHours(now(), 4)', }; + // ADR-0157 D4: the calendar the three working-day probes count with, + // Monday to Friday, maintained over the probe's whole window. + const weekday = '09:00-18:00'; + const workCalendars = { default: buildWorkCalendar({ + code: 'probe', timezone: 'UTC', maintained_from: '2025-01-01', maintained_through: '2027-12-31', + monday_periods: weekday, tuesday_periods: weekday, wednesday_periods: weekday, + thursday_periods: weekday, friday_periods: weekday, + }, []) }; const unresolved: string[] = []; for (const fn of CEL_STDLIB_FUNCTIONS) { const src = call[fn]; expect(src, `no probe call defined for advertised function \`${fn}\``).toBeTruthy(); // `optionLabels` is the data `label()` answers from (#26608); the other // probes read nothing from it. - const r = celEngine.evaluate(cel(src), { now, record: { a: 1 }, optionLabels: { a: { 1: 'One' } } }); + const r = celEngine.evaluate(cel(src), { now, record: { a: 1 }, optionLabels: { a: { 1: 'One' } }, workCalendars }); if (!r.ok) unresolved.push(`${fn}: ${r.error.message.split('\n')[0]}`); } expect(unresolved, `advertised functions that fault at runtime:\n${unresolved.join('\n')}`).toEqual([]); diff --git a/packages/formula/src/cel-engine.ts b/packages/formula/src/cel-engine.ts index 8eb099d83f3..dd31fd192c0 100644 --- a/packages/formula/src/cel-engine.ts +++ b/packages/formula/src/cel-engine.ts @@ -2810,6 +2810,7 @@ export const celEngine: DialectEngine = { systemPermissions: ctx.systemPermissions, }, optionLabels: ctx.optionLabels, + workCalendars: ctx.workCalendars, }; try { // #3183 — coerce a date-field operand compared with `==`/`!=` against a diff --git a/packages/formula/src/cel-to-filter.ts b/packages/formula/src/cel-to-filter.ts index 4c6ef215947..db948e48d8e 100644 --- a/packages/formula/src/cel-to-filter.ts +++ b/packages/formula/src/cel-to-filter.ts @@ -63,6 +63,7 @@ import type { FilterCondition } from '@objectstack/spec/data'; import { CEL_BOUNDS_MEASURE_CAP_FACTOR, parseCelToAstWithReason } from './cel-engine'; import type { CelBoundsOverrun } from './cel-engine'; import { celPushdownLimitsMode } from './cel-pushdown-limits'; +import { WORKING_DAY_FUNCTIONS } from './working-day'; // --------------------------------------------------------------------------- // Public contract @@ -331,10 +332,30 @@ function lowerCondition(node: ASTNode, ctx: Ctx): FilterCondition { throw new CompileError('unsupported', `constant non-true predicate (${String(v)})`); } default: + refuseWorkingDayCall(node); throw new CompileError('unsupported', `unsupported operator "${String(op)}"`); } } +/** + * ADR-0157 D6: a working-day function evaluates in memory only, over the + * calendar the engine loads for it, so a query filter refuses it — as it + * refuses every function call — and says what to write instead. The generic + * `unsupported` refusal below would name only the node kind. + */ +function refuseWorkingDayCall(node: ASTNode): void { + if (node.op !== 'call') return; + const name = (node.args as unknown[] | undefined)?.[0]; + if (typeof name !== 'string' || !(WORKING_DAY_FUNCTIONS as readonly string[]).includes(name)) return; + throw new CompileError( + 'unsupported', + `${name}() counts with a working calendar and evaluates in memory only, so it cannot run as a database ` + + 'filter: no calendar arithmetic runs in SQL. To filter on a working-day due time, store it: ' + + `give the object a datetime field whose \`expression\` calls ${name}(), computed when the record is written, ` + + 'and compare that field with {now}.', + ); +} + function combine(key: '$and' | '$or', node: ASTNode, ctx: Ctx): FilterCondition { const [l, r] = node.args as [ASTNode, ASTNode]; const parts: FilterCondition[] = []; @@ -717,6 +738,7 @@ function classify(node: ASTNode, ctx: Ctx): Leaf { throw new CompileError('unsupported', `cross-object field path "${chain.join('.')}" is not pushdown-able`); } default: + refuseWorkingDayCall(node); throw new CompileError('unsupported', `unsupported operand "${String(node.op)}"`); } } diff --git a/packages/formula/src/index.ts b/packages/formula/src/index.ts index 783f21cc353..8ce4dd4d327 100644 --- a/packages/formula/src/index.ts +++ b/packages/formula/src/index.ts @@ -215,6 +215,13 @@ export { workingDaysBetween, addWorkingHours, } from './work-calendar'; +// ADR-0157 D4 — the working-day formula functions: their names, and which +// calendars an expression names, so a caller resolves those calendars before +// it evaluates (`EvalContext.workCalendars`). +export { WORKING_DAY_FUNCTIONS, workCalendarsNotLoadedMessage } from './working-day'; +export type { WorkingDayFunction } from './working-day'; +export { callsWorkingDayFunction, workingDayCalendarNeeds, computedCalendarCodeMessage } from './working-day-needs'; +export type { WorkingDayCalendarNeeds } from './working-day-needs'; // 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 @@ -230,4 +237,4 @@ export type { ExpressionSourceKind, } from './expression-refusal'; export type { SeedValue, SeedPrimitive } from './seed-eval'; -export type { DialectEngine, EvalContext, EvalResult, EvalError, EvalPermissions, EvalSystemPermissions, EvalOptionLabels } from './types'; +export type { DialectEngine, EvalContext, EvalResult, EvalError, EvalPermissions, EvalSystemPermissions, EvalOptionLabels, EvalWorkCalendar, EvalWorkCalendars } from './types'; diff --git a/packages/formula/src/stdlib.ts b/packages/formula/src/stdlib.ts index de2843af9a5..7ecd11fc44d 100644 --- a/packages/formula/src/stdlib.ts +++ b/packages/formula/src/stdlib.ts @@ -21,8 +21,9 @@ import type { Environment } from '@marcbachmann/cel-js'; -import type { EvalContext, EvalOptionLabels, EvalPermissions, EvalSystemPermissions } from './types'; +import type { EvalContext, EvalOptionLabels, EvalPermissions, EvalSystemPermissions, EvalWorkCalendars } from './types'; import { rmbUpper } from './rmb-upper'; +import { registerWorkingDayFunctions } from './working-day'; import { createEvalUser, type EvalUser } from '@objectstack/spec'; // The verb vocabulary lives on the SECURITY subpath, where the permission // contract it is seeded from lives — not on the root barrel, which exports a @@ -641,6 +642,8 @@ export interface StdLibBinding { readonly timezone: string; readonly permissionBinding: PermissionBinding | undefined; readonly optionLabels?: EvalOptionLabels | undefined; + /** ADR-0157 D4: what the working-day functions count with (`working-day.ts`). */ + readonly workCalendars?: EvalWorkCalendars | undefined; } /** @@ -661,6 +664,7 @@ export function registerBoundStdLib(env: Environment, read: () => StdLibBinding) bindPermissionPredicate(env, () => read().permissionBinding); bindCapabilityPredicate(env, () => read().permissionBinding); bindOptionLabel(env, () => read().optionLabels); + registerWorkingDayFunctions(env, () => read().workCalendars); const now = (): Date => read().now(); const today = (): Date => { const binding = read(); diff --git a/packages/formula/src/types.ts b/packages/formula/src/types.ts index 780455f3402..0b53a30998c 100644 --- a/packages/formula/src/types.ts +++ b/packages/formula/src/types.ts @@ -14,6 +14,7 @@ import type { Expression } from '@objectstack/spec'; import type { EffectiveObjectPermission } from '@objectstack/spec/security'; +import type { WorkCalendar } from '@objectstack/spec/data'; /** * The acting subject's effective object permissions, indexed by object name — @@ -72,6 +73,36 @@ export type EvalSystemPermissions = ReadonlyArray; */ export type EvalOptionLabels = Readonly>>>; +/** + * One working calendar as the working-day functions read it: the resolved + * calendar, or the refusal resolving it met (ADR-0157 D2, D8), held as the + * error the function throws. A refusal is data too: the caller resolved it + * before evaluation, so the function never asks the host again. + */ +export type EvalWorkCalendar = WorkCalendar | Error; + +/** + * The working calendars one evaluation counts with — the + * {@link EvalContext.workCalendars} payload, and the only input + * `addWorkingDays()`, `workingDaysBetween()` and `addWorkingHours()` read + * (ADR-0157 D4). + * + * `default` is the calendar a call that names no code counts with (D2: the + * organization's default); `byCode` holds each calendar a call names by a + * quoted code. The caller resolves both in the record's own organization + * before evaluating, from the calls the expression spells + * (`workingDayCalendarNeeds`), so a code the expression does not spell as a + * literal is never loaded. + * + * **A pure DATA map, never a resolver**, for the reason {@link EvalPermissions} + * gives: the stdlib computes synchronously over pinned data, so the calendar + * service resolves first and the functions count over what it answered. + */ +export interface EvalWorkCalendars { + readonly default?: EvalWorkCalendar; + readonly byCode?: Readonly>; +} + /** * Runtime context for evaluating an expression. * @@ -212,6 +243,21 @@ export interface EvalContext { * options, and `label()` throws for that too. */ optionLabels?: EvalOptionLabels; + /** + * The working calendars of the record's organization — see + * {@link EvalWorkCalendars} for the shape and where it comes from. + * + * Read by exactly three functions, `addWorkingDays()`, + * `workingDaysBetween()` and `addWorkingHours()` (ADR-0157 D4). ⛔ NOT + * mounted as a CEL variable, on the terms {@link permissions} is. + * + * **Absent ≠ refused.** With no map at all the three THROW + * (`ok: false, kind: 'runtime'`): a context that was never given calendars + * cannot count, and counting on the weekly pattern or the wall clock instead + * is the quiet wrong answer ADR-0157 D2 forbids. A calendar the caller could + * not resolve is in the map as its refusal, and the call throws that. + */ + workCalendars?: EvalWorkCalendars; /** Free-form bag for niche call sites; merged onto the variable scope. */ extra?: Record; } diff --git a/packages/formula/src/validate.ts b/packages/formula/src/validate.ts index d551b90c24f..3e82de83c59 100644 --- a/packages/formula/src/validate.ts +++ b/packages/formula/src/validate.ts @@ -2222,6 +2222,8 @@ export const CEL_STDLIB_FUNCTIONS: string[] = [ 'isBlank', 'isEmpty', 'coalesce', 'len', // Options (registered stdlib) — `label(record.)`, a select value's label 'label', + // Working days (registered stdlib, ADR-0157 D4) — counted with the organization's working calendar + 'addWorkingDays', 'workingDaysBetween', 'addWorkingHours', // cel-js built-ins (verified to resolve) 'size', 'has', 'int', 'string', 'bool', 'double', 'timestamp', 'duration', ]; diff --git a/packages/formula/src/working-day-needs.ts b/packages/formula/src/working-day-needs.ts new file mode 100644 index 00000000000..245c1fdcbdc --- /dev/null +++ b/packages/formula/src/working-day-needs.ts @@ -0,0 +1,101 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Which working calendars an expression counts with (ADR-0157 D2, D4): read + * off the calls it spells, so a caller can resolve exactly those calendars + * BEFORE evaluating it. The working-day functions compute synchronously over + * pinned data (`working-day.ts`); the calendar service is asynchronous; this is + * the bridge, and the reason a calendar code is written as a quoted literal. + */ + +import { parseCelToAst } from './cel-engine'; +import { WORKING_DAY_FUNCTIONS, type WorkingDayFunction } from './working-day'; + +/** A call of one of the three in a CEL source: CEL has no comments, so a call is spelled this way or not at all. */ +const WORKING_DAY_CALL = new RegExp(`\\b(?:${WORKING_DAY_FUNCTIONS.join('|')})\\s*\\(`); + +/** Does `source` spell a call of a working-day function? A cheap scan, no parse. */ +export function callsWorkingDayFunction(source: unknown): boolean { + return typeof source === 'string' && WORKING_DAY_CALL.test(source); +} + +/** The calendars one expression counts with. */ +export interface WorkingDayCalendarNeeds { + /** Some call names no calendar, so it counts with the organization default. */ + readonly default: boolean; + /** The calendar codes calls name as quoted literals, each once, in source order. */ + readonly codes: readonly string[]; + /** The functions called with a calendar argument that is not a quoted literal, each once. */ + readonly computedCode: readonly WorkingDayFunction[]; +} + +const NAMES = new Set(WORKING_DAY_FUNCTIONS); + +/** + * The calendars `source` counts with, or `undefined` when it calls none of the + * three (or does not parse, which its evaluation reports). Results are cached + * per source, bounded. + */ +export function workingDayCalendarNeeds(source: unknown): WorkingDayCalendarNeeds | undefined { + if (!callsWorkingDayFunction(source)) return undefined; + const text = source as string; + const hit = cache.get(text); + if (hit !== undefined) return hit ?? undefined; + const found = analyze(text); + if (cache.size >= CACHE_CAP) cache.clear(); + cache.set(text, found ?? null); + return found; +} + +const cache = new Map(); +const CACHE_CAP = 512; + +function analyze(source: string): WorkingDayCalendarNeeds | undefined { + const ast = parseCelToAst(source); + if (ast == null) return undefined; + let usesDefault = false; + const codes: string[] = []; + const computed: WorkingDayFunction[] = []; + let any = false; + const visited = new Set(); + const walk = (node: unknown): void => { + if (!node || typeof node !== 'object' || visited.has(node)) return; + visited.add(node); + if (Array.isArray(node)) { + for (const child of node) walk(child); + return; + } + const { op, args } = node as { op?: unknown; args?: unknown }; + if (op === 'call' && Array.isArray(args) && typeof args[0] === 'string' && NAMES.has(args[0]) && Array.isArray(args[1])) { + const fn = args[0] as WorkingDayFunction; + const callArgs = args[1] as unknown[]; + any = true; + if (callArgs.length === 2) usesDefault = true; + else if (callArgs.length === 3) { + const code = callArgs[2] as { op?: unknown; args?: unknown } | undefined; + if (code?.op === 'value' && typeof code.args === 'string') { + if (!codes.includes(code.args)) codes.push(code.args); + } else if (!computed.includes(fn)) computed.push(fn); + } + } + if (args !== undefined) walk(args); + }; + walk(ast); + return any ? { default: usesDefault, codes, computedCode: computed } : undefined; +} + +/** + * The authoring refusal for a working-day call whose calendar is not a quoted + * literal, or `undefined` when every call names its calendar that way (or + * names none). + */ +export function computedCalendarCodeMessage(source: unknown): string | undefined { + const needs = workingDayCalendarNeeds(source); + if (!needs || needs.computedCode.length === 0) return undefined; + const fns = needs.computedCode.map((fn) => `${fn}()`).join(', '); + return `${fns} names its working calendar with an expression; write the calendar code as a quoted literal ` + + "(`addWorkingDays(record.start, 3, 'cn_mainland')`), because the engine loads the calendars an expression " + + 'names before it evaluates it, and a computed code names a calendar nobody loaded. To choose a calendar per ' + + "record, branch between literal calls: `record.region == 'us' ? addWorkingDays(record.start, 3, 'us') : " + + "addWorkingDays(record.start, 3, 'cn_mainland')`."; +} diff --git a/packages/formula/src/working-day.test.ts b/packages/formula/src/working-day.test.ts new file mode 100644 index 00000000000..a9831a7cc17 --- /dev/null +++ b/packages/formula/src/working-day.test.ts @@ -0,0 +1,222 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { WORK_CALENDAR_NOT_MAINTAINED_CODE, WORK_CALENDAR_UNRESOLVED_CODE } from '@objectstack/spec/data'; +import type { Expression } from '@objectstack/spec'; + +import { celEngine } from './cel-engine'; +import { compileCelToFilter, isPushdownableCel } from './cel-to-filter'; +import type { EvalContext, EvalWorkCalendars } from './types'; +import { WorkCalendarUnresolvedError, buildWorkCalendar } from './work-calendar'; +import { callsWorkingDayFunction, computedCalendarCodeMessage, workingDayCalendarNeeds } from './working-day-needs'; + +// ADR-0157 D4: the three working-day formula functions, evaluated by the CEL +// engine over the calendars an evaluation is handed. 2026-10-01 is a Thursday. +const WEEKDAY = '09:00-12:00, 13:00-18:00'; +const cnRow = { + code: 'cn_mainland', + 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, +}; +// 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 weekly pattern with no exceptions entered, under another code. +const bare = buildWorkCalendar({ ...cnRow, code: 'weekly_only' }, []); + +const calendars: EvalWorkCalendars = { default: cn, byCode: { cn_mainland: cn, weekly_only: bare } }; +const cel = (source: string): Expression => ({ dialect: 'cel', source }); +const run = (source: string, ctx: EvalContext = {}) => celEngine.evaluate(cel(source), { workCalendars: calendars, ...ctx }); +const value = (source: string, ctx: EvalContext = {}) => { + const r = run(source, ctx); + if (!r.ok) throw new Error(`${source}: ${r.error.message}`); + return r.value; +}; +const iso = (v: unknown) => (v as Date).toISOString(); +/** Shanghai wall clock → ISO instant (UTC+8, no DST). */ +const sh = (day: string, hm: string) => new Date(`${day}T${hm}:00+08:00`).toISOString(); + +describe('addWorkingDays() — a weekend, a National Day week and a 调休 make-up Saturday', () => { + it('steps over a weekend', () => { + // Friday 2026-09-18 + 1 working day = Monday 2026-09-21. + expect(iso(value("addWorkingDays('2026-09-18', 1)"))).toBe('2026-09-21T00:00:00.000Z'); + }); + + it('steps over the holiday week and onto the make-up Saturday; the weekly pattern alone does not (CONTROL)', () => { + expect(iso(value("addWorkingDays('2026-09-30', 1)"))).toBe('2026-10-08T00:00:00.000Z'); + expect(iso(value("addWorkingDays('2026-09-30', 3)"))).toBe('2026-10-10T00:00:00.000Z'); + expect(iso(value("addWorkingDays('2026-09-30', 1, 'weekly_only')"))).toBe('2026-10-01T00:00:00.000Z'); + }); + + it('counts back for a negative count, never counts the start, and answers the start for 0', () => { + expect(iso(value("addWorkingDays('2026-10-10', -3)"))).toBe('2026-09-30T00:00:00.000Z'); + expect(iso(value("addWorkingDays('2026-10-03', 0)"))).toBe('2026-10-03T00:00:00.000Z'); + }); + + it('reads a date field, today() and a timestamp on the UTC calendar, and a number field as the count', () => { + expect(iso(value('addWorkingDays(record.start, record.n)', { record: { start: '2026-09-30', n: 3 } }))) + .toBe('2026-10-10T00:00:00.000Z'); + expect(iso(value('addWorkingDays(today(), 1)', { now: new Date('2026-09-30T20:00:00Z'), timezone: 'Asia/Shanghai' }))) + .toBe('2026-10-08T00:00:00.000Z'); // today() in Shanghai is 2026-10-01, a holiday; the next working day is 10-08 + expect(iso(value('addWorkingDays(record.start, 1)', { record: { start: new Date('2026-09-30T00:00:00Z') } }))) + .toBe('2026-10-08T00:00:00.000Z'); + expect(value('isoDate(addWorkingDays(record.start, 3))', { record: { start: '2026-09-30' } })).toBe('2026-10-10'); + }); + + it('answers blank for a blank start, as addDays() does, and refuses a count that is not a whole number', () => { + const blank = value('addWorkingDays(record.start, 1)', { record: { start: null } }); + expect(blank instanceof Date && Number.isNaN(blank.getTime())).toBe(true); + const half = run("addWorkingDays('2026-09-30', 1.5)"); + expect(half.ok).toBe(false); + expect(!half.ok && half.error.kind).toBe('runtime'); + expect(!half.ok && half.error.message).toContain('whole number'); + }); + + it('a blank start answers blank before any calendar is read, so a refusing calendar logs nothing for it', () => { + const refused = { default: new WorkCalendarUnresolvedError('no_default') }; + for (const source of ['addWorkingDays(record.start, 1)', 'addWorkingHours(record.start, 2)']) { + const r = run(source, { record: { start: null }, workCalendars: refused }); + expect(r.ok, source).toBe(true); + expect(r.ok && r.value instanceof Date && Number.isNaN(r.value.getTime())).toBe(true); + } + }); +}); + +describe('workingDaysBetween()', () => { + it('excludes the start, includes the end, is negative backward, and inverts addWorkingDays()', () => { + expect(value("workingDaysBetween('2026-09-30', '2026-10-10')")).toBe(3); + expect(value("workingDaysBetween('2026-10-10', '2026-09-30')")).toBe(-3); + expect(value("workingDaysBetween('2026-09-30', '2026-10-10', 'weekly_only')")).toBe(7); + for (const n of [-4, -1, 0, 1, 2, 5]) { + expect(value(`workingDaysBetween('2026-10-09', addWorkingDays('2026-10-09', ${n}))`)).toBe(n); + } + }); + + it('compares as an int in a predicate', () => { + expect(value("workingDaysBetween(record.opened, record.closed) > 2", { record: { opened: '2026-09-30', closed: '2026-10-10' } })) + .toBe(true); + }); + + it('refuses a blank day: a count of nothing is not zero', () => { + const r = run('workingDaysBetween(record.opened, record.closed)', { record: { opened: '2026-09-30', closed: null } }); + expect(r.ok).toBe(false); + expect(!r.ok && r.error.message).toContain('end day has no value'); + }); +}); + +describe('addWorkingHours()', () => { + it('runs across the holiday week and the make-up Saturday, forward and backward', () => { + expect(iso(value(`addWorkingHours('${sh('2026-09-30', '17:00')}', 2)`))).toBe(sh('2026-10-08', '10:00')); + expect(iso(value(`addWorkingHours('${sh('2026-10-09', '17:00')}', 2)`))).toBe(sh('2026-10-10', '10:00')); + expect(iso(value(`addWorkingHours('${sh('2026-10-08', '10:00')}', -2)`))).toBe(sh('2026-09-30', '17:00')); + // A weekend: Friday 17:00 + 2h = Monday 10:00. + expect(iso(value(`addWorkingHours('${sh('2026-10-16', '17:00')}', 2)`))).toBe(sh('2026-10-19', '10:00')); + }); + + it('reads a datetime field and now()', () => { + expect(iso(value('addWorkingHours(record.opened_at, 4)', { record: { opened_at: new Date(sh('2026-09-30', '16:00')) } }))) + .toBe(sh('2026-10-08', '11:00')); + expect(iso(value('addWorkingHours(now(), 1)', { now: new Date(sh('2026-10-10', '11:30')) }))).toBe(sh('2026-10-10', '13:30')); + }); + + it('counts elapsed time on daylight-saving transition days (ADR-0157 D11)', () => { + const night = '01:00-04:00'; + const ny = buildWorkCalendar({ + code: 'us_night', timezone: 'America/New_York', maintained_from: '2026-01-01', maintained_through: '2026-12-31', + monday_periods: night, tuesday_periods: night, wednesday_periods: night, thursday_periods: night, + friday_periods: night, saturday_periods: night, sunday_periods: night, + }, []); + const ctx = { workCalendars: { default: ny } }; + // Spring forward: the 2026-03-08 period holds two hours, so half an hour spills into 03-09. + expect(iso(value("addWorkingHours('2026-03-08T06:00:00Z', 2.5)", ctx))).toBe('2026-03-09T05:30:00.000Z'); + expect(iso(value("addWorkingHours('2026-03-01T06:00:00Z', 2.5)", ctx))).toBe('2026-03-01T08:30:00.000Z'); // CONTROL + // Fall back: the 2026-11-01 period holds four hours. + expect(iso(value("addWorkingHours('2026-11-01T05:00:00Z', 3.5)", ctx))).toBe('2026-11-01T08:30:00.000Z'); + expect(iso(value("addWorkingHours('2026-11-08T06:00:00Z', 3.5)", ctx))).toBe('2026-11-09T06:30:00.000Z'); // CONTROL + }); +}); + +describe('the calendar a call counts with (ADR-0157 D2, D8)', () => { + it('a call with no code counts with the default; a code names its calendar', () => { + expect(iso(value("addWorkingDays('2026-09-30', 1)", { workCalendars: { default: bare } }))).toBe('2026-10-01T00:00:00.000Z'); + expect(iso(value("addWorkingDays('2026-09-30', 1, 'cn_mainland')", { workCalendars: { default: bare, byCode: { cn_mainland: cn } } }))) + .toBe('2026-10-08T00:00:00.000Z'); + }); + + it('throws the refusal the caller met resolving a calendar, never a count on the wall clock', () => { + const r = run("addWorkingDays('2026-09-30', 1)", { workCalendars: { default: new WorkCalendarUnresolvedError('no_default') } }); + expect(r.ok).toBe(false); + expect(!r.ok && r.error.kind).toBe('runtime'); + expect(!r.ok && r.error.message).toContain('No working calendar is marked as the default'); + // The refusal is the calendar error itself, carried as data. + expect(new WorkCalendarUnresolvedError('no_default').code).toBe(WORK_CALENDAR_UNRESOLVED_CODE); + }); + + it('a count past the maintained span throws the not-maintained refusal (D8)', () => { + const r = run("addWorkingDays('2026-12-30', 5)"); + expect(r.ok).toBe(false); + expect(!r.ok && r.error.message).toContain("is maintained from 2026-01-01 through 2026-12-31"); + expect(WORK_CALENDAR_NOT_MAINTAINED_CODE).toBe('ERR_WORK_CALENDAR_NOT_MAINTAINED'); + }); + + it('an evaluation handed no calendars throws, naming where calendars are loaded', () => { + const r = celEngine.evaluate(cel("addWorkingDays('2026-09-30', 1)"), {}); + expect(r.ok).toBe(false); + expect(!r.ok && r.error.message).toContain("formula field's or a computed field's `expression`"); + }); + + it('a code the evaluation was not given throws, naming the literal rule', () => { + const r = run("addWorkingDays('2026-09-30', 1, 'us_east')"); + expect(r.ok).toBe(false); + expect(!r.ok && r.error.message).toContain("names the working calendar 'us_east'"); + }); +}); + +describe('workingDayCalendarNeeds() — the calendars an expression names', () => { + it('reads the default and each quoted code, once each; none for an expression without a call', () => { + expect(workingDayCalendarNeeds("addWorkingDays(record.a, 1) == addWorkingDays(record.a, 1, 'cn') || workingDaysBetween(record.a, record.b, 'cn') > addWorkingHours(record.c, 2, 'us')")) + .toEqual({ default: true, codes: ['cn', 'us'], computedCode: [] }); + expect(workingDayCalendarNeeds("addWorkingDays(record.a, 1, 'cn')")).toEqual({ default: false, codes: ['cn'], computedCode: [] }); + expect(workingDayCalendarNeeds('addDays(record.a, 1)')).toBeUndefined(); + expect(callsWorkingDayFunction('addDays(record.a, 1)')).toBe(false); + expect(callsWorkingDayFunction('addWorkingHours (record.a, 1)')).toBe(true); + }); + + it('names a call whose calendar is computed, and the authoring message says to write a literal', () => { + expect(workingDayCalendarNeeds('addWorkingDays(record.a, 1, record.calendar)')) + .toEqual({ default: false, codes: [], computedCode: ['addWorkingDays'] }); + expect(computedCalendarCodeMessage('addWorkingDays(record.a, 1, record.calendar)')).toContain('quoted literal'); + expect(computedCalendarCodeMessage("addWorkingDays(record.a, 1, 'cn')")).toBeUndefined(); + }); +}); + +describe('pushdown refuses the working-day functions (ADR-0157 D6)', () => { + for (const source of [ + 'record.due_at < addWorkingDays(today(), 3)', + 'addWorkingHours(record.opened_at, 4) < now()', + 'workingDaysBetween(record.opened, today()) > 3', + ]) { + it(`refuses \`${source}\` with the write-time column prescription`, () => { + const compiled = compileCelToFilter(source); + expect(compiled.ok).toBe(false); + expect(!compiled.ok && compiled.reason).toBe('unsupported'); + expect(!compiled.ok && compiled.detail).toMatch(/evaluates in memory only, so it cannot run as a database filter/); + expect(!compiled.ok && compiled.detail).toContain('{now}'); + const shape = isPushdownableCel(source); + expect(shape.ok).toBe(false); + }); + } + + it('CONTROL: another function call keeps its generic refusal', () => { + const compiled = compileCelToFilter('record.due < addDays(today(), 3)'); + expect(compiled.ok).toBe(false); + expect(!compiled.ok && compiled.detail).not.toMatch(/working calendar/); + }); +}); diff --git a/packages/formula/src/working-day.ts b/packages/formula/src/working-day.ts new file mode 100644 index 00000000000..4168bdaf594 --- /dev/null +++ b/packages/formula/src/working-day.ts @@ -0,0 +1,195 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The working-day formula functions (ADR-0157 D4): `addWorkingDays`, + * `workingDaysBetween` and `addWorkingHours`, as CEL functions over the + * calendars an evaluation was handed ({@link EvalWorkCalendars}). + * + * ## One arithmetic, one daylight-saving rule (D11, open point 3) + * + * Every count is `work-calendar.ts`'s, the module the calendar service and the + * approval clock count with. This module only turns CEL arguments into that + * module's arguments and its answers back into CEL values; it holds no second + * copy of the walk or of the wall-clock conversion. + * + * ## The public contract (D4: the card's to settle, pinned by its tests) + * + * - `addWorkingDays(day, n[, calendar])`: the calendar day `n` working days + * after `day` (before it, for a negative `n`). `day` itself is never + * counted, and `0` answers `day`. The answer is a calendar day: a timestamp + * at UTC midnight, as `today()` and a `date` field are (ADR-0053 D1). + * - `workingDaysBetween(start, end[, calendar])`: the working days stepped + * through from `start` to `end`, `start` excluded and `end` included, + * negative when `end` is earlier: `workingDaysBetween(d, addWorkingDays(d, n))` + * is `n`. + * - `addWorkingHours(start, hours[, calendar])`: 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 that lands on a period's end is that end. + * + * A calendar DAY argument is `YYYY-MM-DD` text, or a timestamp read on the UTC + * calendar, as `isoDate()` reads it: `today()` and a `date` field are that day + * at UTC midnight. To count from an instant's local time, count hours. An + * INSTANT argument is a timestamp, ISO text or epoch milliseconds, as `date()` + * reads it. A blank day or start answers blank (a due date with no start has + * none); a blank count, and a blank end of `workingDaysBetween`, refuse. + * + * `calendar` is a calendar code, written as a quoted literal: the caller loads + * the calendars an expression names before evaluating it, from the calls it + * spells, so a computed code names a calendar nobody loaded. Without it the + * call counts with the organization's default calendar (D2). + * + * ## Refusals (D2, D8) + * + * A calendar that did not resolve, and a count that needs a date outside the + * span the calendar is maintained for, throw the calendar's own refusal. The + * evaluation fails (`kind: 'runtime'`): a formula field reads blank and the + * engine logs one line naming the object, the field and the refusal (D8). Never + * a count on the weekly pattern or the wall clock instead. + */ + +import type { Environment } from '@marcbachmann/cel-js'; +import type { WorkCalendar } from '@objectstack/spec/data'; + +import type { EvalWorkCalendars } from './types'; +import { addWorkingDays, addWorkingHours, calendarDayOf, workingDaysBetween } from './work-calendar'; + +/** The three function names, in the order the catalog lists them. */ +export const WORKING_DAY_FUNCTIONS = ['addWorkingDays', 'workingDaysBetween', 'addWorkingHours'] as const; + +export type WorkingDayFunction = (typeof WORKING_DAY_FUNCTIONS)[number]; + +/** + * Why a working-day call has no calendar to count with: the evaluation was + * handed no calendars at all. Every evaluation the engine runs for a formula + * field or a computed field's `expression` is handed them; every other + * expression is not, and the lint refuses the call there. + */ +export function workCalendarsNotLoadedMessage(fn: WorkingDayFunction): string { + return `${fn}() counts with the organization's working calendar, and this evaluation was given none: ` + + "the engine loads calendars only for a formula field's or a computed field's `expression`, " + + 'evaluated on the server. Move the call into such a field, or read the field this expression needs.'; +} + +function codeNotLoadedMessage(fn: WorkingDayFunction, code: string): string { + return `${fn}() names the working calendar '${code}', which this evaluation was not given: ` + + 'write the calendar code as a quoted literal in the call, so the engine loads that calendar before it evaluates.'; +} + +/** The calendar a call counts with, or the throw that says why it has none. */ +function calendarFor(fn: WorkingDayFunction, calendars: EvalWorkCalendars | undefined, code?: unknown): WorkCalendar { + if (!calendars) throw new Error(workCalendarsNotLoadedMessage(fn)); + let entry: unknown; + if (code === undefined) { + entry = calendars.default; + if (entry === undefined) throw new Error(workCalendarsNotLoadedMessage(fn)); + } else { + if (typeof code !== 'string' || code.trim() === '') { + throw new Error(`${fn}() takes a calendar code as text, such as 'cn_mainland'; got ${code === null ? 'null' : typeof code}.`); + } + const byCode = calendars.byCode ?? {}; + entry = Object.prototype.hasOwnProperty.call(byCode, code) ? byCode[code] : undefined; + if (entry === undefined) throw new Error(codeNotLoadedMessage(fn, code)); + } + if (entry instanceof Error) throw entry; + return entry as WorkCalendar; +} + +const isBlank = (v: unknown): boolean => v === null || v === undefined || (typeof v === 'string' && v.trim() === ''); + +function utcDayOf(ms: number): string { + return new Date(ms).toISOString().slice(0, 10); +} + +/** + * A calendar-day argument as `YYYY-MM-DD`, `undefined` for a blank one, or a + * throw naming the argument when it is not a day. + */ +function dayArg(fn: WorkingDayFunction, name: string, v: unknown): string | undefined { + if (isBlank(v)) return undefined; + if (v instanceof Date) { + if (Number.isNaN(v.getTime())) return undefined; + return utcDayOf(v.getTime()); + } + if (typeof v === 'number' || typeof v === 'bigint') { + const ms = Number(v); + if (Number.isFinite(ms)) return utcDayOf(ms); + } else if (typeof v === 'string') { + const day = calendarDayOf(v); + if (day) return day; + const parsed = new Date(v.trim()); + if (/^\d{4}-\d{2}-\d{2}T/.test(v.trim()) && !Number.isNaN(parsed.getTime())) return utcDayOf(parsed.getTime()); + } + throw new RangeError(`${fn}() takes ${name} as a calendar day (YYYY-MM-DD text, a date field or today()); got '${String(v)}'.`); +} + +/** An instant argument as epoch milliseconds, `undefined` for a blank one, or a throw naming it. */ +function instantArg(fn: WorkingDayFunction, name: string, v: unknown): number | undefined { + if (isBlank(v)) return undefined; + let ms: number; + if (v instanceof Date) { + if (Number.isNaN(v.getTime())) return undefined; + ms = v.getTime(); + } else if (typeof v === 'number' || typeof v === 'bigint') { + ms = Number(v); + } else { + ms = new Date(String(v).trim()).getTime(); + } + if (!Number.isFinite(ms)) { + throw new RangeError(`${fn}() takes ${name} as an instant (a datetime field, now(), ISO text or epoch milliseconds); got '${String(v)}'.`); + } + return ms; +} + +function countArg(fn: WorkingDayFunction, name: string, v: unknown, whole: boolean): number { + const n = isBlank(v) ? Number.NaN : Number(v); + if (whole ? !Number.isSafeInteger(n) : !Number.isFinite(n)) { + throw new RangeError(`${fn}() takes ${name} as ${whole ? 'a whole number' : 'a number'}; got ${isBlank(v) ? 'no value' : `'${String(v)}'`}.`); + } + return n; +} + +/** A calendar day as the timestamp a `date` value is: that day at UTC midnight (ADR-0053 D1). */ +function dayTimestamp(day: string): Date { + return new Date(`${day}T00:00:00.000Z`); +} + +/** + * Register the three functions, each reading its calendars through `read` when + * it is CALLED (the stdlib's binding pattern, `registerBoundStdLib`). Each has + * a two-argument form (the organization default) and a three-argument form + * (a named calendar). Registered unconditionally: whether the names EXIST is a + * fact about the platform, never about one call site's data. + */ +export function registerWorkingDayFunctions(env: Environment, read: () => EvalWorkCalendars | undefined): Environment { + const addDays = (day: unknown, n: unknown, code?: unknown): Date => { + const d = dayArg('addWorkingDays', 'the start day', day); + const count = countArg('addWorkingDays', 'the number of days', n, true); + // A blank start answers blank, before any calendar is read: the unmarked + // invalid Date a formula field serializes to `null`, the answer `addDays()` + // gives one. + if (d === undefined) return new Date(Number.NaN); + return dayTimestamp(addWorkingDays(calendarFor('addWorkingDays', read(), code), d, count)); + }; + const between = (start: unknown, end: unknown, code?: unknown): bigint => { + const s = dayArg('workingDaysBetween', 'the start day', start); + const e = dayArg('workingDaysBetween', 'the end day', end); + if (s === undefined || e === undefined) { + throw new RangeError(`workingDaysBetween() needs both days; the ${s === undefined ? 'start' : 'end'} day has no value.`); + } + return BigInt(workingDaysBetween(calendarFor('workingDaysBetween', read(), code), s, e)); + }; + const addHours = (start: unknown, hours: unknown, code?: unknown): Date => { + const t = instantArg('addWorkingHours', 'the start', start); + const h = countArg('addWorkingHours', 'the number of hours', hours, false); + if (t === undefined) return new Date(Number.NaN); + return new Date(addWorkingHours(calendarFor('addWorkingHours', read(), code), t, h)); + }; + return env + .registerFunction('addWorkingDays(dyn, dyn): google.protobuf.Timestamp', (d: unknown, n: unknown) => addDays(d, n)) + .registerFunction('addWorkingDays(dyn, dyn, string): google.protobuf.Timestamp', (d: unknown, n: unknown, c: unknown) => addDays(d, n, c)) + .registerFunction('workingDaysBetween(dyn, dyn): int', (s: unknown, e: unknown) => between(s, e)) + .registerFunction('workingDaysBetween(dyn, dyn, string): int', (s: unknown, e: unknown, c: unknown) => between(s, e, c)) + .registerFunction('addWorkingHours(dyn, dyn): google.protobuf.Timestamp', (t: unknown, h: unknown) => addHours(t, h)) + .registerFunction('addWorkingHours(dyn, dyn, string): google.protobuf.Timestamp', (t: unknown, h: unknown, c: unknown) => addHours(t, h, c)); +} diff --git a/packages/lint/src/authored-site-expression.test.ts b/packages/lint/src/authored-site-expression.test.ts index e242f840afa..3791bc2a338 100644 --- a/packages/lint/src/authored-site-expression.test.ts +++ b/packages/lint/src/authored-site-expression.test.ts @@ -123,6 +123,8 @@ const WALK_PUSHES: Record = { hookRefusalTemplateIssues: "a hook refusal's template sentences over its declared params: no rule or field expression", // [#34273] The same judge over an action's refusal catalogue. actionRefusalTemplateIssues: "an action refusal's template sentences over its declared params: no rule or field expression", + // [#35356] ADR-0157 D4/D6: working-day calls at value sites the engine loads no calendar for. + workingDayValueSiteIssues: "a field's expression `defaultValue` and a seed record's expression values: no rule or formula `expression`", }; /** The passes the walk pushes whole from INSIDE a site's regions: classified with that site's calls, in `SITE_CALLS`. */ @@ -210,6 +212,11 @@ const SITE_CALLS: Record> = { rulePredicates: { kind: 'plumbing', why: "lists the rule's predicates" }, faultOutcomeOf: { kind: 'plumbing', why: "the rule's fault outcome, from its severity" }, check: { kind: 'plumbing', why: 'the helper whose calls are the first region of this site' }, + // [#35356] ADR-0157 D4: a working-day call where no calendar is loaded. + refuseWorkingDayElsewhere: { + kind: 'pass', + fixture: { objects: [REQ, BAL], expression: 'addWorkingDays(today(), 3) < now()', severity: 'error', names: 'addWorkingDays()' }, + }, validationRuleParentIssue: { kind: 'pass', fixture: { objects: [REQ, BAL], expression: 'parent.remaining > 1', severity: 'error', names: 'parent' }, @@ -224,6 +231,11 @@ const SITE_CALLS: Record> = { celSourceOf: { kind: 'plumbing', why: 'reads the CEL source off the field' }, refuseStoredMetadataBodyHop: { kind: 'pass', fixture: asValue(BODY_HOP) }, refuseUndeclaredHopField: { kind: 'pass', fixture: asValue(HOP_FIELD) }, + // [#35356] ADR-0157 D4: a working-day call whose calendar code is not a quoted literal. + computedCalendarCodeMessage: { + kind: 'pass', + fixture: { objects: [REQ, BAL], expression: 'addWorkingDays(today(), 3, record.title)', severity: 'error', names: 'addWorkingDays()' }, + }, warnUnprovisionedAnchors: { kind: 'pass', fixture: asValue(ANCHOR) }, // [#33100] The formula-cycle pass, after the fields loop. It locates each // finding on a cycle member's own `expression`; the probe is named @@ -494,6 +506,11 @@ const FLOW_CALLS: Record = { checkDeclaredPredicate: { kind: 'plumbing', why: "a `decision` branch's helper, the second region" }, withAttachedBlocks: { kind: 'plumbing', why: 'the field list handed to the shared validator' }, isBareReferenceToAny: { kind: 'plumbing', why: "filters the shared validator's findings on a field-rule slot" }, + // [#35356] ADR-0157 D4: a working-day call where no calendar is loaded. + refuseWorkingDayElsewhere: { + kind: 'pass', + fixture: { objects: [FLOW_OBJ], expression: 'addWorkingDays(today(), 3) < now()', severity: 'error', names: 'addWorkingDays()' }, + }, checkFlowNullGuards: { kind: 'pass', fixture: { objects: [FLOW_OBJ], expression: 'record.days > 3', severity: 'error', names: 'record.days' }, diff --git a/packages/lint/src/validate-expressions.test.ts b/packages/lint/src/validate-expressions.test.ts index e8370a926dd..63750cd6fe3 100644 --- a/packages/lint/src/validate-expressions.test.ts +++ b/packages/lint/src/validate-expressions.test.ts @@ -4487,6 +4487,10 @@ describe('validateStackExpressions — reads only keys the spec declares (meta-t // artefact as `scope` above. The action copy pass reads its metadata in // that module, not here. 'templates', + // [#35356] NOT a receiver either — the tail of the + // `'./validate-working-day-sites.js'` import specifier, the same artefact + // as `templates` above. That pass reads its metadata in that module. + 'sites', // [#19939] The spec's value-slot template judge, one refusal at a time. // Its keys are that helper's own `{ path, label, message, source }` — // never metadata keys — and it is named to stay clear of the `message` / diff --git a/packages/lint/src/validate-expressions.ts b/packages/lint/src/validate-expressions.ts index c10ac8bb787..9ed9e0d8fdf 100644 --- a/packages/lint/src/validate-expressions.ts +++ b/packages/lint/src/validate-expressions.ts @@ -95,6 +95,7 @@ import { analyzeRelationshipTraversals, buildScope, declaresOptionsOnceServed, + computedCalendarCodeMessage, } from '@objectstack/formula'; import type { ExprFaultOutcome, RelationshipTraversalAnalysis } from '@objectstack/formula'; import { @@ -118,6 +119,7 @@ import { bulkConfirmTemplateRoots } from '@objectstack/spec/ui'; // is a `template` slot too, judged in its own module by the same judge. import { actionCopyTemplateIssues } from './validate-action-copy-templates.js'; import { actionRefusalTemplateIssues, hookRefusalTemplateIssues } from './validate-hook-refusal-templates.js'; +import { workingDayElsewhereMessage, workingDayValueSiteIssues } from './validate-working-day-sites.js'; // [#15137] The `value`-role half. Same two published primitives the engine // composes at `registerFlow` (`AutomationEngine.valueEnvelopeRefusals`), in the // same order: the SHAPE rule lives in the spec's `FlowValueSlotSchema` (the @@ -2931,6 +2933,12 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression } }; + /** ADR-0157 D4: a working-day call at a site the engine loads no calendar for (see `workingDayElsewhereMessage`). */ + const refuseWorkingDayElsewhere = (where: string, raw: unknown): void => { + const message = workingDayElsewhereMessage(raw); + if (message) issues.push({ where, message, source: celSourceOf(raw) ?? '', severity: 'error' }); + }; + const check = ( where: string, raw: unknown, @@ -3055,6 +3063,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // in the source, so flattened flow conditions are covered without ever // judging a bare identifier. warnUnprovisionedAnchors(where, raw, objectName); + refuseWorkingDayElsewhere(where, raw); }; /** @@ -3164,6 +3173,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression const res = validateExpression('predicate', raw as string | { dialect?: string; source?: string }); for (const e of res.errors) issues.push({ where, message: e.message, source: e.source, severity: 'error' }); for (const w of res.warnings) issues.push({ where, message: w.message, source: w.source, severity: 'warning' }); + refuseWorkingDayElsewhere(where, raw); return { refused: false }; }; @@ -3222,6 +3232,7 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression for (const w of res.warnings) { issues.push({ where, message: w.message, source: w.source, severity: 'warning' }); } + refuseWorkingDayElsewhere(where, raw); return { refused: false }; }; @@ -3946,6 +3957,10 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#8116] Formulas read the same record binding the predicates do, so // a `record.` read inside one degrades identically. warnUnprovisionedAnchors(fieldWhere, f.expression, objectName); + // ADR-0157 D4: the engine loads the calendars an expression names before + // evaluating it, so a calendar code must be a quoted literal. + const computedCode = computedCalendarCodeMessage(celSourceOf(f.expression)); + if (computedCode) issues.push({ where: fieldWhere, message: computedCode, source: celSourceOf(f.expression) ?? '', severity: 'error' }); // [#32529, #32554] A STORED field's `expression` (any field but a // `formula`) is computed at the write and kept: a read of another // record, of the clock, of the acting user or of a permission is @@ -4841,6 +4856,10 @@ export function runStackExpressionPasses(stack: AnyRec, options: StackExpression // [#34273] An action refusal sentence over declared `params` — the hook // refusal's compile half, on the same collections the copy pass reads. issues.push(...actionRefusalTemplateIssues(stack, { actions: !objectWrite, objects: true })); + // [#35356] ADR-0157 D4/D6: a working-day call in a field's expression + // `defaultValue` (every run) or a seed record's expression value (off an + // object write), the two value sites the passes above do not walk. + issues.push(...workingDayValueSiteIssues(stack, { data: !objectWrite })); return issues; } diff --git a/packages/lint/src/validate-expressions.working-day-35356.test.ts b/packages/lint/src/validate-expressions.working-day-35356.test.ts new file mode 100644 index 00000000000..a7e7d714427 --- /dev/null +++ b/packages/lint/src/validate-expressions.working-day-35356.test.ts @@ -0,0 +1,191 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0157 D4/D6 (#35356): the working-day formula functions count with a + * working calendar the engine loads for a formula field's or a computed + * field's `expression` only. The publish lint accepts them there (with the + * calendar code a quoted literal, the engine's loading contract) and refuses + * them at every other expression site, prescribing the stored due-time field. + * A sharing rule's condition is also refused by the enforceability pass, + * which lowers it to a filter: no calendar arithmetic runs in SQL. + * + * Every fixture goes through `ObjectStackSchema.safeParse` first, so no case + * pins a branch an author cannot reach. + */ + +import { describe, it, expect } from 'vitest'; + +import { ObjectStackSchema } from '@objectstack/spec'; + +import { validateStackExpressions } from './validate-expressions.js'; +import { validateSharingRuleEnforceability } from './validate-sharing-rule-enforceability.js'; + +const MANIFEST = { id: 'com.example.working-day', name: 'working_day_probe', version: '1.0.0', type: 'app' } as const; + +function specValid(stack: Record): Record { + const result = ObjectStackSchema.safeParse({ manifest: MANIFEST, ...stack }); + if (!result.success) { + throw new Error( + 'fixture is not spec-valid: ' + + result.error.issues.map((i) => `${i.path.join('.') || '(root)'}: ${i.message}`).join('; '), + ); + } + return result.data as unknown as Record; +} + +const ticket = (extraFields: Record = {}, rest: Record = {}) => ({ + name: 'ticket_probe', + label: 'Ticket probe', + fields: { + name: { type: 'text', label: 'Name' }, + region: { type: 'text', label: 'Region' }, + start: { type: 'date', label: 'Start' }, + opened_at: { type: 'datetime', label: 'Opened at' }, + ...extraFields, + }, + ...rest, +}); + +const errorsOf = (stack: Record) => + validateStackExpressions(specValid(stack)).filter((i) => i.severity === 'error'); + +describe('publish lint — working-day functions at the two served sites (ADR-0157 D4, D6)', () => { + it.each([ + 'addWorkingDays(record.start, 3)', + "addWorkingDays(record.start, 3, 'cn_mainland')", + "workingDaysBetween(record.start, today(), 'cn_mainland')", + "record.region == 'us' ? addWorkingDays(record.start, 3, 'us') : addWorkingDays(record.start, 3, 'cn_mainland')", + ])('accepts a formula field calling %s', (expression) => { + expect(errorsOf({ objects: [ticket({ due: { type: 'formula', label: 'Due', expression } })] })).toEqual([]); + }); + + it("accepts a stored datetime field's `expression` (the D6 due column)", () => { + const due_at = { type: 'datetime', label: 'Due at', expression: 'addWorkingHours(record.opened_at, 8)' }; + expect(errorsOf({ objects: [ticket({ due_at })] })).toEqual([]); + }); + + it('refuses a calendar code that is not a quoted literal, prescribing the branch between literal calls', () => { + const due = { type: 'formula', label: 'Due', expression: 'addWorkingDays(record.start, 3, record.region)' }; + const errors = errorsOf({ objects: [ticket({ due })] }); + expect(errors).toHaveLength(1); + expect(errors[0]!.message).toContain('addWorkingDays() names its working calendar with an expression'); + expect(errors[0]!.message).toContain('write the calendar code as a quoted literal'); + expect(errors[0]!.message).toContain("record.region == 'us' ? addWorkingDays(record.start, 3, 'us')"); + }); +}); + +describe('publish lint — working-day functions anywhere else are refused (ADR-0157 D4, D6)', () => { + const STORE_IT = 'Store the due time instead: give the object a datetime field whose `expression` calls'; + + it('refuses a validation rule condition, prescribing the stored due-time field', () => { + const errors = errorsOf({ + objects: [ + ticket({}, { + validations: [{ + name: 'not_overdue', type: 'script', severity: 'error', message: 'm', + condition: 'addWorkingDays(record.start, 3) < now()', + }], + }), + ], + }); + expect(errors).toHaveLength(1); + expect(errors[0]!.message).toContain("addWorkingDays() counts with the organization's working calendar"); + expect(errors[0]!.message).toContain(`${STORE_IT} addWorkingDays()`); + }); + + it("refuses an action's `visible`", () => { + const errors = errorsOf({ + objects: [ticket()], + actions: [{ + name: 'probe_action', label: 'Probe', objectName: 'ticket_probe', type: 'script', target: 'fn', + visible: 'workingDaysBetween(record.start, today()) > 2', + }], + }); + expect(errors.map((e) => e.message)).toEqual([expect.stringContaining('workingDaysBetween() counts with')]); + }); + + it('refuses a record-triggered flow condition', () => { + const errors = errorsOf({ + objects: [ticket()], + flows: [{ + name: 'ticket_flow', label: 'Ticket flow', type: 'autolaunched', + nodes: [ + { + id: 'start', type: 'start', label: 'Start', + config: { + objectName: 'ticket_probe', triggerType: 'record-after-update', + condition: 'addWorkingHours(record.opened_at, 4) < now()', + }, + }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [{ id: 'e1', source: 'start', target: 'end' }], + }], + }); + expect(errors.map((e) => e.message)).toEqual([expect.stringContaining('addWorkingHours() counts with')]); + }); + + it('refuses a sharing rule condition at both passes: no calendar arithmetic lowers to a filter', () => { + const stack = specValid({ + objects: [ticket()], + sharingRules: [{ + name: 'sr', type: 'criteria', object: 'ticket_probe', + condition: 'addWorkingDays(record.start, 3) < today()', + sharedWith: { type: 'team', value: 't' }, accessLevel: 'read', + }], + }); + const lint = validateStackExpressions(stack).filter((i) => i.severity === 'error'); + expect(lint.map((e) => e.message)).toEqual([expect.stringContaining('addWorkingDays() counts with')]); + const lowered = validateSharingRuleEnforceability(stack); + expect(lowered.map((f) => f.message)).toEqual([ + expect.stringContaining('addWorkingDays() counts with a working calendar and evaluates in memory only'), + ]); + }); + + it("refuses a field's expression `defaultValue`: the default step has no calendar and would leave every insert blank", () => { + const errors = errorsOf({ + objects: [ticket({ due: { type: 'date', label: 'Due', defaultValue: { dialect: 'cel', source: 'addWorkingDays(today(), 3)' } } })], + }); + expect(errors).toHaveLength(1); + expect(errors[0]!.where).toBe("object 'ticket_probe' · field 'due' defaultValue"); + expect(errors[0]!.message).toContain(`${STORE_IT} addWorkingDays()`); + }); + + it('refuses a seed record\'s expression value, at any depth', () => { + const errors = errorsOf({ + objects: [ticket()], + data: [{ object: 'ticket_probe', records: [{ name: 'a', start: { dialect: 'cel', source: 'addWorkingDays(today(), 2)' } }] }], + }); + expect(errors.map((e) => e.where)).toEqual(["data[0] (object 'ticket_probe') · records[0].start"]); + expect(errors[0]!.message).toContain('addWorkingDays() counts with'); + }); + + it('CONTROL: a bare-string `defaultValue` is a literal, and an `addDays()` default or seed value draws nothing', () => { + const errors = errorsOf({ + objects: [ticket({ + note: { type: 'text', label: 'Note', defaultValue: 'addWorkingDays(today(), 3)' }, + due: { type: 'date', label: 'Due', defaultValue: { dialect: 'cel', source: 'addDays(today(), 3)' } }, + })], + data: [{ object: 'ticket_probe', records: [{ name: 'a', start: { dialect: 'cel', source: 'daysFromNow(2)' } }] }], + }); + expect(errors.filter((e) => e.message.includes('working calendar'))).toEqual([]); + }); + + it('CONTROL: the same sites calling `addDays()` draw no working-day refusal', () => { + const errors = errorsOf({ + objects: [ + ticket({}, { + validations: [{ + name: 'not_overdue', type: 'script', severity: 'error', message: 'm', + condition: 'addDays(record.start, 3) < now()', + }], + }), + ], + actions: [{ + name: 'probe_action', label: 'Probe', objectName: 'ticket_probe', type: 'script', target: 'fn', + visible: "record.region == 'us'", + }], + }); + expect(errors.filter((e) => e.message.includes('working calendar'))).toEqual([]); + }); +}); diff --git a/packages/lint/src/validate-working-day-sites.ts b/packages/lint/src/validate-working-day-sites.ts new file mode 100644 index 00000000000..3a266191d3e --- /dev/null +++ b/packages/lint/src/validate-working-day-sites.ts @@ -0,0 +1,109 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0157 D4/D6 (#35356): where the working-day functions (`addWorkingDays`, + * `workingDaysBetween`, `addWorkingHours`) cannot count. + * + * The engine loads a working calendar for exactly two sites: a formula field's + * and a stored field's `expression`, evaluated on the server. Every other + * expression is handed none, so a call there throws on every evaluation and the + * site's own fault outcome applies. `validate-expressions.ts` refuses the call + * at the predicate and flow-value sites it judges ({@link workingDayElsewhereMessage}); + * this module adds the two value sites that pass does not walk: + * + * - a field's expression `defaultValue` (a `{ dialect, source }` envelope; a + * bare string there is a literal): the engine's default step evaluates it + * with no calendar, logs the fault and leaves the field unset, so every + * insert would land a blank due date; + * - a seed record's expression value (`data[].records`, a `cel` value at any + * depth): the seed loader evaluates it with no calendar either. + * + * Both are refused with the D6 prescription: store the due time in a field + * whose `expression` calls the function. + */ + +import { WORKING_DAY_FUNCTIONS, callsWorkingDayFunction } from '@objectstack/formula'; +import { recordsOf } from './object-graph.js'; +import type { ExprIssue } from './validate-expressions.js'; + +type AnyRec = Record; + +const isRec = (v: unknown): v is AnyRec => !!v && typeof v === 'object' && !Array.isArray(v); + +/** The CEL source of an expression envelope, or `undefined` for anything else (a bare string is a literal at a value site). */ +function envelopeSource(raw: unknown): string | undefined { + if (!isRec(raw) || typeof raw.source !== 'string') return undefined; + if (raw.dialect !== undefined && raw.dialect !== 'cel') return undefined; + return raw.source; +} + +/** The raw CEL source behind an expression slot (string or `{ dialect, source }`). */ +function celSourceOf(raw: unknown): string | undefined { + return typeof raw === 'string' ? raw : envelopeSource(raw); +} + +/** + * The refusal of a working-day call at a site the engine loads no calendar + * for, prescribing the stored due time (D6). `undefined` when `raw` calls none + * of the three. + */ +export function workingDayElsewhereMessage(raw: unknown): string | undefined { + const source = celSourceOf(raw); + if (!callsWorkingDayFunction(source)) return undefined; + const called = WORKING_DAY_FUNCTIONS.filter((fn) => new RegExp(`\\b${fn}\\s*\\(`).test(source!)); + const names = called.map((fn) => `${fn}()`).join(', '); + return `${names} counts with the organization's working calendar, which the engine loads only for a ` + + "formula field's or a computed field's `expression`; here it has no calendar and fails on every evaluation, " + + 'and no calendar arithmetic runs as a database filter. Store the due time instead: give the object a ' + + `datetime field whose \`expression\` calls ${called[0]}(), computed when the record is written, and read ` + + 'or compare that field here.'; +} + +/** Which collections one run judges: the publish gate narrows them per write type. */ +export interface WorkingDayValueSiteScope { + /** The stack's seed data (`data[]`). */ + readonly data: boolean; +} + +function refuseAt(issues: ExprIssue[], where: string, raw: unknown): void { + const source = envelopeSource(raw); + if (source === undefined) return; + const message = workingDayElsewhereMessage(raw); + if (message) issues.push({ where, message, source, severity: 'error' }); +} + +/** Every expression envelope in one seed value, at any depth, with its key path. */ +function walkSeedValue(issues: ExprIssue[], where: string, value: unknown): void { + if (envelopeSource(value) !== undefined) { + refuseAt(issues, where, value); + return; + } + if (Array.isArray(value)) { + value.forEach((item, i) => walkSeedValue(issues, `${where}[${i}]`, item)); + return; + } + if (isRec(value)) { + for (const [key, item] of Object.entries(value)) walkSeedValue(issues, `${where}.${key}`, item); + } +} + +/** The working-day refusals at a field's expression `defaultValue` and at a seed record's expression values. */ +export function workingDayValueSiteIssues(stack: AnyRec, scope: WorkingDayValueSiteScope): ExprIssue[] { + const issues: ExprIssue[] = []; + for (const obj of recordsOf(stack.objects)) { + const objectName = typeof obj.name === 'string' ? obj.name : '?'; + for (const field of recordsOf(obj.fields)) { + const fname = typeof field.name === 'string' ? field.name : '?'; + refuseAt(issues, `object '${objectName}' · field '${fname}' defaultValue`, field.defaultValue); + } + } + if (scope.data && Array.isArray(stack.data)) { + stack.data.forEach((seed, i) => { + if (!isRec(seed)) return; + const objectName = typeof seed.object === 'string' ? seed.object : '?'; + if (!Array.isArray(seed.records)) return; + seed.records.forEach((record, j) => walkSeedValue(issues, `data[${i}] (object '${objectName}') · records[${j}]`, record)); + }); + } + return issues; +} diff --git a/packages/objectql/src/engine-find.ts b/packages/objectql/src/engine-find.ts index 3434ca103d5..ed3cf40131a 100644 --- a/packages/objectql/src/engine-find.ts +++ b/packages/objectql/src/engine-find.ts @@ -29,6 +29,7 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ +import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import { SortNodeSchema, lowerFilterCondition, resolveSearchFieldResolution } from '@objectstack/spec/data'; import type { EngineAggregateOptions, EngineCountOptions, EngineQueryOptions, FilterCondition, FilterLoweringOptions, HookContext, QueryAST, QueryInput, ServiceObject } from '@objectstack/spec/data'; import { mergeDriverOptionsIntoHookView } from './engine-driver-options.js'; @@ -633,7 +634,8 @@ export class FindFacet { // [#24197] One batched read per reference field for this PAGE — // the rows the driver returned, after limit/offset. _findSchema, _findFormula.plan, result, opCtx.context, query, - ), this.formulaOptionLabels(_findSchema, _findFormula.plan, opCtx.context)); + ), this.formulaOptionLabels(_findSchema, _findFormula.plan, opCtx.context), + await formulaWorkCalendarsFor(this.facade, _findFormula.plan, result, opCtx.context)); } // Post-process: expand related records if expand is requested @@ -907,7 +909,8 @@ export class FindFacet { objectName, _findOneFormula.plan, [result], opCtx.context, this.permissionResolution(opCtx.context), ), this.formulaFaultSink(objectName), await this.resolveFormulaRelated( _findOneSchema, _findOneFormula.plan, [result], opCtx.context, query, - ), this.formulaOptionLabels(_findOneSchema, _findOneFormula.plan, opCtx.context)); + ), this.formulaOptionLabels(_findOneSchema, _findOneFormula.plan, opCtx.context), + await formulaWorkCalendarsFor(this.facade, _findOneFormula.plan, [result], opCtx.context)); } // Post-process: expand related records if expand is requested diff --git a/packages/objectql/src/engine-formula-working-day.test.ts b/packages/objectql/src/engine-formula-working-day.test.ts new file mode 100644 index 00000000000..fc83a8cf30a --- /dev/null +++ b/packages/objectql/src/engine-formula-working-day.test.ts @@ -0,0 +1,366 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * ADR-0157 D4, D6, D8 — the working-day formula functions on the engine's + * formula paths, counting through the real `WorkCalendarService` over the + * calendar rows of each record's own organization. + * + * Pinned: + * - a formula field (`find`, `findOne`, the write response) counts over a + * weekend, a National Day week and a 调休 make-up Saturday, with the + * organization default and with a calendar named by code; + * - each row counts with its own organization's calendar; + * - a calendar refusal (D8: not maintained; D2: no default) reads `null` and + * logs ONE line naming the object, the field and the refusal — never a + * count on the weekly pattern or the wall clock; + * - a computed (stored) `datetime` field — the D6 write-time column — stores + * the count, and stores blank when the count is refused, the write itself + * going through (open point 1, the decision this card's contract review + * rules on); + * - the read counts through the service's cache, and sees an edit once the + * cache is dropped (as a calendar or exception write drops it); + * - a formula that calls none of the three reads no calendar at all. + */ +import { beforeEach, describe, expect, it } from 'vitest'; +import { WorkCalendarService } from './work-calendar-service.js'; +import { setFormulaWorkCalendarService } from './formula-work-calendars.js'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQL } from './engine.js'; +import { ObjectQLPlugin } from './plugin.js'; + +type Rec = Record; + +function makeRecordingLogger() { + const warns: Array<{ message: string; meta: Rec | undefined }> = []; + const l: any = { + trace() {}, debug() {}, info() {}, error() {}, fatal() {}, + warn(message: string, meta?: Rec) { warns.push({ message: String(message), meta }); }, + child() { return l; }, + }; + return { logger: l, warns }; +} + +/** Rows keyed by object; shallow COPIES out. Equality filters only; counts every `find`. */ +function makeStubDriver() { + const stores = new Map>(); + const finds: string[] = []; + const projections: Array<{ object: string; fields: string[] }> = []; + const storeFor = (obj: string) => { + let s = stores.get(obj); + if (!s) { s = new Map(); stores.set(obj, s); } + return s; + }; + let nextId = 0; + const matches = (row: Rec, where: unknown): boolean => { + if (!where || typeof where !== 'object') return true; + for (const [k, v] of Object.entries(where as Rec)) { + if (k.startsWith('$')) continue; + const expected = (v && typeof v === 'object' && '$eq' in (v as Rec)) ? (v as Rec).$eq : v; + if ((row[k] ?? null) !== (expected ?? null)) return false; + } + return true; + }; + const driver = { + name: 'memory', version: '0.0.0', supports: {}, + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, + // A projection is honoured as a driver honours it: only the named columns come back. + async find(object: string, ast: { where?: unknown; limit?: number; fields?: string[] }) { + finds.push(object); + if (Array.isArray(ast?.fields)) projections.push({ object, fields: [...ast.fields] }); + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; + const pick = (r: Rec): Rec => Array.isArray(ast?.fields) + ? Object.fromEntries(ast.fields.filter((f) => f in r).map((f) => [f, r[f]])) + : { ...r }; + return page.map(pick); + }, + async findOne(object: string, ast: { where?: unknown }) { + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; + return null; + }, + async create(object: string, data: Rec) { + nextId += 1; + const id = (data.id as string) ?? `r_${nextId}`; + const row: Rec = { ...data, id }; + storeFor(object).set(id, row); + return { ...row }; + }, + async update(object: string, id: string, data: Rec) { + const s = storeFor(object); + const cur = s.get(id); + if (!cur) return null; + const updated = { ...cur, ...data, id }; + s.set(id, updated); + return { ...updated }; + }, + async updateMany() { return 0; }, + async upsert(object: string, data: Rec) { return this.create(object, data); }, + async delete(object: string, id: string) { return storeFor(object).delete(id); }, + async count(object: string, ast: { where?: unknown }) { return (await this.find(object, ast)).length; }, + async bulkCreate(object: string, rows: Rec[]) { return Promise.all(rows.map((r) => this.create(object, r))); }, + async bulkUpdate() { return []; }, + async bulkDelete() {}, + async beginTransaction() { return { commit: async () => {}, rollback: async () => {} }; }, + async commit() {}, + async rollback() {}, + }; + return { driver, storeFor, finds, projections }; +} + +const text = (name: string) => ({ name, label: name, type: 'text' as const }); +const PERIOD_FIELDS = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'] + .map((d) => `${d}_periods`); + +/** The two calendar objects, as far as the service reads them. */ +const SYS_WORK_CALENDAR = { + name: 'sys_work_calendar', + label: 'Working Calendar', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true }, + organization_id: text('organization_id'), + code: text('code'), + timezone: text('timezone'), + is_default: { name: 'is_default', label: 'Default', type: 'boolean' as const }, + maintained_from: { name: 'maintained_from', label: 'From', type: 'date' as const }, + maintained_through: { name: 'maintained_through', label: 'Through', type: 'date' as const }, + ...Object.fromEntries(PERIOD_FIELDS.map((f) => [f, text(f)])), + }, +}; +const SYS_WORK_CALENDAR_EXCEPTION = { + name: 'sys_work_calendar_exception', + label: 'Calendar Exception', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true }, + calendar: text('calendar'), + date: { name: 'date', label: 'Date', type: 'date' as const }, + kind: text('kind'), + periods: text('periods'), + }, +}; + +const cel = (source: string) => ({ dialect: 'cel', source }); +/** A case object: formula fields over a start day and an opened instant, and one stored due time. */ +const WD_CASE = { + name: 'wd_case', + label: 'Case', + fields: { + id: { name: 'id', label: 'ID', type: 'text' as const, primaryKey: true }, + // The column a tenant-scoped object is served with: the row's own organization. + organization_id: text('organization_id'), + start: { name: 'start', label: 'Start', type: 'date' as const }, + opened_at: { name: 'opened_at', label: 'Opened', type: 'datetime' as const }, + due_day: { name: 'due_day', label: 'Due Day', type: 'formula' as const, expression: cel('addWorkingDays(record.start, 3)') }, + due_day_weekly: { + name: 'due_day_weekly', label: 'Due Day (weekly only)', type: 'formula' as const, + expression: cel("addWorkingDays(record.start, 3, 'weekly_only')"), + }, + days_left: { + name: 'days_left', label: 'Days Left', type: 'formula' as const, + expression: cel("workingDaysBetween(record.start, '2026-10-10')"), + }, + due_at_read: { name: 'due_at_read', label: 'Due (read)', type: 'formula' as const, expression: cel('addWorkingHours(record.opened_at, 2)') }, + // ADR-0157 D6: the write-time column a filter can compare with {now}. + due_at: { name: 'due_at', label: 'Due At', type: 'datetime' as const, expression: cel('addWorkingHours(record.opened_at, 2)') }, + plain: { name: 'plain', label: 'Plain', type: 'formula' as const, expression: cel('addDays(record.start, 1)') }, + }, +}; + +const WEEKDAY = '09:00-12:00, 13:00-18:00'; +const weekdays = { monday_periods: WEEKDAY, tuesday_periods: WEEKDAY, wednesday_periods: WEEKDAY, thursday_periods: WEEKDAY, friday_periods: WEEKDAY }; +const calendarRow = (id: string, organization: string, code: string, isDefault: boolean, timezone = 'Asia/Shanghai'): Rec => ({ + id, organization_id: organization, code, timezone, is_default: isDefault, + maintained_from: '2026-01-01', maintained_through: '2026-12-31', ...weekdays, +}); +/** Shanghai wall clock → instant (UTC+8, no DST). */ +const sh = (day: string, hm: string) => new Date(`${day}T${hm}:00+08:00`).toISOString(); +const iso = (v: unknown) => (v instanceof Date ? v.toISOString() : v); + +async function makeRig(options: { defaultInOrgB?: boolean } = {}) { + const { logger, warns } = makeRecordingLogger(); + const engine = new ObjectQL({ logger }); + const { driver, storeFor, finds, projections } = makeStubDriver(); + engine.registerDriver(driver as never, true); + await engine.init(); + for (const obj of [SYS_WORK_CALENDAR, SYS_WORK_CALENDAR_EXCEPTION, WD_CASE]) engine.registry.registerObject(obj as never, 'test'); + const service = new WorkCalendarService({ + // The tenant wall the security plugin applies in a kernel: the service's + // elevated read under `tenantId` sees that organization's calendars only. + getEngine: () => ({ + find: async (object: string, query: Record) => { + const tenant = (query.context as { tenantId?: string } | undefined)?.tenantId; + const rows = await engine.find(object, query as never) as Rec[]; + return tenant === undefined ? rows : rows.filter((r) => r.organization_id === undefined || r.organization_id === tenant); + }, + }), + hasCalendarObject: () => Boolean(engine.registry.getObject('sys_work_calendar')), + posture: () => 'isolated', + }); + setFormulaWorkCalendarService(engine, service); + // org_a: a CN default calendar with a National Day week and a 调休 make-up + // Saturday, and the same weekly pattern with no exceptions under another code. + const cals = storeFor('sys_work_calendar'); + cals.set('cal_cn', calendarRow('cal_cn', 'org_a', 'cn_mainland', true)); + cals.set('cal_weekly', calendarRow('cal_weekly', 'org_a', 'weekly_only', false)); + // org_b: its default counts in New York, with no exceptions. + if (options.defaultInOrgB !== false) cals.set('cal_b', calendarRow('cal_b', 'org_b', 'us_office', true, 'America/New_York')); + const exceptions = storeFor('sys_work_calendar_exception'); + ['01', '02', '03', '04', '05', '06', '07'].forEach((d) => { + exceptions.set(`ex_${d}`, { id: `ex_${d}`, organization_id: 'org_a', calendar: 'cal_cn', date: `2026-10-${d}`, kind: 'off', periods: null }); + }); + exceptions.set('ex_10', { id: 'ex_10', organization_id: 'org_a', calendar: 'cal_cn', date: '2026-10-10', kind: 'on', periods: WEEKDAY }); + const faultLines = (field: string) => warns.filter((w) => w.meta?.object === 'wd_case' && w.meta?.field === field); + return { engine, service, storeFor, finds, projections, warns, faultLines }; +} + +type Rig = Awaited>; + +describe('ADR-0157 D4 — working-day formula fields count with the organization calendar', () => { + let rig: Rig; + beforeEach(async () => { rig = await makeRig(); }); + + it('a read steps over the National Day week and onto the 调休 Saturday; the weekly-only calendar does not (CONTROL)', async () => { + rig.storeFor('wd_case').set('c1', { id: 'c1', organization_id: 'org_a', start: '2026-09-30', opened_at: sh('2026-09-30', '17:00') }); + const [row] = await rig.engine.find('wd_case', {} as never) as Rec[]; + expect(iso(row!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + expect(iso(row!.due_day_weekly)).toBe('2026-10-05T00:00:00.000Z'); + expect(row!.days_left).toBe(3); + expect(iso(row!.due_at_read)).toBe(sh('2026-10-08', '10:00')); + expect(rig.warns, JSON.stringify(rig.warns)).toEqual([]); + }); + + it('a weekend: Friday + 3 working days is Wednesday, on findOne too', async () => { + rig.storeFor('wd_case').set('c2', { id: 'c2', organization_id: 'org_a', start: '2026-09-18' }); + const row = await rig.engine.findOne('wd_case', { where: { id: 'c2' } } as never) as Rec; + expect(iso(row.due_day)).toBe('2026-09-23T00:00:00.000Z'); + }); + + it("each row counts with its own organization's default calendar", async () => { + rig.storeFor('wd_case').set('ca', { id: 'ca', organization_id: 'org_a', start: '2026-09-30' }); + rig.storeFor('wd_case').set('cb', { id: 'cb', organization_id: 'org_b', start: '2026-09-30' }); + const rows = await rig.engine.find('wd_case', {} as never) as Rec[]; + const byId = Object.fromEntries(rows.map((r) => [r.id, r])); + expect(iso(byId.ca!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + // org_b keeps no National Day: Wednesday + 3 = Monday. + expect(iso(byId.cb!.due_day)).toBe('2026-10-05T00:00:00.000Z'); + }); + + it('a projection that leaves organization_id out still counts each row in its own organization', async () => { + // A read across organizations names no tenant, so the row's own column is + // the only organization there is: the formula projection widens to every + // stored column, organization_id included, and cuts it back off the answer. + rig.storeFor('wd_case').set('ca', { id: 'ca', organization_id: 'org_a', start: '2026-09-30' }); + rig.storeFor('wd_case').set('cb', { id: 'cb', organization_id: 'org_b', start: '2026-09-30' }); + const rows = await rig.engine.find('wd_case', { fields: ['id', 'due_day'] } as never) as Rec[]; + const byId = Object.fromEntries(rows.map((r) => [r.id, r])); + expect(iso(byId.ca!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + expect(iso(byId.cb!.due_day)).toBe('2026-10-05T00:00:00.000Z'); + expect(byId.ca).not.toHaveProperty('organization_id'); + // The driver was asked for the column: the row named its organization. + expect(rig.projections.find((p) => p.object === 'wd_case')?.fields).toContain('organization_id'); + }); + + it('the write response counts too', async () => { + const created = await rig.engine.insert('wd_case', { organization_id: 'org_a', start: '2026-09-30' }) as Rec; + expect(iso(created.due_day)).toBe('2026-10-10T00:00:00.000Z'); + }); +}); + +describe('ADR-0157 D8 — a refused count reads null and says so once', () => { + it('past maintained_through: null, and one line naming the object, the field and the refusal', async () => { + const rig = await makeRig(); + rig.storeFor('wd_case').set('late', { id: 'late', organization_id: 'org_a', start: '2026-12-30' }); + rig.storeFor('wd_case').set('late2', { id: 'late2', organization_id: 'org_a', start: '2026-12-29' }); + const rows = await rig.engine.find('wd_case', {} as never) as Rec[]; + for (const row of rows) expect(row.due_day).toBeNull(); + const lines = rig.faultLines('due_day'); + expect(lines).toHaveLength(1); + expect(String(lines[0]!.meta?.error)).toContain("Working calendar 'cn_mainland' is maintained from 2026-01-01 through 2026-12-31"); + // The formula that calls none of the three still evaluates (CONTROL). + expect(iso(rows[0]!.plain)).toBe('2026-12-31T00:00:00.000Z'); + }); + + it('no default calendar in the organization: null and the no-default refusal, never a wall-clock count', async () => { + const rig = await makeRig({ defaultInOrgB: false }); + rig.storeFor('wd_case').set('cb', { id: 'cb', organization_id: 'org_b', start: '2026-09-30' }); + const [row] = await rig.engine.find('wd_case', {} as never) as Rec[]; + expect(row!.due_day).toBeNull(); + expect(String(rig.faultLines('due_day')[0]?.meta?.error)).toContain('No working calendar is marked as the default'); + }); + + it('a kernel with no calendar service refuses the same way', async () => { + const rig = await makeRig(); + setFormulaWorkCalendarService(rig.engine, undefined); + rig.storeFor('wd_case').set('c1', { id: 'c1', organization_id: 'org_a', start: '2026-09-30' }); + const [row] = await rig.engine.find('wd_case', {} as never) as Rec[]; + expect(row!.due_day).toBeNull(); + expect(String(rig.faultLines('due_day')[0]?.meta?.error)).toContain('No working calendar is marked as the default'); + }); +}); + +describe('ADR-0157 D6, open point 1 — the write-time due column', () => { + it('stores the count on the write, so a filter compares a stored datetime', async () => { + const rig = await makeRig(); + const created = await rig.engine.insert('wd_case', { organization_id: 'org_a', opened_at: sh('2026-10-09', '17:00') }) as Rec; + const stored = rig.storeFor('wd_case').get(String(created.id))!; + expect(iso(stored.due_at)).toBe(sh('2026-10-10', '10:00')); + }); + + it('a refused count stores blank and the write goes through, with one line naming the field', async () => { + const rig = await makeRig(); + const created = await rig.engine.insert('wd_case', { organization_id: 'org_a', opened_at: sh('2026-12-31', '17:00') }) as Rec; + const stored = rig.storeFor('wd_case').get(String(created.id))!; + expect(stored).toBeDefined(); + expect(stored.due_at ?? null).toBeNull(); + expect(String(rig.faultLines('due_at')[0]?.meta?.error)).toContain('maintained from 2026-01-01 through 2026-12-31'); + }); +}); + +describe('ADR-0157 D2 — the read counts through the service cache', () => { + it('serves the cached calendar until the cache is dropped, then reads the edit', async () => { + const rig = await makeRig(); + rig.storeFor('wd_case').set('c1', { id: 'c1', organization_id: 'org_a', start: '2026-09-30' }); + expect(iso(((await rig.engine.find('wd_case', {} as never)) as Rec[])[0]!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + // An administrator adds a holiday on 2026-10-08, straight into the store. + rig.storeFor('sys_work_calendar_exception').set('ex_08', { + id: 'ex_08', organization_id: 'org_a', calendar: 'cal_cn', date: '2026-10-08', kind: 'off', periods: null, + }); + expect(iso(((await rig.engine.find('wd_case', {} as never)) as Rec[])[0]!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + // A calendar or exception write drops the cache (the service's write hooks). + rig.service.invalidate(); + expect(iso(((await rig.engine.find('wd_case', {} as never)) as Rec[])[0]!.due_day)).toBe('2026-10-12T00:00:00.000Z'); + }); + + it('a plan that calls none of the three reads no calendar', async () => { + const rig = await makeRig(); + rig.storeFor('wd_case').set('c1', { id: 'c1', organization_id: 'org_a', start: '2026-09-30' }); + await rig.engine.find('wd_case', { fields: ['id', 'plain'] } as never); + expect(rig.finds.filter((o) => o.startsWith('sys_work_calendar'))).toEqual([]); + }); +}); + +describe('ADR-0157 D4 — booted through ObjectQLPlugin, the formula reads the kernel calendar service', () => { + it("the plugin installs its calendar service for the engine the formula paths reach through their host's facade", async () => { + const { logger } = makeRecordingLogger(); + const engine = new ObjectQL({ logger }); + const { driver, storeFor } = makeStubDriver(); + engine.registerDriver(driver as never, true); + for (const obj of [SYS_WORK_CALENDAR, SYS_WORK_CALENDAR_EXCEPTION, WD_CASE]) engine.registry.registerObject(obj as never, 'test'); + storeFor('sys_work_calendar').set('cal_cn', calendarRow('cal_cn', 'org_a', 'cn_mainland', true)); + ['01', '02', '03', '04', '05', '06', '07'].forEach((d) => { + storeFor('sys_work_calendar_exception').set(`ex_${d}`, { id: `ex_${d}`, organization_id: 'org_a', calendar: 'cal_cn', date: `2026-10-${d}`, kind: 'off', periods: null }); + }); + storeFor('sys_work_calendar_exception').set('ex_10', { id: 'ex_10', organization_id: 'org_a', calendar: 'cal_cn', date: '2026-10-10', kind: 'on', periods: WEEKDAY }); + storeFor('wd_case').set('c1', { id: 'c1', organization_id: 'org_a', start: '2026-09-30' }); + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); + try { + await kernel.use(new ObjectQLPlugin({ ql: engine })); + await kernel.bootstrap(); + expect(kernel.getService('objectql')).toBe(engine); + const [row] = await engine.find('wd_case', {} as never) as Rec[]; + // Counted on the kernel's own service: over the National Day week onto the 调休 Saturday. + expect(iso(row!.due_day)).toBe('2026-10-10T00:00:00.000Z'); + } finally { + if (kernel.getState() === 'running') await kernel.shutdown(); + } + }); +}); diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 4aaa6e22c5f..c54c7bbc347 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -35,6 +35,7 @@ * this module. */ +import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import type { DataEngineInsertOptions, EngineCountOptions, EngineQueryOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import type { PendingSecretRow } from './engine-secret-internal-fields.js'; @@ -569,6 +570,7 @@ export class InsertFacet { onFault: this.formulaFaultSink(object), relatedFor: (plan, records) => this.resolveFormulaRelated(this._registry.getObject(object), plan, records, opCtx.context), optionLabelsFor: (plan) => declaredOptionLabels(this._registry.getObject(object), plan), + workCalendarsFor: (plan, records) => formulaWorkCalendarsFor(this.facade, plan, records, opCtx.context), }; if (storedExpressionPlan.length > 0) { const defaultedRows = (isBatch ? defaultedData : [defaultedData]) as Array>; @@ -1652,6 +1654,7 @@ export class InsertFacet { (plan, records) => this.resolveFormulaRelated(schemaForValidation, plan, records, opCtx.context), // [#26608] The 201 body is what the save toast names the record from. (plan) => this.formulaOptionLabels(schemaForValidation, plan, opCtx.context), + (plan, records) => formulaWorkCalendarsFor(this.facade, plan, records, opCtx.context), ); for (let k = 0; k < liveIndexes.length; k++) { const rowCtx = rowHookContexts[liveIndexes[k]]; diff --git a/packages/objectql/src/engine-security-resolvers.ts b/packages/objectql/src/engine-security-resolvers.ts index 3eb5431cf7d..3e3367bdc92 100644 --- a/packages/objectql/src/engine-security-resolvers.ts +++ b/packages/objectql/src/engine-security-resolvers.ts @@ -35,6 +35,7 @@ * evaluation cycle. `index.ts` re-exports nothing from this module. */ +import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import { isPlannedRelationLeaf } from './relation-semi-join.js'; import { referenceTargetOf } from '@objectstack/spec/data'; import type { EngineQueryOptions, QueryAST } from '@objectstack/spec/data'; @@ -384,7 +385,7 @@ export class SecurityResolversFacet { } /** The body of `ObjectQL#serveFormulaField`; the method's docblock there is its contract. */ - static async serveFormulaField(this: Pick, objectName: string, record: Record, field: string, context?: ExecutionContext): Promise { + static async serveFormulaField(this: Pick, objectName: string, record: Record, field: string, context?: ExecutionContext): Promise { const schema = this._registry.getObject(objectName); const { plan } = planFormulaProjection(schema, [field]); if (plan.length === 0) return undefined; @@ -392,12 +393,12 @@ export class SecurityResolversFacet { applyFormulaPlan(plan, [scratch], context, await this.resolveFormulaPermissions( objectName, plan, [scratch], context, this.permissionResolution(context), ), this.formulaFaultSink(objectName), await this.resolveFormulaRelated(schema, plan, [scratch], context), - this.formulaOptionLabels(schema, plan, context)); + this.formulaOptionLabels(schema, plan, context), await formulaWorkCalendarsFor(this.facade, plan, [scratch], context)); return scratch[field]; } /** The body of `ObjectQL#computeStoredExpressionsOver` (#29961); the method's docblock there is its contract. */ - static async computeStoredExpressionsOver(this: Pick, object: string, rows: ReadonlyArray>, context?: ExecutionContext, onFault?: (field: string, message: string) => void): Promise>> { + static async computeStoredExpressionsOver(this: Pick, object: string, rows: ReadonlyArray>, context?: ExecutionContext, onFault?: (field: string, message: string) => void): Promise>> { const schema = this._registry.getObject(object); const resolution = this.permissionResolution(context); return computeStoredExpressions(planStoredExpressions(schema), rows, context, { @@ -405,6 +406,7 @@ export class SecurityResolversFacet { onFault: onFault ? (field, error) => onFault(field, error.message) : this.formulaFaultSink(object), relatedFor: (plan, records) => this.resolveFormulaRelated(schema, plan, records, context), optionLabelsFor: (plan) => declaredOptionLabels(schema, plan), + workCalendarsFor: (plan, records) => formulaWorkCalendarsFor(this.facade, plan, records, context), }); } diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index 8391e87068d..8b4ca293631 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -37,6 +37,7 @@ import { SEARCHABLE_ENUM_TYPES, SEARCHABLE_TEXTUAL_TYPES } from './search-filter import { ExpressionEngine, analyzeRelationshipTraversals, formulaReadOrder, isUnparseableDate } from '@objectstack/formula'; import type { EvalError, EvalOptionLabels, EvalPermissions } from '@objectstack/formula'; import { declaredOptionLabels, planCallsOptionLabel } from './formula-option-labels.js'; +import { planWorkCalendarNeeds, type FormulaWorkCalendars } from './formula-work-calendars.js'; import { ASSEMBLED_VIEW_ITEMS_KEY, AssembledViewArtifactSchema, isAggregatedViewContainer, isViewContainerShaped } from '@objectstack/spec'; import type { Expression } from '@objectstack/spec'; import { deriveViewContainerObject } from '@objectstack/metadata/view-container'; @@ -3023,6 +3024,14 @@ function applyFormulaPlan( * when no formula of the plan calls `label()`. */ optionLabels?: EvalOptionLabels, + /** + * [ADR-0157 D4] What the working-day functions count with: each row's + * organization's calendars, resolved once per call by + * `formulaWorkCalendarsFor` (`formula-work-calendars.ts`). `undefined` when no formula + * of the plan calls one, or where no resolution runs (a synchronous + * evaluation), where such a formula then reads `null` and says why. + */ + workCalendars?: FormulaWorkCalendars, ): void { if (!plan.length) return; const now = new Date(); @@ -3058,7 +3067,9 @@ function applyFormulaPlan( scope = hop.record; empty = hop.empty; } - const evaluated = ExpressionEngine.evaluate(fp.expression, { now, timezone, user, org, permissions, optionLabels, record: scope }); + const evaluated = ExpressionEngine.evaluate(fp.expression, { + now, timezone, user, org, permissions, optionLabels, workCalendars: workCalendars?.(rec), record: scope, + }); // An invalid Date minted from text `date()` could not parse evaluates // `ok` (a predicate relies on that) but serializes to the `null` an empty // source gives: for a field it is a fault, said like any other. @@ -3138,6 +3149,8 @@ async function hydrateWriteFormulas( relatedFor?: (plan: FormulaPlanEntry[], records: ReadonlyArray>) => Promise, /** [#26608] The option labels `label()` reads, in the writer's locale — the reader of this response. */ optionLabelsFor?: (plan: FormulaPlanEntry[]) => EvalOptionLabels | undefined, + /** [ADR-0157 D4] The calendars the working-day functions count with, resolved over `records`. */ + workCalendarsFor?: (plan: FormulaPlanEntry[], records: ReadonlyArray>) => Promise, ): Promise { const records = results.filter( (r): r is Record => r != null && typeof r === 'object', @@ -3147,7 +3160,7 @@ async function hydrateWriteFormulas( if (plan.length === 0) return; applyFormulaPlan( plan, records, execCtx, await permissionsFor(plan, records), onFault, await relatedFor?.(plan, records), - optionLabelsFor?.(plan), + optionLabelsFor?.(plan), await workCalendarsFor?.(plan, records), ); } @@ -3241,6 +3254,10 @@ function unservableReason( return { reason: `reads through ${[...entry.hops.keys()].map((f) => `'${f}'`).join(', ')}, a reference the write path does not follow` }; } if (planCallsOptionLabel([entry])) return { reason: 'calls label(), which the write path does not answer' }; + // [ADR-0157 D4] The validator's formula values resolve no working calendar. + if (planWorkCalendarNeeds([entry])) { + return { reason: 'calls a working-day function, which counts with a working calendar the write path does not load' }; + } if (!permissions && readsPermissionPredicate(entry.expression)) { return { reason: 'calls current_user.can(), and this write resolved no permission map' }; } @@ -3356,6 +3373,14 @@ interface StoredExpressionServing { * every later reader and by search, so it never depends on the writer's locale. */ optionLabelsFor?: (plan: FormulaPlanEntry[]) => EvalOptionLabels | undefined; + /** + * [ADR-0157 D4, open point 1] The calendars the working-day functions count + * with, resolved over the images in each one's organization. A calendar + * refusal (D8) stores the field blank, as any expression that does not + * evaluate does, with the fault reported once through `onFault`; the write + * itself goes through. + */ + workCalendarsFor?: (plan: FormulaPlanEntry[], records: ReadonlyArray>) => Promise; } /** @@ -3377,7 +3402,7 @@ async function computeStoredExpressions( const scratch = images.map((image) => ({ ...image })); applyFormulaPlan( plan, scratch, execCtx, await serving.permissionsFor(plan, scratch), serving.onFault, - await serving.relatedFor?.(plan, scratch), serving.optionLabelsFor?.(plan), + await serving.relatedFor?.(plan, scratch), serving.optionLabelsFor?.(plan), await serving.workCalendarsFor?.(plan, scratch), ); return scratch.map((row) => { const values: Record = {}; diff --git a/packages/objectql/src/engine-update.ts b/packages/objectql/src/engine-update.ts index 0eec7a84db7..7bce63aff11 100644 --- a/packages/objectql/src/engine-update.ts +++ b/packages/objectql/src/engine-update.ts @@ -32,6 +32,7 @@ * this module. */ +import { formulaWorkCalendarsFor } from './formula-work-calendars.js'; import type { DroppedFieldsEvent, EngineUpdateOptions, HookContext, QueryAST } from '@objectstack/spec/data'; import type { WriteObservabilityOptions } from '@objectstack/spec/contracts'; import { collectComposableReadableIds } from './filter-comparand-shape.js'; @@ -564,6 +565,7 @@ export class UpdateFacet { onFault: this.formulaFaultSink(object), relatedFor: (plan, records) => this.resolveFormulaRelated(updateSchema, plan, records, opCtx.context), optionLabelsFor: (plan) => declaredOptionLabels(updateSchema, plan), + workCalendarsFor: (plan, records) => formulaWorkCalendarsFor(this.facade, plan, records, opCtx.context), }; const undeclared = undeclaredWriteFieldErrors( object, @@ -2342,6 +2344,7 @@ export class UpdateFacet { this.formulaFaultSink(object), (plan, records) => this.resolveFormulaRelated(updateSchema, plan, records, opCtx.context), (plan) => this.formulaOptionLabels(updateSchema, plan, opCtx.context), + (plan, records) => formulaWorkCalendarsFor(this.facade, plan, records, opCtx.context), ); } // Coerce boolean fields (SQLite 0/1 → JS bool) on the after-hook view @@ -2611,6 +2614,7 @@ export async function loadSummaryFoldDependents( related: Awaited>; storedLabels: ReturnType; formulaLabels: ReturnType; + calendars: Awaited>; }>(); const systemCtx = { ...(context ?? {}), isSystem: true } as typeof context; const systemResolution = host.permissionResolution(systemCtx); @@ -2642,6 +2646,7 @@ export async function loadSummaryFoldDependents( related: await host.resolveFormulaRelated(schema, plan, storedRows, systemCtx), storedLabels: declaredOptionLabels(schema, storedPlan), formulaLabels: host.formulaOptionLabels(schema, formulaPlan, systemCtx), + calendars: await formulaWorkCalendarsFor(host.facade, plan, storedRows, systemCtx), }); } type Served = NonNullable>; @@ -2651,7 +2656,7 @@ export async function loadSummaryFoldDependents( for (const name of entry.formulaFields) delete scratch[name]; // Twice, as the write computes them: before its hooks, then over the row with the moved values. for (let pass = 0; pass < 2 && entry.storedPlan.length > 0; pass += 1) { - applyFormulaPlan(entry.storedPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.storedLabels); + applyFormulaPlan(entry.storedPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.storedLabels, entry.calendars); } return scratch; }; @@ -2667,7 +2672,7 @@ export async function loadSummaryFoldDependents( const scratch = image ? { ...image, ...moved } : written(entry, stored, moved); // The read's row: the formulas the plan does not recompute back at their stored values. for (const name of entry.unplannedFormulas) if (name in stored) scratch[name] = stored[name]; - if (entry.formulaPlan.length > 0) applyFormulaPlan(entry.formulaPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.formulaLabels); + if (entry.formulaPlan.length > 0) applyFormulaPlan(entry.formulaPlan, [scratch], systemCtx, entry.permissions, undefined, entry.related, entry.formulaLabels, entry.calendars); const values: Record = {}; for (const step of [...entry.storedPlan, ...entry.formulaPlan]) values[step.name] = scratch[step.name]; return values; diff --git a/packages/objectql/src/formula-work-calendars.ts b/packages/objectql/src/formula-work-calendars.ts new file mode 100644 index 00000000000..83777b28942 --- /dev/null +++ b/packages/objectql/src/formula-work-calendars.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * # The working calendars a formula's working-day functions count with (ADR-0157 D2, D4, D8) + * + * `addWorkingDays()`, `workingDaysBetween()` and `addWorkingHours()` + * (`@objectstack/formula`) compute synchronously over the calendars an + * evaluation is handed (`EvalContext.workCalendars`); the calendar service + * (`WorkCalendarService`, `work-calendar-service.ts`) resolves asynchronously. + * This module is where the engine resolves, before a formula plan is + * evaluated, exactly the calendars the plan's expressions name + * (`workingDayCalendarNeeds`: the organization default for a call with no + * code, and each code a call spells as a quoted literal). + * + * ## In which organization (open point 4) + * + * The record's own: `organization_id` on the row, else the read's tenant + * (`ExecutionContext.tenantId`, the organization a row read under a wall + * belongs to when its projection left the column out). The service refuses a + * computation that names no organization outside the `single` posture, so a + * system read across organizations that names none gets that refusal, never a + * calendar of whichever organization holds one. + * + * A projection never decides it: a read that names fields and a formula + * widens to every stored column the object declares (`planFormulaProjection`), + * `organization_id` included, and cuts the widening back off the answer, so a + * row reads the same with `fields: ['id', 'due']` as with no projection. + * + * ## The cache, and a calendar edit + * + * The service's own (one entry per organization and code, dropped on every + * calendar or exception write on this node, at most its TTL elsewhere): this + * module keeps nothing between evaluations. A refusal is never cached there, + * so the read after an administrator's fix counts. + * + * ## Where the service is held + * + * Beside the engine, not on it: the plugin installs the kernel's service + * ({@link setFormulaWorkCalendarService}) and each formula path reaches it + * through its host's `facade` ({@link formulaWorkCalendarsFor}), so the + * engine facade gains no member for it. + * + * ## A refusal is data + * + * A calendar that did not resolve is handed to the evaluation as its refusal, + * which the function throws: the formula reads blank, and the engine logs one + * line naming the object, the field and the refusal (D8) through its formula + * fault sink. A kernel without the calendar service holds no calendar, and + * refuses as the service refuses then. + */ + +import type { WorkCalendarRef } from '@objectstack/spec/contracts'; +import type { WorkCalendar } from '@objectstack/spec/data'; +import { + WorkCalendarUnresolvedError, + workingDayCalendarNeeds, + type EvalWorkCalendar, + type EvalWorkCalendars, +} from '@objectstack/formula'; + +/** The slice of the calendar service this module reads. */ +export interface FormulaWorkCalendarResolver { + resolve(ref: WorkCalendarRef): Promise; +} + +/** The calendars of one row's organization, or `undefined` when the plan calls no working-day function. */ +export type FormulaWorkCalendars = (row: Record) => EvalWorkCalendars | undefined; + +/** The slice of a formula plan entry this module reads: its expression. */ +interface PlannedExpression { + readonly expression: unknown; +} + +function sourceOf(expression: unknown): string | undefined { + const expr = expression as { source?: unknown; dialect?: unknown } | string | undefined; + if (typeof expr === 'string') return expr; + if (expr && typeof expr === 'object' && (expr.dialect === undefined || expr.dialect === 'cel')) { + return typeof expr.source === 'string' ? expr.source : undefined; + } + return undefined; +} + +/** The union of the calendars every entry of `plan` names, or `undefined` when none calls a working-day function. */ +export function planWorkCalendarNeeds( + plan: ReadonlyArray, +): { default: boolean; codes: string[] } | undefined { + let any = false; + let usesDefault = false; + const codes: string[] = []; + for (const entry of plan) { + const needs = workingDayCalendarNeeds(sourceOf(entry.expression)); + if (!needs) continue; + any = true; + if (needs.default) usesDefault = true; + for (const code of needs.codes) if (!codes.includes(code)) codes.push(code); + } + return any ? { default: usesDefault, codes } : undefined; +} + +function organizationOf(value: unknown): string | undefined { + return value === undefined || value === null || value === '' ? undefined : String(value); +} + +/** One resolution, settled: the calendar, or the refusal it met, as data. */ +async function settle(service: FormulaWorkCalendarResolver | undefined, ref: WorkCalendarRef): Promise { + const code = typeof ref.calendar === 'string' ? ref.calendar : undefined; + // A kernel without the service holds no calendar: the service's own refusal then. + if (!service) return new WorkCalendarUnresolvedError(code === undefined ? 'no_default' : 'not_found', code); + try { + return await service.resolve(ref); + } catch (err) { + return err instanceof Error ? err : new Error(String(err)); + } +} + +/** + * Resolve the calendars `plan` names for each organization `rows` belong to, + * and answer each row's binding. `undefined` when no entry of `plan` calls a + * working-day function, so a read whose formulas call none pays one source + * scan per formula and nothing else. + */ +export async function resolveFormulaWorkCalendars( + service: FormulaWorkCalendarResolver | undefined, + plan: ReadonlyArray, + rows: ReadonlyArray | null | undefined>, + context: { tenantId?: unknown } | undefined, +): Promise { + const needs = planWorkCalendarNeeds(plan); + if (!needs) return undefined; + const fallback = organizationOf(context?.tenantId); + const orgOf = (row: Record | null | undefined): string | undefined => + organizationOf(row?.organization_id) ?? fallback; + const keyOf = (org: string | undefined) => org ?? ''; + const organizations = new Map(); + for (const row of rows) { + if (row == null) continue; + const org = orgOf(row); + organizations.set(keyOf(org), org); + } + if (organizations.size === 0) organizations.set(keyOf(fallback), fallback); + const bindings = new Map(); + await Promise.all([...organizations].map(async ([key, organizationId]) => { + const [defaultCalendar, ...named] = await Promise.all([ + needs.default ? settle(service, { organizationId }) : Promise.resolve(undefined), + ...needs.codes.map((calendar) => settle(service, { organizationId, calendar })), + ]); + const byCode: Record = {}; + needs.codes.forEach((code, i) => { byCode[code] = named[i]!; }); + bindings.set(key, defaultCalendar === undefined ? { byCode } : { default: defaultCalendar, byCode }); + })); + return (row) => bindings.get(keyOf(orgOf(row))); +} + +/** The calendar service each engine's working-day formulas count through, installed by the engine plugin. */ +const servicesByEngine = new WeakMap(); + +/** Install (or, with `undefined`, remove) the calendar service `engine`'s working-day formulas resolve through. */ +export function setFormulaWorkCalendarService(engine: object, service: FormulaWorkCalendarResolver | undefined): void { + if (service) servicesByEngine.set(engine, service); + else servicesByEngine.delete(engine); +} + +/** + * {@link resolveFormulaWorkCalendars} through the service installed for + * `engine` (the formula path's host `facade`); without one, every call refuses + * as a kernel without calendars does. + */ +export function formulaWorkCalendarsFor( + engine: object, + plan: ReadonlyArray, + rows: ReadonlyArray | null | undefined>, + context: { tenantId?: unknown } | undefined, +): Promise { + return resolveFormulaWorkCalendars(servicesByEngine.get(engine), plan, rows, context); +} diff --git a/packages/objectql/src/plugin.ts b/packages/objectql/src/plugin.ts index f2f2235fdfa..494776b097d 100644 --- a/packages/objectql/src/plugin.ts +++ b/packages/objectql/src/plugin.ts @@ -1,5 +1,6 @@ // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. +import { setFormulaWorkCalendarService } from './formula-work-calendars.js'; import { ObjectQL, SECURITY_SERVICE_SOURCE_SLOT, @@ -1667,6 +1668,10 @@ export class ObjectQLPlugin implements Plugin { // that leaves `timezone` out takes the organization's // `localization.timezone` from the same read. if (this.workCalendarService) { + // [ADR-0157 D4] The working-day formula functions resolve their + // calendars through the same service, so a formula and the + // approval clock count with one cache and one refusal. + setFormulaWorkCalendarService(this.ql, this.workCalendarService); installWorkCalendarHooks(this.ql as never, this.workCalendarService, { timezoneOf: async (organizationId) => (await readLocalization(organizationId))?.timezone, }, ctx.logger); diff --git a/packages/spec/scripts/lib/platform-catalog.ts b/packages/spec/scripts/lib/platform-catalog.ts index 23d1dd397f8..f49b173cb60 100644 --- a/packages/spec/scripts/lib/platform-catalog.ts +++ b/packages/spec/scripts/lib/platform-catalog.ts @@ -119,7 +119,7 @@ export const APP_FACING_OBJECT_GROUPS: readonly { readonly title: string; readon rows: [ { name: 'sys_exchange_rate', builds: 'an exchange-rate table', reach: '`currencyConfig.homeAmount` converts at write; Setup edits rates; data API' }, { name: 'sys_unit', builds: 'a unit table or picklist', reach: '`unitConfig` on a `number` field (`unitMode: \'fixed\'` with `unit`, `\'record\'` with `unitField`) or a `text` field (`\'code\'`); a stored code is standard (UN/ECE Rec 20: `KGM`, `H87`) or a row added here in Setup; data API, no delete' }, - { name: 'sys_work_calendar', builds: 'a business-hours calendar', reach: 'kept per organization in Setup; an approval\'s `escalation.clock: \'working_time\'` reads it; data API' }, + { name: 'sys_work_calendar', builds: 'a business-hours calendar', reach: 'kept per organization in Setup; an approval\'s `escalation.clock: \'working_time\'` and `addWorkingDays()`, `workingDaysBetween()`, `addWorkingHours()` read it; data API' }, { name: 'sys_work_calendar_exception', builds: 'a holiday table', reach: 'a calendar\'s holidays and make-up workdays, kept in Setup; data API' }, { name: 'sys_import_job', builds: 'a bulk-import job table', reach: '`POST /api/v1/data/OBJECT/import/jobs`; data API read' }, { name: 'sys_approval_request', builds: 'an approvals table', reach: 'a flow approval node opens it; `/api/v1/approvals` routes decide; data API read' }, @@ -204,11 +204,6 @@ export const PLANNED_ROWS: readonly { readonly concept: string; readonly state: state: 'contract accepted; a quantity shows and sums as a bare number', link: 'https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0158-units-of-measure-standard-unit-table-org-units-quantity-unit-declaration-base-quantity.md', }, - { - concept: 'Working-day formulas', - state: 'contract accepted; no formula reads a calendar yet', - link: 'https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0157-working-calendars-are-org-editable-runtime-data-resolved-by-code-or-refused.md', - }, ]; /** diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 582384924b7..c3bd8ab5f32 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -734,7 +734,20 @@ export const CEILINGS = new Map([ // bytes -> ceil(24030 / 4) = 6008; the ceiling moves +11, the measured // remainder only. Pinned AT the measurement. // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 20) / 4) == ceil(24030 / 4) - ['skills/objectstack-formula/SKILL.md', 6008], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997) + // #35356 (ADR-0157 D4), by the standing ruling 「A:先削重复,余额按实测提高」 + // (record 6513306068): the working-day functions paragraph, with the + // contract review's asks on PR #36796 (start excluded and end included, the + // refused sites, the blank-until-next-write consequence, and the PRIOR() and + // date `+ duration` sentences it found were not restatement). Paid first by + // deleting restatement IN THIS FILE: the "No date arithmetic" note folded + // into the table header it repeated, the Salesforce-flavor examples the + // translation table lists, and the ISBLANK() translation. Priced bytes + // against `main`'s 24016 (headroom 4): the changed lines remove 789 bytes and + // add 1130, so the LANDED priced text is 24357 bytes -> ceil(24357 / 4) = + // 6090; the ceiling moves +82, the measured remainder only. Pinned AT the + // measurement. + // ceil(($(wc -c < skills/objectstack-formula/SKILL.md) - 20) / 4) == ceil(24357 / 4) + ['skills/objectstack-formula/SKILL.md', 6090], // -53 (was 6055), then -5 A2′ (was 6002), then +11 (was 5997), then +82 (was 6008) ['skills/objectstack-i18n/SKILL.md', 6333], // -11 (was 6349), then -5 A2′ (was 6338) // 12705 -> 12984 (2026-08-31 app-repo-principles raise, see the block above). // The largest of the five and the frame the other four are read under: what an diff --git a/skills/objectstack-formula/SKILL.md b/skills/objectstack-formula/SKILL.md index 34b399fe47a..bf6be2469f3 100644 --- a/skills/objectstack-formula/SKILL.md +++ b/skills/objectstack-formula/SKILL.md @@ -178,11 +178,7 @@ tests: every entry resolves at runtime, and this table documents them all. > `isoDate(date(record.start_at))`, `date(record.start_date).getFullYear()`. > `+` with text and ordering against a text literal take the text as is. -> **No date arithmetic.** The build refuses `date + n` and `end - start`: a -> date or date-time mixed with a number, or minus another, reads `null`, and -> `today()` / `now()` minus a date field reads `{}`. - -| Want | Write — never bare `end - start`, `date + n`, `today() + 30` | +| Want | The build refuses `end - start`, `date + n`, `today() + 30` (they read `null` / `{}`); write | |:---|:---| | Inclusive span | `daysBetween(record.start_date, record.end_date) + 1` | | Shift a date | `daysFromNow(n)` / `addDays(d, n)` / `addMonths(d, n)` | @@ -190,6 +186,14 @@ tests: every entry resolves at runtime, and this table documents them all. | Hours between | `double((datetime(record.end_at) - datetime(record.start_at)).getMinutes()) / 60.0` | | Sub-day offset | `now() + duration("3h")` | +**Working days** (the organization's working calendar, holidays and make-up days included): +`addWorkingDays(d, n[, code])` is the day `n` working days after `d` (`d` not counted); +`workingDaysBetween(a, b[, code])` its inverse (`b` counted); `addWorkingHours(t, h[, code])` the +instant `h` working hours after `t`. No `code`: the default calendar; a `code` is a quoted literal. +Only in a formula or a stored field's `expression` (refused in rules, flows, defaults, seeds and +filters): to filter, store the due time in a `datetime` field. No default calendar, or a count past +its maintained span, reads null; a stored due time is then blank until the record's next write. + **Numbers** | Function | Returns | Notes | @@ -227,10 +231,8 @@ tests: every entry resolves at runtime, and this table documents them all. | `label(record.f)` | string | A select value's option label in the reader's locale: `'v' + string(record.version_no) + ' · ' + label(record.kind)` reads `v2 · 清稿` (zh-CN), `v2 · Clean` (en-US). Only `record.`; `''` for null or an empty selection. A multi-select (`multiple: true`) reads each selected label in stored order, joined with `, `. A stored (non-formula) field stores the declared label. Formula fields only: in a predicate (validation, visibility, hook) it faults, so compare the stored value | Plus CEL built-ins: `has(x)`, `size(x)`, `int(x)`, `string(x)`, `bool(x)`, -`double(x)`, `timestamp(s)`, `duration(s)`. `timestamp()` parses only a full -ISO instant, so over a `date` field (`YYYY-MM-DD`) the build refuses it -(`date-text-call`), `+ duration(…)` included; shift a date with -`isoDate(addDays(record.d, n))`. +`double(x)`, `timestamp(s)` (a full ISO instant only; over a `date` field write +`isoDate(addDays(record.d, n))`, never `+ duration(…)`), `duration(s)`. > Receiver methods (`s.split(',')`, > `list.map(...)`) are called on a value, never bare, and are not in this table; @@ -238,8 +240,7 @@ ISO instant, so over a `date` field (`YYYY-MM-DD`) the build refuses it > from the catalogue by an authoring decision — don't reach for them. An UNKNOWN > function — `PRIOR()`, a legacy `ISBLANK()`, a typo'd `isBlnk()` — **fails > `os build`** with a "no matching overload" type error, rather than silently -> no-op'ing the predicate at run time. Use `previous.x` (not `PRIOR()`), -> `isBlank()` (not `ISBLANK()`). +> no-op'ing the predicate at run time. Use `previous.x`, not `PRIOR()`; more in the table below. --- @@ -291,14 +292,7 @@ P`!isBlank(record.po_number)`; ``` Conditional requiredness: [objectstack-data](../objectstack-data/SKILL.md#conditional-field-rules). - -❌ Salesforce-flavor — **fails CEL compile**: - -```ts -"status = 'qualified'" -"amount > 10000 AND region IN ('us', 'eu')" -"NOT(ISBLANK(po_number))" -``` +Salesforce-flavor (`AND`, `IN (…)`, `NOT(ISBLANK(x))`) fails CEL compile: see the translation table. ### 4. Dynamic seed value — use `cel\`\`` not `new Date()` diff --git a/skills/objectstack-project/evals/project-process.json b/skills/objectstack-project/evals/project-process.json index 39ad5ed3065..ce00b5b540a 100644 --- a/skills/objectstack-project/evals/project-process.json +++ b/skills/objectstack-project/evals/project-process.json @@ -123,18 +123,19 @@ { "id": 8, "prompt": "Our ObjectStack app's case SLA must count business hours only. Add a `business_hours_calendar` object (weekday ranges per organization) and a `holiday` table, and make the SLA formula read them.", - "expected_output": "Does not create `business_hours_calendar` or `holiday`: the platform catalog lists `sys_work_calendar` (weekly working periods, per organization) and `sys_work_calendar_exception` (dated holidays and make-up workdays) as what the platform ships, and each organization keeps its own rows in Setup. The formula half is different: working-day formulas are in the catalog's Planned section, marked not available, so no formula reads a calendar today. That is a missing capability, not a defect, so §3 does not apply: the app is not blocked and no workaround language is used. It links the contract at objectstack-ai/objectstack and may compute the business-hours due time in the app meanwhile, reading the platform's calendar rows and marked `// PLATFORM-CANDIDATE: ` so the bump sweep (§5 step 4) replaces it when the platform ships the formulas. Where the SLA is an approval step's deadline, it sets `escalation.clock: 'working_time'` instead, which reads the calendar today.", + "expected_output": "Does not create `business_hours_calendar` or `holiday`: the platform catalog lists `sys_work_calendar` (weekly working periods, per organization) and `sys_work_calendar_exception` (dated holidays and make-up workdays) as what the platform ships, and each organization keeps its own rows in Setup. The formula half ships too: the SLA due time is a formula over the platform calendar, `addWorkingHours(record.opened_at, 8)` (or `addWorkingDays` for a due day), counting with the organization's default calendar or a calendar code written as a quoted literal. Because a list view, a report or an escalation flow filters on the due time, and no calendar arithmetic runs as a database filter, it stores it: a `datetime` field (not `formula`) whose `expression` calls `addWorkingHours()`, computed on each write, which a filter compares with `{now}` and a CEL condition with `now()`. It writes no hand-rolled calendar walk and no workaround marker, since nothing is missing. Where the SLA is an approval step's deadline, it sets `escalation.clock: 'working_time'` instead.", "files": [], "assertions": { "must_contain": [ "sys_work_calendar", - "PLATFORM-CANDIDATE" + "addWorkingHours(" ], "must_not_contain": [ "name: 'business_hours_calendar'", "name: 'holiday'", "Blocked by", - "PLATFORM-GAP" + "PLATFORM-GAP", + "PLATFORM-CANDIDATE" ] } }, diff --git a/skills/objectstack-project/references/platform-catalog.md b/skills/objectstack-project/references/platform-catalog.md index 46b21e8e3a7..28c6c89669a 100644 --- a/skills/objectstack-project/references/platform-catalog.md +++ b/skills/objectstack-project/references/platform-catalog.md @@ -51,7 +51,7 @@ a seed) without declaring it. |:--|:--|:--|:--| | `sys_exchange_rate` | every boot | an exchange-rate table | `currencyConfig.homeAmount` converts at write; Setup edits rates; data API | | `sys_unit` | every boot | a unit table or picklist | `unitConfig` on a `number` field (`unitMode: 'fixed'` with `unit`, `'record'` with `unitField`) or a `text` field (`'code'`); a stored code is standard (UN/ECE Rec 20: `KGM`, `H87`) or a row added here in Setup; data API, no delete | -| `sys_work_calendar` | every boot | a business-hours calendar | kept per organization in Setup; an approval's `escalation.clock: 'working_time'` reads it; data API | +| `sys_work_calendar` | every boot | a business-hours calendar | kept per organization in Setup; an approval's `escalation.clock: 'working_time'` and `addWorkingDays()`, `workingDaysBetween()`, `addWorkingHours()` read it; data API | | `sys_work_calendar_exception` | every boot | a holiday table | a calendar's holidays and make-up workdays, kept in Setup; data API | | `sys_import_job` | every boot | a bulk-import job table | `POST /api/v1/data/OBJECT/import/jobs`; data API read | | `sys_approval_request` | `requires: ['approvals']` | an approvals table | a flow approval node opens it; `/api/v1/approvals` routes decide; data API read | @@ -150,4 +150,3 @@ meanwhile, marked `// PLATFORM-CANDIDATE:` with the link. | Concept | State | Contract | |:--|:--|:--| | Unit display, totals and conversion | **not available** (contract accepted; a quantity shows and sums as a bare number) | https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0158-units-of-measure-standard-unit-table-org-units-quantity-unit-declaration-base-quantity.md | -| Working-day formulas | **not available** (contract accepted; no formula reads a calendar yet) | https://github.com/objectstack-ai/objectstack/blob/main/docs/adr/0157-working-calendars-are-org-editable-runtime-data-resolved-by-code-or-refused.md | diff --git a/ui/packages/core/src/evaluator/__tests__/formulaRecord-35033.test.ts b/ui/packages/core/src/evaluator/__tests__/formulaRecord-35033.test.ts index 642ea4c5566..cf78273e0a0 100644 --- a/ui/packages/core/src/evaluator/__tests__/formulaRecord-35033.test.ts +++ b/ui/packages/core/src/evaluator/__tests__/formulaRecord-35033.test.ts @@ -106,6 +106,21 @@ describe('planObjectFormulas — computing formulas over the live record (object expect(plan.unservable.get('masked')).toMatch(/no expression/); }); + it('a working-day function is unservable: its calendar is loaded for the read, never handed to the form (ADR-0157 D4)', () => { + const plan = planObjectFormulas({ + start: { type: 'date' }, + due: { type: 'formula', expression: 'addWorkingDays(record.start, 3)' }, + days_left: { type: 'formula', expression: "workingDaysBetween(today(), record.start, 'cn_mainland')" }, + overdue: { type: 'formula', expression: 'record.due < today()' }, + plain: { type: 'formula', expression: 'addDays(record.start, 3)' }, + })!; + expect(plan.unservable.get('due')).toMatch(/working-day function/); + expect(plan.unservable.get('days_left')).toMatch(/working-day function/); + // Reading one is unservable too; `addDays()` (CONTROL) computes. + expect(plan.unservable.get('overdue')).toMatch(/reads the formula 'due'/); + expect(plan.unservable.has('plain')).toBe(false); + }); + it('binds the acting user as the server does (id and positions): current_user, user and ctx compute; can() and os stay unservable', () => { const fields = { owner: { type: 'text' }, diff --git a/ui/packages/core/src/evaluator/formulaRecord.ts b/ui/packages/core/src/evaluator/formulaRecord.ts index 7ec7ac0f748..79d7aa7ebd9 100644 --- a/ui/packages/core/src/evaluator/formulaRecord.ts +++ b/ui/packages/core/src/evaluator/formulaRecord.ts @@ -53,6 +53,8 @@ * The unservable set is the server's (objectql `unservableReason`) plus the * two things the server binds and the form cannot hold: `os` (for `os.org`) * and `current_user.can()` (a permission map, which a write may resolve). + * A working-day function (ADR-0157 D4) is in the server's set too: its + * calendar is loaded for the read, never handed to the form. * Every other formula the form computes as the server does. A field whose * `visibleWhen` reads an unservable one is shown and keeps its `required` * flag; for those two the form can be stricter than the server, which stays @@ -61,6 +63,7 @@ import { ExpressionEngine, analyzeRelationshipTraversals, + callsWorkingDayFunction, collectCelRootIdentifiers, findTraversalConflicts, formulaReadOrder, @@ -269,6 +272,13 @@ export function planObjectFormulas( unservable.set(name, 'calls label(), which the form does not answer'); continue; } + // ADR-0157 D4: a working-day function counts with the organization's + // working calendar, which the server loads for the read and the form does + // not hold (objectql `unservableReason` says the same of the write path). + if (callsWorkingDayFunction(source)) { + unservable.set(name, 'calls a working-day function, which counts with a working calendar the form does not hold'); + continue; + } if (callsReceiverMethod(parseCelToAst(source), 'can')) { unservable.set(name, 'calls current_user.can(), which the form does not answer for a formula'); continue;