Skip to content

Commit 3d6dea2

Browse files
feat(formula): working-day functions addWorkingDays, workingDaysBetween and addWorkingHours over the organization calendar (#36796)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBEaJzgBWzjWCNjBjkVoeRto)_ Fixes #35356 repo:objectstack#3 · os-support-ai · session_01WGufzi4y7vb1rP9MERYbw2 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) ## 维护者速读 - 用户能看到什么变化:管理员和建模人员在公式字段里可以按组织的工作日历算到期日和剩余工作日,节假日、周末和调休上班日都会被正确跳过或计入。 - 为什么做:工作日历系列的第三步,让服务时限和到期提醒不必再由各个应用自己写日历计算。 - 出错会怎样:日历缺失或维护期不够时该公式读为空并在服务端记一行日志,记录照常保存,不会按自然日乱算;要撤回只需回滚本次改动。 - 要你做什么:无。 ## Review round 2 (L1-b 7118804738, contract 7118785761) - **M1.** `Metadata-protocol: added` with `@objectstack/formula` at minor (the three names are a new accepted value of an authored `expression`, as with `rmbUpper`), and the `Skills-docs:` line, in this body and the changeset. - **S1.** `os build` now refuses the three in a field's expression `defaultValue` (the default step has no calendar, so every insert would land blank) and in a seed record's expression values at any depth (the seed loader has none either), with the stored due-time prescription. New module `packages/lint/src/validate-working-day-sites.ts`; a bare-string `defaultValue` is a literal and draws nothing (CONTROL). - **S2.** Already held: `planFormulaProjection` widens a named projection to every stored column, `organization_id` included, and cuts it back after evaluation. Now pinned: the stub driver honours `fields`, and "a projection that leaves organization_id out still counts each row in its own organization" asserts both the per-organization answer and that the driver was asked for `organization_id`. Ablation: skipping `organization_id` in the widening turns it red. Documented in the header of `formula-work-calendars.ts`. - **S3.** A kernel boot test: `ObjectKernel` + `ObjectQLPlugin({ ql: engine })` serves `objectql` as the same engine and its formula counts with the plugin-installed calendar service. Ablation: removing the plugin's `setFormulaWorkCalendarService` call turns it red. - **Open point 1 (option A stands).** The docs page and the skill each say a blank stored due time stays blank until the record's next write; the docs and changeset add that a write while the calendar refuses blanks a previously valid value. - **Nits.** N1 the skill's `timestamp(s)` line and `PRIOR()` note reworded; N3 eval 8 says `{now}` for a filter and `now()` for a CEL condition; N4 the catalog's `sys_work_calendar` row names all three functions; N5 a blank start answers blank before any calendar is read (test added). - **#36673.** Still open at this head; this branch merges `main` once it lands, per the seat. ## What changes Three formula functions over the organization's working calendar (ADR-0157 D4), with the evaluation contract this card had to settle. - `addWorkingDays(day, n[, code])`: the calendar day `n` working days after `day` (before it, for a negative `n`). `day` itself never counts, and `0` answers `day`. The answer is a calendar day at UTC midnight, as `today()` and a `date` field are. - `workingDaysBetween(start, end[, code])`: the working days after `start` up to and including `end`, negative when `end` is earlier. It is the inverse: `workingDaysBetween(d, addWorkingDays(d, n)) == n`. - `addWorkingHours(start, hours[, code])`: the instant `hours` of working time after `start`, counted as elapsed time in the calendar's time zone (D11, open point 3). A start outside working time begins at the next working period's start. All three count through `work-calendar.ts`, the arithmetic the calendar service and the approval clock already use, so there is one walk and one daylight-saving rule. **Packages.** - `@objectstack/formula`: `working-day.ts` registers the functions as CEL stdlib over `EvalContext.workCalendars` (pure data, the existing binding pattern). `working-day-needs.ts` reads, from an expression's AST, which calendars it names: the default for a two-argument call, and each quoted-literal code. `cel-to-filter.ts` refuses the three as a filter (`CompileError('unsupported')`), prescribing the stored due-time field. They join `CEL_STDLIB_FUNCTIONS`. - `@objectstack/objectql`: `formula-work-calendars.ts` resolves exactly the calendars a formula plan names, per row organization (`organization_id`, else the read's tenant), through `WorkCalendarService.resolve`, so its cache and invalidation are reused. A refusal is handed over as data. Wired into find / findOne, the insert and update responses, the summary-fold dependents and stored expressions (`computeStoredExpressions`). The plugin installs the kernel's calendar service beside the engine (`setFormulaWorkCalendarService`), and each formula path reaches it through its host's `facade`, so `engine.ts` stays at its facade line ceiling (6857) with no new member. - `@objectstack/lint`: refuses the three at every expression site except a formula field's and a stored field's `expression` (`check()`, the declared flow predicate and value slots, a field's expression `defaultValue`, seed values), and refuses a calendar code that is not a quoted literal (`judgeFieldFormula`). - `@object-ui/core`: a form treats a formula that calls one as unservable, because the calendar is loaded for the server's read and never handed to the form. - Docs and skills: the formula docs page gains a Working days section; objectstack-formula documents the three functions inside its existing ceiling; the platform catalog drops the "Working-day formulas" Planned row and names the formulas on `sys_work_calendar`'s row; project-process eval 8 now expects `addWorkingHours(` and a stored due time, and refuses `PLATFORM-CANDIDATE`. **Contract choices (D4: the card's to settle, pinned by tests).** - The calendar code is a quoted literal. The engine loads the calendars an expression names before it evaluates it, so a computed code names a calendar nobody loaded. To choose a calendar per record, branch between literal calls. The lint refuses a computed code with that prescription. - A blank start day or start instant answers blank (a due date with no start has none), before any calendar is read. A blank count, or a blank end of `workingDaysBetween`, refuses. - Hook sandbox: no host function is added. A hook reads the stored due-time field. ## Decision for review **Open point 1: a stored field's `expression` that meets a D8 refusal stores blank, and the write goes through, with one log line naming the object, the field and the refusal.** Why this option and not "the write fails": - It matches D8's read behaviour: a formula field that meets the same refusal reads `null` and logs once. A stored due time and a computed one then answer the same way for the same calendar state. - A failing write would block every record whose span crosses the end of the maintained period, for example every case opened in late December before an administrator enters next year's holidays. That is the non-blocking stance ADR-0157 D9 takes for the approval clock. - The column is not silently wrong: it is blank, never a weekly-pattern or wall-clock guess, and the next write after the calendar is fixed counts. The author-facing cost is said in the docs and the skill: a blank stored due time stays blank until the record's next write, and a write while the calendar refuses blanks a value that was valid before. Pinned by `engine-formula-working-day.test.ts` › "a refused count stores blank and the write goes through, with one line naming the field". The alternative is one branch in `computeStoredExpressions`: rethrow instead of storing blank. ## Tests - `packages/formula/src/working-day.test.ts`: a `cn_mainland` calendar (Asia/Shanghai, 09:00-12:00 and 13:00-18:00, National Day 10-01..07 off, Saturday 10-10 on) against a weekly-only CONTROL calendar. Covers a weekend, the National Day week, the 调休 Saturday, negative and zero counts, date, `today()` and timestamp inputs, blank handling, the inverse property, DST spring-forward and fall-back, every refusal (no default, not maintained, not loaded, code not loaded), the needs analysis, and the pushdown refusal with an `addDays` CONTROL. - `packages/objectql/src/engine-formula-working-day.test.ts`: the real `WorkCalendarService` over a stub driver. A read over the National Day week onto the 调休 Saturday, a weekend on findOne, two organizations each on its own default, the write response, D8 past `maintained_through` and with no default (null, one log line, never a wall-clock count), no service, D6 stored count and stored blank on refusal, the cache serving until `invalidate()`, no calendar read for a projection whose formulas call none, a projection without `organization_id` (S2), and a kernel boot through `ObjectQLPlugin` (S3). - `packages/lint/src/validate-expressions.working-day-35356.test.ts`: accepted at a formula and a stored `expression` (including the branch between literal codes); refused at a validation rule, an action's `visible`, a flow condition, a sharing rule (both the expression lint and the enforceability pass), a field's expression `defaultValue` and a seed value; a computed code refused; `addDays` and bare-string CONTROLs. - `authored-site-expression.test.ts` classifies the new gate passes and the value-site walk; `validate-expressions.test.ts` excuses the new import tail `sites`. - `ui/packages/core/.../formulaRecord-35033.test.ts`: a working-day formula and a formula reading it are unservable; `addDays` CONTROL computes. ## Acceptance notes - Release pairing (D4, same release as the objects): `npm view @objectstack/objectql version` and `@objectstack/formula` read `18.6.0`, which carries no calendar code. The changesets of #35355 and #35357 are still pending on `main`, so this PR ships in the same release as them. - Contract-review tier: `packages/spec` carries no function list or schema that changes (its only diff is the catalog generator's row list, `packages/spec/scripts/**`, unpublished). The published list that widens is `@objectstack/formula`'s `CEL_STDLIB_FUNCTIONS` (three names). Measured: not CONTRACT_REVIEW_TIER by the order's spec criterion; the seat decides. - Metadata-protocol `added`: no authorable key or `authorable-surface/**` shard moves, but an authored `expression` accepts three new function names (corrected in round 2 from `none`). - File surface beyond the order's list, each declared: objectql engine facets (`engine-find.ts`, `engine-insert.ts`, `engine-update.ts`, `engine-security-resolvers.ts`, `engine-top-level.ts`, `plugin.ts`) and the new `formula-work-calendars.ts`, because the formula read and write paths are where the calendars are loaded; `engine.ts` and `work-calendar-service.ts` are unchanged. `packages/lint/**` is the measured expression-lint location. `ui/packages/core/**` keeps the form from computing a formula the server's write-path check already calls unservable. - Skills readings (`skills/**`, published): `skills/objectstack-formula/SKILL.md` 491 → 485 lines, 6090 tokens. Its ceiling rises 6008 → 6090 (+82) under the standing ruling 「A:先削重复,余额按实测提高」 (record 6513306068): restatement was deleted first in the same file (changed lines remove 789 priced bytes and add 1130), and the balance the round-2 sentences need is raised to the measured value, as the comment in `scripts/check-skills-token-ratchet.mjs` records. `skills/**` makes this PR governed. ## Verification Two-minute check: `pnpm --filter @objectstack/formula exec vitest run src/working-day.test.ts` shows the National Day and 调休 Saturday cases passing. Read first (by risk): `packages/objectql/src/formula-work-calendars.ts` (which organization a row counts in), `packages/objectql/src/engine-top-level.ts` (`computeStoredExpressions`, the open point 1 branch), `packages/formula/src/working-day.ts` (the public contract). <details><summary>Local gates (dispatch-gates --ran: 122 derived families accounted for, 118 run, 4 NOT-MEASURED)</summary> - Round 2 at 5e11588: formula `working-day.test.ts` 23 passed; objectql `engine-formula-working-day.test.ts` 13 passed; lint `validate-expressions.working-day-35356`, `validate-expressions`, `authored-site-expression` 606 passed; `platform-catalog.test.ts` 20 passed; `tsc --noEmit` formula, objectql, lint green; `check-skills-token-ratchet`, `check-facade-delegation-only`, `check-nul-bytes`, `check-skill-links`, `check-skill-identifier-liveness`, `check-skill-top-level-keys`, `check-skill-frame-sync`, `check-changeset-fixed`, `check-empty-changeset`, `check-changeset-no-major` green. Round 1: - All 139 derived commands run at the final source; green except the following. - NOT MEASURED (exit 3, need a built closure; CI builds it): `check:skill-examples`, `check:dual-build-cjs-loads`, `check:lean-entry-closure`, `check-plugin-teardown-shape --self-test` (its positive control is pinned to a commit this shallow clone cannot reach). - `pnpm --dir ui exec vitest run scripts/`: 1 red, `unit-registry-absence-collision` cannot import modules that resolve `@objectstack/client`, which is unbuilt here. Environment, not this diff; CI runs it built. - `check:facade-delegation-only` was red on the first run (`engine.ts` 32 lines over its ceiling); fixed by moving the calendar wiring into `formula-work-calendars.ts`, re-run green. - Typecheck (`tsc --noEmit` and `check:test-typecheck`): `@objectstack/formula`, `@objectstack/objectql`, `@objectstack/lint` green. - Suites: `@objectstack/formula` 2133 passed; `@objectstack/objectql` 14363 passed; `@objectstack/lint` 9475 of 9479 passed, the 4 reds were two ledgers naming the new gate passes, fixed and both files re-run green (592 passed); `ui/packages/core` 4769 passed, 27 skipped. </details> <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufzi4y7vb1rP9MERYbw2 --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d9c799c commit 3d6dea2

32 files changed

Lines changed: 1690 additions & 44 deletions
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
'@objectstack/formula': minor
3+
'@objectstack/objectql': patch
4+
'@objectstack/lint': patch
5+
'@object-ui/core': patch
6+
'@objectstack/skills': patch
7+
---
8+
9+
feat(formula): `addWorkingDays()`, `workingDaysBetween()` and `addWorkingHours()` count with the organization's working calendar (ADR-0157 D4)
10+
11+
Clause-②: yes (widening)
12+
Metadata-protocol: added — a formula field's or a stored field's `expression` may now call `addWorkingDays(...)`, `workingDaysBetween(...)` and `addWorkingHours(...)`
13+
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)
14+
15+
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.
16+
17+
- **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`).
18+
- **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.
19+
- **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.
20+
- **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).
21+
- **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.
22+
- **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.
23+
- **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.

‎content/docs/data-modeling/formulas.mdx‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,9 @@ All functions are pure given a pinned `now`, which is what makes
200200
| `date(s)` / `datetime(s)` | timestamp | Parse an ISO date / date-time string (aliases) |
201201
| `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 |
202202
| `daysBetween(a, b)` | int | Whole days from `a` to `b` (negative when `b` is earlier) |
203+
| `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) |
204+
| `workingDaysBetween(a, b[, code])` | int | Working days after `a` up to and including `b` (negative when `b` is earlier); the inverse of `addWorkingDays` |
205+
| `addWorkingHours(t, h[, code])` | timestamp | The instant `h` working hours after `t`, counted as elapsed time in the calendar's time zone |
203206
| `isBlank(v)` | bool | True for `null`, `undefined`, `''`, `[]` |
204207
| `isEmpty(v)` | bool | True for `null` or zero-length string/list/map |
205208
| `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
573576
works; `+`/`-` arithmetic is rejected.
574577
</Callout>
575578

579+
### Working days
580+
581+
`addWorkingDays`, `workingDaysBetween` and `addWorkingHours` count with the
582+
organization's **working calendar** (ADR-0157): its weekly working hours, its
583+
holidays, and its make-up working days, such as a Saturday worked in exchange for
584+
a holiday week. A due date "three working days later" steps over a weekend, a
585+
National Day week, and onto a make-up Saturday.
586+
587+
```typescript
588+
// Response due three working days after the case opened (a calendar day)
589+
Field.formula({
590+
label: 'Respond By',
591+
returnType: 'date',
592+
expression: 'addWorkingDays(record.opened_on, 3)',
593+
})
594+
595+
// Working days left until the deadline, on a named calendar
596+
Field.formula({
597+
label: 'Working Days Left',
598+
returnType: 'number',
599+
expression: "workingDaysBetween(today(), record.deadline, 'cn_mainland')",
600+
})
601+
602+
// SLA due time, STORED: computed on each write, so a list view, a report
603+
// or a flow can filter on it
604+
Field.datetime({
605+
label: 'SLA Due',
606+
expression: 'addWorkingHours(record.opened_at, 8)',
607+
})
608+
```
609+
610+
- **Which calendar.** With two arguments, the organization's default calendar;
611+
the third names a calendar by its code, and it must be a quoted literal: the
612+
engine loads the calendars an expression names before it evaluates it. To pick
613+
a calendar per record, branch between literal calls:
614+
`record.region == 'us' ? addWorkingDays(record.start, 3, 'us') : addWorkingDays(record.start, 3, 'cn_mainland')`.
615+
- **Days and instants.** `addWorkingDays` and `workingDaysBetween` take calendar
616+
days (a `date` field, `today()`, or `YYYY-MM-DD` text) and the start day itself
617+
never counts, so `0` answers the start. `addWorkingHours` takes an instant; a
618+
start outside working time begins at the next working period.
619+
- **Where they run.** Only in a `formula` field and in a stored field's
620+
`expression`, evaluated on the server. No calendar arithmetic runs in SQL, so a
621+
filter cannot call them; neither can a validation rule, a visibility rule, a
622+
flow condition, a sharing rule, a field's expression `defaultValue` or a seed
623+
value. `os build` refuses them there and points at the stored due-time field
624+
above, which a filter compares with `{now}` and a CEL condition with `now()`.
625+
- **When the calendar cannot answer.** With no default calendar in the
626+
organization, or a count that reaches past the span the calendar is maintained
627+
for, the formula reads `null` (a stored field stores blank and the write goes
628+
through), and the server logs one line naming the object, the field and the
629+
reason. It never falls back to counting the weekly pattern or the wall clock.
630+
- **After a calendar edit.** A formula field counts again on its next read; a
631+
stored due time keeps the value computed on its last write. So a stored due
632+
time left blank by a refusal stays blank until that record is written again,
633+
and a write made while the calendar refuses blanks a value that was valid
634+
before. A filter such as "due before now" never matches a blank, so keep the
635+
calendar's maintained span ahead of the records it counts for.
636+
576637
### Financial Calculations
577638

578639
```typescript

‎packages/formula/src/cel-engine.test.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';
22

33
import { celEngine, rewriteTemporalEquality, collectCelRootIdentifiers } from './cel-engine';
44
import { CEL_STDLIB_FUNCTIONS } from './validate';
5+
import { buildWorkCalendar } from './work-calendar';
56
import type { Expression } from '@objectstack/spec';
67

78
const cel = (source: string): Expression => ({ dialect: 'cel', source });
@@ -512,14 +513,24 @@ describe('celEngine', () => {
512513
size: 'size([1, 2])', has: 'has(record.a)', int: 'int("3")', string: 'string(3)',
513514
bool: 'bool("true")', double: 'double("3.5")', timestamp: 'timestamp("2026-01-01T00:00:00Z")',
514515
duration: 'duration("3600s")', label: 'label(record.a)',
516+
addWorkingDays: 'addWorkingDays(today(), 2)', workingDaysBetween: 'workingDaysBetween(today(), daysFromNow(7))',
517+
addWorkingHours: 'addWorkingHours(now(), 4)',
515518
};
519+
// ADR-0157 D4: the calendar the three working-day probes count with,
520+
// Monday to Friday, maintained over the probe's whole window.
521+
const weekday = '09:00-18:00';
522+
const workCalendars = { default: buildWorkCalendar({
523+
code: 'probe', timezone: 'UTC', maintained_from: '2025-01-01', maintained_through: '2027-12-31',
524+
monday_periods: weekday, tuesday_periods: weekday, wednesday_periods: weekday,
525+
thursday_periods: weekday, friday_periods: weekday,
526+
}, []) };
516527
const unresolved: string[] = [];
517528
for (const fn of CEL_STDLIB_FUNCTIONS) {
518529
const src = call[fn];
519530
expect(src, `no probe call defined for advertised function \`${fn}\``).toBeTruthy();
520531
// `optionLabels` is the data `label()` answers from (#26608); the other
521532
// probes read nothing from it.
522-
const r = celEngine.evaluate(cel(src), { now, record: { a: 1 }, optionLabels: { a: { 1: 'One' } } });
533+
const r = celEngine.evaluate(cel(src), { now, record: { a: 1 }, optionLabels: { a: { 1: 'One' } }, workCalendars });
523534
if (!r.ok) unresolved.push(`${fn}: ${r.error.message.split('\n')[0]}`);
524535
}
525536
expect(unresolved, `advertised functions that fault at runtime:\n${unresolved.join('\n')}`).toEqual([]);

‎packages/formula/src/cel-engine.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2810,6 +2810,7 @@ export const celEngine: DialectEngine = {
28102810
systemPermissions: ctx.systemPermissions,
28112811
},
28122812
optionLabels: ctx.optionLabels,
2813+
workCalendars: ctx.workCalendars,
28132814
};
28142815
try {
28152816
// #3183 — coerce a date-field operand compared with `==`/`!=` against a

‎packages/formula/src/cel-to-filter.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ import type { FilterCondition } from '@objectstack/spec/data';
6363
import { CEL_BOUNDS_MEASURE_CAP_FACTOR, parseCelToAstWithReason } from './cel-engine';
6464
import type { CelBoundsOverrun } from './cel-engine';
6565
import { celPushdownLimitsMode } from './cel-pushdown-limits';
66+
import { WORKING_DAY_FUNCTIONS } from './working-day';
6667

6768
// ---------------------------------------------------------------------------
6869
// Public contract
@@ -331,10 +332,30 @@ function lowerCondition(node: ASTNode, ctx: Ctx): FilterCondition {
331332
throw new CompileError('unsupported', `constant non-true predicate (${String(v)})`);
332333
}
333334
default:
335+
refuseWorkingDayCall(node);
334336
throw new CompileError('unsupported', `unsupported operator "${String(op)}"`);
335337
}
336338
}
337339

340+
/**
341+
* ADR-0157 D6: a working-day function evaluates in memory only, over the
342+
* calendar the engine loads for it, so a query filter refuses it — as it
343+
* refuses every function call — and says what to write instead. The generic
344+
* `unsupported` refusal below would name only the node kind.
345+
*/
346+
function refuseWorkingDayCall(node: ASTNode): void {
347+
if (node.op !== 'call') return;
348+
const name = (node.args as unknown[] | undefined)?.[0];
349+
if (typeof name !== 'string' || !(WORKING_DAY_FUNCTIONS as readonly string[]).includes(name)) return;
350+
throw new CompileError(
351+
'unsupported',
352+
`${name}() counts with a working calendar and evaluates in memory only, so it cannot run as a database ` +
353+
'filter: no calendar arithmetic runs in SQL. To filter on a working-day due time, store it: ' +
354+
`give the object a datetime field whose \`expression\` calls ${name}(), computed when the record is written, ` +
355+
'and compare that field with {now}.',
356+
);
357+
}
358+
338359
function combine(key: '$and' | '$or', node: ASTNode, ctx: Ctx): FilterCondition {
339360
const [l, r] = node.args as [ASTNode, ASTNode];
340361
const parts: FilterCondition[] = [];
@@ -717,6 +738,7 @@ function classify(node: ASTNode, ctx: Ctx): Leaf {
717738
throw new CompileError('unsupported', `cross-object field path "${chain.join('.')}" is not pushdown-able`);
718739
}
719740
default:
741+
refuseWorkingDayCall(node);
720742
throw new CompileError('unsupported', `unsupported operand "${String(node.op)}"`);
721743
}
722744
}

‎packages/formula/src/index.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,13 @@ export {
215215
workingDaysBetween,
216216
addWorkingHours,
217217
} from './work-calendar';
218+
// ADR-0157 D4 — the working-day formula functions: their names, and which
219+
// calendars an expression names, so a caller resolves those calendars before
220+
// it evaluates (`EvalContext.workCalendars`).
221+
export { WORKING_DAY_FUNCTIONS, workCalendarsNotLoadedMessage } from './working-day';
222+
export type { WorkingDayFunction } from './working-day';
223+
export { callsWorkingDayFunction, workingDayCalendarNeeds, computedCalendarCodeMessage } from './working-day-needs';
224+
export type { WorkingDayCalendarNeeds } from './working-day-needs';
218225
// The closed set of refusal codes `validateExpression` and
219226
// `collectCelRootIdentifiers` carry beside their English message, with the
220227
// typed params each message interpolates — so a localized author surface keys
@@ -230,4 +237,4 @@ export type {
230237
ExpressionSourceKind,
231238
} from './expression-refusal';
232239
export type { SeedValue, SeedPrimitive } from './seed-eval';
233-
export type { DialectEngine, EvalContext, EvalResult, EvalError, EvalPermissions, EvalSystemPermissions, EvalOptionLabels } from './types';
240+
export type { DialectEngine, EvalContext, EvalResult, EvalError, EvalPermissions, EvalSystemPermissions, EvalOptionLabels, EvalWorkCalendar, EvalWorkCalendars } from './types';

‎packages/formula/src/stdlib.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@
2121

2222
import type { Environment } from '@marcbachmann/cel-js';
2323

24-
import type { EvalContext, EvalOptionLabels, EvalPermissions, EvalSystemPermissions } from './types';
24+
import type { EvalContext, EvalOptionLabels, EvalPermissions, EvalSystemPermissions, EvalWorkCalendars } from './types';
2525
import { rmbUpper } from './rmb-upper';
26+
import { registerWorkingDayFunctions } from './working-day';
2627
import { createEvalUser, type EvalUser } from '@objectstack/spec';
2728
// The verb vocabulary lives on the SECURITY subpath, where the permission
2829
// contract it is seeded from lives — not on the root barrel, which exports a
@@ -641,6 +642,8 @@ export interface StdLibBinding {
641642
readonly timezone: string;
642643
readonly permissionBinding: PermissionBinding | undefined;
643644
readonly optionLabels?: EvalOptionLabels | undefined;
645+
/** ADR-0157 D4: what the working-day functions count with (`working-day.ts`). */
646+
readonly workCalendars?: EvalWorkCalendars | undefined;
644647
}
645648

646649
/**
@@ -661,6 +664,7 @@ export function registerBoundStdLib(env: Environment, read: () => StdLibBinding)
661664
bindPermissionPredicate(env, () => read().permissionBinding);
662665
bindCapabilityPredicate(env, () => read().permissionBinding);
663666
bindOptionLabel(env, () => read().optionLabels);
667+
registerWorkingDayFunctions(env, () => read().workCalendars);
664668
const now = (): Date => read().now();
665669
const today = (): Date => {
666670
const binding = read();

‎packages/formula/src/types.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import type { Expression } from '@objectstack/spec';
1616
import type { EffectiveObjectPermission } from '@objectstack/spec/security';
17+
import type { WorkCalendar } from '@objectstack/spec/data';
1718

1819
/**
1920
* The acting subject's effective object permissions, indexed by object name —
@@ -72,6 +73,36 @@ export type EvalSystemPermissions = ReadonlyArray<string>;
7273
*/
7374
export type EvalOptionLabels = Readonly<Record<string, Readonly<Record<string, string>>>>;
7475

76+
/**
77+
* One working calendar as the working-day functions read it: the resolved
78+
* calendar, or the refusal resolving it met (ADR-0157 D2, D8), held as the
79+
* error the function throws. A refusal is data too: the caller resolved it
80+
* before evaluation, so the function never asks the host again.
81+
*/
82+
export type EvalWorkCalendar = WorkCalendar | Error;
83+
84+
/**
85+
* The working calendars one evaluation counts with — the
86+
* {@link EvalContext.workCalendars} payload, and the only input
87+
* `addWorkingDays()`, `workingDaysBetween()` and `addWorkingHours()` read
88+
* (ADR-0157 D4).
89+
*
90+
* `default` is the calendar a call that names no code counts with (D2: the
91+
* organization's default); `byCode` holds each calendar a call names by a
92+
* quoted code. The caller resolves both in the record's own organization
93+
* before evaluating, from the calls the expression spells
94+
* (`workingDayCalendarNeeds`), so a code the expression does not spell as a
95+
* literal is never loaded.
96+
*
97+
* **A pure DATA map, never a resolver**, for the reason {@link EvalPermissions}
98+
* gives: the stdlib computes synchronously over pinned data, so the calendar
99+
* service resolves first and the functions count over what it answered.
100+
*/
101+
export interface EvalWorkCalendars {
102+
readonly default?: EvalWorkCalendar;
103+
readonly byCode?: Readonly<Record<string, EvalWorkCalendar>>;
104+
}
105+
75106
/**
76107
* Runtime context for evaluating an expression.
77108
*
@@ -212,6 +243,21 @@ export interface EvalContext {
212243
* options, and `label()` throws for that too.
213244
*/
214245
optionLabels?: EvalOptionLabels;
246+
/**
247+
* The working calendars of the record's organization — see
248+
* {@link EvalWorkCalendars} for the shape and where it comes from.
249+
*
250+
* Read by exactly three functions, `addWorkingDays()`,
251+
* `workingDaysBetween()` and `addWorkingHours()` (ADR-0157 D4). ⛔ NOT
252+
* mounted as a CEL variable, on the terms {@link permissions} is.
253+
*
254+
* **Absent ≠ refused.** With no map at all the three THROW
255+
* (`ok: false, kind: 'runtime'`): a context that was never given calendars
256+
* cannot count, and counting on the weekly pattern or the wall clock instead
257+
* is the quiet wrong answer ADR-0157 D2 forbids. A calendar the caller could
258+
* not resolve is in the map as its refusal, and the call throws that.
259+
*/
260+
workCalendars?: EvalWorkCalendars;
215261
/** Free-form bag for niche call sites; merged onto the variable scope. */
216262
extra?: Record<string, unknown>;
217263
}

‎packages/formula/src/validate.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2222,6 +2222,8 @@ export const CEL_STDLIB_FUNCTIONS: string[] = [
22222222
'isBlank', 'isEmpty', 'coalesce', 'len',
22232223
// Options (registered stdlib) — `label(record.<field>)`, a select value's label
22242224
'label',
2225+
// Working days (registered stdlib, ADR-0157 D4) — counted with the organization's working calendar
2226+
'addWorkingDays', 'workingDaysBetween', 'addWorkingHours',
22252227
// cel-js built-ins (verified to resolve)
22262228
'size', 'has', 'int', 'string', 'bool', 'double', 'timestamp', 'duration',
22272229
];

0 commit comments

Comments
 (0)