|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * `ApprovalEscalation.timeoutHours` is CALENDAR (wall-clock) hours — pinned |
| 5 | + * through the real code path, not restated. |
| 6 | + * |
| 7 | + * The declaration's `describe` text on `ApprovalEscalationSchema` says the |
| 8 | + * clock out loud; `slaDueAt` in `approval-service.ts` is the one runtime site |
| 9 | + * that turns the declared number into a deadline; the escalation sweep compares |
| 10 | + * that deadline against the injected clock. This file drives all three through |
| 11 | + * `openNodeRequest` → `getRequest` → `runEscalations`, so the sentence in the |
| 12 | + * schema and the arithmetic in the service cannot drift apart without a red |
| 13 | + * here. |
| 14 | + * |
| 15 | + * Timezone assumption, stated: NONE is required. Every timestamp the service |
| 16 | + * reads or writes is an ISO-8601 UTC string (`toISOString()` / `Date.parse` of |
| 17 | + * a `Z`-suffixed literal) and the deadline is `created_at` plus elapsed |
| 18 | + * milliseconds, so the assertions hold under any `TZ` the runner sets — they |
| 19 | + * are written against UTC instants and never call a local-time accessor. The |
| 20 | + * DST cases document what the SAME instants read as on a wall clock in |
| 21 | + * America/New_York, to make the elapsed-time-versus-local-time distinction |
| 22 | + * visible where a reader would otherwise infer it. |
| 23 | + */ |
| 24 | + |
| 25 | +import { describe, it, expect } from 'vitest'; |
| 26 | +import { ApprovalService } from './approval-service.js'; |
| 27 | + |
| 28 | +interface Row { [k: string]: any } |
| 29 | + |
| 30 | +/** |
| 31 | + * Read-and-append engine double: `find` + `insert` only. |
| 32 | + * |
| 33 | + * The three paths under test dispatch nothing else — `openNodeRequest` finds |
| 34 | + * and inserts, `getRequest` finds, and the `notify` escalation arm finds and |
| 35 | + * inserts the audit action. No `update` / `delete` member exists on purpose: |
| 36 | + * `check:engine-double-contract` pins those write verbs to the real engine's |
| 37 | + * dispatch, and a double that does not declare them has nothing to pin. |
| 38 | + */ |
| 39 | +function makeEngine() { |
| 40 | + const tables: Record<string, Row[]> = {}; |
| 41 | + const ensure = (n: string) => (tables[n] ??= []); |
| 42 | + const matches = (row: Row, filter: any): boolean => { |
| 43 | + if (!filter || typeof filter !== 'object') return true; |
| 44 | + for (const [k, v] of Object.entries(filter)) { |
| 45 | + if (k === '$or') { |
| 46 | + if (!(v as any[]).some((sub) => matches(row, sub))) return false; |
| 47 | + continue; |
| 48 | + } |
| 49 | + if (k.startsWith('$')) throw new Error(`fake engine: unsupported filter operator ${k}`); |
| 50 | + const rv = row[k]; |
| 51 | + if (v != null && typeof v === 'object' && '$in' in (v as any)) { |
| 52 | + if (!(v as any).$in.includes(rv)) return false; |
| 53 | + continue; |
| 54 | + } |
| 55 | + if (v != null && typeof v === 'object' && '$ne' in (v as any)) { |
| 56 | + if (rv === (v as any).$ne) return false; |
| 57 | + continue; |
| 58 | + } |
| 59 | + if (rv !== v) return false; |
| 60 | + } |
| 61 | + return true; |
| 62 | + }; |
| 63 | + return { |
| 64 | + _tables: tables, |
| 65 | + async find(object: string, options?: any) { |
| 66 | + return ensure(object).filter((r) => matches(r, options?.filter ?? options?.where)); |
| 67 | + }, |
| 68 | + async insert(object: string, data: Row) { ensure(object).push({ ...data }); return { ...data }; }, |
| 69 | + async count(object: string) { return ensure(object).length; }, |
| 70 | + registerHook() { /* no-op */ }, |
| 71 | + unregisterHooksByPackage() { /* no-op */ }, |
| 72 | + }; |
| 73 | +} |
| 74 | + |
| 75 | +const HOUR = 3_600_000; |
| 76 | +const SYS = { isSystem: true, positions: [], permissions: [] } as any; |
| 77 | +const CTX = { userId: 'u1', tenantId: 't1', positions: [], permissions: [] } as any; |
| 78 | + |
| 79 | +/** A node whose only escalation dependency is the clock: `notify`, no reassign. */ |
| 80 | +function input(nodeId: string, timeoutHours: number) { |
| 81 | + return { |
| 82 | + object: 'opportunity', |
| 83 | + recordId: 'opp1', |
| 84 | + runId: 'run_1', |
| 85 | + nodeId, |
| 86 | + flowName: 'deal_approval', |
| 87 | + config: { |
| 88 | + approvers: [{ type: 'user' as const, value: 'u9' }], |
| 89 | + behavior: 'first_response' as const, |
| 90 | + lockRecord: false, |
| 91 | + escalation: { timeoutHours, action: 'notify' as const, escalateTo: 'boss', notifySubmitter: false }, |
| 92 | + }, |
| 93 | + record: { id: 'opp1', amount: 100 }, |
| 94 | + }; |
| 95 | +} |
| 96 | + |
| 97 | +/** |
| 98 | + * Open a node request and return the PENDING row. `openNodeRequest` can also |
| 99 | + * answer with an auto outcome (an empty approver slate under |
| 100 | + * `onEmptyApprovers: 'auto_approve'`), which carries no `id` and no SLA — the |
| 101 | + * arm this file is not about, so it is refused loudly rather than narrowed |
| 102 | + * away with a cast. |
| 103 | + */ |
| 104 | +async function openPending(svc: ApprovalService, nodeInput: ReturnType<typeof input>) { |
| 105 | + const opened = await svc.openNodeRequest(nodeInput, CTX); |
| 106 | + if (!('id' in opened)) throw new Error('expected a pending approval request, got an auto outcome'); |
| 107 | + return opened; |
| 108 | +} |
| 109 | + |
| 110 | +/** A service whose clock is set by the test, in UTC instants. */ |
| 111 | +function serviceAt(iso: string) { |
| 112 | + let nowMs = Date.parse(iso); |
| 113 | + const engine = makeEngine(); |
| 114 | + const svc = new ApprovalService({ engine: engine as any, clock: { now: () => new Date(nowMs) } }); |
| 115 | + return { svc, engine, setNow: (at: string) => { nowMs = Date.parse(at); } }; |
| 116 | +} |
| 117 | + |
| 118 | +const utcDay = (iso: string) => new Date(iso).getUTCDay(); // 0 = Sunday … 5 = Friday, 6 = Saturday |
| 119 | + |
| 120 | +// 2026-01-16 is a Friday; the calendar claims below are about the dates they name. |
| 121 | +const FRIDAY_1700 = '2026-01-16T17:00:00.000Z'; |
| 122 | +const MONDAY_0900 = '2026-01-19T09:00:00.000Z'; |
| 123 | + |
| 124 | +describe('ApprovalEscalation.timeoutHours is calendar (wall-clock) hours', () => { |
| 125 | + it('the fixture dates are the weekdays the assertions name', () => { |
| 126 | + expect(utcDay(FRIDAY_1700)).toBe(5); |
| 127 | + expect(utcDay(MONDAY_0900)).toBe(1); |
| 128 | + }); |
| 129 | + |
| 130 | + it('Friday 17:00 + timeoutHours 4 is due Friday 21:00 — the same evening, not the next business day', async () => { |
| 131 | + const { svc, setNow } = serviceAt(FRIDAY_1700); |
| 132 | + const req = await openPending(svc, input('sla_4h', 4)); |
| 133 | + |
| 134 | + const row = await svc.getRequest(req.id, SYS); |
| 135 | + expect(row?.created_at).toBe(FRIDAY_1700); |
| 136 | + expect(row?.sla_due_at).toBe('2026-01-16T21:00:00.000Z'); |
| 137 | + expect(utcDay(row!.sla_due_at!)).toBe(5); |
| 138 | + // A business-hours reading would put this deadline on Monday at the |
| 139 | + // earliest; the wall clock puts it before Monday's first working hour. |
| 140 | + expect(Date.parse(row!.sla_due_at!)).toBeLessThan(Date.parse(MONDAY_0900)); |
| 141 | + |
| 142 | + // The sweep reads the same deadline: one millisecond early is not overdue, |
| 143 | + // the deadline instant itself is — on Friday night, with nobody at work. |
| 144 | + setNow('2026-01-16T20:59:59.999Z'); |
| 145 | + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); |
| 146 | + setNow('2026-01-16T21:00:00.000Z'); |
| 147 | + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); |
| 148 | + |
| 149 | + const actions = await svc.listActions(req.id, SYS); |
| 150 | + expect(actions.at(-1)).toMatchObject({ action: 'escalate', actor_id: 'system:sla' }); |
| 151 | + }); |
| 152 | + |
| 153 | + it('a 168-hour deadline spans the weekend: due the next Friday at the same hour, 7 × 24 elapsed hours', async () => { |
| 154 | + const { svc, setNow } = serviceAt(FRIDAY_1700); |
| 155 | + const req = await openPending(svc, input('sla_168h', 168)); |
| 156 | + |
| 157 | + const row = await svc.getRequest(req.id, SYS); |
| 158 | + const due = row!.sla_due_at!; |
| 159 | + expect(due).toBe('2026-01-23T17:00:00.000Z'); |
| 160 | + expect(utcDay(due)).toBe(5); |
| 161 | + expect(Date.parse(due) - Date.parse(FRIDAY_1700)).toBe(168 * HOUR); |
| 162 | + |
| 163 | + // Saturday and Sunday sit inside the window and are not skipped: the |
| 164 | + // deadline is not 168 working hours later (that would be four weeks out). |
| 165 | + const saturday = '2026-01-17T12:00:00.000Z'; |
| 166 | + const sunday = '2026-01-18T12:00:00.000Z'; |
| 167 | + expect(utcDay(saturday)).toBe(6); |
| 168 | + expect(utcDay(sunday)).toBe(0); |
| 169 | + for (const weekendInstant of [saturday, sunday]) { |
| 170 | + expect(Date.parse(weekendInstant)).toBeGreaterThan(Date.parse(FRIDAY_1700)); |
| 171 | + expect(Date.parse(weekendInstant)).toBeLessThan(Date.parse(due)); |
| 172 | + } |
| 173 | + |
| 174 | + setNow(MONDAY_0900); |
| 175 | + expect(await svc.runEscalations()).toMatchObject({ escalated: 0 }); |
| 176 | + setNow(due); |
| 177 | + expect(await svc.runEscalations()).toMatchObject({ escalated: 1 }); |
| 178 | + }); |
| 179 | + |
| 180 | + it('a DST transition changes nothing: elapsed hours, not local wall-clock hours (spring forward)', async () => { |
| 181 | + // 2026-03-08T05:00:00Z is 00:00 EST in America/New_York; at 02:00 local the |
| 182 | + // clocks jump to 03:00 EDT. Four ELAPSED hours later is 09:00Z = 05:00 EDT — |
| 183 | + // five o'clock on the local wall, four hours of real time. The service adds |
| 184 | + // elapsed milliseconds, so the deadline is the 09:00Z instant on every host. |
| 185 | + const created = '2026-03-08T05:00:00.000Z'; |
| 186 | + const { svc } = serviceAt(created); |
| 187 | + const req = await openPending(svc, input('sla_dst_spring', 4)); |
| 188 | + const row = await svc.getRequest(req.id, SYS); |
| 189 | + expect(row?.sla_due_at).toBe('2026-03-08T09:00:00.000Z'); |
| 190 | + expect(Date.parse(row!.sla_due_at!) - Date.parse(created)).toBe(4 * HOUR); |
| 191 | + }); |
| 192 | + |
| 193 | + it('a DST transition changes nothing: elapsed hours, not local wall-clock hours (fall back)', async () => { |
| 194 | + // 2026-11-01T05:00:00Z is 01:00 EDT in America/New_York; at 02:00 EDT the |
| 195 | + // clocks go back to 01:00 EST. Four ELAPSED hours later is 09:00Z = 04:00 |
| 196 | + // EST — three o'clock-hours on the local wall, four hours of real time. |
| 197 | + const created = '2026-11-01T05:00:00.000Z'; |
| 198 | + const { svc } = serviceAt(created); |
| 199 | + const req = await openPending(svc, input('sla_dst_fall', 4)); |
| 200 | + const row = await svc.getRequest(req.id, SYS); |
| 201 | + expect(row?.sla_due_at).toBe('2026-11-01T09:00:00.000Z'); |
| 202 | + expect(Date.parse(row!.sla_due_at!) - Date.parse(created)).toBe(4 * HOUR); |
| 203 | + }); |
| 204 | +}); |
0 commit comments