Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/35356-working-day-formula-functions.md
Original file line number Diff line number Diff line change
@@ -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.
61 changes: 61 additions & 0 deletions content/docs/data-modeling/formulas.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -573,6 +576,64 @@ counterpart to the date-arithmetic build error above — equality is rewritten a
works; `+`/`-` arithmetic is rejected.
</Callout>

### 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
Expand Down
13 changes: 12 additions & 1 deletion packages/formula/src/cel-engine.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down Expand Up @@ -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([]);
Expand Down
1 change: 1 addition & 0 deletions packages/formula/src/cel-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
22 changes: 22 additions & 0 deletions packages/formula/src/cel-to-filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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[] = [];
Expand Down Expand Up @@ -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)}"`);
}
}
Expand Down
9 changes: 8 additions & 1 deletion packages/formula/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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';
6 changes: 5 additions & 1 deletion packages/formula/src/stdlib.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
}

/**
Expand All @@ -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();
Expand Down
46 changes: 46 additions & 0 deletions packages/formula/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 —
Expand Down Expand Up @@ -72,6 +73,36 @@ export type EvalSystemPermissions = ReadonlyArray<string>;
*/
export type EvalOptionLabels = Readonly<Record<string, Readonly<Record<string, string>>>>;

/**
* 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<Record<string, EvalWorkCalendar>>;
}

/**
* Runtime context for evaluating an expression.
*
Expand Down Expand Up @@ -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<string, unknown>;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/formula/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2222,6 +2222,8 @@ export const CEL_STDLIB_FUNCTIONS: string[] = [
'isBlank', 'isEmpty', 'coalesce', 'len',
// Options (registered stdlib) — `label(record.<field>)`, 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',
];
Loading
Loading