diff --git a/examples/app-todo/src/objects/task.object.ts b/examples/app-todo/src/objects/task.object.ts index d1bee05fa98..bae175811d2 100644 --- a/examples/app-todo/src/objects/task.object.ts +++ b/examples/app-todo/src/objects/task.object.ts @@ -1,4 +1,4 @@ -import { P } from '@objectstack/spec'; +import { cel, P } from '@objectstack/spec'; // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. import { ObjectSchema, Field } from '@objectstack/spec/data'; @@ -156,6 +156,34 @@ export const Task = ObjectSchema.create({ // Consistent by construction, with no second writer that can drift — which is // the pattern a reference app should be teaching. + // [#18584] `days_overdue` IS a formula, and the paragraph above is the + // reason that is not a contradiction. What killed `is_completed` / + // `is_overdue` as formulas was one specific consumer — a FILTER naming a + // virtual field matches nothing, because no driver materialises a column + // for it. This field has no filter reading it, by construction: its one + // consumer is the `overdue_escalation` flow's `notify` message, which + // READS the value off a record the `get_record` step already fetched. + // `ObjectQL.find` evaluates every formula field on the schema when the + // caller asks for no explicit projection (`planFormulaProjection(schema, + // undefined)`), and `flows/task.flow.ts` declares no `fields`, so the + // rows handed to the `loop` iterator carry this value computed. + // ⛔ Do NOT add a view/report/flow FILTER on this field — use the stored + // `due_date` column, exactly as the paragraph above prescribes. + // + // Semantics, per the ruling on #18584: whole days between `due_date` and + // now, `0` when the task is not overdue and `0` when `due_date` is empty. + // ⛔ No working-day calendar and ⛔ no timezone option — an example + // demonstrates the capability, it is not a scheduling product. + // `today()` is the platform's calendar-day function (UTC by default) and + // `daysBetween(a, b)` its whole-day span, so the pair is the registered + // stdlib spelling of "UTC whole days" — no hand-rolled millisecond math. + days_overdue: Field.formula({ + label: 'Days Overdue', + description: 'Whole days past the due date; 0 when not overdue or no due date.', + returnType: 'number', + expression: cel`record.due_date == null || daysBetween(record.due_date, today()) < 0 ? 0 : daysBetween(record.due_date, today())`, + }), + // Progress progress_percent: Field.percent({ label: 'Progress (%)', diff --git a/examples/app-todo/src/translations/en.ts b/examples/app-todo/src/translations/en.ts index 6c09a9d5b01..88014fde190 100644 --- a/examples/app-todo/src/translations/en.ts +++ b/examples/app-todo/src/translations/en.ts @@ -47,6 +47,7 @@ export const en: TranslationData = { }, }, due_date: { label: 'Due Date' }, + days_overdue: { label: 'Days Overdue' }, reminder_date: { label: 'Reminder Date/Time' }, completed_date: { label: 'Completed Date' }, owner: { label: 'Assigned To' }, diff --git a/examples/app-todo/src/translations/ja-JP.ts b/examples/app-todo/src/translations/ja-JP.ts index 904ee264733..bf87e2ecd37 100644 --- a/examples/app-todo/src/translations/ja-JP.ts +++ b/examples/app-todo/src/translations/ja-JP.ts @@ -46,6 +46,7 @@ export const jaJP: TranslationData = { }, }, due_date: { label: '期日' }, + days_overdue: { label: '超過日数', help: '期日を過ぎた整日数。期日前または期日未設定の場合は 0' }, reminder_date: { label: 'リマインダー日時' }, completed_date: { label: '完了日' }, owner: { label: '担当者' }, diff --git a/examples/app-todo/src/translations/zh-CN.ts b/examples/app-todo/src/translations/zh-CN.ts index 316a389df73..00f66f2284d 100644 --- a/examples/app-todo/src/translations/zh-CN.ts +++ b/examples/app-todo/src/translations/zh-CN.ts @@ -50,6 +50,7 @@ export const zhCN: TranslationData = { }, }, due_date: { label: '截止日期' }, + days_overdue: { label: '逾期天数', help: '距截止日期已过的整天数;未逾期或未设置截止日期时为 0' }, reminder_date: { label: '提醒日期/时间' }, completed_date: { label: '完成日期' }, owner: { label: '负责人' }, diff --git a/examples/app-todo/test/overdue-escalation-days-overdue.test.ts b/examples/app-todo/test/overdue-escalation-days-overdue.test.ts new file mode 100644 index 00000000000..470644019f5 --- /dev/null +++ b/examples/app-todo/test/overdue-escalation-days-overdue.test.ts @@ -0,0 +1,147 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#18584] The record projection the `overdue_escalation` loop iterates carries + * every field its notification template names — `days_overdue` included. + * + * The defect this pins was silent: `flows/task.flow.ts` interpolates + * `{currentTask.days_overdue}` into the escalation body while `todo_task` + * declared no such field. The widened `validate-flow-template-paths` rule + * (PR #18583) reported it as its first true positive, advisory — and no CI job + * runs `objectstack validate` over `examples/`, so nothing was red. + * + * ⭐ WHY THIS SUITE DRIVES A REAL READ INSTEAD OF ASSERTING ON METADATA. + * "A formula field exists on the object" and "the projection the flow iterates + * carries its COMPUTED value" are different questions, and only the second one + * decides whether the template can promise a day count at all. A formula field + * is VIRTUAL — no driver materialises a column for it, which is exactly why + * `is_completed` / `is_overdue` are NOT formulas (see the long paragraph in + * `src/objects/task.object.ts`). So the value is observed where it is + * consumed: off rows returned by a real `ObjectQL.find` over a real driver, + * called the way the flow's `get_record` step calls it. + * + * The one condition that decides the answer is the PROJECTION: `find` runs + * `planFormulaProjection(schema, ast.fields)`, which evaluates every formula on + * the schema when `fields` is absent and only the named ones when it is not. + * `get_overdue_tasks` declares no `fields`, so the rows carry the value — and + * the first test below asserts that precondition off the app's own flow rather + * than trusting it, because adding a `fields` list to that step is precisely + * the edit that would silently empty the day count again. + */ + +import { describe, it, expect, afterEach } from 'vitest'; +import { ObjectKernel } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { SqliteWasmDriver } from '@objectstack/driver-sqlite-wasm'; + +import { OverdueEscalationFlow } from '../src/flows/index.js'; +import { Task } from '../src/objects/task.object.js'; + +const openDrivers: Array<{ disconnect?: () => Promise }> = []; +afterEach(async () => { + while (openDrivers.length) { + try { await openDrivers.pop()?.disconnect?.(); } catch { /* noop */ } + } +}); + +/** A node of the app's real flow, by id. */ +function node(id: string): { type?: string; config?: Record } { + const found = OverdueEscalationFlow.nodes?.find((n) => n.id === id); + if (!found) throw new Error(`#18584 harness: node '${id}' is gone from overdue_escalation`); + return found as { type?: string; config?: Record }; +} + +/** `n` whole days before today, as a `Field.date` string (UTC). */ +function daysAgoIso(n: number): string { + const d = new Date(); + d.setUTCHours(0, 0, 0, 0); + d.setUTCDate(d.getUTCDate() - n); + return d.toISOString().slice(0, 10); +} + +/** A real kernel with the app's real `todo_task` over in-process sqlite-wasm. */ +async function bootTodoData(): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' } } as any); + await kernel.use(new ObjectQLPlugin()); + await kernel.bootstrap(); + + const objectql: any = kernel.getService('objectql'); + const driver: any = new SqliteWasmDriver({ filename: ':memory:' }); + await driver.connect(); + objectql.registerDriver(driver, true); + openDrivers.push(driver); + objectql.registry.registerObject(Task, 'todo', 'todo'); + await objectql.syncSchemas(); + + return kernel.getService('data'); +} + +const SYSTEM = { context: { isSystem: true } }; + +describe('#18584 — the overdue escalation projection carries a day count', () => { + it('the `get_record` step declares no projection, which is what makes formulas evaluate', () => { + // `planFormulaProjection(schema, undefined)` evaluates EVERY formula on the + // schema; a `fields` list narrows it to the named ones. Adding one here + // without adding `days_overdue` would blank the notice again, silently. + const cfg = node('get_overdue_tasks').config ?? {}; + expect(cfg.fields).toBeUndefined(); + expect(cfg.objectName).toBe('todo_task'); + }); + + it('every `{currentTask.…}` token in the escalation body names a key the row carries', async () => { + const data = await bootTodoData(); + const due = daysAgoIso(5); + await data.insert('todo_task', { + subject: 'Renew the domain', + status: 'not_started', + priority: 'normal', + due_date: due, + owner: 'usr_test_owner', + }, SYSTEM); + + // Read exactly as `get_overdue_tasks` does: list read, NO `fields`. + const rows: Array> = await data.find('todo_task', { + where: { status: { $ne: 'completed' } }, + limit: node('get_overdue_tasks').config?.limit, + context: { isSystem: true }, + }); + expect(rows).toHaveLength(1); + const row = rows[0]; + + // The card's defect, stated as an assertion over the real template: the + // notify body's tokens are resolved against this row, so a token naming a + // key the row does not carry renders as a blank — no error, no refusal. + const message = String(node('notify_owner').config?.message ?? ''); + const tokens = [...message.matchAll(/\{currentTask\.([a-z_]+)\}/g)].map((m) => m[1]); + expect(tokens).toContain('days_overdue'); + for (const token of tokens) { + expect(row, `notify body names {currentTask.${token}}`).toHaveProperty(token); + expect(String(row[token] ?? ''), `{currentTask.${token}} renders blank`).not.toBe(''); + } + + // And the value is the real span, not merely "something present". + expect(Number(row.days_overdue)).toBe(5); + }); + + it('0 when the task is not overdue, and 0 when `due_date` is empty', async () => { + const data = await bootTodoData(); + await data.insert('todo_task', { + subject: 'Future task', status: 'not_started', priority: 'normal', + due_date: daysAgoIso(-3), owner: 'usr_test_owner', + }, SYSTEM); + await data.insert('todo_task', { + subject: 'No due date', status: 'not_started', priority: 'normal', + owner: 'usr_test_owner', + }, SYSTEM); + + const rows: Array> = await data.find('todo_task', { + where: {}, limit: 200, context: { isSystem: true }, + }); + const bySubject = new Map(rows.map((r) => [String(r.subject), r])); + + // Ruled semantics: `0` when not overdue, `0` when `due_date` is empty — + // never a negative "days remaining", never null. + expect(Number(bySubject.get('Future task')?.days_overdue)).toBe(0); + expect(Number(bySubject.get('No due date')?.days_overdue)).toBe(0); + }); +});