Skip to content

Commit 56cac5e

Browse files
feat(ui): undo a business-record delete from its toast through the recycle bin (#31795)
<!-- claude-projects-attribution: {"github_login":"zhuangjianguo"} --> _Requested by **Steedos** · [project thread](https://claude.ai/code/project/chan_018ETKaNwMZCNRYD7D8Q9Ubb?thread=cmsg_018ETKaNwMZCNRYD7D8Q9UbbPnyAMycuSU2XHXgpgorGJU)_ Part of #30239 Clause-②: yes (widening) Metadata-protocol: none ## 维护者速读 - 改了什么:删除一条业务对象记录后,“已删除”提示多了一个「撤销」按钮(控制台列表、插件列表、记录页三处)。撤销走回收站恢复接口 `POST {data}/:object/recycle-bin/:entryId/restore`,按原 id 恢复,不会重新创建记录;恢复被拒时按原因给出七句之一(唯一值被占、父记录已彻底删除、包已卸载、父记录也在回收站、条目不存在、无权限、本部署没有回收站)。业务对象的删除确认改成只问“确定要删除这条记录吗?”,不再说“此操作无法撤销”;平台对象(`sys_`、`cloud_`、`ai_`)保持原文。 - 为什么改:ADR-0148 之后业务对象删除会进回收站,但控制台既拿不到 `recycleBinEntryId`(适配器丢了它),确认框还在说“无法撤销”,这和服务端的实际行为不一致。 - 风险与回滚:撤销按钮只在同时满足两点时出现:服务端返回了条目 id,并且调用者在该对象上有 `allowRestoreOwnDeleted`(经 `objectPermissionGrants` 读取,`manageRecycleBin`、`modifyAllRecords` 也算)。缺任一项时提示与今天逐字相同;批量删除的提示不变。`DataSource` 只做加法(`delete` 仍返回 boolean)。回滚即撤销本 PR。 - 先看:`ui/packages/core/src/actions/recordDelete.ts` 的 `successToast` 和 `undo`,再看 `core/src/actions/recycleBinRestore.ts`(拒绝码到语言包键的映射)和 `app-shell/src/utils/recycleBinRestore.ts`(权限判断)。 - 两分钟验证:在 `ui/` 下跑 `pnpm exec vitest run packages/app-shell/src/hooks/__tests__/useObjectActions.deleteDialog-11695.test.tsx -t 30239`,预期 8 个用例全绿(en、zh 各四个:往返、拒绝原因、无权限对照、无条目对照)。 - 需要你做的:无,席位落地。管理端回收站页面在第二个 PR(`Fixes #30239`),它复用本 PR 的拒绝原因映射。 ## What changes - **(A) `@object-ui/types` `DataSource`**, additive only: `delete(resource, id, opts?)` options gain `onRecycleBinEntry?: (entryId: string) => void`, and `DataSource` gains an optional `restoreRecycleBinEntry?(resource, entryId)`. `delete` still resolves to a boolean. - **(A) `@object-ui/data-objectstack`**: `delete` calls `onRecycleBinEntry` with the server's `recycleBinEntryId`, after the delete's mutation event, only when the delete succeeded and the answer carries a non-empty id. `restoreRecycleBinEntry` is the SDK's `recycleBin.restore`. It emits no mutation event (the vocabulary has no restore, and a restore is never a create), and a refusal is normalised as every write's is, so a 409 `RESTORE_*` keeps its `code` and `details` and is not a `ConcurrentUpdateError`. - **`@object-ui/core`**: - New `recycleBinRestoreRefusalText(t, error, labels)` with `RECYCLE_BIN_RESTORE_REFUSAL_KEYS`. It maps the door's seven codes (the spec's four `RECYCLE_BIN_RESTORE_REFUSAL_CODES` plus `RECORD_NOT_FOUND`, `PERMISSION_DENIED`, `NOT_IMPLEMENTED`) to one `recycleBin.refusal.*` sentence each, naming objects and fields by label with the machine name as fallback. An unknown code answers `undefined`, so the caller keeps its generic copy. The admin page in PR 2 reuses it. - `recordDelete`: the host passes an optional `restore` (and `refusalLabels`). With both an entry id and `restore`, the success toast carries an `actions.undo` action. Undo restores, refreshes, and toasts `restoredNamed` / `restoreSuccess`; a refusal toasts `restoreFailed` with the refusal sentence, or the server message for an unknown code. With neither, `toast.success(message)` is called with exactly one argument, as today. The entry id is asked for only when `restore` is present, so a host without it calls `delete(object, id)` exactly as before. - `recordDelete.entersRecycleBin(name)` is the engine's own predicate (`!hasPlatformObjectPrefix`). It picks the confirm copy: `objectActions.deleteConfirmQuestion` and `console.objectView.bulkDeleteQuestion` for a business object, today's keys for a platform object. - **The hosts decide the grant; core reads no permission.** - `app-shell` `useObjectActions` (console list) and `RecordDetailView` (record page) build `restore` through the new `utils/recycleBinRestore.ts`. That util reads `usePermissions().effectiveObjects` as `MePermissionsProvider` does (lowercase key, the key as given, then `'*'`) and folds it with `objectPermissionGrants(…, 'allowRestoreOwnDeleted')`. On the record page, a successful Undo also navigates back to the record. - `plugin-view` `ObjectView` (the plugin list) does the same with a local reader, since it cannot import app-shell, and its fallback dictionary gains the new English keys. - `plugin-detail` `DetailView`: the confirm reads `detail.deleteConfirmQuestion` for a business object, per the amendment. Platform objects and a declared `schema.deleteConfirmation` are unchanged. - **`@object-ui/i18n`**, every pack: `objectActions.deleteConfirmQuestion`, `restoredNamed`, `restoreSuccess`, `restoreFailed`; `detail.deleteConfirmQuestion`; the `console.objectView.bulkDeleteQuestion` count family; and `recycleBin.refusal.{uniqueValueTaken, parentPurged, packageUninstalled, parentInRecycleBin, notFound, permissionDenied, notAvailable}`. zh-Hant is generated with `gen:zh-hant`. Each question is the platform sentence minus its permanence sentence. - Changeset: `.changeset/30239-recycle-bin-undo-toast.md` (seven `@object-ui/*` packages, patch). ## Tests New: - `core/src/actions/__tests__/recycleBinRestore.test.ts`: the key map covers the spec's `RECYCLE_BIN_RESTORE_REFUSAL_CODES`; an `it.each` over the seven codes checks the exact key and placeholders; the field label falls back to the machine name; CONTROL: an unknown code and a codeless error answer `undefined`. - `core/src/actions/__tests__/recordDelete.test.ts`, new describe "recordDelete and the recycle bin": business vs platform confirm copy; a round trip where Undo restores once with `(object, entryId)`, never calls `create`, refreshes and names the record; a refusal toasts its sentence, not the server message; CONTROLs for an unknown code, no entry id, no `restore`, and a batch. - `i18n/src/__tests__/recycle-bin-delete-copy-30239.test.ts`: in every pack, each question equals its platform sentence minus the permanence sentence, the seven refusal sentences are distinct, none equals the generic failure, and each carries en's placeholders; the restore toasts' placeholders; exact en and zh-Hans sentences. - `app-shell/src/hooks/__tests__/useObjectActions.deleteDialog-11695.test.tsx`, new `describe.each` en/zh "console list Delete undo", through the real `MePermissionsProvider`: round trip; a refusal in the session language; CONTROL with no grant (`delete` called with two arguments and a one-argument toast); CONTROL with no entry id. - `app-shell/src/utils/__tests__/recycleBinRestore-30239.test.ts`: the grant fold (`allowRestoreOwnDeleted`, `manageRecycleBin`, `'*'` `modifyAllRecords`, case), plus CONTROLs: no read, no row, permissions not loaded, no restore on the data source. - `data-objectstack/src/recycleBinEntry-30239.test.ts`: the entry id is reported after the mutation event; no report without an id or for an unconfirmed delete; restore calls `recycleBin.restore` with no create and no event; a 409 refusal keeps `code` and `details`. Edited pins. Each asserted the permanence sentence or key on a business object, which this card retires; nothing else in them changes and no assertion is removed: - `app-shell/src/hooks/__tests__/useObjectActions.test.tsx`: `objectActions.deleteConfirm` → `objectActions.deleteConfirmQuestion`, and `console.objectView.bulkDeleteConfirm` → `console.objectView.bulkDeleteQuestion` (crm_product). - `app-shell/src/hooks/__tests__/useObjectActions.deleteCascade-28472.test.tsx`: `EN/ZH.objectActions.deleteConfirm` → `deleteConfirmQuestion`, and `bulkDeleteConfirm_other` → `bulkDeleteQuestion_other`, as the base the cascade line is appended to. - `app-shell/src/views/RecordDetailView.deleteCascade-28472.test.tsx`: `EN.objectActions.deleteConfirm` → `deleteConfirmQuestion`, the same base. - `app-shell/src/views/RecordDetailView.deleteConfirmDialog-11001.test.tsx`: the body is found by `deleteConfirmQuestion` (en and zh). The #27823 assertion "the body contains `This cannot be undone.`" becomes "the dialog does not contain it" for this business record (crm_call). The platform-object side is still pinned, unedited, in `i18n/src/__tests__/record-delete-permanent-27823.test.ts`. - `plugin-view/src/__tests__/ObjectView.gridDelete-10383.test.tsx`: the two literal sentences lose ` This cannot be undone.`, and the docblock bullet says why. - `core/src/actions/__tests__/recordDelete.test.ts` (confirmCopy) and `recordDelete.cascade-28472.test.ts`: the business-object cases expect the Question keys. - `i18n/src/__tests__/record-delete-permanent-27823.test.ts`: docblock only, saying the sentence is now the platform keys'. ## Acceptance notes - Before the delete, the console cannot know whether the server will write a recycle-bin entry, so the confirm promises neither permanence nor recovery. The toast tells the truth afterwards. - A batch delete keeps today's toast, as the amendment confirmed: each record writes its own entry, and one toast action would have to restore N entries, any of which can be refused on its own. The admin page in PR 2 is where several entries are restored. - `member_default` holds neither `allowRestoreOwnDeleted` nor `manageRecycleBin`, so a default member sees no Undo until an admin grants it. The restore door would refuse them anyway, and the toast never offers an action the runtime refuses. - Out of this PR: the admin recycle-bin page and its Setup nav item (PR 2), per-entry purge and "restore the parent first" (out of v1). ## Verification Head `e6d5861b`. Branch cut from `c2bb879f`, with origin/main merged at `e253f3ab` (five incoming commits; none touches this diff's files, and no parallel fix was found). <details><summary>Tests (ui vitest from ui/, under the verify lock)</summary> - core and i18n, 8 files: `Tests 155 passed (155)`. - app-shell, plugin-view and plugin-detail delete files (`useObjectActions.deleteDialog-11695`, `useObjectActions`, `useObjectActions.deleteCascade-28472`, `RecordDetailView.deleteConfirmDialog-11001`, `RecordDetailView.deleteCascade-28472`, `ObjectView.gridDelete-10383`, `DetailView`, `DetailView.permissions`): `Test Files 8 passed (8)`, `Tests 78 passed (78)`. - `recycleBinRestore-30239`, `recycleBinEntry-30239`, `onMutation`, `bulkDelete`: all passed (52 tests). - `pnpm exec turbo run type-check` on types, core, data-objectstack, app-shell, plugin-view, plugin-detail and i18n: `Tasks: 75 successful, 75 total`. </details> <details><summary>Ablation (scripts/ablation-replace.mjs, anchor x1 -> x0, restored blob == HEAD 1283125 and git diff HEAD empty)</summary> The undo attach line in `recordDelete.ts`, `if (!entryId || !restore) {`, replaced by `if (true) {`, so no toast ever carries Undo. `recordDelete.test.ts` with `useObjectActions.deleteDialog-11695.test.tsx`: `Tests 7 failed | 29 passed (36)`. The 7 are the core round trip, the refusal and unknown-code cases, and the app-shell round trip and refusal in en and zh. The no-grant and no-entry CONTROLs stay green, as they should. The core module is imported from `src`, so there is no dist leg. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands --repo objectstack-ai/objectstack`: 40 derived commands, each run at `e6d5861b` with exit 0 (`check:type-check-debt` under the verify lock, `check:query-options-erasure` alone). `--ran` reconciliation: `40 derived, 40 run, 0 NOT-MEASURED, 0 UNRUN`. `--tier`: no path-derived mandate. `check-governed-merges --branch`: 0 of 36 paths hit the register, not governed. Examples census (`git grep` of the touched copy, keys and members in `ui/examples/**` and `ui/e2e/**`): no hit that reads the changed copy. `eslint` on the touched sources and new tests: 0 errors. Changed lines 1432 (+1369 / -63): implementation about 420, tests about 690, locale packs about 235. The body gates (`check-changeset-no-major`, `check-adr-0087-registration`, `check-closing-keyword-parity`, `check-partof-closing-keyword`) were run on this body. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01QsR2jR7jBcj3r4Rii4HA82)_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01QsR2jR7jBcj3r4Rii4HA82 --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent cbc05db commit 56cac5e

37 files changed

Lines changed: 1378 additions & 66 deletions
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/types': patch
3+
'@object-ui/data-objectstack': patch
4+
'@object-ui/core': patch
5+
'@object-ui/i18n': patch
6+
'@object-ui/app-shell': patch
7+
'@object-ui/plugin-view': patch
8+
'@object-ui/plugin-detail': patch
9+
---
10+
11+
feat(ui): undo a business-record delete from its toast, through the recycle bin
12+
13+
Clause-②: yes (widening)
14+
Metadata-protocol: none
15+
16+
A delete of one business record (an object without the `sys_`, `cloud_` or `ai_` prefix) enters the recycle bin (ADR-0148). When the server answers with its `recycleBinEntryId` and the caller holds `allowRestoreOwnDeleted` on the object (read through `objectPermissionGrants`, so `manageRecycleBin` and `modifyAllRecords` grant it too), the "deleted" toast on the console list, the plugin list and the record page now carries an Undo action. Undo restores that entry under its original ids (`POST {data}/:object/recycle-bin/:entryId/restore`), never re-creates the record, refreshes the view and toasts "{label} "{name}" restored". On the record page, Undo also returns to the record.
17+
18+
A refused restore toasts one sentence per reason, in the session language: another record now holds the same unique value, the parent record was purged, the package was uninstalled, the parent is itself in the recycle bin, the entry is gone, no permission, or no recycle bin on this deployment. An unknown code keeps the server's message. Without the grant, without an entry id, or for a batch delete, the toast is unchanged.
19+
20+
The delete confirmation for a business record (one record and a selection, on the console list, the plugin list, the record page and the plugin detail view) is now the question alone ("Are you sure you want to delete this record?", "Delete N selected records?"). It no longer says "This cannot be undone." Platform objects keep today's copy.
21+
22+
`@object-ui/types`: `DataSource.delete` options gain `onRecycleBinEntry?`, and `DataSource` gains an optional `restoreRecycleBinEntry?`. `delete` still returns a boolean. `@object-ui/data-objectstack` implements both. `@object-ui/core` exports `recycleBinRestoreRefusalText`, `RECYCLE_BIN_RESTORE_REFUSAL_KEYS` and the `RecycleBinRefusalLabels` type, and `recordDelete` gains `successToast`, `undo` and `entersRecycleBin`. `@object-ui/i18n` adds `objectActions.deleteConfirmQuestion`, `restoredNamed`, `restoreSuccess` and `restoreFailed`, `detail.deleteConfirmQuestion`, the `console.objectView.bulkDeleteQuestion` family and the seven `recycleBin.refusal.*` sentences to every pack.

‎ui/packages/app-shell/src/hooks/__tests__/useObjectActions.deleteCascade-28472.test.tsx‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ vi.mock('sonner', () => ({
3333
import { useObjectActions } from '../useObjectActions';
3434

3535
type Pack = {
36-
objectActions: { deleteConfirm: string; deleteCascade: string };
37-
console: { objectView: { bulkDeleteConfirm_other: string } };
36+
objectActions: { deleteConfirmQuestion: string; deleteCascade: string };
37+
console: { objectView: { bulkDeleteQuestion_other: string } };
3838
};
3939
const EN = builtInLocales.en as unknown as Pack;
4040
const ZH = builtInLocales['zh-Hans'] as unknown as Pack;
@@ -98,7 +98,7 @@ describe('console row Delete names the cascade objects (objectstack#28472)', ()
9898
const message = await askedMessage(onConfirm, 'row-delete');
9999
expect(getObjectSchema).toHaveBeenCalledWith('crm_lead');
100100
expect(message).toBe(
101-
`${EN.objectActions.deleteConfirm} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
101+
`${EN.objectActions.deleteConfirmQuestion} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
102102
);
103103
expect(message).not.toContain('crm_campaign_member');
104104
});
@@ -108,31 +108,31 @@ describe('console row Delete names the cascade objects (objectstack#28472)', ()
108108
const message = await askedMessage(onConfirm, 'row-delete');
109109
expect(ZH.objectActions.deleteCascade).not.toBe(EN.objectActions.deleteCascade);
110110
expect(message).toBe(
111-
`${ZH.objectActions.deleteConfirm} ${fill(ZH.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
111+
`${ZH.objectActions.deleteConfirmQuestion} ${fill(ZH.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
112112
);
113113
});
114114

115115
it('a served empty list adds nothing', async () => {
116116
const { onConfirm } = mount([]);
117-
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
117+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirmQuestion);
118118
});
119119

120120
it('no served list adds nothing and keeps today\'s text', async () => {
121121
const { onConfirm } = mount(undefined);
122-
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
122+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirmQuestion);
123123
});
124124

125125
it('a failed schema read adds nothing and still asks', async () => {
126126
const { onConfirm, dataSource } = mount('throw');
127-
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirm);
127+
expect(await askedMessage(onConfirm, 'row-delete')).toBe(EN.objectActions.deleteConfirmQuestion);
128128
expect(dataSource.delete).not.toHaveBeenCalled();
129129
});
130130

131131
it('a selection gains the same line after the batch question', async () => {
132132
const { onConfirm } = mount(['crm_campaign_member']);
133133
const message = await askedMessage(onConfirm, 'bulk-delete');
134134
expect(message).toBe(
135-
`${fill(EN.console.objectView.bulkDeleteConfirm_other, { count: 2 })} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
135+
`${fill(EN.console.objectView.bulkDeleteQuestion_other, { count: 2 })} ${fill(EN.objectActions.deleteCascade, { objects: 'Campaign Member' })}`,
136136
);
137137
});
138138
});

‎ui/packages/app-shell/src/hooks/__tests__/useObjectActions.deleteDialog-11695.test.tsx‎

Lines changed: 123 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,10 +50,18 @@ vi.mock('sonner', () => ({
5050

5151
import { useObjectActions } from '../useObjectActions';
5252
import { ActionConfirmDialog, type ConfirmDialogState } from '../../views/ActionConfirmDialog';
53+
import { toast } from 'sonner';
54+
import { MePermissionsProvider, type MePermissionsResponse } from '@object-ui/permissions';
5355

5456
type Pack = {
57+
actions: { undo: string };
58+
recycleBin: { refusal: Record<string, string> };
5559
objectActions: {
5660
deleteConfirm: string;
61+
deleteConfirmQuestion: string;
62+
deletedNamed: string;
63+
restoredNamed: string;
64+
restoreFailed: string;
5765
deleteConfirmTitle: string;
5866
deleteConfirmButton: string;
5967
bulkDeleteConfirmTitle_other: string;
@@ -139,7 +147,10 @@ describe.each(['en', 'zh'] as const)('console list Delete in %s (objectui#11695)
139147
// The named subject itself, independent of the template's words.
140148
expect(within(dialog).getByRole('heading')).toHaveTextContent('QA Widget 0');
141149
expect(within(dialog).getByRole('heading')).not.toHaveTextContent(pack.actionConfirm.title);
142-
expect(within(dialog).getByText(pack.objectActions.deleteConfirm)).toBeInTheDocument();
150+
// A business object's delete goes to the recycle bin (objectstack#30239):
151+
// the question alone, never "cannot be undone".
152+
expect(within(dialog).getByText(pack.objectActions.deleteConfirmQuestion)).toBeInTheDocument();
153+
expect(within(dialog).queryByText(pack.objectActions.deleteConfirm)).toBeNull();
143154

144155
const confirm = within(dialog).getByRole('button', { name: pack.objectActions.deleteConfirmButton });
145156
expect(confirm.className).toContain('bg-destructive');
@@ -177,3 +188,114 @@ describe.each(['en', 'zh'] as const)('console list Delete in %s (objectui#11695)
177188
expect(confirm.className).not.toContain('bg-destructive');
178189
});
179190
});
191+
192+
/**
193+
* objectstack#30239 (ADR-0148) — the list's one-record Delete offers Undo on
194+
* its toast when the delete wrote a recycle-bin entry and the caller holds
195+
* `allowRestoreOwnDeleted` on the object (the effective map, served by
196+
* `/auth/me/permissions`). Real chain: `useObjectActions`, the core, the
197+
* shipped packs, a real `MePermissionsProvider`; sonner is the one stand-in.
198+
*/
199+
200+
function grants(objects: Record<string, Record<string, boolean>>): MePermissionsResponse {
201+
return {
202+
authenticated: true,
203+
userId: 'u1',
204+
tenantId: null,
205+
positions: [],
206+
permissionSets: [],
207+
objects,
208+
fields: {},
209+
hasAnyQueue: false,
210+
} as MePermissionsResponse;
211+
}
212+
213+
function mountBin(
214+
language: keyof typeof PACKS,
215+
permissions: MePermissionsResponse,
216+
opts: { entryId?: string; restoreError?: unknown } = {},
217+
) {
218+
const dataSource = {
219+
delete: vi.fn(async (_r: string, _id: string, o?: { onRecycleBinEntry?: (id: string) => void }) => {
220+
if (opts.entryId) o?.onRecycleBinEntry?.(opts.entryId);
221+
return true;
222+
}),
223+
create: vi.fn(),
224+
findOne: vi.fn(),
225+
restoreRecycleBinEntry: vi.fn(async () => {
226+
if (opts.restoreError) throw opts.restoreError;
227+
return { entryId: opts.entryId };
228+
}),
229+
};
230+
render(
231+
<I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>
232+
<MePermissionsProvider initialPermissions={permissions}>
233+
<MemoryRouter initialEntries={['/apps/crm/crm_product']}>
234+
<ListDeleteHarness dataSource={dataSource as any} />
235+
</MemoryRouter>
236+
</MePermissionsProvider>
237+
</I18nProvider>,
238+
);
239+
return dataSource;
240+
}
241+
242+
async function confirmRowDelete(pack: Pack) {
243+
fireEvent.click(screen.getByText('row-delete'));
244+
const dialog = await screen.findByRole('alertdialog');
245+
fireEvent.click(within(dialog).getByRole('button', { name: pack.objectActions.deleteConfirmButton }));
246+
}
247+
248+
const MAY_RESTORE = grants({ crm_product: { allowRead: true, allowDelete: true, allowRestoreOwnDeleted: true } });
249+
const MAY_NOT_RESTORE = grants({ crm_product: { allowRead: true, allowDelete: true } });
250+
251+
describe.each(['en', 'zh'] as const)('console list Delete undo in %s (objectstack#30239)', (language) => {
252+
const pack = PACKS[language];
253+
const deleted = fill(pack.objectActions.deletedNamed, { label: 'Product', name: 'QA Widget 0' });
254+
255+
it('round trip: Undo restores the entry the delete wrote, never re-creates, and names the record', async () => {
256+
const dataSource = mountBin(language, MAY_RESTORE, { entryId: 'rb1' });
257+
await confirmRowDelete(pack);
258+
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
259+
const [message, data] = (toast.success as any).mock.calls[0];
260+
expect(message).toBe(deleted);
261+
expect(data.action.label).toBe(pack.actions.undo);
262+
263+
data.action.onClick();
264+
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(2));
265+
expect(dataSource.restoreRecycleBinEntry).toHaveBeenCalledWith('crm_product', 'rb1');
266+
expect(dataSource.create).not.toHaveBeenCalled();
267+
expect((toast.success as any).mock.calls[1]).toEqual([
268+
fill(pack.objectActions.restoredNamed, { label: 'Product', name: 'QA Widget 0' }),
269+
]);
270+
});
271+
272+
it('a refused undo reads the refusal sentence in the session language', async () => {
273+
const refusal = Object.assign(new Error('raw server text'), {
274+
code: 'RESTORE_UNIQUE_VALUE_TAKEN',
275+
details: { object: 'crm_product', recordId: 'p1', field: 'product_name' },
276+
});
277+
mountBin(language, MAY_RESTORE, { entryId: 'rb1', restoreError: refusal });
278+
await confirmRowDelete(pack);
279+
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
280+
(toast.success as any).mock.calls[0][1].action.onClick();
281+
await waitFor(() => expect(toast.error).toHaveBeenCalledTimes(1));
282+
expect(toast.error).toHaveBeenCalledWith(fill(pack.objectActions.restoreFailed, { label: 'Product' }), {
283+
description: fill(pack.recycleBin.refusal.uniqueValueTaken, { field: 'product_name' }),
284+
});
285+
});
286+
287+
it('control: without allowRestoreOwnDeleted the toast is today\'s, and no entry id is asked for', async () => {
288+
const dataSource = mountBin(language, MAY_NOT_RESTORE, { entryId: 'rb1' });
289+
await confirmRowDelete(pack);
290+
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
291+
expect((toast.success as any).mock.calls[0]).toEqual([deleted]);
292+
expect(dataSource.delete.mock.calls).toEqual([['crm_product', 'p1']]);
293+
});
294+
295+
it('control: an answer with no recycle-bin entry keeps today\'s toast', async () => {
296+
mountBin(language, MAY_RESTORE, {});
297+
await confirmRowDelete(pack);
298+
await waitFor(() => expect(toast.success).toHaveBeenCalledTimes(1));
299+
expect((toast.success as any).mock.calls[0]).toEqual([deleted]);
300+
});
301+
});

‎ui/packages/app-shell/src/hooks/__tests__/useObjectActions.test.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ describe('useObjectActions — the delete confirmation names what it deletes (ob
171171
});
172172

173173
expect(confirmSpy).toHaveBeenCalledTimes(1);
174-
expect(confirmSpy).toHaveBeenCalledWith('objectActions.deleteConfirm', {
174+
expect(confirmSpy).toHaveBeenCalledWith('objectActions.deleteConfirmQuestion', {
175175
title: 'objectActions.deleteConfirmTitle',
176176
confirmText: 'objectActions.deleteConfirmButton',
177177
destructive: true,
@@ -189,7 +189,7 @@ describe('useObjectActions — the delete confirmation names what it deletes (ob
189189
});
190190

191191
expect(confirmSpy).toHaveBeenCalledTimes(1);
192-
expect(confirmSpy).toHaveBeenCalledWith('console.objectView.bulkDeleteConfirm', {
192+
expect(confirmSpy).toHaveBeenCalledWith('console.objectView.bulkDeleteQuestion', {
193193
title: 'objectActions.bulkDeleteConfirmTitle',
194194
confirmText: 'objectActions.deleteConfirmButton',
195195
destructive: true,

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

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +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 { usePermissions } from '@object-ui/permissions';
1920
import {
2021
recordDelete,
2122
readCascadeDeleteObjects,
@@ -24,6 +25,7 @@ import {
2425
type ConfirmationHandler,
2526
type RecordDeleteConfirmCopy,
2627
} from '@object-ui/core';
28+
import { recycleBinRefusalLabelsOf, recycleBinRestoreOf } from '../utils/recycleBinRestore.js';
2729

2830
/** The browser's native box — the fallback when the host passes no `onConfirm`. */
2931
const nativeConfirm: ConfirmationHandler = async (message) => window.confirm(message);
@@ -111,6 +113,9 @@ export function useObjectActions({
111113
const navigate = useNavigate();
112114
const { appName } = useParams();
113115
const { t } = useObjectTranslation();
116+
// ADR-0148 — the delete toast's Undo needs the caller's own-delete restore
117+
// grant on the object, read from the effective map (recycleBinRestoreOf).
118+
const { effectiveObjects } = usePermissions();
114119
const baseUrl = `/apps/${appName}`;
115120

116121
const { execute, loading, error, runner } = useActionRunner({
@@ -141,7 +146,17 @@ export function useObjectActions({
141146
// success), so the runner's post-execution hook adds no second toast.
142147
runner.registerHandler('delete', (action: any) =>
143148
recordDelete.run(
144-
{ objectName, label: objectLabel || objectName, objectDef, dataSource, t, toast, onRefresh },
149+
{
150+
objectName,
151+
label: objectLabel || objectName,
152+
objectDef,
153+
dataSource,
154+
t,
155+
toast,
156+
onRefresh,
157+
restore: recycleBinRestoreOf(dataSource, objectName, effectiveObjects),
158+
refusalLabels: recycleBinRefusalLabelsOf(objectName, objectDef, objectLabelOf),
159+
},
145160
action,
146161
),
147162
);
@@ -160,7 +175,7 @@ export function useObjectActions({
160175
onRefresh?.();
161176
return { success: true, reload: true };
162177
});
163-
}, [runner, objectName, dataSource, onEdit, onRefresh, navigate, baseUrl, t, objectLabel, objectDef]);
178+
}, [runner, objectName, dataSource, onEdit, onRefresh, navigate, baseUrl, t, objectLabel, objectDef, effectiveObjects, objectLabelOf]);
164179

165180
const create = useCallback(() => {
166181
onEdit?.(null);
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* objectstack#30239 — whether the console offers the Undo on a delete toast.
5+
* The grant is `allowRestoreOwnDeleted`, read through the spec's own fold
6+
* (`manageRecycleBin` and `modifyAllRecords` imply it), and the data source
7+
* must be able to restore at all.
8+
*/
9+
import { describe, it, expect, vi } from 'vitest';
10+
import { canRestoreOwnDeletes, recycleBinRestoreOf, recycleBinRefusalLabelsOf } from '../recycleBinRestore';
11+
12+
describe('canRestoreOwnDeletes (objectstack#30239)', () => {
13+
it.each([
14+
['allowRestoreOwnDeleted', { crm_lead: { allowRead: true, allowRestoreOwnDeleted: true } }, true],
15+
['manageRecycleBin implies it', { crm_lead: { allowRead: true, manageRecycleBin: true } }, true],
16+
["the '*' row's modifyAllRecords implies it", { '*': { modifyAllRecords: true } }, true],
17+
['control: a row without the grant', { crm_lead: { allowRead: true, allowDelete: true } }, false],
18+
['control: the grant without read (the fold needs read)', { crm_lead: { allowRestoreOwnDeleted: true } }, false],
19+
['control: no row and no wildcard', { crm_account: { allowRead: true, allowRestoreOwnDeleted: true } }, false],
20+
])('%s', (_label, map, expected) => {
21+
expect(canRestoreOwnDeletes(map, 'crm_lead')).toBe(expected);
22+
});
23+
24+
it('reads the lowercase key for a name given in another case', () => {
25+
expect(canRestoreOwnDeletes({ crm_lead: { allowRead: true, allowRestoreOwnDeleted: true } }, 'CRM_Lead')).toBe(true);
26+
});
27+
28+
it('control: permissions not loaded is no', () => {
29+
expect(canRestoreOwnDeletes(undefined, 'crm_lead')).toBe(false);
30+
});
31+
});
32+
33+
describe('recycleBinRestoreOf (objectstack#30239)', () => {
34+
const granted = { crm_lead: { allowRead: true, allowRestoreOwnDeleted: true } };
35+
36+
it('binds the data source restore to the object', async () => {
37+
const dataSource = { restoreRecycleBinEntry: vi.fn().mockResolvedValue({ restored: 1 }) };
38+
const restore = recycleBinRestoreOf(dataSource, 'crm_lead', granted);
39+
await restore!('rb_1');
40+
expect(dataSource.restoreRecycleBinEntry).toHaveBeenCalledWith('crm_lead', 'rb_1');
41+
});
42+
43+
it('control: a data source with no recycle bin offers no restore', () => {
44+
expect(recycleBinRestoreOf({}, 'crm_lead', granted)).toBeUndefined();
45+
});
46+
47+
it('control: a caller without the grant gets no restore', () => {
48+
const dataSource = { restoreRecycleBinEntry: vi.fn() };
49+
expect(recycleBinRestoreOf(dataSource, 'crm_lead', { crm_lead: {} })).toBeUndefined();
50+
});
51+
});
52+
53+
describe('recycleBinRefusalLabelsOf (objectstack#30239)', () => {
54+
it('names a field of the deleted object by its label, and nothing else', () => {
55+
const labels = recycleBinRefusalLabelsOf('crm_lead', { fields: { email: { label: 'Email' } } });
56+
expect(labels.fieldLabel!('crm_lead', 'email')).toBe('Email');
57+
expect(labels.fieldLabel!('crm_lead', 'phone')).toBeUndefined();
58+
expect(labels.fieldLabel!('crm_account', 'email')).toBeUndefined();
59+
});
60+
});

0 commit comments

Comments
 (0)