Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

Commit ff14e29

Browse files
fix(plugin-view): the grid's row and bulk Delete delete on the registered object-view path (#10424)
Fixes #10383 Clause-②: yes ## What was wrong On the registered `object-view` renderer path (`ObjectView` with no host `renderListView`), `ObjectGrid` hands the clicked row, or the selection, to `onDelete` / `onBulkDelete` and performs no delete of its own: its own comments say the consumer's delete flow "owns the confirmation, the toast and the refresh". `ObjectView`'s `handleDelete` / `handleBulkDelete` ignored their argument and only bumped `refreshKey`. Delete is offered by default (`operations.delete` defaults to true), so the click deleted nothing and the row came back after the refresh. Reproduced on `origin/main` `a70719765` before any edit, through the REAL `ObjectGrid` (a temporary probe, never committed): row Delete and bulk Delete each gave `dataSource.delete` 0 calls, `bulkDelete` 0, `bulk` 0, and the row was still shown (`AssertionError: expected 0 to be greater than 0`, 2 of 2 failed). ## Measured first: how the console's own list deletes (read only) - Host: the `app-shell` object page renders `ListView`, which forwards `onDelete` / `onBulkDelete` to the same `ObjectGrid`. - Row: `actions.deleteRecord(String(record.id), record)`, skipping a row with no `id`, which runs `execute({ type: 'delete', confirmText: t('objectActions.deleteConfirm'), params })`. The confirm goes through the console runtime's `confirmHandler`, which opens `ActionConfirmDialog`: a Shadcn AlertDialog titled `actionConfirm.title`, buttons `actionConfirm.cancel` / `actionConfirm.confirm`, the question as the description. - Bulk: keeps the rows that have an `id`, then `execute({ type: 'delete', confirmText: t('console.objectView.bulkDeleteConfirm', { count }), params: { records } })`, so there is one confirm for the batch. - Data call: `useObjectActions`' registered `delete` handler. More than one record: `Promise.allSettled(records.map(r => dataSource.delete(objectName, r.id)))`. One record: `dataSource.delete(objectName, recordId)`. It does not use the optional `DataSource.bulkDelete`. - After: bulk refreshes, then toasts `objectActions.bulkDeleteSuccess` or `objectActions.bulkDeletePartial`. Single: on success it refreshes and toasts `objectActions.deleteSuccess`; on failure it toasts `objectActions.deleteFailed` with the error message as the description, and does not refresh. - Permission: the console list's handlers read no permission. Whether Delete is offered at all is decided by `ObjectGrid`: `operations.delete`, AND the principal's `perms.can(object, 'delete')`, AND the object's bucket / `userActions` / effective API operations, AND the per-record explain verdict. It is the same component on both paths, so it is the same gate. ## The fix: ONE record-delete core, and both hosts bind to it The first head (`ea0c5c627`) copied the console's delete steps into `plugin-view`. The seat sent it back: that was a second implementation of the same operation, and it already diverged on consent. It asked a package-owned `sys_permission_set` row the plain delete question, where the console asks the ADR-0094 reset question. The seat's rule for one operation with two diverging implementations: the governed side wins and the other re-binds to it. ⛔ No copying, ⛔ no double-writing. - **`recordDelete` in `@object-ui/core`** (`packages/core/src/actions/recordDelete.ts`, exported through `actions/index.ts`). It is the one new public export (hence `Clause-②: yes`): a frozen `{ confirmText, run }`. - `confirmText(deps, record?)` picks `objectActions.deleteConfirm`, or `objectActions.resetPackageSetConfirm` for a `sys_permission_set` row with `managed_by: 'package'`. - `run(deps, request)` is the console's former inline `delete` handler, moved statement for statement: the id chain, the single delete with the ADR-0094 detection (the row first, then a best-effort `findOne`), the bulk `allSettled`, the four toasts, and the runner-shaped returns (`silent` on success, no `error` key, so no double toast). - `t`, `toast`, `dataSource`, `onRefresh` and the label are INJECTED, so core gains no i18n or toast dependency. Core is the lowest package both hosts already depend on: no new dependency edge, and nothing is inverted. - **Console re-bind** (`app-shell` `useObjectActions`): the `delete` handler is `recordDelete.run(...)`, and `deleteRecord`'s question is `recordDelete.confirmText(...)`. The behaviour is byte-identical; `useObjectActions.test.tsx` is unchanged (a 0-line diff) and green. - **plugin-view re-bind** (`ObjectView`): `performDelete` and the local question are gone. The `AlertDialog` stays as this host's confirm UI (`actionConfirm.*` chrome, the exit-animation `open` guard). The question and the delete come from the core, with the same request shapes the console hands its runner. So a package-owned permission set on this path now gets the reset question and the reset toast. - Whether Delete is offered at all is unchanged: it is `ObjectGrid`'s verdict on both paths (`operations.delete`, the delete grant, the object's lifecycle, `userActions` and API operations, and the per-record verdict). - No new i18n key: every key is already in the ten packs. The en defaults sit in `VIEW_DEFAULT_TRANSLATIONS` for the provider-less path, byte-identical to `en`. - `ObjectGrid.tsx`, `RowActionMenu.tsx`, `useConsoleActionRuntime.tsx` and `ActionRunner.ts` are untouched. The grid branch's remount-to-refresh is untouched. ## Pins - `packages/core/src/actions/__tests__/recordDelete.test.ts`, 13 cases: - the question (plain, reset, and env-owned or no row); - single success and single refused (no refresh, no `error` key); - the id chain, and no id (the `error` goes to the runner); - bulk success and bulk partial; - reset via the passed row and reset via `findOne`; - the env-owned and failed-lookup controls; - an ordinary object is never looked up. - `packages/app-shell/src/hooks/__tests__/useObjectActions.test.tsx`, UNCHANGED: toast de-duplication and the ADR-0094 reset copy, including the `findOne` fallback. - `packages/plugin-view/src/__tests__/ObjectView.gridDelete-10383.test.tsx`, 9 cases through the real `ObjectGrid` against an in-memory source: - row confirm then delete, and the row is gone; - Cancel; - a refused row delete; - bulk (2 `delete`, 0 `bulkDelete`) and partial bulk; - the permission pair; - a package-owned permission set asks the RESET question and toasts the reset, and its env-owned control keeps the plain copy. - `scripts/__tests__/check-i18n-call-site-keys.test.ts`: the objectui#3845 pin follows the call site into `recordDelete.ts`, with the same absent / present pair, plus one added sister assertion (`deleteSuccess` still interpolates `label`). ## Reverse verification (`ablation-replace.mjs`, WRAP mode, at `e9668789f`; expectations pre-registered) | Leg | Mutation | Result | Restore | |:--|:--|:--|:--| | A | plugin-view's `handleDelete` / `handleBulkDelete` back to their refresh-only bodies | `Tests 7 failed \| 2 passed (9)`: the 5 delete cases and the 2 ADR-0094 cases red; the permission pair, which pins `ObjectGrid`, green | blob `a8eb765b` == HEAD, `git diff HEAD` empty | | B | the core's reset branch removed (`isPackageOwned` → `return false`) | `Tests 6 failed \| 22 passed (28)` across core, console and plugin-view: every reset case red on all three, every env-owned control green | blob `bc25ece0` == HEAD, `git diff HEAD` empty | ## Gates (head `473c86933`; code identical to `e9668789f`, which adds only changesets on top) - CI on `473c86933`: 43 check-runs, 40 success and 3 skipped, 0 failures. On the intermediate head `6c374d382`, shard 4/8 was red in `check-i18n-call-site-keys` (the pin still pointed at `useObjectActions.ts`). `e9668789f` fixed it by re-pointing the pin, without weakening it. - `turbo run build --filter='@object-ui/app-shell^...'`: 28/28. Type-check exits 0 for core, plugin-view and app-shell. - `vitest run packages/plugin-view/ packages/core/`: 215 files, 3951 passed. `packages/app-shell/` in 6 shards: 775 files, 7624 passed, 9 skipped, 0 failed. `scripts/__tests__/`: 179 files, 5306 passed, 2 skipped by design. The 17 other text readers of the touched sources: 1111 passed. - `check:control-bytes` OK. `check:new-line-citations` 0 new. `check-changeset-presence`: 2 changesets over 3 released packages, and it demands no app-shell entry. `check-changeset-no-major` OK. `check:changeset-claims` exits 0 (the same 5 pending changesets, re-read, still true). `check:i18n-keys` OK. Governed guard: NOT GOVERNED. - eslint per-rule counts: `ObjectView.tsx` equal to base; `useObjectActions.ts` `no-explicit-any` 8 → 4; the new files have 0. - Changesets: `@object-ui/core: minor` (the new export) and `@object-ui/plugin-view: minor` (the behaviour change). ⛔ No `major`. ## Acceptance notes - `packages/core/README.md` does not document `recordDelete`. None of the sibling action-module exports is documented there either, and the README export gate checks only README→code. Surfaced to the maintainer on the card; not added here. - plugin-view resolves the console's `console.objectView.bulkDeleteConfirm` key. There is precedent on main (`console.objectView.new` in plugin-view, and nine `console.objectView.viewType*` keys in plugin-list). Reusing it is what keeps both paths word-for-word in every language. - `void recordDelete.run(...)` in plugin-view has no `.catch`. A synchronous throw inside the bulk map would surface as an unhandled rejection, but no in-tree adapter throws synchronously (`DataSource.delete` is `Promise`-returning everywhere). Left as is. - Bulk ids are forwarded raw, as the console's handler always did. Row ids are stringified at each host, as before. - With an adapter that emits `onMutation`, a delete refreshes twice (the handler bump plus the subscription). The console list behaves the same. - `check:changeset-claims` listed 5 pending changesets naming `plugin-view/src/ObjectView.tsx` (6726, 7070, 7499, 8653, 7779). None describes the delete handlers, and all are still true. - Observation, not filed: plugin-detail's `DetailView.handleDelete` comment says the `ActionProvider`'s `onConfirm` "will intercept" a native `window.confirm`; nothing does. Session: `https://claude.ai/code/session_01BA3nKVUwKQJf8DBxrSVtNC` (domain:ui seat 1). Body updated by the seat at `473c86933` after the contract review; the code is the dev's. --- _Generated by [Claude Code](https://claude.ai/code/session_01BA3nKVUwKQJf8DBxrSVtNC)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 36e27db commit ff14e29

9 files changed

Lines changed: 1054 additions & 118 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@object-ui/plugin-view': minor
3+
---
4+
5+
The grid's row Delete and bulk Delete now delete the record when `ObjectView` renders the grid itself — the registered `object-view` renderer, with no host list view (objectui#10383).
6+
7+
`ObjectGrid` hands the clicked row, or the selection, to its `onDelete` / `onBulkDelete` consumer and leaves the delete to it. `ObjectView`'s two handlers ignored the record and only refreshed, so a Delete the grid offers by default asked no question, called `dataSource.delete` zero times, and the row was still there after the refresh.
8+
9+
They now bind to the same record-delete core as the console's own object list (`recordDelete` from `@object-ui/core`), so the two paths behave the same:
10+
11+
- a row Delete asks "Are you sure you want to delete this record?". A package-owned permission set (a `sys_permission_set` row whose `managed_by` is `'package'`) is asked the reset question instead, because deleting it resets it to its shipped baseline rather than removing it. A bulk Delete asks once for the whole selection ("Delete N selected records? This cannot be undone.");
12+
- Continue calls `dataSource.delete(objectName, id)` for each record, then refreshes the grid, so the deleted rows are gone. Cancel deletes nothing;
13+
- the outcome is reported with the console's toasts: "LABEL deleted successfully" (or the reset message for a package-owned permission set) / "Deleted N LABEL records", or "Failed to delete LABEL" (with the error message, and no refresh) / "N deleted, M failed".
14+
15+
The confirm dialog is `ObjectView`'s own, in the console's dialog shape. Its texts reuse translation keys the console already resolves, so they read the same in every shipped language. Whether Delete is offered at all is unchanged. It is still the grid's own verdict, the same one the console list uses: `operations.delete`, the principal's delete grant, the object's lifecycle and `userActions`, its API operations and the per-record verdict.
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@object-ui/core': minor
3+
---
4+
5+
New export `recordDelete` — the one record-delete core that list hosts bind to, so a Delete behaves the same wherever it is offered (objectui#10383).
6+
7+
`recordDelete.confirmText({ objectName, t }, record?)` returns the question to ask before deleting one record. `recordDelete.run(deps, request)` performs the delete and reports it: one record, or several deleted one call each and settled together, then a refresh and the success, failure or "N deleted, M failed" toast. `deps` carries the host's `objectName`, `label`, `t`, `toast`, `dataSource` and optional `onRefresh`, so `@object-ui/core` takes no i18n or toast dependency. `request` is the action runner's `delete` shape (`params.records`, or `params.recordId` with an optional `params.record`), and the result is what a runner `delete` handler returns: the toasts are the feedback, so no path returns an `error` except a request with no record id.
8+
9+
ADR-0094 lives here: a `sys_permission_set` row whose `managed_by` is `'package'` is reset to its shipped baseline, not removed, so it is asked the reset question and gets the reset toast. The row passed in is read first, with a best-effort `findOne` when only the id is known.
10+
11+
The console's object list (`@object-ui/app-shell` `useObjectActions`) and the registered `object-view` grid (`@object-ui/plugin-view`) both call it. The console's behaviour is unchanged: its handler code moved here with no behaviour change, including the returns that keep the runner from showing a second toast.

‎packages/app-shell/src/hooks/useObjectActions.ts‎

Lines changed: 21 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import { useNavigate, useParams } from 'react-router-dom';
1616
import { useActionRunner } from '@object-ui/react';
1717
import { useObjectTranslation } from '@object-ui/i18n';
1818
import { toast } from 'sonner';
19-
import type { ActionDef, ActionResult } from '@object-ui/core';
19+
import { recordDelete, type ActionDef, type ActionResult } from '@object-ui/core';
2020

2121
interface ObjectActionConfig {
2222
objectName: string;
@@ -83,102 +83,21 @@ export function useObjectActions({
8383
return { success: true };
8484
});
8585

86-
// Handler: delete
87-
runner.registerHandler('delete', async (action: any) => {
88-
// Accept several param shapes used across call sites:
89-
// { params: { recordId } } — toolbar / programmatic deletes
90-
// { params: { record } } — ObjectGrid row dropdown
91-
// { params: { records: [...] } } — bulk delete (multi-row)
92-
// { recordId } (legacy) — pre-params shape
93-
const records = Array.isArray(action.params?.records)
94-
? action.params.records.filter((r: any) => r?.id != null)
95-
: null;
96-
97-
// Bulk path — delete every record in parallel and report a summary.
98-
if (records && records.length > 1) {
99-
const results = await Promise.allSettled(
100-
records.map((r: any) => dataSource.delete(objectName, r.id)),
101-
);
102-
const failed = results.filter(r => r.status === 'rejected').length;
103-
const succeeded = results.length - failed;
104-
onRefresh?.();
105-
if (failed === 0) {
106-
toast.success(
107-
t('objectActions.bulkDeleteSuccess', {
108-
count: succeeded,
109-
label: objectLabel || objectName,
110-
defaultValue: `Deleted ${succeeded} ${objectLabel || objectName} records`,
111-
}),
112-
);
113-
// `silent`: the handler already toasted the localized summary above;
114-
// without this the runner's post-execution hook adds a second, generic
115-
// "Action completed successfully" toast (double success toast).
116-
return { success: true, reload: true, silent: true };
117-
}
118-
toast.error(
119-
t('objectActions.bulkDeletePartial', {
120-
succeeded,
121-
failed,
122-
defaultValue: `${succeeded} deleted, ${failed} failed`,
123-
}),
124-
);
125-
// The toast above is the authoritative feedback (it carries the
126-
// succeeded/failed summary the runner can't reconstruct). Return
127-
// WITHOUT `error` so the ActionRunner post-execution hook — this runner
128-
// has a toastHandler (onToast) — doesn't fire a second, duplicate toast.
129-
return { success: false };
130-
}
131-
132-
const recordId =
133-
action.params?.recordId ??
134-
action.params?.record?.id ??
135-
records?.[0]?.id ??
136-
action.recordId;
137-
if (!recordId) return { success: false, error: t('objectActions.noRecordId') };
138-
139-
// [ADR-0094] "Deleting" a PACKAGE-OWNED permission set doesn't remove
140-
// the row — the backend drops the environment overlay and RESETS the
141-
// set to its shipped baseline. Detect it BEFORE the delete (the row
142-
// still exists) so the success toast tells the truth; a caller that
143-
// passed the row spares the lookup.
144-
let packagedSetReset = false;
145-
if (objectName === 'sys_permission_set') {
146-
try {
147-
const row =
148-
action.params?.record?.managed_by !== undefined
149-
? action.params.record
150-
: await dataSource.findOne(objectName, recordId);
151-
packagedSetReset = row?.managed_by === 'package';
152-
} catch { /* best-effort — fall back to the generic delete copy */ }
153-
}
154-
155-
try {
156-
await dataSource.delete(objectName, recordId);
157-
onRefresh?.();
158-
toast.success(
159-
packagedSetReset
160-
// No `label` argument, unlike the `deleteSuccess` branch below: this
161-
// sentence names the permission set by kind rather than by label, so
162-
// none of the ten packs has a `{{label}}` hole and i18next dropped
163-
// the argument in silence (objectui#3845).
164-
? t('objectActions.resetPackageSetSuccess', {
165-
defaultValue: 'Permission set reset to its shipped baseline',
166-
})
167-
: t('objectActions.deleteSuccess', { label: objectLabel || objectName }),
168-
);
169-
// `silent`: handler owns the localized success toast above — suppress the
170-
// runner's generic duplicate (see the bulk branch).
171-
return { success: true, reload: true, silent: true };
172-
} catch (err: any) {
173-
toast.error(t('objectActions.deleteFailed', { label: objectLabel || objectName }), {
174-
description: err.message,
175-
});
176-
// Keep the richer toast above (label + error description) and return
177-
// WITHOUT `error` so the ActionRunner post-execution hook doesn't toast
178-
// the raw message a second time. See the bulk branch for the rationale.
179-
return { success: false };
180-
}
181-
});
86+
// Handler: delete — the shared record-delete core (objectui#10383), the
87+
// same one `plugin-view`'s grid Delete binds to. Its param shapes:
88+
// { params: { recordId } } — toolbar / programmatic deletes
89+
// { params: { record } } — ObjectGrid row dropdown
90+
// { params: { records: [...] } } — bulk delete (multi-row)
91+
// { recordId } (legacy) — pre-params shape
92+
// It owns the toasts and returns without `error` (and `silent` on
93+
// success), so the runner's post-execution hook adds no second toast; the
94+
// ADR-0094 package-owned permission-set reset copy lives there too.
95+
runner.registerHandler('delete', (action: any) =>
96+
recordDelete.run(
97+
{ objectName, label: objectLabel || objectName, dataSource, t, toast, onRefresh },
98+
action,
99+
),
100+
);
182101

183102
// Handler: navigate
184103
runner.registerHandler('navigate', async (action: any) => {
@@ -202,21 +121,13 @@ export function useObjectActions({
202121

203122
const deleteRecord = useCallback(
204123
async (recordId: string, record?: Record<string, unknown>) => {
205-
// [ADR-0094] A package-owned permission set is never removed by the data
206-
// door — the backend drops the environment overlay and RESETS the set to
207-
// its shipped baseline. Ask the honest question instead of promising an
208-
// irreversible delete the user can see doesn't happen (the row stays).
209-
const packagedSetReset =
210-
objectName === 'sys_permission_set' && (record as any)?.managed_by === 'package';
124+
// The question comes from the shared record-delete core (objectui#10383):
125+
// for a package-owned permission set it is the honest RESET question
126+
// (ADR-0094), not a promise of an irreversible delete the user can see
127+
// doesn't happen (the row stays).
211128
return execute({
212129
type: 'delete',
213-
confirmText: packagedSetReset
214-
? t('objectActions.resetPackageSetConfirm', {
215-
defaultValue:
216-
'This permission set ships with an installed package and cannot be removed. ' +
217-
'Deleting resets it to the shipped baseline and discards your environment customization. Continue?',
218-
})
219-
: t('objectActions.deleteConfirm'),
130+
confirmText: recordDelete.confirmText({ objectName, t }, record),
220131
params: record ? { recordId, record } : { recordId },
221132
});
222133
},
Lines changed: 213 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,213 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* The shared record-delete core (objectui#10383, ADR-0094), pinned at the unit
11+
* level: the question, the single delete, the bulk delete, the partial failure
12+
* and the package-owned permission-set reset — with the runner-facing result
13+
* shape each path returns, because the console registers `run` as its action
14+
* runner's `delete` handler and those shapes are what keep the runner from
15+
* toasting a second time.
16+
*
17+
* The translator echoes the key (plus `|defaultValue` when one is passed) so
18+
* each assertion names the copy it expects without depending on a pack.
19+
*/
20+
21+
import { describe, it, expect, vi } from 'vitest';
22+
import { recordDelete } from '../recordDelete';
23+
24+
const t = (key: string, options?: Record<string, unknown>) => {
25+
const vars = { ...(options ?? {}) };
26+
delete vars.defaultValue;
27+
const suffix = Object.keys(vars).length ? ` ${JSON.stringify(vars)}` : '';
28+
return `${key}${suffix}`;
29+
};
30+
31+
function harness(opts: {
32+
objectName?: string;
33+
failIds?: string[];
34+
findOne?: (resource: string, id: string) => Promise<unknown>;
35+
} = {}) {
36+
const failIds = opts.failIds ?? [];
37+
const dataSource = {
38+
delete: vi.fn(async (_resource: string, id: string) => {
39+
if (failIds.includes(id)) throw new Error(`refused ${id}`);
40+
return true;
41+
}),
42+
findOne: vi.fn(opts.findOne ?? (async () => null)),
43+
};
44+
const toast = { success: vi.fn(), error: vi.fn() };
45+
const onRefresh = vi.fn();
46+
const deps = {
47+
objectName: opts.objectName ?? 'crm_lead',
48+
label: 'Lead',
49+
t,
50+
dataSource,
51+
toast,
52+
onRefresh,
53+
};
54+
return { deps, dataSource, toast, onRefresh };
55+
}
56+
57+
describe('recordDelete.confirmText', () => {
58+
it('asks the plain delete question for an ordinary record', () => {
59+
expect(recordDelete.confirmText({ objectName: 'crm_lead', t }, { id: 'l1' })).toBe(
60+
'objectActions.deleteConfirm',
61+
);
62+
});
63+
64+
it('asks the RESET question for a package-owned permission set (ADR-0094)', () => {
65+
expect(
66+
recordDelete.confirmText(
67+
{ objectName: 'sys_permission_set', t },
68+
{ id: 'ps1', managed_by: 'package' },
69+
),
70+
).toBe('objectActions.resetPackageSetConfirm');
71+
});
72+
73+
it('keeps the plain question for an environment-owned permission set, or with no row', () => {
74+
expect(
75+
recordDelete.confirmText({ objectName: 'sys_permission_set', t }, { id: 'ps1', managed_by: 'user' }),
76+
).toBe('objectActions.deleteConfirm');
77+
expect(recordDelete.confirmText({ objectName: 'sys_permission_set', t })).toBe(
78+
'objectActions.deleteConfirm',
79+
);
80+
});
81+
});
82+
83+
describe('recordDelete.run — one record', () => {
84+
it('deletes, refreshes, toasts success, and returns the silent success the runner expects', async () => {
85+
const { deps, dataSource, toast, onRefresh } = harness();
86+
const res = await recordDelete.run(deps, { params: { recordId: 'l1' } });
87+
88+
expect(dataSource.delete).toHaveBeenCalledTimes(1);
89+
expect(dataSource.delete).toHaveBeenCalledWith('crm_lead', 'l1');
90+
expect(onRefresh).toHaveBeenCalledTimes(1);
91+
expect(toast.success).toHaveBeenCalledWith('objectActions.deleteSuccess {"label":"Lead"}');
92+
expect(toast.error).not.toHaveBeenCalled();
93+
expect(res).toEqual({ success: true, reload: true, silent: true });
94+
});
95+
96+
it('a refused delete toasts the failure with its message, does not refresh, and returns no `error`', async () => {
97+
const { deps, toast, onRefresh } = harness({ failIds: ['l1'] });
98+
const res = await recordDelete.run(deps, { params: { recordId: 'l1' } });
99+
100+
expect(toast.error).toHaveBeenCalledTimes(1);
101+
expect(toast.error).toHaveBeenCalledWith('objectActions.deleteFailed {"label":"Lead"}', {
102+
description: 'refused l1',
103+
});
104+
expect(onRefresh).not.toHaveBeenCalled();
105+
expect(res).toEqual({ success: false });
106+
});
107+
108+
it('reads the id off `params.record`, then a single `params.records` entry, then the legacy top-level `recordId`', async () => {
109+
const a = harness();
110+
await recordDelete.run(a.deps, { params: { record: { id: 'from-record' } } });
111+
expect(a.dataSource.delete).toHaveBeenCalledWith('crm_lead', 'from-record');
112+
113+
const b = harness();
114+
await recordDelete.run(b.deps, { params: { records: [{ id: 'only-one' }] } });
115+
expect(b.dataSource.delete).toHaveBeenCalledWith('crm_lead', 'only-one');
116+
117+
const c = harness();
118+
await recordDelete.run(c.deps, { recordId: 'legacy' });
119+
expect(c.dataSource.delete).toHaveBeenCalledWith('crm_lead', 'legacy');
120+
});
121+
122+
it('with no id at all, deletes nothing and returns the `error` for the runner to report', async () => {
123+
const { deps, dataSource, toast } = harness();
124+
const res = await recordDelete.run(deps, { params: {} });
125+
126+
expect(dataSource.delete).not.toHaveBeenCalled();
127+
expect(toast.success).not.toHaveBeenCalled();
128+
expect(toast.error).not.toHaveBeenCalled();
129+
expect(res).toEqual({ success: false, error: 'objectActions.noRecordId' });
130+
});
131+
});
132+
133+
describe('recordDelete.run — several records', () => {
134+
it('deletes each record, refreshes once, and toasts ONE summary', async () => {
135+
const { deps, dataSource, toast, onRefresh } = harness();
136+
const res = await recordDelete.run(deps, {
137+
params: { records: [{ id: 'a' }, { id: 'b' }, { name: 'no id — skipped' }] },
138+
});
139+
140+
expect(dataSource.delete).toHaveBeenCalledTimes(2);
141+
expect(dataSource.delete).toHaveBeenCalledWith('crm_lead', 'a');
142+
expect(dataSource.delete).toHaveBeenCalledWith('crm_lead', 'b');
143+
expect(onRefresh).toHaveBeenCalledTimes(1);
144+
expect(toast.success).toHaveBeenCalledTimes(1);
145+
expect(toast.success).toHaveBeenCalledWith(
146+
'objectActions.bulkDeleteSuccess {"count":2,"label":"Lead"}',
147+
);
148+
expect(res).toEqual({ success: true, reload: true, silent: true });
149+
});
150+
151+
it('a partial failure toasts "N deleted, M failed" once, still refreshes, and returns no `error`', async () => {
152+
const { deps, dataSource, toast, onRefresh } = harness({ failIds: ['b'] });
153+
const res = await recordDelete.run(deps, { params: { records: [{ id: 'a' }, { id: 'b' }] } });
154+
155+
expect(dataSource.delete).toHaveBeenCalledTimes(2);
156+
expect(onRefresh).toHaveBeenCalledTimes(1);
157+
expect(toast.error).toHaveBeenCalledTimes(1);
158+
expect(toast.error).toHaveBeenCalledWith(
159+
'objectActions.bulkDeletePartial {"succeeded":1,"failed":1}',
160+
);
161+
expect(toast.success).not.toHaveBeenCalled();
162+
expect(res).toEqual({ success: false });
163+
});
164+
});
165+
166+
describe('recordDelete.run — ADR-0094 package-owned permission set', () => {
167+
it('toasts the RESET when the row passed in is package-owned, without a lookup', async () => {
168+
const { deps, dataSource, toast } = harness({ objectName: 'sys_permission_set' });
169+
await recordDelete.run(deps, {
170+
params: { recordId: 'ps1', record: { id: 'ps1', managed_by: 'package' } },
171+
});
172+
173+
expect(dataSource.delete).toHaveBeenCalledWith('sys_permission_set', 'ps1');
174+
expect(dataSource.findOne).not.toHaveBeenCalled();
175+
expect(toast.success).toHaveBeenCalledWith('objectActions.resetPackageSetSuccess');
176+
});
177+
178+
it('looks the row up with findOne when only the id is known, and toasts the reset', async () => {
179+
const { deps, dataSource, toast } = harness({
180+
objectName: 'sys_permission_set',
181+
findOne: async () => ({ id: 'ps1', managed_by: 'package' }),
182+
});
183+
await recordDelete.run(deps, { params: { recordId: 'ps1' } });
184+
185+
expect(dataSource.findOne).toHaveBeenCalledWith('sys_permission_set', 'ps1');
186+
expect(toast.success).toHaveBeenCalledWith('objectActions.resetPackageSetSuccess');
187+
});
188+
189+
it('an environment-owned set, or a failed lookup, keeps the plain delete copy (control)', async () => {
190+
const env = harness({ objectName: 'sys_permission_set' });
191+
await recordDelete.run(env.deps, {
192+
params: { recordId: 'ps1', record: { id: 'ps1', managed_by: 'user' } },
193+
});
194+
expect(env.toast.success).toHaveBeenCalledWith('objectActions.deleteSuccess {"label":"Lead"}');
195+
196+
const lost = harness({
197+
objectName: 'sys_permission_set',
198+
findOne: async () => {
199+
throw new Error('lookup failed');
200+
},
201+
});
202+
await recordDelete.run(lost.deps, { params: { recordId: 'ps1' } });
203+
// Best-effort: the lookup failing does not block the delete.
204+
expect(lost.dataSource.delete).toHaveBeenCalledWith('sys_permission_set', 'ps1');
205+
expect(lost.toast.success).toHaveBeenCalledWith('objectActions.deleteSuccess {"label":"Lead"}');
206+
});
207+
208+
it('an ordinary object is never looked up', async () => {
209+
const { deps, dataSource } = harness();
210+
await recordDelete.run(deps, { params: { recordId: 'l1' } });
211+
expect(dataSource.findOne).not.toHaveBeenCalled();
212+
});
213+
});

0 commit comments

Comments
 (0)