|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | +// |
| 3 | +// ── A roll-up recompute is a SYSTEM write on the master's audit trail ── |
| 4 | +// |
| 5 | +// A child write recomputes the master's `summary` columns through |
| 6 | +// `recomputeSummaries`, which issues an ordinary `update` of the master under a |
| 7 | +// `sudo()`-shaped context (`{ ...caller, isSystem: true }`). The caller's |
| 8 | +// `userId` rides along on purpose — hooks and record-triggered flows on the |
| 9 | +// master still know who triggered the write — but the audit stamp read that |
| 10 | +// same `userId` and wrote it into the master's `updated_by`. A finance user who |
| 11 | +// inserted an invoice under a contract therefore showed up as the contract's |
| 12 | +// last editor, though they edit neither record and hold no edit on it. |
| 13 | +// |
| 14 | +// Ruling (recorded on the card, comment 6902001862): 「确定汇总字段自动重算时 |
| 15 | +// 主记录的修改人和修改时间怎么记」 → 「记为系统并刷新时间」. Under ADR-0118 D1 |
| 16 | +// a system actor is `null` in a user lookup column (no system account, no |
| 17 | +// sentinel), so the recompute stamps `updated_by = null` and refreshes |
| 18 | +// `updated_at`; the UI renders the null as 系统. |
| 19 | +// |
| 20 | +// Every child write that recomputes goes through the same door, so each one is |
| 21 | +// a row here: insert, update, delete, and a re-parent (which recomputes BOTH the |
| 22 | +// old and the new master). The CONTROL is the other half of the contract: a |
| 23 | +// direct edit of the master by the same user still stamps that user — the fix |
| 24 | +// is scoped to the recompute's own write, not to `isSystem` writes in general. |
| 25 | +// |
| 26 | +// The harness boots the real `ObjectQLPlugin`, because the stamp under test is |
| 27 | +// its `sys_stamp_audit_update` hook. What reaches the fake driver's store IS the |
| 28 | +// stored row, so the store is the verdict. |
| 29 | + |
| 30 | +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; |
| 31 | +import { ObjectKernel } from '@objectstack/core'; |
| 32 | +import { ObjectQLPlugin } from './plugin.js'; |
| 33 | +import { ObjectQL } from './engine.js'; |
| 34 | + |
| 35 | +const USER_A = 'u_owner_a'; |
| 36 | +const USER_B = 'u_child_writer_b'; |
| 37 | +/** An `updated_at` far in the past, so "the recompute refreshed it" is never a same-millisecond tie. */ |
| 38 | +const STALE_AT = '2000-01-01T00:00:00.000Z'; |
| 39 | + |
| 40 | +function makeDriver() { |
| 41 | + const stores = new Map<string, Map<string, any>>(); |
| 42 | + const storeFor = (o: string) => { |
| 43 | + let s = stores.get(o); |
| 44 | + if (!s) { s = new Map(); stores.set(o, s); } |
| 45 | + return s; |
| 46 | + }; |
| 47 | + const matches = (row: any, where: any): boolean => { |
| 48 | + if (!where || typeof where !== 'object') return true; |
| 49 | + return Object.entries(where).every(([k, v]: [string, any]) => { |
| 50 | + if (k === '$and') return (v as any[]).every((w) => matches(row, w)); |
| 51 | + if (k === '$or') return (v as any[]).some((w) => matches(row, w)); |
| 52 | + if (v !== null && typeof v === 'object' && !Array.isArray(v)) { |
| 53 | + if ('$eq' in v) return row?.[k] === v.$eq; |
| 54 | + if ('$in' in v) return Array.isArray(v.$in) && v.$in.includes(row?.[k]); |
| 55 | + throw new Error(`fake driver: unsupported operator in ${JSON.stringify(v)}`); |
| 56 | + } |
| 57 | + return row?.[k] === v; |
| 58 | + }); |
| 59 | + }; |
| 60 | + let n = 0; |
| 61 | + const driver: any = { |
| 62 | + name: 'rollup-audit', version: '0.0.0', supports: {}, |
| 63 | + async connect() {}, async disconnect() {}, async checkHealth() { return true; }, async execute() { return null; }, |
| 64 | + async syncSchema() {}, |
| 65 | + async find(object: string, ast: any) { |
| 66 | + const rows = Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)); |
| 67 | + const page = typeof ast?.limit === 'number' ? rows.slice(0, ast.limit) : rows; |
| 68 | + return page.map((r) => ({ ...r })); |
| 69 | + }, |
| 70 | + async findOne(object: string, ast: any) { |
| 71 | + for (const r of storeFor(object).values()) if (matches(r, ast?.where)) return { ...r }; |
| 72 | + return null; |
| 73 | + }, |
| 74 | + async create(object: string, data: Record<string, unknown>) { |
| 75 | + n += 1; |
| 76 | + const id = (data.id as string) ?? `r_${n}`; |
| 77 | + const row = { ...data, id }; |
| 78 | + storeFor(object).set(id, row); |
| 79 | + return { ...row }; |
| 80 | + }, |
| 81 | + async update(object: string, id: string, data: Record<string, unknown>) { |
| 82 | + const s = storeFor(object); |
| 83 | + const row = { ...s.get(id), ...data, id }; |
| 84 | + s.set(id, row); |
| 85 | + return { ...row }; |
| 86 | + }, |
| 87 | + async delete(object: string, id: string) { return storeFor(object).delete(id); }, |
| 88 | + async count(object: string, ast: any) { |
| 89 | + return Array.from(storeFor(object).values()).filter((r) => matches(r, ast?.where)).length; |
| 90 | + }, |
| 91 | + async bulkCreate(object: string, rows: Record<string, unknown>[]) { |
| 92 | + return Promise.all(rows.map((r) => this.create(object, r))); |
| 93 | + }, |
| 94 | + async bulkUpdate() { return []; }, async bulkDelete() {}, |
| 95 | + async beginTransaction() { return { __trx: true, commit: async () => {}, rollback: async () => {} }; }, |
| 96 | + async commit() {}, async rollback() {}, |
| 97 | + }; |
| 98 | + return { driver, storeFor }; |
| 99 | +} |
| 100 | + |
| 101 | +describe('roll-up recompute stamps the master as a system write (updated_by = null)', () => { |
| 102 | + let kernel: ObjectKernel; |
| 103 | + let ql: ObjectQL; |
| 104 | + let storeFor: ReturnType<typeof makeDriver>['storeFor']; |
| 105 | + |
| 106 | + beforeEach(async () => { |
| 107 | + kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false }); |
| 108 | + const d = makeDriver(); |
| 109 | + storeFor = d.storeFor; |
| 110 | + await kernel.use({ |
| 111 | + name: 'rollup-audit-driver-plugin', type: 'driver', version: '1.0.0', |
| 112 | + init: async (ctx: any) => { ctx.registerService('driver.rollup-audit', d.driver); }, |
| 113 | + } as any); |
| 114 | + await kernel.use(new ObjectQLPlugin()); |
| 115 | + await kernel.bootstrap(); |
| 116 | + ql = kernel.getService<ObjectQL>('objectql'); |
| 117 | + // The audit family (`updated_by` / `updated_at` / …) is NOT declared: the |
| 118 | + // registry injects it, exactly as on an authored business object. |
| 119 | + ql.registry.registerObject({ |
| 120 | + name: 'contract', |
| 121 | + label: 'Contract', |
| 122 | + datasource: 'rollup-audit', |
| 123 | + fields: { |
| 124 | + name: { name: 'name', label: 'Name', type: 'text' }, |
| 125 | + invoiced: { name: 'invoiced', label: 'Invoiced', type: 'summary', summaryOperations: { object: 'invoice', field: 'amount', function: 'sum' } }, |
| 126 | + invoice_count: { name: 'invoice_count', label: 'Invoices', type: 'summary', summaryOperations: { object: 'invoice', function: 'count' } }, |
| 127 | + }, |
| 128 | + } as any, 'test', 'test'); |
| 129 | + ql.registry.registerObject({ |
| 130 | + name: 'invoice', |
| 131 | + label: 'Invoice', |
| 132 | + datasource: 'rollup-audit', |
| 133 | + fields: { |
| 134 | + amount: { name: 'amount', label: 'Amount', type: 'number' }, |
| 135 | + contract: { name: 'contract', label: 'Contract', type: 'master_detail', reference: 'contract' }, |
| 136 | + }, |
| 137 | + } as any, 'test', 'test'); |
| 138 | + }); |
| 139 | + |
| 140 | + afterEach(async () => { |
| 141 | + if (kernel.getState() === 'running') await kernel.shutdown(); |
| 142 | + }); |
| 143 | + |
| 144 | + const as = (userId: string) => ({ context: { userId } as any }); |
| 145 | + const master = (id: string) => storeFor('contract').get(id); |
| 146 | + |
| 147 | + /** User A creates and last edits the master; its `updated_at` is then aged so a refresh is visible. */ |
| 148 | + async function masterLastEditedByA(name: string): Promise<string> { |
| 149 | + const c = await ql.insert('contract', { name }, as(USER_A)); |
| 150 | + await ql.update('contract', { id: c.id, name: `${name} (edited)` }, as(USER_A)); |
| 151 | + expect(master(c.id).updated_by).toBe(USER_A); |
| 152 | + storeFor('contract').set(c.id, { ...master(c.id), updated_at: STALE_AT }); |
| 153 | + return c.id; |
| 154 | + } |
| 155 | + |
| 156 | + function expectSystemStamp(id: string) { |
| 157 | + const row = master(id); |
| 158 | + expect(row.updated_by).toBeNull(); |
| 159 | + expect(row.updated_by).not.toBe(USER_B); |
| 160 | + expect(typeof row.updated_at).toBe('string'); |
| 161 | + expect(Date.parse(row.updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); |
| 162 | + } |
| 163 | + |
| 164 | + it('CONTROL: a direct edit of the master by B still stamps B', async () => { |
| 165 | + const id = await masterLastEditedByA('CTR-CONTROL'); |
| 166 | + await ql.update('contract', { id, name: 'CTR-CONTROL (B)' }, as(USER_B)); |
| 167 | + expect(master(id).updated_by).toBe(USER_B); |
| 168 | + expect(Date.parse(master(id).updated_at)).toBeGreaterThan(Date.parse(STALE_AT)); |
| 169 | + }); |
| 170 | + |
| 171 | + it('a child INSERT by B recomputes the master and stamps it as the system', async () => { |
| 172 | + const id = await masterLastEditedByA('CTR-INSERT'); |
| 173 | + await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_B)); |
| 174 | + expect(master(id).invoiced).toBe(40); |
| 175 | + expect(master(id).invoice_count).toBe(1); |
| 176 | + expectSystemStamp(id); |
| 177 | + }); |
| 178 | + |
| 179 | + it('a child UPDATE by B recomputes the master and stamps it as the system', async () => { |
| 180 | + const id = await masterLastEditedByA('CTR-UPDATE'); |
| 181 | + const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A)); |
| 182 | + await ql.update('contract', { id, name: 'CTR-UPDATE (A again)' }, as(USER_A)); |
| 183 | + storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT }); |
| 184 | + expect(master(id).updated_by).toBe(USER_A); |
| 185 | + |
| 186 | + await ql.update('invoice', { id: inv.id, amount: 55 }, as(USER_B)); |
| 187 | + expect(master(id).invoiced).toBe(55); |
| 188 | + expectSystemStamp(id); |
| 189 | + }); |
| 190 | + |
| 191 | + it('a child DELETE by B recomputes the master and stamps it as the system', async () => { |
| 192 | + const id = await masterLastEditedByA('CTR-DELETE'); |
| 193 | + const inv = await ql.insert('invoice', { contract: id, amount: 40 }, as(USER_A)); |
| 194 | + await ql.update('contract', { id, name: 'CTR-DELETE (A again)' }, as(USER_A)); |
| 195 | + storeFor('contract').set(id, { ...master(id), updated_at: STALE_AT }); |
| 196 | + expect(master(id).updated_by).toBe(USER_A); |
| 197 | + |
| 198 | + await ql.delete('invoice', { where: { id: inv.id }, ...as(USER_B) } as any); |
| 199 | + expect(master(id).invoiced).toBe(0); |
| 200 | + expect(master(id).invoice_count).toBe(0); |
| 201 | + expectSystemStamp(id); |
| 202 | + }); |
| 203 | + |
| 204 | + it('a child RE-PARENT by B recomputes BOTH masters and stamps each as the system', async () => { |
| 205 | + const from = await masterLastEditedByA('CTR-FROM'); |
| 206 | + const inv = await ql.insert('invoice', { contract: from, amount: 40 }, as(USER_A)); |
| 207 | + await ql.update('contract', { id: from, name: 'CTR-FROM (A again)' }, as(USER_A)); |
| 208 | + storeFor('contract').set(from, { ...master(from), updated_at: STALE_AT }); |
| 209 | + const to = await masterLastEditedByA('CTR-TO'); |
| 210 | + |
| 211 | + await ql.update('invoice', { id: inv.id, contract: to }, as(USER_B)); |
| 212 | + expect(master(from).invoiced).toBe(0); |
| 213 | + expect(master(to).invoiced).toBe(40); |
| 214 | + expectSystemStamp(from); |
| 215 | + expectSystemStamp(to); |
| 216 | + }); |
| 217 | +}); |
0 commit comments