diff --git a/.changeset/36258-change-owner-readback-queue.md b/.changeset/36258-change-owner-readback-queue.md new file mode 100644 index 00000000000..9035f6fcb96 --- /dev/null +++ b/.changeset/36258-change-owner-readback-queue.md @@ -0,0 +1,13 @@ +--- +'@objectstack/core': patch +--- + +fix(core): Change Owner answers a hand-away that leaves the caller's view as moved, and refuses a queue target on an object with no queue column behind it + +Clause-②: no +Metadata-protocol: none + +- **A record handed away that the caller can no longer see moved.** When storage reads the record back under the caller's row access, a record handed to someone else reads back as nothing straight after the write. The write still landed, and the engine says so. Change Owner read that empty answer as "not found": the single door answered `404 RECORD_NOT_FOUND` and told nobody, the bulk door listed the record under `failures`, and a cascaded child counted as refused. Now the single door answers `200` and sends the notice when asked, the bulk door counts the record under `updated`, and the child counts as moved. A record the caller cannot reach is still answered `404 RECORD_NOT_FOUND`, by the engine, before anything is written. The built-in SQL storage keeps the record visible to the caller after the write, so it never showed this. +- **A queue target on an external object is refused.** A queue target needs the platform's `queue` column with storage behind it. Change Owner checked only for a field named `queue`. The platform registers that field on every object that has an owner, external objects included, where no column backs it, so an external object got a queue write in place of the `400 VALIDATION_ERROR` ("has no ownership queue column"). An object whose fields are registered as a list was refused with that sentence although it has the column. Now Change Owner uses the engine's own test for the column, `resolveInjectedColumnProvenance(def, 'queue') === 'injected-provisioned'`, so list-shaped and record-shaped `fields` get the same answer. A field the author declared and named `queue` is not the ownership queue. It does not let a queue target through, which matches the engine's assignment rules. + +Nothing to migrate. diff --git a/packages/core/src/security/change-record-owner.test.ts b/packages/core/src/security/change-record-owner.test.ts index 249007faa51..a5171ac8c4e 100644 --- a/packages/core/src/security/change-record-owner.test.ts +++ b/packages/core/src/security/change-record-owner.test.ts @@ -4,7 +4,7 @@ import { describe, it, expect, vi } from 'vitest'; import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { OWNER_FIELD_DEF } from '@objectstack/spec/data'; +import { OWNER_FIELD_DEF, QUEUE_FIELD_DEF } from '@objectstack/spec/data'; import { CHANGE_OWNER_DISABLED, CHANGE_OWNER_NOTIFICATION_TOPIC, @@ -15,11 +15,10 @@ import { type ChangeOwnerEngine, } from './change-record-owner.js'; import { USER_WORK_TRANSFER_ROW_CAP, UserWorkTransferRefusal } from './user-assigned-work.js'; +import { recordNotFoundError } from '../utils/record-not-found.js'; type Row = Record; -const QUEUE_FIELD_DEF = { type: 'text', system: true }; - // Registered shapes, as `applySystemFields` leaves them: the owner column and // the queue column ride together on an owner-bearing object (ADR-0142 D3). const lead = { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { name: { type: 'text' }, owner_id: OWNER_FIELD_DEF, queue: QUEUE_FIELD_DEF } }; @@ -30,6 +29,19 @@ const orgOwned = { name: 'setting_row', ownership: 'org', fields: { name: { type const managed = { name: 'auth_session', managedBy: 'better-auth', fields: { user_id: { type: 'lookup', reference: 'sys_user' } } }; const platform = { name: 'sys_team', fields: { name: { type: 'text' } } }; const noQueue = { name: 'memo', fields: { owner_id: OWNER_FIELD_DEF } }; +// [#36262] An external (ADR-0015) object with a provable owner: the injection +// still registers `queue` beside `owner_id`, with no column behind it. +const extAccount = { + name: 'ext_account', label: 'Account', sharingModel: 'private', external: { remoteName: 'accounts' }, + fields: { name: { type: 'text' }, owner_id: { type: 'lookup', reference: 'sys_user', label: 'Account owner' }, queue: QUEUE_FIELD_DEF }, +}; +// [#36262] The registered list shape of `fields`, the platform's queue column among them. +const listed = { + name: 'listed_lead', sharingModel: 'private', + fields: [{ name: 'name', type: 'text' }, { name: 'owner_id', ...OWNER_FIELD_DEF }, { name: 'queue', ...QUEUE_FIELD_DEF }], +}; +// [#36262] A field the author named `queue`: theirs, not the ownership queue. +const authoredQueue = { name: 'ticket', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF, queue: { type: 'text', label: 'Support queue' } } }; // [#35315 phase 2] The cascade's children of `lead`: one declared cascade, one // plain lookup, and — registered raw, past the parse that refuses it — a // cascade on a controlled_by_parent detail, which is never a candidate. @@ -38,7 +50,7 @@ const leadCall = { name: 'lead_call', sharingModel: 'private', fields: { lead: { const leadLine = { name: 'lead_line', sharingModel: 'controlled_by_parent', fields: { lead: { type: 'master_detail', reference: 'lead', transferBehavior: 'cascade' }, owner_id: OWNER_FIELD_DEF } }; const SCHEMAS: Record = Object.fromEntries( - [lead, pinned, line, lineOptedIn, orgOwned, managed, platform, noQueue, leadTask, leadCall, leadLine].map((o) => [o.name, o]), + [lead, pinned, line, lineOptedIn, orgOwned, managed, platform, noQueue, extAccount, listed, authoredQueue, leadTask, leadCall, leadLine].map((o) => [o.name, o]), ); const CALLER = { userId: 'u_manager', tenantId: 'org_1' }; @@ -50,7 +62,14 @@ const CALLER = { userId: 'u_manager', tenantId: 'org_1' }; * without, answering the stored row; refused before any write, as * `ERR_READONLY_FIELD_REJECTED`, under `strictReadonlyWrites`. */ -function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: string[]; locked?: (row: Row) => string[]; disabledPackageObjects?: string[] } = {}) { +function fakeEngine(opts: { + refuse?: (id: string) => unknown; + hiddenUsers?: string[]; + locked?: (row: Row) => string[]; + disabledPackageObjects?: string[]; + /** Rows the write moves out of the caller's row scope: the update lands, and its read-back is `null`, as the engine answers one. */ + leavesScope?: (object: string, id: string) => boolean; +} = {}) { /** Per update call, in order: whether it passed `strictReadonlyWrites: true`. */ const strictWrites: boolean[] = []; const tables: Record = { @@ -58,6 +77,9 @@ function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: stri lead: [{ id: 'l1', owner_id: 'u_a' }, { id: 'l2', owner_id: 'u_b' }, { id: 'l3', owner_id: 'u_a' }], contract_line: [{ id: 'c1', owner_id: 'u_a' }], memo: [{ id: 'm1', owner_id: 'u_a' }], + ext_account: [{ id: 'x1', owner_id: 'u_a' }], + listed_lead: [{ id: 'd1', owner_id: 'u_a' }], + ticket: [{ id: 'k1', owner_id: 'u_a' }], lead_task: [ { id: 't1', lead: 'l1', owner_id: 'u_a' }, { id: 't2', lead: 'l1', owner_id: 'u_b' }, @@ -99,14 +121,17 @@ function fakeEngine(opts: { refuse?: (id: string) => unknown; hiddenUsers?: stri calls.push({ op: 'update', object, data, where: o?.where, context: o?.context }); strictWrites.push(o?.strictReadonlyWrites === true); const row = (tables[object] ?? []).find((r) => r.id === o?.where?.id); - if (!row) return null; + // The engine's not-found gate: a by-id update reads the row first and + // throws before the write when the caller cannot reach it (`engine-update.ts`). + if (!row) throw recordNotFoundError(object, String(o?.where?.id), o?.context as Parameters[2]); const refusal = opts.refuse?.(row.id); if (refusal) throw refusal; const lockedKeys = (opts.locked?.(row) ?? []).filter((k) => Object.prototype.hasOwnProperty.call(data, k)); if (lockedKeys.length > 0 && o?.strictReadonlyWrites === true) throw readonlyRejected(object, lockedKeys); const kept = Object.fromEntries(Object.entries(data).filter(([k]) => !lockedKeys.includes(k))); Object.assign(row, kept); - return row; + // A write that took the row out of the caller's scope reads back nothing, though it landed. + return opts.leavesScope?.(object, row.id) === true ? null : row; }, }; return engine; @@ -188,7 +213,7 @@ describe('[#35402] changeRecordOwner — one record', () => { it('a queue target on an object with no queue column is refused before any write', async () => { const engine = fakeEngine(); - const err = await refusalOf(changeRecordOwner(engine, 'memo', 'm1', { queue: 'triage' }, CALLER)); + const err = await refusalOf(changeRecordOwner(engine, 'ext_account', 'x1', { queue: 'triage' }, CALLER)); expect(err).toBeInstanceOf(UserWorkTransferRefusal); expect({ code: err.code, status: err.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); expect(engine.calls.some((c) => c.op === 'update')).toBe(false); @@ -234,6 +259,47 @@ describe('[#35402] changeRecordOwner — one record', () => { }); }); +describe('[#36262] a queue target asks for the queue column with storage behind it, as the engine does', () => { + it('an external object with an owner, whose injected queue has no column, is refused 400 before any write: single and bulk', async () => { + const engine = fakeEngine(); + const single = await refusalOf(changeRecordOwner(engine, 'ext_account', 'x1', { queue: 'triage' }, CALLER)); + expect({ code: single.code, status: single.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); + expect(single.message).toMatch(/^'ext_account' has no ownership queue column/); + const bulk = await refusalOf(changeRecordsOwner(engine, 'ext_account', ['x1'], { queue: 'triage' }, CALLER)); + expect({ code: bulk.code, status: bulk.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); + expect(engine.calls.some((c) => c.op === 'update')).toBe(false); + expect(engine.tables.ext_account[0]).toEqual({ id: 'x1', owner_id: 'u_a' }); + }); + + it('the external object still takes a person target: only the queue column is missing', async () => { + const result = await changeRecordOwner(fakeEngine(), 'ext_account', 'x1', { ownerId: 'u_next' }, CALLER); + expect(result).toEqual({ object: 'ext_account', id: 'x1', ownerId: 'u_next', notified: false }); + }); + + it('list-shaped fields with the platform\'s queue column are admitted, single and bulk', async () => { + const engine = fakeEngine(); + const result = await changeRecordOwner(engine, 'listed_lead', 'd1', { queue: 'triage' }, CALLER); + expect(result).toEqual({ object: 'listed_lead', id: 'd1', ownerId: null, queue: 'triage', notified: false }); + const report = await changeRecordsOwner(engine, 'listed_lead', ['d1'], { queue: 'triage' }, CALLER); + expect(report).toMatchObject({ updated: 1, failed: 0 }); + }); + + it('control: a local object with the provisioned queue column is admitted, whether its document lists the column or the injection adds it', async () => { + for (const [object, id] of [['lead', 'l1'], ['memo', 'm1']] as const) { + const engine = fakeEngine(); + const result = await changeRecordOwner(engine, object, id, { queue: 'triage' }, CALLER); + expect(result, object).toEqual({ object, id, ownerId: null, queue: 'triage', notified: false }); + } + }); + + it('a field the author named queue is not the ownership queue: refused 400 before any write', async () => { + const engine = fakeEngine(); + const err = await refusalOf(changeRecordOwner(engine, 'ticket', 'k1', { queue: 'triage' }, CALLER)); + expect({ code: err.code, status: err.status }).toEqual({ code: 'VALIDATION_ERROR', status: 400 }); + expect(engine.calls.some((c) => c.op === 'update')).toBe(false); + }); +}); + describe('[#35402] changeRecordsOwner — the bulk form', () => { it('a mixed batch: one moves, one refused by the owner guard, one out of reach — every failure listed with its id', async () => { const engine = fakeEngine({ refuse: (id) => (id === 'l2' ? transferDenied() : undefined) }); @@ -282,6 +348,50 @@ describe('[#35402] changeRecordsOwner — the bulk form', () => { }); }); +describe('a hand-away whose read-back is out of the caller\'s scope moved: the engine\'s null read-back is not "not found"', () => { + // Every row of `lead` reads back `null` once written: the move took it out of the caller's scope. + const scoped = () => fakeEngine({ leavesScope: (object) => object === 'lead' }); + + it('single: answers the move and tells the new owner', async () => { + const engine = scoped(); + const messaging = { emit: vi.fn(async () => SENT) }; + const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, { notify: true, messaging }); + expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: 'u_next', notified: true }); + expect(engine.tables.lead[0]!.owner_id).toBe('u_next'); + expect(messaging.emit).toHaveBeenCalledTimes(1); + }); + + it('bulk: the row counts under updated, none under failed, and the notice names it', async () => { + const engine = scoped(); + const messaging = { emit: vi.fn(async () => SENT) }; + const report = await changeRecordsOwner(engine, 'lead', ['l1'], { ownerId: 'u_next' }, CALLER, { notify: true, messaging }); + expect(report).toMatchObject({ updated: 1, failed: 0, failures: [], notified: true }); + expect((messaging.emit.mock.calls[0] as any[])[0].payload.recordIds).toEqual(['l1']); + }); + + it('a queue target whose read-back is null moved too', async () => { + const result = await changeRecordOwner(scoped(), 'lead', 'l1', { queue: 'triage' }, CALLER); + expect(result).toEqual({ object: 'lead', id: 'l1', ownerId: null, queue: 'triage', notified: false }); + }); + + it('a cascade still runs from a moved record, and a child whose read-back is null counts as moved', async () => { + const engine = fakeEngine({ leavesScope: () => true }); + const result = await changeRecordOwner(engine, 'lead', 'l1', { ownerId: 'u_next' }, CALLER, { + cascade: [{ object: 'lead_task', field: 'lead' }], + }); + expect(result.cascade).toEqual([{ object: 'lead_task', field: 'lead', updated: 2, failed: 0, failures: [], remaining: 0 }]); + expect(engine.tables.lead_task.map((r) => [r.id, r.owner_id])).toEqual([['t1', 'u_next'], ['t2', 'u_b'], ['t3', 'u_next'], ['t4', 'u_b']]); + }); + + it('a row that is not there is the engine\'s own 404 RECORD_NOT_FOUND, thrown before the write: single refused, bulk lists it', async () => { + const single = await refusalOf(changeRecordOwner(scoped(), 'lead', 'l9', { ownerId: 'u_next' }, CALLER)); + expect({ code: single.code, status: single.status }).toEqual({ code: 'RECORD_NOT_FOUND', status: 404 }); + const report = await changeRecordsOwner(scoped(), 'lead', ['l1', 'l9'], { ownerId: 'u_next' }, CALLER); + expect(report).toMatchObject({ updated: 1, failed: 1 }); + expect(report.failures.map((f) => [f.id, f.code])).toEqual([['l9', 'RECORD_NOT_FOUND']]); + }); +}); + describe('a readonlyWhen lock that holds: the answer is what was saved, not what was asked', () => { const closed = (engine: ReturnType, ids: string[]) => { for (const r of engine.tables.lead) if (ids.includes(r.id)) r.status = 'closed'; diff --git a/packages/core/src/security/change-record-owner.ts b/packages/core/src/security/change-record-owner.ts index b99e4576874..ce2ccba0d0c 100644 --- a/packages/core/src/security/change-record-owner.ts +++ b/packages/core/src/security/change-record-owner.ts @@ -93,6 +93,7 @@ import { canServeApiOperation, type EnableLike, referenceTargetOf, + resolveInjectedColumnProvenance, resolveUserActionTransfer, transferCascadeIneligibilityReason, transferIneligibilityReason, @@ -100,7 +101,6 @@ import { import { SystemFieldName } from '@objectstack/spec/system'; import { objectNotFoundError } from '../utils/object-not-found.js'; import { objectPackageDisabledError } from '../utils/object-package-disabled.js'; -import { recordNotFoundError } from '../utils/record-not-found.js'; import { assertAssignableUser, failureOf, @@ -159,11 +159,24 @@ function lockedOwnerRefusal(err: unknown, object: string, id: string): Error | u /** * One record's owner write: a by-id update under the caller's context with * {@link OWNER_WRITE_OPTIONS}, a locked owner or queue answered as - * {@link lockedOwnerRefusal}. Answers what the engine answers. + * {@link lockedOwnerRefusal}. Resolves once the write landed; any other + * outcome is a throw. + * + * The engine's answer is never read as "not found". A by-id update reads the + * row as the caller BEFORE it writes and throws `404 RECORD_NOT_FOUND` itself + * when the caller cannot reach it (`engine-update.ts`, the not-found gate), + * so a call that returns wrote the row. What it returns is the driver's + * post-write read-back, and that is `null` for a write that landed: a change + * of owner that moves the row out of the caller's own row scope (handing a + * record away under an owner-scoped read) reads back nothing, the case the + * engine names when it explains why it asks existence before the write. A + * driver that answers the write with nothing at all wrote it too. Reading + * either as "not found" would answer 404, list the row as failed and tell + * nobody, for a record that moved. */ -async function writeOwner(engine: ChangeOwnerEngine, object: string, id: string, changeSet: AnyRec, context: unknown): Promise { +async function writeOwner(engine: ChangeOwnerEngine, object: string, id: string, changeSet: AnyRec, context: unknown): Promise { try { - return await engine.update(object, changeSet, { where: { id }, context, ...OWNER_WRITE_OPTIONS }); + await engine.update(object, changeSet, { where: { id }, context, ...OWNER_WRITE_OPTIONS }); } catch (err) { throw lockedOwnerRefusal(err, object, id) ?? err; } @@ -344,6 +357,8 @@ export function changeOwnerOffRefusal(object: string, reason: string): Error { * read and before any write or notification. `getSchema` still resolves such * an object (disable is reversible and keeps it registered), so the switch * alone would let it through. + * + * Whether the object can take a queue target is {@link carriesQueueColumn}. */ function offeredDefinition(engine: ChangeOwnerEngine, object: string, target: ChangeOwnerTarget): AnyRec { const def = asRecord(engine.getSchema(object)); @@ -351,16 +366,31 @@ function offeredDefinition(engine: ChangeOwnerEngine, object: string, target: Ch if (engine.registry?.isObjectPackageDisabled?.(object) === true) throw objectPackageDisabledError(object); const reason = changeOwnerOffReason(object, def); if (reason) throw changeOwnerOffRefusal(object, reason); - if (target.queue !== undefined) { - const fields = asRecord(def.fields); - if (!fields || !Object.prototype.hasOwnProperty.call(fields, QUEUE_FIELD)) { - throw new UserWorkTransferRefusal(400, 'VALIDATION_ERROR', - `'${object}' has no ownership queue column, so its records cannot be moved to a queue; name a person in ownerId instead`); - } + if (target.queue !== undefined && !carriesQueueColumn(def)) { + throw new UserWorkTransferRefusal(400, 'VALIDATION_ERROR', + `'${object}' has no ownership queue column, so its records cannot be moved to a queue; name a person in ownerId instead`); } return def; } +/** + * [ADR-0142 D3] Does `def` carry the platform's `queue` column with storage + * behind it — the engine's own test (`carriesQueueColumn`, `@objectstack/objectql`'s + * assignment rules), asked of the spec's provenance verdict so this package + * and the engine judge one answer. + * + * Not "does a field named `queue` appear in `fields`". The injection registers + * `queue` wherever it registers `owner_id`, on an external (ADR-0015) object + * too, where no column backs it: a name test admits that object and sends the + * remote system a queue write instead of refusing. A `queue` field the author + * declared is the author's, not the ownership queue, and admits nothing. And + * the verdict reads either registered `fields` shape, a list as well as a + * record keyed by name. + */ +function carriesQueueColumn(def: AnyRec): boolean { + return resolveInjectedColumnProvenance(def, QUEUE_FIELD) === 'injected-provisioned'; +} + /** The change-set one record's owner change writes. */ function ownerChangeSet(target: ChangeOwnerTarget): AnyRec { return target.queue !== undefined @@ -632,10 +662,7 @@ async function runCascade( // The parent's own owner write, so a child whose `owner_id` is locked // on that row (read-only, or a `readonlyWhen` that holds) is refused // `403 FIELD_NOT_ACCESSIBLE` and listed here, never counted as moved. - const written = await writeOwner(engine, rel.object, String(childId), { [SystemFieldName.OWNER_ID]: newOwner }, context); - if (written === null || written === undefined || written === 0) { - throw recordNotFoundError(rel.object, String(childId), context as Parameters[2]); - } + await writeOwner(engine, rel.object, String(childId), { [SystemFieldName.OWNER_ID]: newOwner }, context); outcome.updated += 1; } catch (err) { outcome.failed += 1; @@ -665,8 +692,10 @@ async function runCascade( * refusal for a row the caller may not move (the route answers it as the * `/data` door answers the same throw), `403 FIELD_NOT_ACCESSIBLE` when a * `readonlyWhen` lock holds `owner_id` or `queue` on the row, `404 - * RECORD_NOT_FOUND` for a row the caller cannot reach, and the whole-call - * refusals of {@link changeRecordsOwner}. + * RECORD_NOT_FOUND` for a row the caller cannot reach (the engine's own + * refusal, thrown before the write), and the whole-call refusals of + * {@link changeRecordsOwner}. A row the move takes out of the caller's sight + * moved, and is answered as moved ({@link writeOwner}). */ export async function changeRecordOwner( engine: ChangeOwnerEngine, @@ -687,10 +716,7 @@ export async function changeRecordOwner( const relations = cascadeRelationsOf(engine, object, options.cascade, target); await assertTarget(engine, target, context); const before = relations.length > 0 ? await previousOwners(engine, object, [id], context) : undefined; - const written = await writeOwner(engine, object, id, ownerChangeSet(target), context); - if (written === null || written === undefined || written === 0) { - throw recordNotFoundError(object, id, context as Parameters[2]); - } + await writeOwner(engine, object, id, ownerChangeSet(target), context); const ownerId = target.ownerId ?? null; const cascade = before && ownerId !== null ? await runCascade(engine, relations, [{ id, previousOwner: before.get(id) }], ownerId, context, @@ -763,10 +789,7 @@ export async function changeRecordsOwner( const moved: string[] = []; for (const id of ids) { try { - const written = await writeOwner(engine, object, id, { ...changeSet }, context); - if (written === null || written === undefined || written === 0) { - throw recordNotFoundError(object, id, context as Parameters[2]); - } + await writeOwner(engine, object, id, { ...changeSet }, context); report.updated += 1; moved.push(id); } catch (err) { diff --git a/packages/rest/src/change-owner-routes.test.ts b/packages/rest/src/change-owner-routes.test.ts index 1dfd980dc20..cccdcf39615 100644 --- a/packages/rest/src/change-owner-routes.test.ts +++ b/packages/rest/src/change-owner-routes.test.ts @@ -7,7 +7,8 @@ import { describe, it, expect, vi, afterEach } from 'vitest'; import { ObjectQL } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; import { assertEngineUpdateDispatch } from '@objectstack/metadata-core'; -import { OWNER_FIELD_DEF } from '@objectstack/spec/data'; +import { recordNotFoundError } from '@objectstack/core'; +import { OWNER_FIELD_DEF, QUEUE_FIELD_DEF } from '@objectstack/spec/data'; import { RestServer } from './rest-server'; import { DEFAULT_ORGANIZATION_ID, installDefaultOrganization } from './default-organization.testkit.js'; @@ -31,7 +32,7 @@ function mockRes() { const CALLER = { userId: 'u_manager', tenantId: 'org_1' }; const SCHEMAS: Record = { - lead: { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF, queue: { type: 'text' } } }, + lead: { name: 'lead', label: 'Lead', sharingModel: 'private', fields: { owner_id: OWNER_FIELD_DEF, queue: QUEUE_FIELD_DEF } }, // A `private` object whose author switched the action off (ruling 7000907189, acceptance). pinned_lead: { name: 'pinned_lead', sharingModel: 'private', userActions: { transfer: false }, fields: { owner_id: OWNER_FIELD_DEF } }, // [#35315 phase 2] A declared cascade to `lead`, and a plain lookup beside it. @@ -45,7 +46,11 @@ const transferDenied = () => Object.assign( { name: 'PermissionDeniedError', code: 'PERMISSION_DENIED', status: 403 }, ); -function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledPackageObjects: string[] = []) { +/** + * `leavesScope`: the rows a write moves out of the caller's row scope — the + * update lands and reads back `null`, as the engine answers one. + */ +function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledPackageObjects: string[] = [], leavesScope: (id: string) => boolean = () => false) { const rows: Record[] = [{ id: 'l1', owner_id: 'u_a' }, { id: 'l2', owner_id: 'u_b' }]; const users = [{ id: 'u_next', banned: false }, { id: 'u_gone', banned: true }]; const tasks: Record[] = [{ id: 't1', lead: 'l1', owner_id: 'u_a' }, { id: 't2', lead: 'l1', owner_id: 'u_b' }]; @@ -68,11 +73,12 @@ function mockEngine(refuse: (id: string) => unknown = () => undefined, disabledP update: vi.fn(async (o: string, data: any, opts: any) => { assertEngineUpdateDispatch(data, opts); const row = tableOf(o).find((r) => r.id === opts.where.id); - if (!row) return null; + // The engine's not-found gate: read first, thrown before the write. + if (!row) throw recordNotFoundError(o, String(opts.where.id), opts.context); const refusal = refuse(row.id); if (refusal) throw refusal; Object.assign(row, data); - return row; + return leavesScope(row.id) ? null : row; }), }; } @@ -168,6 +174,21 @@ describe('[#35402] POST /data/:object/:id/change-owner', () => { expect(engine.update).toHaveBeenCalledWith('lead', { owner_id: null, queue: 'triage' }, { where: { id: 'l1' }, context: CALLER, strictReadonlyWrites: true }); }); + it('a hand-away whose read-back is out of the caller\'s scope answers 200 and notifies, single and bulk', async () => { + const messaging = { emit: vi.fn(async () => ({ delivered: 0, enqueued: 1 })) }; + const engine = mockEngine(undefined, [], () => true); + const { single, bulk } = buildServer(engine, { messaging }); + const res = mockRes(); + await single!.handler(req({ object: 'lead', id: 'l1' }, { ownerId: 'u_next', notify: true }), res); + expect(res.statusCode).toBe(200); + expect(res.body.data).toEqual({ object: 'lead', id: 'l1', ownerId: 'u_next', notified: true }); + const many = mockRes(); + await bulk!.handler(req({ object: 'lead' }, { ids: ['l2'], ownerId: 'u_next' }), many); + expect(many.statusCode).toBe(200); + expect(many.body.data).toMatchObject({ updated: 1, failed: 0, failures: [] }); + expect(engine.rows.map((r) => r.owner_id)).toEqual(['u_next', 'u_next']); + }); + it('notify sends through the messaging service and says so', async () => { const messaging = { emit: vi.fn(async () => ({ delivered: 0, enqueued: 1 })) }; const { single } = buildServer(mockEngine(), { messaging });