|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#29655] The approver business-unit expansion's `sys_business_unit` reads — |
| 5 | + * the seed check and the child-unit descent — answer EVERY unit, or refuse. |
| 6 | + * #29606 closed the member read; this closes the unit reads it is keyed by. |
| 7 | + * |
| 8 | + * The seed check answered `[]` on a read that threw, and the descent read |
| 9 | + * each parent's child units once at a 1,000-row bound and answered `[]` on any |
| 10 | + * failure: a failed seed read logged "expanded to nobody", indistinguishable |
| 11 | + * from an unstaffed unit, and a failed or cut descent routed to a shrunk slate |
| 12 | + * with no signal at all. |
| 13 | + * |
| 14 | + * What a caller sees now: the expansion throws, the approver-spec resolver's |
| 15 | + * directory catch takes it, and the slot falls back to its literal with the |
| 16 | + * warning that names the failed read and carries its `error`. A unit object |
| 17 | + * that does not exist is still no members. |
| 18 | + * |
| 19 | + * Measured on a REAL engine (ObjectQL + SqlDriver over in-memory SQLite) |
| 20 | + * carrying the shipped `SysBusinessUnit` and `SysBusinessUnitMember`. |
| 21 | + */ |
| 22 | + |
| 23 | +import { describe, it, expect, afterEach, vi } from 'vitest'; |
| 24 | +import { ObjectQL } from '@objectstack/objectql'; |
| 25 | +import { SqlDriver } from '@objectstack/driver-sql'; |
| 26 | +import { SysBusinessUnit, SysBusinessUnitMember, SysMember, SysOrganization } from '@objectstack/platform-objects/identity'; |
| 27 | +import { ApprovalService } from './approval-service.js'; |
| 28 | + |
| 29 | +const ORG = 'org_tree'; |
| 30 | +const ROOT = 'bu_root'; |
| 31 | +const CHILD = 'bu_child'; |
| 32 | +/** The bound each child-unit read is paged at. */ |
| 33 | +const PAGE = 1000; |
| 34 | + |
| 35 | +const pad = (n: number) => String(n).padStart(5, '0'); |
| 36 | + |
| 37 | +/** Which `sys_business_unit` read a fault targets. */ |
| 38 | +type UnitRead = 'seed' | 'descent'; |
| 39 | + |
| 40 | +interface Rig { |
| 41 | + engine: ObjectQL; |
| 42 | + driver: SqlDriver; |
| 43 | + svc: ApprovalService; |
| 44 | + warn: ReturnType<typeof vi.fn>; |
| 45 | + /** Every member of the tree, sorted. */ |
| 46 | + members: string[]; |
| 47 | + /** The child-unit reads the driver ran for ROOT's children. */ |
| 48 | + rootChildReads: () => number; |
| 49 | + /** Fail every read of one kind; every other read runs as before. */ |
| 50 | + failUnitReads: (which: UnitRead) => void; |
| 51 | +} |
| 52 | + |
| 53 | +const engines: ObjectQL[] = []; |
| 54 | +afterEach(async () => { |
| 55 | + vi.restoreAllMocks(); |
| 56 | + while (engines.length) { |
| 57 | + try { await engines.pop()?.destroy(); } catch { /* noop */ } |
| 58 | + } |
| 59 | +}); |
| 60 | + |
| 61 | +/** |
| 62 | + * ROOT, its child CHILD, and `extra` more child units of ROOT, each with one |
| 63 | + * member. Unit ids are scrambled against creation order. |
| 64 | + */ |
| 65 | +async function boot(extra: number, opts: { omit?: string[] } = {}): Promise<Rig> { |
| 66 | + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true } as never); |
| 67 | + const engine = new ObjectQL(); |
| 68 | + engine.registerDriver(driver as never, true); |
| 69 | + await engine.init(); |
| 70 | + const omit = new Set(opts.omit ?? []); |
| 71 | + engine.registerApp({ |
| 72 | + id: 'com.objectstack.qa.business-unit-hierarchy-complete', |
| 73 | + name: 'business unit hierarchy complete', |
| 74 | + version: '1.0.0', |
| 75 | + type: 'plugin', |
| 76 | + scope: 'system', |
| 77 | + objects: [SysOrganization, SysMember, SysBusinessUnit, SysBusinessUnitMember].filter((o) => !omit.has(o.name)), |
| 78 | + } as never); |
| 79 | + await engine.syncSchemas(); |
| 80 | + engines.push(engine); |
| 81 | + |
| 82 | + const e = engine as any; |
| 83 | + await e.insert('sys_organization', { id: ORG, name: ORG, slug: 'tree' }, { context: { isSystem: true } }); |
| 84 | + const kids = Array.from({ length: extra }, (_, i) => `bu_kid_${pad((i * 7919) % 100003)}`); |
| 85 | + const units = [ROOT, CHILD, ...kids]; |
| 86 | + if (!omit.has('sys_business_unit')) { |
| 87 | + const rows: Record<string, unknown>[] = [ |
| 88 | + { id: ROOT, name: 'Root', kind: 'division', active: true, organization_id: ORG }, |
| 89 | + { id: CHILD, name: 'Child', kind: 'department', active: true, parent_business_unit_id: ROOT, organization_id: ORG }, |
| 90 | + ...kids.map((id) => ({ id, name: id, kind: 'department', active: true, parent_business_unit_id: ROOT, organization_id: ORG })), |
| 91 | + ]; |
| 92 | + const d = e.getDriverForObject('sys_business_unit'); |
| 93 | + for (let i = 0; i < rows.length; i += 250) await d.bulkCreate('sys_business_unit', rows.slice(i, i + 250)); |
| 94 | + } |
| 95 | + const members = units.map((u) => `usr_of_${u}`); |
| 96 | + const memberRows = units.map((u, i) => ({ |
| 97 | + id: `bum_${pad(i)}`, user_id: `usr_of_${u}`, business_unit_id: u, organization_id: ORG, |
| 98 | + })); |
| 99 | + const md = e.getDriverForObject('sys_business_unit_member'); |
| 100 | + for (let i = 0; i < memberRows.length; i += 250) await md.bulkCreate('sys_business_unit_member', memberRows.slice(i, i + 250)); |
| 101 | + |
| 102 | + let rootChildReads = 0; |
| 103 | + (driver as any).knex.on('query', (q: { sql: string; bindings?: unknown[] }) => { |
| 104 | + if (/^select .* from [`"]sys_business_unit[`"]/i.test(q.sql) && /parent_business_unit_id/.test(q.sql) |
| 105 | + && (q.bindings ?? []).includes(ROOT)) rootChildReads += 1; |
| 106 | + }); |
| 107 | + const failUnitReads = (which: UnitRead) => { |
| 108 | + const d = e.getDriverForObject('sys_business_unit'); |
| 109 | + const real = d.find.bind(d); |
| 110 | + vi.spyOn(d, 'find').mockImplementation(((obj: string, ...rest: unknown[]) => { |
| 111 | + const descent = JSON.stringify(rest).includes('parent_business_unit_id'); |
| 112 | + if (obj === 'sys_business_unit' && (which === 'descent') === descent) { |
| 113 | + return Promise.reject(Object.assign(new Error('SQLITE_IOERR: disk I/O error'), { code: 'SQLITE_IOERR' })); |
| 114 | + } |
| 115 | + return real(obj, ...rest); |
| 116 | + }) as never); |
| 117 | + }; |
| 118 | + const warn = vi.fn(); |
| 119 | + const svc = new ApprovalService({ |
| 120 | + engine: engine as any, |
| 121 | + logger: { warn, info: () => {}, error: () => {}, debug: () => {} } as any, |
| 122 | + }); |
| 123 | + return { engine, driver, svc, warn, members: [...members].sort(), rootChildReads: () => rootChildReads, failUnitReads }; |
| 124 | +} |
| 125 | + |
| 126 | +/** The private expansion and the resolver, as the request opener calls them. */ |
| 127 | +const department = (rig: Rig, value = ROOT) => |
| 128 | + (rig.svc as any).expandBusinessUnitUsers(value, ORG) as Promise<string[]>; |
| 129 | +const resolveSpec = (rig: Rig, a: { type: string; value: string }) => |
| 130 | + (rig.svc as any).resolveApproverSpec(a, undefined, ORG, Date.now()) as Promise<string[]>; |
| 131 | +const failureWarnings = (rig: Rig) => rig.warn.mock.calls.filter(([, meta]) => typeof meta?.error === 'string'); |
| 132 | + |
| 133 | +describe('[#29655] approvals business-unit expansion: a failed seed read refuses', () => { |
| 134 | + it('⛔ the expansion refuses — it never answers an invented empty slate', async () => { |
| 135 | + const rig = await boot(0); |
| 136 | + rig.failUnitReads('seed'); |
| 137 | + |
| 138 | + await expect(department(rig)).rejects.toThrow( |
| 139 | + /\[approvals\] business unit 'bu_root' in organization 'org_tree' could not be read: SQLITE_IOERR/, |
| 140 | + ); |
| 141 | + }); |
| 142 | + |
| 143 | + it('⛔ what the caller sees: the department slot falls back to its literal, and the warning names the failed read', async () => { |
| 144 | + const rig = await boot(0); |
| 145 | + rig.failUnitReads('seed'); |
| 146 | + |
| 147 | + expect(await resolveSpec(rig, { type: 'department', value: ROOT })).toEqual([`department:${ROOT}`]); |
| 148 | + const failed = failureWarnings(rig); |
| 149 | + expect(failed.map(([, meta]) => meta.type)).toEqual(['department']); |
| 150 | + expect(failed[0][0]).toMatch(/could not be expanded — a directory or read-filter lookup failed/); |
| 151 | + expect(failed[0][1].error).toMatch(/SQLITE_IOERR/); |
| 152 | + }); |
| 153 | +}); |
| 154 | + |
| 155 | +describe('[#29655] approvals business-unit expansion: a failed descent read refuses', () => { |
| 156 | + it('⛔ the expansion refuses — the slate never shrinks to the seed unit', async () => { |
| 157 | + const rig = await boot(0); |
| 158 | + rig.failUnitReads('descent'); |
| 159 | + |
| 160 | + await expect(department(rig)).rejects.toThrow( |
| 161 | + /\[approvals\] the child units of business unit 'bu_root' in organization 'org_tree' could not be read: SQLITE_IOERR/, |
| 162 | + ); |
| 163 | + }); |
| 164 | + |
| 165 | + it('⛔ what the caller sees: the literal and the failed-read warning, not a shrunk slate', async () => { |
| 166 | + const rig = await boot(0); |
| 167 | + rig.failUnitReads('descent'); |
| 168 | + |
| 169 | + expect(await resolveSpec(rig, { type: 'department', value: ROOT })).toEqual([`department:${ROOT}`]); |
| 170 | + expect(failureWarnings(rig).map(([, meta]) => meta.type)).toEqual(['department']); |
| 171 | + }); |
| 172 | +}); |
| 173 | + |
| 174 | +describe('[#29655] approvals business-unit expansion reads every child unit past the 1,000-row bound', () => { |
| 175 | + it('⭐ 1,001 child units: every member of every child is on the slate', async () => { |
| 176 | + // CHILD plus 1,000 more: 1,001 children of ROOT. |
| 177 | + const rig = await boot(PAGE); |
| 178 | + |
| 179 | + expect([...(await department(rig))].sort()).toEqual(rig.members); |
| 180 | + expect(rig.members).toHaveLength(PAGE + 2); |
| 181 | + expect(rig.rootChildReads()).toBe(2); |
| 182 | + }, 60_000); |
| 183 | + |
| 184 | + it('control — under the bound: one child-unit read, the same slate as before', async () => { |
| 185 | + // CHILD plus 998 more: 999 children of ROOT. |
| 186 | + const rig = await boot(PAGE - 2); |
| 187 | + |
| 188 | + expect([...(await department(rig))].sort()).toEqual(rig.members); |
| 189 | + expect(rig.rootChildReads()).toBe(1); |
| 190 | + }, 60_000); |
| 191 | +}); |
| 192 | + |
| 193 | +describe('[#29655] approvals business-unit expansion: absence still answers nobody', () => { |
| 194 | + it('a composition that never registers sys_business_unit has no departments: the literal, with no failure warning', async () => { |
| 195 | + const rig = await boot(0, { omit: ['sys_business_unit'] }); |
| 196 | + |
| 197 | + expect(await department(rig)).toEqual([]); |
| 198 | + expect(await resolveSpec(rig, { type: 'department', value: ROOT })).toEqual([`department:${ROOT}`]); |
| 199 | + expect(failureWarnings(rig)).toEqual([]); |
| 200 | + }); |
| 201 | + |
| 202 | + it('a stack whose sys_business_unit table was never created has no departments', async () => { |
| 203 | + const rig = await boot(0); |
| 204 | + await (rig.driver as any).knex.schema.dropTable('sys_business_unit'); |
| 205 | + |
| 206 | + expect(await department(rig)).toEqual([]); |
| 207 | + }); |
| 208 | +}); |
0 commit comments