diff --git a/.changeset/35357-approval-escalation-working-time-clock.md b/.changeset/35357-approval-escalation-working-time-clock.md new file mode 100644 index 00000000000..2587adeba9a --- /dev/null +++ b/.changeset/35357-approval-escalation-working-time-clock.md @@ -0,0 +1,24 @@ +--- +'@objectstack/spec': minor +'@objectstack/plugin-approvals': minor +'@objectstack/lint': minor +'@object-ui/console': minor +'@object-ui/i18n': minor +--- + +feat(approvals): an escalation deadline can count working time on an organization's working calendar (`escalation.clock: 'working_time'`) + +Clause-②: yes (widening) +Metadata-protocol: added +Skills-docs: follow-up owed — skills/objectstack-automation/references/state-machines-and-approvals.md + +An approval node's `escalation` gains two optional keys (ADR-0157 D5): + +- **`clock`**: `'wall_clock'` (the default) or `'working_time'`. Under `wall_clock` nothing changes: `timeoutHours` counts elapsed hours from `created_at`, nights, weekends and holidays included, and every request already open keeps its deadline (a stored snapshot carries no `clock`). Under `working_time` the hours count only the working periods of a working calendar (`sys_work_calendar`), skipping its holidays and counting its make-up workdays: a request opened at 17:00 on a Friday with `timeoutHours: 4`, on 09:00-12:00 and 13:00-18:00 periods, escalates at 12:00 on the next working day. +- **`calendar`**: the code of the working calendar to count on. Left out, the request organization's default calendar counts. There is never a fallback to wall-clock hours. + +The approvals sweep and the request read share one deadline function. A `working_time` deadline is counted again on every sweep and every read and is never stored, so a holiday entered after a request opened moves its deadline; an escalation that already fired stays fired (single-shot, ADR-0042). When the calendar cannot count the deadline (no calendar has the code, the organization has no default, or the calendar is not maintained as far as the deadline needs), the request does not escalate, the next sweep tries again, and the request read carries a new additive field, `sla_due_refusal` (`code`, `reason` or `date`, `message`), in place of `sla_due_at`. The approvals inbox shows "Calendar can't compute" with the reason where the SLA countdown sits, in every console language. + +`@objectstack/lint` refuses a `calendar` written beside the wall clock (`approval-escalation-calendar-without-working-time`, error): nothing would read it. Whether the named calendar exists is the organization's runtime data and is never checked at publish. The Studio approval inspector offers the clock and, under working time only, the calendar. + +Not released alone: this ships in the same release as the working-calendar objects and service and the working-day formula functions (ADR-0157 D4). diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 43b998a3e0f..3ca80825f6b 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -1147,10 +1147,44 @@ resumes exactly as if a human had clicked. Every escalation writes an audit row of kind `escalate` naming the configured action; it, the auto decision that follows it, and the escalation's notifications record no actor, because no person acted (ADR-0118 D1). -`timeoutHours` counts **calendar (wall-clock) hours** — nights, weekends and -holidays included, because the platform ships no business-hours calendar — so a -request opened at 17:00 on a Friday with `timeoutHours: 4` escalates at 21:00 -that same Friday. +`timeoutHours` counts from the moment the request was submitted, and +`clock` decides how its hours count (ADR-0157 D5): + +- **`wall_clock`** (the default) counts every hour — nights, weekends and + holidays included — so a request opened at 17:00 on a Friday with + `timeoutHours: 4` escalates at 21:00 that same Friday. +- **`working_time`** counts only the working periods of a working calendar + (`sys_work_calendar`, kept by the organization's administrators in Setup), + skipping its holidays and counting its make-up workdays. With 09:00–12:00 + and 13:00–18:00 working periods, the same Friday request escalates at 12:00 + on the next working day: Monday, or Tuesday when Monday is a holiday, or the + Saturday itself when it is a make-up workday. + +```ts +escalation: { + timeoutHours: 4, + clock: 'working_time', + calendar: 'cn_standard', // optional: the organization's default calendar when left out + action: 'notify', + escalateTo: 'approvals_supervisor', +} +``` + +The calendar is the one `calendar` names, else the organization's default +calendar; there is never a fallback to wall-clock hours. The deadline is +counted again on every sweep and every read, so a holiday entered after a +request opened moves its deadline (an escalation that already fired stays +fired). When the calendar cannot count the deadline — no calendar has that +code, the organization has no default, or the calendar is not maintained as +far as the deadline needs — the request does **not** escalate. Its read +carries no `sla_due_at` and a `sla_due_refusal` instead (the refusal `code`, +its `reason` or the `date` it needs, and a `message`), the approvals inbox +shows "Calendar can't compute" with the reason, and the next sweep tries +again, so fixing the calendar is the only step. Publishing checks only what is +written: a `calendar` beside the wall clock is refused +(`approval-escalation-calendar-without-working-time`), since nothing would read +it; whether the named calendar exists is the organization's data, checked when +the deadline is counted. **Escalation needs the job service.** The plugin sweeps pending requests on an diff --git a/content/docs/references/automation/approval.mdx b/content/docs/references/automation/approval.mdx index 0e99db84477..6b15b029ccb 100644 --- a/content/docs/references/automation/approval.mdx +++ b/content/docs/references/automation/approval.mdx @@ -39,7 +39,9 @@ const result = ApprovalDecision.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **enabled** | `boolean` | optional (default: `true`) | Turns this step's deadline on or off. It is on by default once a deadline is set: switch it off to keep the settings without acting on them, or remove the escalation to drop the deadline altogether | -| **timeoutHours** | `number` | ✅ | How many hours a request may wait before the escalation runs. These are calendar (wall-clock) hours — nights, weekends and holidays count. The platform ships no business-hours calendar: a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that same Friday | +| **timeoutHours** | `number` | ✅ | How many hours a request may wait before the escalation runs, counted from when it was submitted. The clock decides how the hours count: wall-clock hours (the default) count nights, weekends and holidays, so a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that Friday; working hours count only the working periods of a working calendar | +| **clock** | `Enum<'wall_clock' \| 'working_time'>` | optional (default: `"wall_clock"`) | How the timeout's hours count: every hour, or only working hours. Wall-clock hours ('wall_clock', the default) count nights, weekends and holidays. Working hours ('working_time') count only the working periods of the organization's working calendar, skipping its holidays and counting its make-up workdays; when the calendar cannot count the deadline (no such calendar, or not maintained that far) the request does not escalate and shows why, until the calendar is fixed | +| **calendar** | `string` | optional | Which working calendar counts the hours under working time, by its code. Leave it empty to use the organization's default calendar | | **action** | `Enum<'reassign' \| 'auto_approve' \| 'auto_reject' \| 'notify'>` | optional (default: `"notify"`) | What happens when the deadline passes: hand the request to someone else, approve it, reject it, or notify someone (the default) | | **escalateTo** | `string` | optional | Who takes over or is notified when the deadline passes: usually a position, or a specific person. Write a position machine name or 'position:``', a user id or an email. A 'team:', 'department:', 'org_membership_level:' or 'role:' address is refused: no approver acts under one | | **notifySubmitter** | `boolean` | optional (default: `true`) | Tell the person who submitted the request when it escalates | @@ -77,7 +79,7 @@ const result = ApprovalDecision.parse(data); | **onEmptyApprovers** | `Enum<'admin_rescue' \| 'fail' \| 'auto_approve' \| 'fallback'>` | optional (default: `"admin_rescue"`) | What happens when this step finds no one to approve: by default the organization's administrators decide; you can instead name backup approvers, fail the step, or approve it automatically. 'admin_rescue' (default) opens the request on the administrators; 'fallback' opens it on fallbackApprovers instead, naming who decides; 'fail' fails the step; 'auto_approve' approves it with no one deciding | | **fallbackApprovers** | `{ type: Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| …>; value?: string; resolveAs?: Enum<'user' \| 'department' \| 'position' \| 'team'>; group?: string; … }[]` | optional | Backup approvers who decide when this step finds no one else. Read only when onEmptyApprovers is 'fallback' | | **decisionOutputs** | `(string \| { key: string; label?: string; type?: Enum<'text' \| 'user' \| 'department' \| 'position' \| 'team'>; multiple?: boolean; … })[]` | optional | Extra answers the approver gives with the decision, such as who approves a later step; later steps read them. Each entry is a plain name (a text box) or `{ key, type, multiple }` to show a picker | -| **escalation** | `{ enabled?: boolean; timeoutHours: number; action?: Enum<'reassign' \| 'auto_approve' \| 'auto_reject' \| 'notify'>; escalateTo?: string; … }` | optional | A deadline for this step, and what happens when it passes | +| **escalation** | `{ enabled?: boolean; timeoutHours: number; clock?: Enum<'wall_clock' \| 'working_time'>; calendar?: string; … }` | optional | A deadline for this step, and what happens when it passes | | **maxRevisions** | `integer` | optional (default: `3`) | How many times a request can be sent back for changes before it is rejected automatically (0 turns send-back off) | ### Nested Shape: `ApprovalNodeConfig.approvers[number]` @@ -115,7 +117,9 @@ const result = ApprovalDecision.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | | **enabled** | `boolean` | optional (default: `true`) | Turns this step's deadline on or off. It is on by default once a deadline is set: switch it off to keep the settings without acting on them, or remove the escalation to drop the deadline altogether | -| **timeoutHours** | `number` | ✅ | How many hours a request may wait before the escalation runs. These are calendar (wall-clock) hours — nights, weekends and holidays count. The platform ships no business-hours calendar: a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that same Friday | +| **timeoutHours** | `number` | ✅ | How many hours a request may wait before the escalation runs, counted from when it was submitted. The clock decides how the hours count: wall-clock hours (the default) count nights, weekends and holidays, so a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that Friday; working hours count only the working periods of a working calendar | +| **clock** | `Enum<'wall_clock' \| 'working_time'>` | optional (default: `"wall_clock"`) | How the timeout's hours count: every hour, or only working hours. Wall-clock hours ('wall_clock', the default) count nights, weekends and holidays. Working hours ('working_time') count only the working periods of the organization's working calendar, skipping its holidays and counting its make-up workdays; when the calendar cannot count the deadline (no such calendar, or not maintained that far) the request does not escalate and shows why, until the calendar is fixed | +| **calendar** | `string` | optional | Which working calendar counts the hours under working time, by its code. Leave it empty to use the organization's default calendar | | **action** | `Enum<'reassign' \| 'auto_approve' \| 'auto_reject' \| 'notify'>` | optional (default: `"notify"`) | What happens when the deadline passes: hand the request to someone else, approve it, reject it, or notify someone (the default) | | **escalateTo** | `string` | optional | Who takes over or is notified when the deadline passes: usually a position, or a specific person. Write a position machine name or 'position:``', a user id or an email. A 'team:', 'department:', 'org_membership_level:' or 'role:' address is refused: no approver acts under one | | **notifySubmitter** | `boolean` | optional (default: `true`) | Tell the person who submitted the request when it escalates | diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index a3fe2cacbae..9b76a2e0d6a 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -344,6 +344,7 @@ export { APPROVAL_APPROVER_TYPE_UNKNOWN, APPROVAL_APPROVER_TYPE_UNSUPPORTED, APPROVAL_ESCALATION_REASSIGN_NO_TARGET, + APPROVAL_ESCALATION_CALENDAR_WITHOUT_WORKING_TIME, APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, APPROVAL_EXPRESSION_INVALID, APPROVAL_EXPRESSION_NO_EMPTY_POLICY, diff --git a/packages/lint/src/validate-approval-approvers.test.ts b/packages/lint/src/validate-approval-approvers.test.ts index dc2dccf57ef..0f1120e8292 100644 --- a/packages/lint/src/validate-approval-approvers.test.ts +++ b/packages/lint/src/validate-approval-approvers.test.ts @@ -10,6 +10,7 @@ import { APPROVAL_APPROVER_TYPE_UNKNOWN, APPROVAL_APPROVER_TYPE_UNSUPPORTED, APPROVAL_ESCALATION_REASSIGN_NO_TARGET, + APPROVAL_ESCALATION_CALENDAR_WITHOUT_WORKING_TIME, APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY, APPROVAL_EXPRESSION_INVALID, APPROVAL_EXPRESSION_NO_EMPTY_POLICY, @@ -176,6 +177,30 @@ describe('validateApprovalApprovers', () => { expect(findings[0].hint).toContain('position'); }); + it("refuses an escalation.calendar beside the wall clock: nothing reads it (ADR-0157 D9)", () => { + const stack = stackWithApprovers([{ type: 'user', value: 'u1' }]); + const node = (stack.flows as any)[0].nodes[1]; + for (const clock of [undefined, 'wall_clock']) { + node.config.escalation = { enabled: true, timeoutHours: 4, action: 'notify', calendar: 'cn_standard', ...(clock ? { clock } : {}) }; + const findings = validateApprovalApprovers(stack); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatchObject({ + severity: 'error', + rule: APPROVAL_ESCALATION_CALENDAR_WITHOUT_WORKING_TIME, + path: 'flows[0].nodes[1].config.escalation.calendar', + }); + } + }); + + it("accepts a calendar on 'working_time', and 'working_time' with no calendar: whether a calendar exists is never judged here", () => { + const stack = stackWithApprovers([{ type: 'user', value: 'u1' }]); + const node = (stack.flows as any)[0].nodes[1]; + node.config.escalation = { enabled: true, timeoutHours: 4, action: 'notify', clock: 'working_time', calendar: 'no_such_calendar' }; + expect(validateApprovalApprovers(stack)).toEqual([]); + node.config.escalation = { enabled: true, timeoutHours: 4, action: 'notify', clock: 'working_time' }; + expect(validateApprovalApprovers(stack)).toEqual([]); + }); + it('accepts reassign escalation with a target, and non-reassign actions without one', () => { const stack = stackWithApprovers([{ type: 'user', value: 'u1' }]); const node = (stack.flows as any)[0].nodes[1]; diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 625348a0e9f..0b0062c4b96 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -21,6 +21,7 @@ * | approval-approver-type-deprecated | warning | ADR-0090 D3 (#3133) | * | approval-approver-type-unknown | warning | contract-first (PD #12) | * | approval-escalation-reassign-no-target | warning | silent notify degradation | + * | approval-escalation-calendar-without-working-time | error | ADR-0157 D9 (static only) | * | approval-approvers-may-resolve-empty | info | empty-position dead-end (#3424) | * | approval-approvers-may-resolve-empty | info | unset-manager dead-end (#16748) | * | approval-expression-invalid | error/info | #3447 P2 closed-root expressions | @@ -61,6 +62,7 @@ export const APPROVAL_APPROVER_TYPE_DEPRECATED = 'approval-approver-type-depreca export const APPROVAL_APPROVER_TYPE_UNKNOWN = 'approval-approver-type-unknown'; export const APPROVAL_APPROVER_TYPE_UNSUPPORTED = 'approval-approver-type-unsupported'; export const APPROVAL_ESCALATION_REASSIGN_NO_TARGET = 'approval-escalation-reassign-no-target'; +export const APPROVAL_ESCALATION_CALENDAR_WITHOUT_WORKING_TIME = 'approval-escalation-calendar-without-working-time'; export const APPROVAL_APPROVERS_MAY_RESOLVE_EMPTY = 'approval-approvers-may-resolve-empty'; export const APPROVAL_EXPRESSION_INVALID = 'approval-expression-invalid'; export const APPROVAL_EXPRESSION_NO_EMPTY_POLICY = 'approval-expression-no-empty-policy'; @@ -795,6 +797,27 @@ export function validateApprovalApprovers( }); } } + + // ADR-0157 D9, the static half of the working-time clock: a calendar + // code beside the wall clock (written, or the default) names a calendar + // nothing reads — the hours count on the wall clock, while the author + // who named a calendar meant working time. Whether the named calendar + // EXISTS is per-organization runtime data and is never judged here. + const calendar = escalation && typeof escalation === 'object' && typeof escalation.calendar === 'string' + ? escalation.calendar.trim() + : ''; + if (calendar && escalation!.clock !== 'working_time') { + findings.push({ + severity: 'error', + rule: APPROVAL_ESCALATION_CALENDAR_WITHOUT_WORKING_TIME, + where, + path: `${nodePath}.config.escalation.calendar`, + message: + `escalation.calendar '${calendar}' is set but escalation.clock is not 'working_time' — the ` + + `wall clock counts the timeout and nothing reads the calendar.`, + hint: `Set escalation.clock to 'working_time' to count working hours on that calendar, or remove escalation.calendar.`, + }); + } } } diff --git a/packages/plugins/plugin-approvals/src/approval-service-sla-calendar-clock.test.ts b/packages/plugins/plugin-approvals/src/approval-service-sla-calendar-clock.test.ts index 4b6cf86341e..585a0ae0694 100644 --- a/packages/plugins/plugin-approvals/src/approval-service-sla-calendar-clock.test.ts +++ b/packages/plugins/plugin-approvals/src/approval-service-sla-calendar-clock.test.ts @@ -1,12 +1,16 @@ // Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. /** - * `ApprovalEscalation.timeoutHours` is CALENDAR (wall-clock) hours — pinned - * through the real code path, not restated. + * `ApprovalEscalation.timeoutHours` counts on the escalation's `clock` — + * wall-clock hours by default, working hours on a working calendar under + * `'working_time'` (ADR-0157 D5) — pinned through the real code path, not + * restated. * * The declaration's `describe` text on `ApprovalEscalationSchema` says the * clock out loud; `slaDueAt` in `approval-service.ts` is the one runtime site - * that turns the declared number into a deadline; the escalation sweep compares + * that turns the declared number into a wall-clock deadline, reached with the + * working-time count through `ApprovalService.slaDeadline`, the one function + * the read projection and the sweep share; the escalation sweep compares * that deadline against the injected clock. This file drives all three through * `openNodeRequest` → `getRequest` → `runEscalations`, so the sentence in the * schema and the arithmetic in the service cannot drift apart without a red @@ -23,6 +27,7 @@ */ import { describe, it, expect } from 'vitest'; +import { WorkCalendarService } from '@objectstack/objectql'; import { ApprovalService } from './approval-service.js'; interface Row { [k: string]: any } @@ -125,7 +130,7 @@ const utcDay = (iso: string) => new Date(iso).getUTCDay(); // 0 = Sunday … 5 = const FRIDAY_1700 = '2026-01-16T17:00:00.000Z'; const MONDAY_0900 = '2026-01-19T09:00:00.000Z'; -describe('ApprovalEscalation.timeoutHours is calendar (wall-clock) hours', () => { +describe('ApprovalEscalation.timeoutHours on the default clock is wall-clock hours', () => { it('the fixture dates are the weekdays the assertions name', () => { expect(utcDay(FRIDAY_1700)).toBe(5); expect(utcDay(MONDAY_0900)).toBe(1); @@ -207,3 +212,181 @@ describe('ApprovalEscalation.timeoutHours is calendar (wall-clock) hours', () => expect(Date.parse(row!.sla_due_at!) - Date.parse(created)).toBe(4 * HOUR); }); }); + +// ── escalation.clock: 'working_time' (ADR-0157 D5, D9, D12) ───────────────── +// +// The REAL calendar service (`@objectstack/objectql`) over a read double of the +// two calendar objects, so the D2 resolution (the named code, else the +// organization default, else a refusal) is the shipped one, not restated here. +// Calendar instants are written in Asia/Shanghai (+08:00), the calendar's own +// zone; the assertions compare UTC instants, so no runner `TZ` matters. + +const WEEKDAY = '09:00-12:00, 13:00-18:00'; +const CN_CALENDAR: Row = { + id: 'cal_cn', organization_id: 't1', code: 'cn_standard', name: 'China', timezone: 'Asia/Shanghai', + is_default: true, maintained_from: '2026-01-01', maintained_through: '2026-12-31', + monday_periods: WEEKDAY, tuesday_periods: WEEKDAY, wednesday_periods: WEEKDAY, + thursday_periods: WEEKDAY, friday_periods: WEEKDAY, saturday_periods: '', sunday_periods: '', +}; +// A Monday holiday (2026-04-06), the National Day week (2026-10-01..07, off) +// and its 调休 make-up Saturday (2026-10-10, on). +const CN_EXCEPTIONS: Row[] = [ + { id: 'ex_0406', calendar: 'cal_cn', organization_id: 't1', date: '2026-04-06', kind: 'off' }, + ...['01', '02', '03', '04', '05', '06', '07'].map((d) => ({ + id: `ex_10${d}`, calendar: 'cal_cn', organization_id: 't1', date: `2026-10-${d}`, kind: 'off', + })), + { id: 'ex_1010', calendar: 'cal_cn', organization_id: 't1', date: '2026-10-10', kind: 'on', periods: WEEKDAY }, +]; +const sh = (day: string, hm: string) => new Date(`${day}T${hm}:00+08:00`).toISOString(); + +/** A read double over the two calendar objects: equality `where`s, scoped by the read's tenant. */ +function calendarReads(calendars: Row[], exceptions: Row[]) { + return { + async find(object: string, query: Row) { + const src = object === 'sys_work_calendar' ? calendars : exceptions; + const tenant = query.context?.tenantId; + const hits = src + .filter((r) => tenant === undefined || r.organization_id === tenant) + .filter((r) => Object.entries(query.where ?? {}).every(([k, v]) => { + // Equality only: a combinator or an operator object is refused, never answered wrong. + if (k.startsWith('$') || (v !== null && typeof v === 'object')) throw new Error(`calendarReads answers equality only, not ${k}`); + return r[k] === v; + })); + const from = query.offset ?? 0; + return hits.slice(from, from + (query.limit ?? hits.length)); + }, + }; +} + +/** A service on the real calendar service; `ttlMs: 0` so every computation reads the rows (D12). */ +function workingTimeServiceAt(iso: string, calendars: Row[] = [CN_CALENDAR], exceptions: Row[] = CN_EXCEPTIONS) { + let nowMs = Date.parse(iso); + const engine = makeEngine(); + const reads = calendarReads(calendars, exceptions); + const calendar = new WorkCalendarService({ getEngine: () => reads, posture: () => 'isolated', ttlMs: 0 }); + const svc = new ApprovalService({ + engine: engine as any, + clock: { now: () => new Date(nowMs) }, + workCalendar: () => calendar, + }); + return { svc, engine, setNow: (at: string) => { nowMs = Date.parse(at); } }; +} + +function workingTimeInput(nodeId: string, timeoutHours: number, extra: Row = {}) { + const base = input(nodeId, timeoutHours); + return { ...base, config: { ...base.config, escalation: { ...base.config.escalation, clock: 'working_time' as const, ...extra } } }; +} + +describe("ApprovalEscalation.clock 'working_time' counts the hours on a working calendar", () => { + it('Friday 17:00 + 4 working hours, Monday a holiday: due Tuesday 12:00, and the sweep fires then, not earlier', async () => { + const created = sh('2026-04-03', '17:00'); // a Friday + expect(utcDay(created)).toBe(5); + const { svc, setNow } = workingTimeServiceAt(created); + const req = await openPending(svc, workingTimeInput('wt_holiday', 4)); + expect(req.sla_due_at).toBe(sh('2026-04-07', '12:00')); + + const row = await svc.getRequest(req.id, SYS); + // One hour on Friday (17:00-18:00), the weekend and the Monday holiday + // skipped, three hours on Tuesday morning (09:00-12:00). + expect(row?.sla_due_at).toBe(sh('2026-04-07', '12:00')); + expect(row?.sla_due_refusal).toBeUndefined(); + + // The wall-clock deadline (Friday 21:00) and the Monday that would be the + // next working day without the holiday both pass without an escalation. + for (const at of [sh('2026-04-03', '21:00'), sh('2026-04-06', '12:00'), sh('2026-04-07', '11:59')]) { + setNow(at); + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); + } + setNow(sh('2026-04-07', '12:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); + expect((await svc.listActions(req.id, SYS)).at(-1)).toMatchObject({ action: 'escalate' }); + }); + + it('Friday 17:00 + 4 working hours before a 调休 make-up Saturday: due that Saturday 12:00', async () => { + const created = sh('2026-10-09', '17:00'); // the Friday after National Day week + expect(utcDay(created)).toBe(5); + const { svc, setNow } = workingTimeServiceAt(created); + const req = await openPending(svc, workingTimeInput('wt_makeup', 4, { calendar: 'cn_standard' })); + expect((await svc.getRequest(req.id, SYS))?.sla_due_at).toBe(sh('2026-10-10', '12:00')); + + setNow(sh('2026-10-10', '11:59')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); + setNow(sh('2026-10-10', '12:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); + }); + + it('the deadline is recomputed on every read and sweep, never stored: a holiday entered later moves it (D12)', async () => { + const created = sh('2026-04-03', '17:00'); + const exceptions = [...CN_EXCEPTIONS]; + const { svc, setNow } = workingTimeServiceAt(created, [CN_CALENDAR], exceptions); + const req = await openPending(svc, workingTimeInput('wt_moves', 4)); + expect((await svc.getRequest(req.id, SYS))?.sla_due_at).toBe(sh('2026-04-07', '12:00')); + + exceptions.push({ id: 'ex_0407', calendar: 'cal_cn', organization_id: 't1', date: '2026-04-07', kind: 'off' }); + expect((await svc.getRequest(req.id, SYS))?.sla_due_at).toBe(sh('2026-04-08', '12:00')); + setNow(sh('2026-04-07', '12:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); + setNow(sh('2026-04-08', '12:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); + }); + + it('a calendar that cannot answer: no escalation, the reason is served, and the next sweep retries (D9)', async () => { + const created = sh('2026-04-03', '17:00'); + const calendars: Row[] = []; + const { svc, setNow } = workingTimeServiceAt(created, calendars); + const req = await openPending(svc, workingTimeInput('wt_missing', 4, { calendar: 'cn_standard' })); + + const row = await svc.getRequest(req.id, SYS); + expect(row?.sla_due_at).toBeUndefined(); + expect(row?.sla_due_refusal).toMatchObject({ + code: 'ERR_WORK_CALENDAR_UNRESOLVED', reason: 'not_found', calendar: 'cn_standard', + }); + expect(row?.sla_due_refusal?.message).toEqual(expect.any(String)); + + // Long past any deadline: still no escalation, and no wall-clock fallback. + setNow(sh('2026-04-20', '12:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); + expect((await svc.listActions(req.id, SYS)).some((a) => a.action === 'escalate')).toBe(false); + + // The administrator fixes the calendar; the next sweep recovers with no other step. + calendars.push(CN_CALENDAR); + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); + const fixed = await svc.getRequest(req.id, SYS); + expect(fixed?.sla_due_at).toBe(sh('2026-04-07', '12:00')); + expect(fixed?.sla_due_refusal).toBeUndefined(); + }); + + it('no named calendar and no organization default refuses no_default; a calendar not maintained that far names the date', async () => { + const { svc } = workingTimeServiceAt(sh('2026-04-03', '17:00'), [{ ...CN_CALENDAR, is_default: false }]); + const req = await openPending(svc, workingTimeInput('wt_no_default', 4)); + expect((await svc.getRequest(req.id, SYS))?.sla_due_refusal).toMatchObject({ + code: 'ERR_WORK_CALENDAR_UNRESOLVED', reason: 'no_default', + }); + + const short = workingTimeServiceAt(sh('2026-10-09', '17:00'), [{ ...CN_CALENDAR, maintained_through: '2026-10-09' }]); + const late = await openPending(short.svc, workingTimeInput('wt_unmaintained', 4)); + const read = await short.svc.getRequest(late.id, SYS); + expect(read?.sla_due_at).toBeUndefined(); + expect(read?.sla_due_refusal).toMatchObject({ code: 'ERR_WORK_CALENDAR_NOT_MAINTAINED', calendar: 'cn_standard', date: '2026-10-10' }); + short.setNow(sh('2026-12-31', '12:00')); + expect(await short.svc.runEscalations()).toMatchObject({ escalated: 0 }); + }); + + it("a service with no calendar service refuses too: 'working_time' never falls back to wall-clock hours", async () => { + const { svc, setNow } = serviceAt(sh('2026-04-03', '17:00')); + const req = await openPending(svc, workingTimeInput('wt_no_service', 4)); + const row = await svc.getRequest(req.id, SYS); + expect(row?.sla_due_at).toBeUndefined(); + expect(row?.sla_due_refusal).toMatchObject({ code: 'ERR_WORK_CALENDAR_UNRESOLVED', reason: 'no_default' }); + setNow(sh('2026-04-03', '21:00')); + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); + }); + + it("an explicit 'wall_clock' is the default clock: Friday 17:00 + 4 is due Friday 21:00 with a calendar present", async () => { + const { svc } = workingTimeServiceAt(FRIDAY_1700); + const req = await openPending(svc, workingTimeInput('wc_explicit', 4, { clock: 'wall_clock' })); + const row = await svc.getRequest(req.id, SYS); + expect(row?.sla_due_at).toBe('2026-01-16T21:00:00.000Z'); + expect(row?.sla_due_refusal).toBeUndefined(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 4c675f1e351..ecfd18ef803 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -12,7 +12,12 @@ import { // liveness classification below is checked against it member for member. type ExecutionStatus, } from '@objectstack/spec/automation'; -import { ExpressionEngine, collectCelRootIdentifiers } from '@objectstack/formula'; +import { + ExpressionEngine, + WorkCalendarUnresolvedError, + collectCelRootIdentifiers, + isWorkCalendarRefusal, +} from '@objectstack/formula'; // [#10101] The SHARED platform-row organization resolver — the cloud#1395 // ruling ("A platform row's organization is the SUBJECT record's organization; // actor context is the fallback, never the primary"), implemented once in @@ -64,6 +69,7 @@ import type { ExecutionContext } from '@objectstack/spec/kernel'; import { FlowInnerRefusalSchema } from '@objectstack/spec/api'; import { RESUME_AUTHORITY_SERVICE } from '@objectstack/spec/contracts'; import type { IOwnershipQueueService } from '@objectstack/spec/contracts'; +import type { IWorkCalendarService } from '@objectstack/spec/contracts'; import { canServeApiOperation, isFileIdToken, referenceTargetOf, SINGLE_OPTION_TYPES, MULTI_OPTION_TYPES, } from '@objectstack/spec/data'; @@ -1852,20 +1858,27 @@ function rowFromRequest(row: any): ApprovalRequestRow { } /** - * `created_at + escalation.timeoutHours`, when the node declares an SLA. + * `created_at + escalation.timeoutHours`, when the node declares an SLA on the + * `wall_clock` clock (the default, and every snapshot stored before + * `escalation.clock` existed). * - * Calendar (wall-clock) hours, by construction: the hours are added as elapsed - * milliseconds, so the deadline does not skip nights, weekends or holidays — - * the platform ships no business-hours calendar to count against. This is the - * one runtime site that turns the declared number into a deadline; the sweep - * below and the `sla_due_at` read projection both go through it, and + * Wall-clock hours, by construction: the hours are added as elapsed + * milliseconds, so the deadline does not skip nights, weekends or holidays. + * This is the one runtime site that turns the declared number into a + * wall-clock deadline; the sweep and the `sla_due_at` read projection both + * reach it through {@link ApprovalService.slaDeadline}, and * `approval-service-sla-calendar-clock.test.ts` pins the clock (a request * opened Friday 17:00 with `timeoutHours: 4` is due Friday 21:00; a 168-hour * deadline spans the weekend; a DST transition changes nothing, because the * arithmetic is elapsed time, not local calendar time). The same sentence * lives in the declaration's `describe` text on `ApprovalEscalationSchema`. + * + * A `working_time` escalation has no wall-clock deadline: it answers + * `undefined` here, and only the working calendar counts it (ADR-0157 D2 — no + * silent fallback to wall-clock time). */ function slaDueAt(createdAt: unknown, cfg: any): string | undefined { + if (escalationCountsWorkingTime(cfg)) return undefined; const hours = cfg?.escalation?.timeoutHours; if (typeof hours !== 'number' || hours <= 0 || !createdAt) return undefined; const t = Date.parse(String(createdAt)); @@ -1873,6 +1886,33 @@ function slaDueAt(createdAt: unknown, cfg: any): string | undefined { return new Date(t + hours * 3600_000).toISOString(); } +/** + * [ADR-0157 D5] Does the escalation count its hours on a working calendar? Only + * an explicit `clock: 'working_time'`: a snapshot stored before the key existed + * carries none, and the schema default is `wall_clock`. + */ +function escalationCountsWorkingTime(cfg: any): boolean { + return cfg?.escalation?.clock === 'working_time'; +} + +/** [ADR-0157 D9] What a request's read serves when its calendar cannot count the deadline. */ +type SlaDueRefusal = NonNullable; + +/** The SLA deadline of one stored request, or why its working calendar cannot count it. */ +type SlaDeadline = { due: string } | { refusal: SlaDueRefusal }; + +/** The served form of a calendar refusal (`isWorkCalendarRefusal`): its code and the facts it names. */ +function slaDueRefusalOf(err: { code: SlaDueRefusal['code']; message: string }): SlaDueRefusal { + const e = err as { reason?: unknown; calendar?: unknown; date?: unknown }; + return { + code: err.code, + ...(typeof e.reason === 'string' ? { reason: e.reason as SlaDueRefusal['reason'] } : {}), + ...(typeof e.calendar === 'string' ? { calendar: e.calendar } : {}), + ...(typeof e.date === 'string' ? { date: e.date } : {}), + message: err.message, + }; +} + /** * Normalize one raw `attachments` entry into an {@link ApprovalActionAttachment}. * @@ -2038,6 +2078,18 @@ export interface ApprovalServiceOptions { * decides a slate it leaves empty. */ ownershipQueues?: () => ApproverQueueSource | undefined; + /** + * [ADR-0157 D5] The working-calendar service (`WORK_CALENDAR_SERVICE`) a + * `clock: 'working_time'` escalation counts its hours through. Resolved + * LAZILY per deadline, for the reason {@link ApprovalServiceOptions.tenancyPosture} + * is: `@objectstack/objectql` registers it and may start after this plugin. + * + * Absent (or resolving to `undefined`), a `working_time` deadline is refused + * as an unresolved calendar, exactly as a kernel without the calendar object + * refuses it: the request does not escalate and its read says why (D9) — + * never a wall-clock answer (D2). + */ + workCalendar?: () => Pick | undefined; } /** [ADR-0142 D6] The slice of the queue service a `queue` approver reads. */ @@ -2154,6 +2206,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega private i18nServiceSource?: () => ReaderLabelI18n | undefined; /** [ADR-0142 D6] Lazily-resolved `ownership-queue` service a `queue` approver expands through. */ private ownershipQueues?: () => ApproverQueueSource | undefined; + /** [ADR-0157 D5] Lazily-resolved working-calendar service a `working_time` escalation counts through. */ + private workCalendar?: () => Pick | undefined; /** * [#8652] The HOST-named object set for the record-reader visibility tier * (the constructor option). EMPTY is the default, and the tier is then off @@ -2195,6 +2249,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega this.messageTranslator = opts.messageTranslator; this.i18nServiceSource = opts.i18nServiceSource; this.ownershipQueues = opts.ownershipQueues; + this.workCalendar = opts.workCalendar; this.recordReaderVisibleObjects = new Set( (Array.isArray(opts.recordReaderVisibleObjects) ? opts.recordReaderVisibleObjects : []) .map((n) => String(n ?? '').trim()) @@ -5563,7 +5618,9 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); } - return rowFromRequest(row); + const opened = rowFromRequest(row); + await this.projectWorkingTimeDue([row], [opened]); + return opened; } /** @@ -8182,6 +8239,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega } let escalated = 0; + let calendarRefused = 0; for (const raw of rows) { try { const cfg = parseJson(raw.node_config_json, undefined); @@ -8196,8 +8254,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // preserves them verbatim; see ESCALATION_ENABLED_FLIP_CUTOFF_MS. if (esc.enabled === false && Date.parse(raw.created_at ?? '') >= ESCALATION_ENABLED_FLIP_CUTOFF_MS) continue; - const due = slaDueAt(raw.created_at, cfg); - if (!due || Date.parse(due) > this.clock.now().getTime()) continue; + // ADR-0157 D9: a working calendar that cannot count the deadline + // escalates nothing, and the next sweep asks it again (D12: the + // deadline is recomputed every sweep, never stored). + const deadline = await this.slaDeadline(raw, cfg); + if (!deadline) continue; + if ('refusal' in deadline) { + calendarRefused++; + continue; + } + if (Date.parse(deadline.due) > this.clock.now().getTime()) continue; // Single-shot: a prior 'escalate' action means this request is done. const prior = await this.engine.find('sys_approval_action', { @@ -8216,9 +8282,72 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (escalated > 0) { this.logger?.info?.('[approvals] SLA escalation sweep', { scanned: rows.length, escalated }); } + if (calendarRefused > 0) { + this.logger?.warn?.( + '[approvals] SLA escalation sweep: a working calendar could not count the deadline of some pending ' + + 'requests, so they were not escalated; each request read says why, and the next sweep tries again', + { calendarRefused }, + ); + } return { scanned: rows.length, escalated }; } + /** + * The SLA deadline of one stored request — the ONE function the sweep and + * the `sla_due_at` read projection share (ADR-0157 D12), so the displayed due + * time is the one the sweep acts on. `undefined` when the node declares no + * SLA. + * + * `wall_clock` (the default): {@link slaDueAt}, unchanged. `working_time`: + * `timeoutHours` working hours after `created_at` on the request + * organization's calendar, named by `escalation.calendar` or else its default + * (D2), recomputed on every call and never stored (D12). A calendar refusal + * (none resolves, or it is not maintained that far, D8) answers + * `{ refusal }` instead of a deadline (D9); every other failure throws. + */ + private async slaDeadline(raw: any, cfg: any): Promise { + if (!escalationCountsWorkingTime(cfg)) { + const due = slaDueAt(raw?.created_at, cfg); + return due ? { due } : undefined; + } + const esc = cfg.escalation; + const hours = esc.timeoutHours; + if (typeof hours !== 'number' || hours <= 0 || !raw?.created_at) return undefined; + const start = Date.parse(String(raw.created_at)); + if (Number.isNaN(start)) return undefined; + const calendar = typeof esc.calendar === 'string' && esc.calendar.trim() !== '' ? esc.calendar.trim() : undefined; + try { + const service = this.workCalendar?.(); + if (!service) throw new WorkCalendarUnresolvedError(calendar === undefined ? 'no_default' : 'not_found', calendar); + const due = await service.addWorkingHours( + { organizationId: raw.organization_id ? String(raw.organization_id) : undefined, calendar }, + start, + hours, + ); + return { due: new Date(due).toISOString() }; + } catch (err) { + if (isWorkCalendarRefusal(err)) return { refusal: slaDueRefusalOf(err) }; + throw err; + } + } + + /** + * [ADR-0157 D9, D12] Serve each `working_time` row's deadline, or why its + * calendar cannot count it, through {@link slaDeadline}. `raws[i]` is the + * stored row `rows[i]` was mapped from; a `wall_clock` row already carries + * its deadline from the synchronous mapper and is left alone. + */ + private async projectWorkingTimeDue(raws: readonly any[], rows: ApprovalRequestRow[]): Promise { + for (let i = 0; i < rows.length; i++) { + const cfg = parseJson(raws[i]?.node_config_json, undefined); + if (!escalationCountsWorkingTime(cfg)) continue; + const deadline = await this.slaDeadline(raws[i], cfg); + if (!deadline) continue; + if ('refusal' in deadline) rows[i]!.sla_due_refusal = deadline.refusal; + else rows[i]!.sla_due_at = deadline.due; + } + } + // ── Dead-run release (#3456) ────────────────────────────────── /** @@ -10669,6 +10798,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const rows = await this.engine.find('sys_approval_request', findOpts); const list = Array.isArray(rows) ? rows.map(rowFromRequest) : []; + if (Array.isArray(rows)) await this.projectWorkingTimeDue(rows, list); // [#10749] Redact before enrichment — see `redactPayloads`. [#23594] The // snapshot and the subject title are narrowed by ONE answer for the reader; // [#23618] the lookup targets' titles by the same reader's answers for them. @@ -10911,6 +11041,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (!read) return null; const { raw, caller } = read; const row = rowFromRequest(raw); + await this.projectWorkingTimeDue([raw], [row]); // [#10749] Redact before enrichment — see `redactPayloads`. [#23594] The // snapshot and the subject title are narrowed by ONE answer for the reader; // [#23618] the lookup targets' titles by the same reader's answers for them. diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index 5940ae255ba..b5bf19aeb45 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -7,7 +7,8 @@ import type { IJobService, IObjectQLEngine, } from '@objectstack/spec/contracts'; -import { OWNERSHIP_QUEUE_SERVICE } from '@objectstack/spec/contracts'; +import { OWNERSHIP_QUEUE_SERVICE, WORK_CALENDAR_SERVICE } from '@objectstack/spec/contracts'; +import type { IWorkCalendarService } from '@objectstack/spec/contracts'; import { SysApprovalRequest } from './sys-approval-request.object.js'; import { SysApprovalAction } from './sys-approval-action.object.js'; import { SysApprovalApprover } from './sys-approval-approver.object.js'; @@ -302,6 +303,17 @@ export class ApprovalsServicePlugin implements Plugin { return undefined; } }, + // [ADR-0157 D5] The working-calendar service a `clock: 'working_time'` + // escalation counts through. Resolved LAZILY for the reason the + // providers above are: objectql registers it and may start after this + // one. Absent, a working-time deadline is refused, never wall-clock. + workCalendar: () => { + try { + return ctx.getService(WORK_CALENDAR_SERVICE); + } catch { + return undefined; + } + }, }); // [#10749] Field-visibility authority for payload-snapshot redaction. diff --git a/packages/spec/authorable-defaults/automation.json b/packages/spec/authorable-defaults/automation.json index f118f612622..87ce0a73564 100644 --- a/packages/spec/authorable-defaults/automation.json +++ b/packages/spec/authorable-defaults/automation.json @@ -13,6 +13,7 @@ "automation/ActionDescriptor:supportsPause = false", "automation/ActionDescriptor:supportsRetry = true", "automation/ApprovalEscalation:action = \"notify\"", + "automation/ApprovalEscalation:clock = \"wall_clock\"", "automation/ApprovalEscalation:enabled = true", "automation/ApprovalEscalation:notifySubmitter = true", "automation/ApprovalNodeConfig:behavior = \"first_response\"", diff --git a/packages/spec/authorable-surface/automation.json b/packages/spec/authorable-surface/automation.json index b63428f4a1a..6f2879d733f 100644 --- a/packages/spec/authorable-surface/automation.json +++ b/packages/spec/authorable-surface/automation.json @@ -33,6 +33,8 @@ "automation/ApiTriggerTimestampedSignature:signs", "automation/ApiTriggerTimestampedSignature:timestampElement", "automation/ApprovalEscalation:action", + "automation/ApprovalEscalation:calendar", + "automation/ApprovalEscalation:clock", "automation/ApprovalEscalation:enabled", "automation/ApprovalEscalation:escalateTo", "automation/ApprovalEscalation:notifySubmitter", diff --git a/packages/spec/src/automation/approval.zod.ts b/packages/spec/src/automation/approval.zod.ts index 3f2ceeb11ec..f9b0f16b08f 100644 --- a/packages/spec/src/automation/approval.zod.ts +++ b/packages/spec/src/automation/approval.zod.ts @@ -4,6 +4,7 @@ import { z } from 'zod'; import { BUILTIN_MEMBERSHIP_ROLES } from '../identity/membership-role'; import { lazySchema } from '../shared/lazy-schema'; import { strictObject } from '../shared/strict-object'; +import { WORK_CALENDAR_CODE_PATTERN } from '../data/work-calendar'; // Why the members sit in THIS order (the generated reference renders the JSDoc // below; this rationale stays in source): @@ -860,16 +861,29 @@ export const ApprovalEscalationSchema = lazySchema(() => strictObject( // feature-level switch is whether the block exists at all. enabled: z.boolean().default(true).describe("Turns this step's deadline on or off. It is on by default once a deadline is set: switch it off to keep the settings without acting on them, or remove the escalation to drop the deadline altogether"), /** - * Wall-clock SLA. The approvals service adds `timeoutHours` to the request's - * `created_at` as elapsed milliseconds (hours × 3_600_000), so the deadline - * does not skip nights, weekends or holidays — the platform ships no - * business-hours calendar to count against. The clock is named in the - * declaration's own contract text rather than in prose beside it, so the - * number cannot be read as working hours at authoring time. No `clock` key - * exists because only one clock exists: a key with a single legal value would - * be declared-but-inert (ADR-0049). + * The deadline, in hours from the request's `created_at`. How the hours count + * is `clock`'s (ADR-0157 D5): under `wall_clock` the approvals service adds + * them as elapsed milliseconds (hours × 3_600_000), so nights, weekends and + * holidays count; under `working_time` it counts them through a working + * calendar (`addWorkingHours`), recomputed on every sweep (D12). The clock is + * named in the declaration's own contract text, so the number cannot be read + * as the other clock's hours at authoring time. */ - timeoutHours: z.number().min(1).describe('How many hours a request may wait before the escalation runs. These are calendar (wall-clock) hours — nights, weekends and holidays count. The platform ships no business-hours calendar: a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that same Friday'), + timeoutHours: z.number().min(1).describe('How many hours a request may wait before the escalation runs, counted from when it was submitted. The clock decides how the hours count: wall-clock hours (the default) count nights, weekends and holidays, so a request opened at 17:00 on a Friday with 4 hours escalates at 21:00 that Friday; working hours count only the working periods of a working calendar'), + // ADR-0157 D5: the second clock. The default stays `wall_clock` because the + // sweep reads the node-config snapshot stored on each request, and a snapshot + // written before this key existed carries none — flipping the default would + // move every open deadline. "Calendar hours" is deliberately not a value + // name: it read as wall-clock hours before a working calendar existed. + clock: z.enum(['wall_clock', 'working_time']).default('wall_clock') + .describe("How the timeout's hours count: every hour, or only working hours. Wall-clock hours ('wall_clock', the default) count nights, weekends and holidays. Working hours ('working_time') count only the working periods of the organization's working calendar, skipping its holidays and counting its make-up workdays; when the calendar cannot count the deadline (no such calendar, or not maintained that far) the request does not escalate and shows why, until the calendar is fixed"), + // ADR-0157 D2: the explicit code, else the organization's default calendar, + // else a refusal — never wall-clock time. Read only under `working_time`; the + // approval lint refuses it beside `wall_clock`, where nothing reads it + // (`approval-escalation-calendar-without-working-time`). Whether the calendar + // exists is runtime data per organization, never a publish-time check (D9). + calendar: z.string().regex(new RegExp(WORK_CALENDAR_CODE_PATTERN)).optional() + .describe("Which working calendar counts the hours under working time, by its code. Leave it empty to use the organization's default calendar"), action: z.enum(['reassign', 'auto_approve', 'auto_reject', 'notify']).default('notify') .describe('What happens when the deadline passes: hand the request to someone else, approve it, reject it, or notify someone (the default)'), // Escalation hands the request to a position (the common case — e.g. an diff --git a/packages/spec/src/contracts/approval-service.ts b/packages/spec/src/contracts/approval-service.ts index 7600f992270..9f077ff18a5 100644 --- a/packages/spec/src/contracts/approval-service.ts +++ b/packages/spec/src/contracts/approval-service.ts @@ -27,6 +27,12 @@ import type { ExecutionContext } from '../kernel/execution-context.zod.js'; import type { ErrorCode } from '../api/error-code-ledger.zod.js'; import type { FlowInnerRefusal, ResumeFailureDetails } from '../api/automation-api.zod.js'; +import type { + WORK_CALENDAR_INVALID_CODE, + WORK_CALENDAR_NOT_MAINTAINED_CODE, + WORK_CALENDAR_UNRESOLVED_CODE, + WorkCalendarUnresolvedReason, +} from '../data/work-calendar.js'; /** * Lifecycle states of an approval request, in the order the @@ -299,11 +305,33 @@ export interface ApprovalRequestRow { */ payload_labels?: Record; /** - * SLA deadline, when the node config carries `escalation.timeoutHours`: - * `created_at + timeoutHours`. Display-only for now — automatic escalation - * needs a scheduler pass and is not yet wired. + * SLA deadline, when the node config carries `escalation.timeoutHours`: the + * instant the escalation sweep acts on, computed by the same function the + * sweep uses. Under `escalation.clock: 'wall_clock'` it is `created_at + + * timeoutHours` elapsed hours; under `'working_time'` it is `timeoutHours` + * working hours after `created_at` on the escalation's working calendar, + * recomputed on every read (ADR-0157 D12). Absent when the calendar cannot + * count it; {@link ApprovalRequestRow.sla_due_refusal} then says why. */ sla_due_at?: string; + /** + * [ADR-0157 D9] Why a `working_time` escalation has no `sla_due_at`: its + * working calendar cannot count the deadline. The sweep does not escalate the + * request and tries again on its next pass, so once an administrator fixes + * the calendar the deadline returns with no other step. `code` is the + * calendar refusal's ledger code; `reason` (on `ERR_WORK_CALENDAR_UNRESOLVED`) + * says which resolution step failed; `date` (on + * `ERR_WORK_CALENDAR_NOT_MAINTAINED`) is the day the calendar is not + * maintained for; `message` is the refusal's own English sentence. Absent + * whenever `sla_due_at` is present, and on every `wall_clock` escalation. + */ + sla_due_refusal?: { + code: typeof WORK_CALENDAR_UNRESOLVED_CODE | typeof WORK_CALENDAR_NOT_MAINTAINED_CODE | typeof WORK_CALENDAR_INVALID_CODE; + reason?: WorkCalendarUnresolvedReason; + calendar?: string; + date?: string; + message: string; + }; /** * The owning flow's approval steps in graph order, for progress display * (resolved on single-request reads when the automation engine is diff --git a/scripts/adr-anchors/packages__plugins__plugin-approvals__src__approval-service.ts.json b/scripts/adr-anchors/packages__plugins__plugin-approvals__src__approval-service.ts.json new file mode 100644 index 00000000000..a0abfb77f5a --- /dev/null +++ b/scripts/adr-anchors/packages__plugins__plugin-approvals__src__approval-service.ts.json @@ -0,0 +1,5 @@ +{ + "file": "packages/plugins/plugin-approvals/src/approval-service.ts", + "adrs": ["ADR-0157", "ADR-0042"], + "invariant": "ADR-0157 D5, D9, D12: an approval escalation's deadline comes from one function (ApprovalService.slaDeadline) that both the escalation sweep and the sla_due_at read projection call. The default wall_clock counts created_at + timeoutHours elapsed hours (ADR-0042 §3). working_time counts timeoutHours working hours on the request organization's calendar, named by escalation.calendar or else its default, recomputed on every sweep and read and never stored, with no wall-clock fallback; when the calendar refuses, the sweep does not escalate and the read serves sla_due_refusal, and the next sweep asks again. ADR-0042 §1 single-shot escalation stands." +} diff --git a/ui/apps/console/src/pages/system/ApprovalsInboxPage.slaCalendarRefusal.test.tsx b/ui/apps/console/src/pages/system/ApprovalsInboxPage.slaCalendarRefusal.test.tsx new file mode 100644 index 00000000000..192562add0c --- /dev/null +++ b/ui/apps/console/src/pages/system/ApprovalsInboxPage.slaCalendarRefusal.test.tsx @@ -0,0 +1,151 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * A working-time SLA whose calendar cannot count the deadline shows WHY in the + * place the SLA countdown sits (ADR-0157 D9): 「日历算不出」 and the reason, + * from the row's `sla_due_refusal`, in the UI language. A row with a due time + * keeps its countdown (the control), and a row with neither shows nothing. + * + * The harness is the queue page's own (`ApprovalsInboxPage.displayLocale-10375.test.tsx`): + * the real `I18nProvider`, with the approvals API stubbed to the served rows. + */ + +import '@testing-library/jest-dom/vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { cleanup, render, screen } from '@testing-library/react'; +import { MemoryRouter, Route, Routes } from 'react-router-dom'; +import { MePermissionsProvider, type MePermissionsAuthenticatedResponse } from '@object-ui/permissions'; +import { I18nProvider } from '@object-ui/i18n'; + +const { approvalsApiStub, ADAPTER, AUTH } = vi.hoisted(() => { + const SUBMITTED = new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(); + const row = (id: string, extra: Record): Record => ({ + id, + process_name: 'purchase_approval', + process_label: 'Purchase Approval', + object_name: 'showcase_purchase', + object_label: 'Purchase', + record_id: `po_${id}`, + record_title: `PO ${id}`, + status: 'pending', + pending_approvers: ['u_1'], + submitter_id: 'u_2', + submitter_name: 'Sam Submitter', + submitted_at: SUBMITTED, + ...extra, + }); + const ROWS = [ + row('missing', { + sla_due_refusal: { + code: 'ERR_WORK_CALENDAR_UNRESOLVED', reason: 'not_found', calendar: 'cn_standard', + message: "No working calendar has the code 'cn_standard' in this organization.", + }, + }), + row('unmaintained', { + sla_due_refusal: { + code: 'ERR_WORK_CALENDAR_NOT_MAINTAINED', calendar: 'cn_standard', date: '2027-01-04', + message: "Working calendar 'cn_standard' is maintained through 2026-12-31.", + }, + }), + row('timed', { sla_due_at: new Date(Date.now() + 5 * 60 * 60 * 1000).toISOString() }), + ]; + const approvalsApiStub = { + listRequests: async () => ({ data: ROWS, total: ROWS.length }), + getRequest: async () => ({ data: ROWS[0] }), + listActions: async () => ({ data: [] }), + approve: async () => ({ data: ROWS[0], finalized: true }), + reject: async () => ({ data: ROWS[0], finalized: true }), + }; + const ADAPTER = { + find: async () => ({ data: ROWS.map((r) => ({ id: r.record_id })) }), + getObjectSchema: async () => ({ fields: {} }), + }; + const AUTH = { user: { id: 'u_1', email: 'approver@example.com' } }; + return { approvalsApiStub, ADAPTER, AUTH }; +}); + +vi.mock('@object-ui/auth', async (importOriginal) => { + const authFetch = async () => new Response('{}', { status: 200 }); + return { + ...(await importOriginal>()), + useAuth: () => AUTH, + createAuthenticatedFetch: () => authFetch, + TokenStorage: { get: () => null }, + }; +}); + +vi.mock('@object-ui/app-shell', async (importOriginal) => ({ + ...(await importOriginal>()), + useAdapter: () => ADAPTER, + useMetadata: () => ({ objects: [] }), + DeclaredActionsBar: () => null, + isViaOverrideRow: () => false, +})); + +vi.mock('../../services/approvalsApi', async (importOriginal) => ({ + ...(await importOriginal>()), + approvalsApi: approvalsApiStub, +})); + +import { ApprovalsInboxPage } from './ApprovalsInboxPage'; + +afterEach(() => cleanup()); + +function permissions(): MePermissionsAuthenticatedResponse { + return { + authenticated: true, + userId: 'u_1', + tenantId: 't_1', + positions: [], + hasAnyQueue: false, + objectsUsingQueues: [], + permissionSets: [], + objects: {}, + fields: {}, + systemPermissions: ['setup.access'], + }; +} + +function renderInbox(language: string) { + return render( + + + + + } /> + + + + , + ); +} + +/** The queue cell's SLA line of the row whose record title is `title`. */ +async function slaLine(title: string): Promise { + const link = (await screen.findAllByText(title))[0]!; + const row = link.closest('tr'); + expect(row, `no queue row for ${title}`).not.toBeNull(); + const cell = row!.querySelector('td[title]'); + return (cell?.querySelector('div')?.textContent ?? '').trim(); +} + +describe('ApprovalsInboxPage — a working calendar that cannot count the SLA says why (ADR-0157 D9)', () => { + it('shows the reason in place of the countdown, and keeps the countdown where a due time is served', async () => { + renderInbox('en'); + expect(await slaLine('PO missing')).toBe('Calendar can\'t compute: no calendar "cn_standard"'); + expect(await slaLine('PO unmaintained')).toBe('Calendar can\'t compute: not maintained for 2027-01-04'); + expect(await slaLine('PO timed')).toMatch(/^SLA .* left$/); + }); + + it("reads in the UI language: 「日历算不出」 under zh-CN", async () => { + renderInbox('zh-CN'); + expect(await slaLine('PO missing')).toBe('日历算不出:没有日历“cn_standard”'); + expect(await slaLine('PO unmaintained')).toBe('日历算不出:未维护到 2027-01-04'); + }); +}); diff --git a/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx b/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx index 52f03970d58..d612029b2ad 100644 --- a/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx +++ b/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx @@ -901,6 +901,27 @@ function ApprovalsQueue() { [tr], ); + /** + * Why the SLA has no due time (ADR-0157 D9): 「日历算不出」 and the reason, + * from the refusal's code. A code or reason this page does not know reads as + * a calendar to fix, never as no SLA. + */ + const slaRefusalLabel = useCallback( + (refusal: NonNullable): string => { + if (refusal.code === 'ERR_WORK_CALENDAR_NOT_MAINTAINED' && refusal.date) { + return tr('slaCalendarNotMaintained', 'Calendar can\'t compute: not maintained for {{date}}', { date: refusal.date }); + } + if (refusal.code === 'ERR_WORK_CALENDAR_UNRESOLVED' && refusal.reason === 'not_found' && refusal.calendar) { + return tr('slaCalendarNotFound', 'Calendar can\'t compute: no calendar "{{calendar}}"', { calendar: refusal.calendar }); + } + if (refusal.code === 'ERR_WORK_CALENDAR_UNRESOLVED' && refusal.reason === 'no_default') { + return tr('slaCalendarNoDefault', 'Calendar can\'t compute: no default calendar'); + } + return tr('slaCalendarUnusable', 'Calendar can\'t compute: fix the calendar in Setup'); + }, + [tr], + ); + const recordHref = useCallback((r: ApprovalRequestRow): string => { const app = appName || 'setup'; return `/apps/${app}/${encodeURIComponent(r.object_name)}/record/${encodeURIComponent(r.record_id)}`; @@ -1592,6 +1613,15 @@ function ApprovalsQueue() { {formatRelative(submittedAt(r))} {r.status === 'pending' && (() => { const sla = slaState(r.sla_due_at, now); + if (!sla && r.sla_due_refusal) { + // ADR-0157 D9: the working calendar cannot count the + // deadline, so the request waits; say why in its place. + return ( +
+ {slaRefusalLabel(r.sla_due_refusal)} +
+ ); + } return sla ? (
; /** Display labels for `payload` fields (field key → target object's field label). */ payload_labels?: Record; - /** SLA deadline (`created_at + escalation.timeoutHours`), display-only. */ + /** + * SLA deadline: `created_at + escalation.timeoutHours` on the wall clock, or + * that many working hours on a working calendar under `clock: 'working_time'`. + */ sla_due_at?: string; + /** + * Why a working-time escalation has no `sla_due_at`: its working calendar + * cannot count the deadline (ADR-0157 D9). The request does not escalate + * until the calendar is fixed; the inbox shows the reason in place of the + * SLA countdown. + */ + sla_due_refusal?: { + code: 'ERR_WORK_CALENDAR_UNRESOLVED' | 'ERR_WORK_CALENDAR_NOT_MAINTAINED' | 'ERR_WORK_CALENDAR_INVALID'; + reason?: 'not_found' | 'no_default' | 'ambiguous' | 'no_organization'; + calendar?: string; + date?: string; + message: string; + }; /** * Owning flow's approval steps (single reads only): one trunk of the graph, * not this request's route past a decision, so nothing draws it. diff --git a/ui/packages/app-shell/src/views/metadata-admin/i18n.ts b/ui/packages/app-shell/src/views/metadata-admin/i18n.ts index 1d3164ccb39..178fe6e1254 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/i18n.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/i18n.ts @@ -489,7 +489,17 @@ const FLOW_FIELD_ZH: Record> = { 'escalation.enabled': { label: 'SLA 升级', help: '在超时内未做决策时升级。' }, 'escalation.timeoutHours': { label: '超时(小时)', - help: '请求最多等多少小时后执行升级。按日历小时计算,夜间、周末和节假日都算在内;平台没有工作时间日历:周五 17:00 发起、设为 4 小时的请求会在当天 21:00 升级。', + help: '请求从提交起最多等多少小时后执行升级。小时怎么算由「计时方式」决定:按自然小时(默认)时夜间、周末和节假日都算在内,周五 17:00 发起、设为 4 小时的请求会在当天 21:00 升级;按工作时间时只计算工作日历中的工作时段。', + }, + 'escalation.clock': { + label: '计时方式', + help: '自然小时把夜间、周末和节假日都算在内;工作时间只计算工作日历中的工作时段。', + opts: { wall_clock: '自然小时', working_time: '工作时间' }, + }, + 'escalation.calendar': { + label: '工作日历', + help: '用来计算工作时间的工作日历编码。留空则使用组织的默认日历。', + placeholder: '组织默认日历', }, 'escalation.action': { label: '超时动作', diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.declaredDefault.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.declaredDefault.test.tsx index 33f0b9f8189..ac60dd63bed 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.declaredDefault.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.declaredDefault.test.tsx @@ -81,6 +81,9 @@ vi.mock('../previews/useObjectFields', () => ({ import { FlowNodeInspector } from './FlowNodeInspector'; import { fieldsForNodeType, FLOW_NODE_CONFIG_TYPES } from './flow-node-config'; import type { MetadataSelection } from '../preview-registry'; +// The inspector's CEL authoring reaches `@objectstack/lint` by a dynamic import; +// paying its first load here, at collection, keeps it out of a clocked case. +import '@objectstack/lint'; // The runtime's own answer for an omitted `escalation` key. Imported so the // #6620 rows below compare the RENDERED control against the installed contract // instead of against a literal this file would then own a second copy of. @@ -998,7 +1001,7 @@ describe('the declaration surface this card names', () => { */ const OFF_PICKER_TYPES = ['boundary_event', 'parallel_gateway', 'join_gateway', 'legacy_action', 'notify']; - it('exactly ten fields declare a defaultValue, and these are they', () => { + it('exactly eleven fields declare a defaultValue, and these are they', () => { const swept = FLOW_NODE_CONFIG_TYPES; expect( swept, @@ -1013,6 +1016,8 @@ describe('the declaration surface this card names', () => { } expect([...declaring].sort()).toEqual([ 'approval.escalation.action', + // The eleventh: ADR-0157 D5's `clock`, whose spec default is 'wall_clock'. + 'approval.escalation.clock', 'approval.escalation.enabled', 'approval.escalation.notifySubmitter', 'approval.behavior', @@ -1062,10 +1067,11 @@ describe('the declaration surface this card names', () => { expect( cases.map((c) => c.id).sort(), - 'the select-kind half of the declaration surface — five of the ten', + 'the select-kind half of the declaration surface — six of the eleven', ).toEqual([ 'approval.behavior', 'approval.escalation.action', + 'approval.escalation.clock', 'approval.onEmptyApprovers', 'end.outcome', 'screen.mode', diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.escalationOff-11660.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.escalationOff-11660.test.tsx index 487fe3ef5ae..4365bdead9e 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.escalationOff-11660.test.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/FlowNodeInspector.escalationOff-11660.test.tsx @@ -61,6 +61,9 @@ vi.mock('../previews/useObjectFields', () => ({ import { FlowNodeInspector } from './FlowNodeInspector'; import type { MetadataSelection } from '../preview-registry'; import { ApprovalNodeConfigSchema, getApprovalNodeConfigJsonSchema } from '@objectstack/spec/automation'; +// The inspector's CEL authoring reaches `@objectstack/lint` by a dynamic import; +// paying its first load here, at collection, keeps it out of a clocked case. +import '@objectstack/lint'; /* ── The `meta/*` double (objectui#7307), as the sibling inspector files * serve it: an empty registry in the `{ type, items: [] }` envelope, and an @@ -343,7 +346,8 @@ for (const source of SOURCES) { expect(onConfig.escalation, 'the inspector stored exactly what the author entered').toEqual(authored); const on = ApprovalNodeConfigSchema.safeParse(onConfig); expect(on.success, on.success ? '' : JSON.stringify(on.error.issues)).toBe(true); - expect((on.data as { escalation?: unknown }).escalation, 'and the contract keeps every value').toEqual(authored); + // The parse adds the one default the author left unset, `clock` (ADR-0157 D5). + expect((on.data as { escalation?: unknown }).escalation, 'and the contract keeps every value').toEqual({ ...authored, clock: 'wall_clock' }); // OFF, values retained. gateBox(l)!.click(); @@ -352,7 +356,7 @@ for (const source of SOURCES) { expect(JSON.stringify(offConfig.escalation), 'every value identical, the switch false').toBe(JSON.stringify(retained)); const off = ApprovalNodeConfigSchema.safeParse(offConfig); expect(off.success, off.success ? '' : JSON.stringify(off.error.issues)).toBe(true); - expect((off.data as { escalation?: unknown }).escalation, 'and the contract keeps them, switched off').toEqual(retained); + expect((off.data as { escalation?: unknown }).escalation, 'and the contract keeps them, switched off').toEqual({ ...retained, clock: 'wall_clock' }); }); }); @@ -393,3 +397,41 @@ for (const source of SOURCES) { }); }); } + +/* ── ADR-0157 D5: the escalation's clock, and the working calendar it reads. + * The calendar is read only under `clock: 'working_time'`, so it is on screen + * only there, from both descriptor sources (`SIBLING_GATES`). ── */ +const CLOCK_LABELS: Record<'offline' | 'engine', { clock: string; calendar: string }> = { + offline: { clock: 'Count hours as', calendar: 'Working calendar' }, + engine: { clock: 'Clock', calendar: 'Calendar' }, +}; + +for (const source of SOURCES) { + const l = CLOCK_LABELS[source.name]; + + describe(`${source.name} descriptors: the working calendar shows only under working time (ADR-0157 D5)`, () => { + beforeEach(() => source.install()); + + it('an escalation on the default clock shows the clock and hides the calendar', () => { + mount(draftWith({ approvers: APPROVERS, escalation: { timeoutHours: 4 } })); + expect(screen.queryByText(l.clock)).not.toBeNull(); + expect(screen.queryByText(l.calendar)).toBeNull(); + }); + + it("an explicit 'wall_clock' hides the calendar too", () => { + mount(draftWith({ approvers: APPROVERS, escalation: { timeoutHours: 4, clock: 'wall_clock' } })); + expect(screen.queryByText(l.calendar)).toBeNull(); + }); + + it("'working_time' shows the calendar, and a code typed there round-trips through ApprovalNodeConfigSchema", () => { + const { latest } = mount(draftWith({ approvers: APPROVERS, escalation: { timeoutHours: 4, clock: 'working_time' } })); + expect(screen.queryByText(l.calendar)).not.toBeNull(); + const calendarInput = screen.getByText(l.calendar).parentElement?.querySelector('input'); + if (!calendarInput) throw new Error(`no input beside '${l.calendar}'`); + fireEvent.change(calendarInput, { target: { value: 'cn_standard' } }); + const after = configOf(latest())!; + expect(after.escalation).toEqual({ timeoutHours: 4, clock: 'working_time', calendar: 'cn_standard' }); + expect(ApprovalNodeConfigSchema.safeParse(after).success).toBe(true); + }); + }); +} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.inactiveRetained.test.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.inactiveRetained.test.ts index cd3e7071733..acca4a7ad8b 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.inactiveRetained.test.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.inactiveRetained.test.ts @@ -167,9 +167,11 @@ describe('inactiveRetainedKind — mechanical coverage of every showWhen group', // objectui#12742: 23 -> 22 ungated types — `webhook` left the alias list // (spec 18 reserves it as a node type), and `http_request` became `http`, // a key `FLOW_NODE_CONFIG_TYPES` already contributes. + // ⚑ RE-MEASURED for ADR-0157 D5: the approval escalation gained `clock` + // (gated on `escalation.enabled`) and `calendar` (gated on `clock`), 33 -> 35. expect(gatedByType.size).toBe(9); // 9 (name, ...) buckets — 8 canonical + the `script_task` alias const totalGated = [...gatedByType.values()].reduce((n, fs) => n + fs.length, 0); - expect(totalGated).toBe(33); + expect(totalGated).toBe(35); // The discriminating control: most node types have NO showWhen at all, so a // predicate that simply said "yes" everywhere would fail here. const ungatedTypes = TYPES.filter((t) => !gatedByType.has(t)); @@ -214,7 +216,7 @@ describe('inactiveRetainedKind — mechanical coverage of every showWhen group', checked += 1; } } - expect(checked).toBe(33); // objectui#9336 added `end.message`, objectui#12780 ungated `start.condition` — see the note above. + expect(checked).toBe(35); // objectui#9336 added `end.message`, objectui#12780 ungated `start.condition`, ADR-0157 D5 added `escalation.clock` and `escalation.calendar` — see the note above. }); }); diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts index 6652bf1acdc..f80481e8485 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/flow-node-config.ts @@ -30,7 +30,7 @@ */ import type { FlowTriggerKind } from '@objectstack/spec/automation'; -import type { DeclaredConfigKey } from './json-schema-to-fields.js'; +import { SIBLING_GATES, type DeclaredConfigKey } from './json-schema-to-fields.js'; import type { RegistryAndDataValueSource, RegistryValueSource } from '../../../utils/approverValueSources.js'; import { flowFieldZh, isZhLocale } from '../i18n.js'; @@ -1163,6 +1163,23 @@ const FLOW_NODE_CONFIG: Record = { // same: the rule is keyed by path, not declared here. { id: 'escalation.enabled', path: ['config', 'escalation', 'enabled'], label: 'SLA escalation', kind: 'boolean', defaultValue: 'true', help: 'Escalate when a decision is not recorded within the timeout.' }, { id: 'escalation.timeoutHours', path: ['config', 'escalation', 'timeoutHours'], label: 'Timeout (hours)', kind: 'number', placeholder: '24', showWhen: { field: 'escalation.enabled', equals: ['true'] } }, + // ADR-0157 D5: how the timeout's hours count. `defaultValue` mirrors the + // spec's `.default('wall_clock')` (held by the spec-reconciliation test). + // The calendar shows only under working time (`SIBLING_GATES`). + { + id: 'escalation.clock', path: ['config', 'escalation', 'clock'], label: 'Count hours as', kind: 'select', defaultValue: 'wall_clock', + options: [ + { value: 'wall_clock', label: 'Wall-clock hours' }, + { value: 'working_time', label: 'Working hours' }, + ], + help: 'Wall-clock hours count nights, weekends and holidays. Working hours count only the working periods of a working calendar.', + showWhen: { field: 'escalation.enabled', equals: ['true'] }, + }, + { + id: 'escalation.calendar', path: ['config', 'escalation', 'calendar'], label: 'Working calendar', kind: 'text', placeholder: 'Organization default', + help: "The code of the working calendar that counts the hours. Leave it empty to use the organization's default calendar.", + showWhen: SIBLING_GATES['escalation.calendar'], + }, { id: 'escalation.action', path: ['config', 'escalation', 'action'], label: 'On timeout', kind: 'select', defaultValue: 'notify', options: [ diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/json-schema-to-fields.ts b/ui/packages/app-shell/src/views/metadata-admin/inspectors/json-schema-to-fields.ts index f12818610a3..debb1f2825a 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/json-schema-to-fields.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/json-schema-to-fields.ts @@ -45,6 +45,20 @@ import type { FlowConfigField, FlowConfigColumn, FlowConfigFieldKind, FlowReferenceSpec, ReferenceKind, RefValueSource } from './flow-node-config.js'; +/** + * A nested group's field that a SIBLING gates, not the group's `enabled` + * switch: a JSON schema has no way to say it, so the rule is keyed by field id + * and read by both descriptor sources — this mapper for the engine-published + * `configSchema`, and the hand-written table in `flow-node-config.ts`. + * + * `escalation.calendar` is read only under `escalation.clock: 'working_time'` + * (ADR-0157 D5), so it shows only there. Its controller shows only while the + * escalation is on, so the calendar follows the switch through it. + */ +export const SIBLING_GATES: Readonly> = { + 'escalation.calendar': { field: 'escalation.clock', equals: ['working_time'] }, +}; + /** Loose JSON Schema node shape — we only read the keys we map. */ interface JsonSchemaNode { type?: string | string[]; @@ -504,7 +518,9 @@ export function jsonSchemaToFlowFields(schema: unknown): FlowConfigField[] | nul ...(subRef ? { ref: subRef } : {}), ...(scalar?.refMode ? { refMode: scalar.refMode } : {}), ...(kind === 'select' && Array.isArray(sp.enum) ? { options: enumOptions(sp.enum, sp.xEnumDeprecated) } : {}), - ...(hasEnabled && !isGate ? { showWhen: { field: `${key}.enabled`, equals: ['true'] } } : {}), + ...(SIBLING_GATES[id] + ? { showWhen: SIBLING_GATES[id] } + : hasEnabled && !isGate ? { showWhen: { field: `${key}.enabled`, equals: ['true'] } } : {}), }; fields.push(field); } diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index f22fa02ca4c..5609f491290 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -445,7 +445,11 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // suggested-field mark („{{mark}}“) — one interpolated span, pack text. // 118 once objectstack-ai/objectstack#34740 retired // `empty.objectNotFoundDescription` („{{name}}“) — one interpolated span fewer. - expect(okSpans, 'correctly paired spans').toBe(118); + // 119 once objectstack-ai/objectstack#35357 added + // `approvalsInbox.slaCalendarNotFound`, the inbox naming the calendar an + // escalation deadline cannot be counted on („{{calendar}}“) — one + // interpolated span, runtime data. + expect(okSpans, 'correctly paired spans').toBe(119); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -558,8 +562,10 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 119 / 119 / 0 after objectstack-ai/objectstack#33419 added // `chatbot.plan.suggestedFieldLegend`, one more matched pair. 118 / 118 / 0 // after objectstack-ai/objectstack#34740 retired - // `empty.objectNotFoundDescription`, one matched pair fewer. - expect({ open, close, rdq }).toEqual({ open: 118, close: 118, rdq: 0 }); + // `empty.objectNotFoundDescription`, one matched pair fewer. 119 / 119 / 0 + // after objectstack-ai/objectstack#35357 added + // `approvalsInbox.slaCalendarNotFound`, one more matched pair. + expect({ open, close, rdq }).toEqual({ open: 119, close: 119, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 14b652d847d..3d8f464194a 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4885,6 +4885,10 @@ const ar = { replyPlaceholder: 'الرد على هذا الطلب…', slaRemaining: 'SLA المتبقي {{dur}}', slaOverdue: 'SLA متأخر {{dur}}', + slaCalendarNotFound: 'تعذّر الحساب بالتقويم: لا يوجد تقويم "{{calendar}}"', + slaCalendarNoDefault: 'تعذّر الحساب بالتقويم: لا يوجد تقويم افتراضي', + slaCalendarNotMaintained: 'تعذّر الحساب بالتقويم: غير مُحدَّث حتى {{date}}', + slaCalendarUnusable: 'تعذّر الحساب بالتقويم: صحّح التقويم في الإعدادات', actReassign: 'إعادة إسناد', reassignFromTo: 'من {{from}} إلى {{to}}', actRemind: 'تذكير', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 58e70f7edbe..7a8d87b92a1 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4471,6 +4471,10 @@ const de = { replyPlaceholder: 'Auf diese Anfrage antworten…', slaRemaining: 'SLA noch {{dur}}', slaOverdue: 'SLA überfällig {{dur}}', + slaCalendarNotFound: 'Kalender kann nicht rechnen: kein Kalender „{{calendar}}“', + slaCalendarNoDefault: 'Kalender kann nicht rechnen: kein Standardkalender', + slaCalendarNotMaintained: 'Kalender kann nicht rechnen: nicht gepflegt für {{date}}', + slaCalendarUnusable: 'Kalender kann nicht rechnen: Kalender in den Einstellungen korrigieren', actReassign: 'Übergeben', reassignFromTo: 'von {{from}} an {{to}}', actRemind: 'Erinnert', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index dff9e7910d5..02fada012aa 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5422,6 +5422,10 @@ const en = { replyPlaceholder: 'Reply on this request…', slaRemaining: 'SLA {{dur}} left', slaOverdue: 'SLA overdue {{dur}}', + slaCalendarNotFound: "Calendar can't compute: no calendar \"{{calendar}}\"", + slaCalendarNoDefault: "Calendar can't compute: no default calendar", + slaCalendarNotMaintained: "Calendar can't compute: not maintained for {{date}}", + slaCalendarUnusable: "Calendar can't compute: fix the calendar in Setup", actReassign: 'Reassigned', reassignFromTo: 'from {{from}} to {{to}}', actRemind: 'Reminder sent', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index e0c7e224bfd..1af624f41da 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4575,6 +4575,10 @@ const es = { replyPlaceholder: 'Responder en esta solicitud…', slaRemaining: 'SLA: quedan {{dur}}', slaOverdue: 'SLA vencido {{dur}}', + slaCalendarNotFound: 'El calendario no puede calcularlo: no existe el calendario "{{calendar}}"', + slaCalendarNoDefault: 'El calendario no puede calcularlo: no hay calendario predeterminado', + slaCalendarNotMaintained: 'El calendario no puede calcularlo: no está mantenido para el {{date}}', + slaCalendarUnusable: 'El calendario no puede calcularlo: corrija el calendario en Configuración', actReassign: 'Reasignada', reassignFromTo: 'de {{from}} a {{to}}', actRemind: 'Recordatorio', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 82acd914de1..38c72337d1e 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4571,6 +4571,10 @@ const fr = { replyPlaceholder: 'Répondre sur cette demande…', slaRemaining: 'SLA : {{dur}} restants', slaOverdue: 'SLA dépassé de {{dur}}', + slaCalendarNotFound: 'Calcul impossible par le calendrier : aucun calendrier « {{calendar}} »', + slaCalendarNoDefault: 'Calcul impossible par le calendrier : aucun calendrier par défaut', + slaCalendarNotMaintained: 'Calcul impossible par le calendrier : non tenu à jour pour le {{date}}', + slaCalendarUnusable: 'Calcul impossible par le calendrier : corrigez le calendrier dans les paramètres', actReassign: 'Réattribuée', reassignFromTo: 'de {{from}} à {{to}}', actRemind: 'Relance', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 6991ebb6490..4f31189a307 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4473,6 +4473,10 @@ const ja = { replyPlaceholder: 'このリクエストに返信…', slaRemaining: 'SLA 残り {{dur}}', slaOverdue: 'SLA 超過 {{dur}}', + slaCalendarNotFound: 'カレンダーで計算できません:カレンダー「{{calendar}}」がありません', + slaCalendarNoDefault: 'カレンダーで計算できません:既定のカレンダーがありません', + slaCalendarNotMaintained: 'カレンダーで計算できません:{{date}} まで管理されていません', + slaCalendarUnusable: 'カレンダーで計算できません:設定でカレンダーを修正してください', actReassign: '引き継ぎ', reassignFromTo: '{{from}} から {{to}} へ', actRemind: 'リマインド', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 13f7a980535..1ce97392230 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4470,6 +4470,10 @@ const ko = { replyPlaceholder: '이 요청에 답하기…', slaRemaining: 'SLA {{dur}} 남음', slaOverdue: 'SLA {{dur}} 초과', + slaCalendarNotFound: '달력으로 계산할 수 없음: 달력 "{{calendar}}" 없음', + slaCalendarNoDefault: '달력으로 계산할 수 없음: 기본 달력 없음', + slaCalendarNotMaintained: '달력으로 계산할 수 없음: {{date}}까지 관리되지 않음', + slaCalendarUnusable: '달력으로 계산할 수 없음: 설정에서 달력을 수정하세요', actReassign: '재할당', reassignFromTo: '{{from}} 님에서 {{to}} 님으로', actRemind: '독촉', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 171f9615455..adb45db5035 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4570,6 +4570,10 @@ const pt = { replyPlaceholder: 'Responder nesta solicitação…', slaRemaining: 'SLA: faltam {{dur}}', slaOverdue: 'SLA vencido há {{dur}}', + slaCalendarNotFound: 'O calendário não consegue calcular: não há calendário "{{calendar}}"', + slaCalendarNoDefault: 'O calendário não consegue calcular: não há calendário padrão', + slaCalendarNotMaintained: 'O calendário não consegue calcular: não mantido para {{date}}', + slaCalendarUnusable: 'O calendário não consegue calcular: corrija o calendário na Configuração', actReassign: 'Reatribuída', reassignFromTo: 'de {{from}} para {{to}}', actRemind: 'Lembrete', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0629e208996..5d178e1f773 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4688,6 +4688,10 @@ const ru = { replyPlaceholder: 'Ответить по этому запросу…', slaRemaining: 'SLA: осталось {{dur}}', slaOverdue: 'SLA просрочен на {{dur}}', + slaCalendarNotFound: 'Календарь не может рассчитать: нет календаря «{{calendar}}»', + slaCalendarNoDefault: 'Календарь не может рассчитать: нет календаря по умолчанию', + slaCalendarNotMaintained: 'Календарь не может рассчитать: не ведётся на {{date}}', + slaCalendarUnusable: 'Календарь не может рассчитать: исправьте календарь в настройках', actReassign: 'Передано', reassignFromTo: 'от {{from}} к {{to}}', actRemind: 'Напоминание', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 3812641e6a2..c8912464e5b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4730,6 +4730,10 @@ const zh = { replyPlaceholder: '在此回复…', slaRemaining: 'SLA 剩余 {{dur}}', slaOverdue: 'SLA 已超期 {{dur}}', + slaCalendarNotFound: '日历算不出:没有日历“{{calendar}}”', + slaCalendarNoDefault: '日历算不出:没有默认日历', + slaCalendarNotMaintained: '日历算不出:未维护到 {{date}}', + slaCalendarUnusable: '日历算不出:请在设置中修正日历', actReassign: '转签', reassignFromTo: '从 {{from}} 转给 {{to}}', actRemind: '催办', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 3ff3be4e69d..424dd5f62f0 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4730,6 +4730,10 @@ const zhHant = { replyPlaceholder: '在此回覆…', slaRemaining: 'SLA 剩餘 {{dur}}', slaOverdue: 'SLA 已超期 {{dur}}', + slaCalendarNotFound: '日曆算不出:沒有日曆“{{calendar}}”', + slaCalendarNoDefault: '日曆算不出:沒有預設日曆', + slaCalendarNotMaintained: '日曆算不出:未維護到 {{date}}', + slaCalendarUnusable: '日曆算不出:請在設定中修正日曆', actReassign: '轉籤', reassignFromTo: '從 {{from}} 轉給 {{to}}', actRemind: '催辦',