Skip to content
Merged
26 changes: 26 additions & 0 deletions .changeset/36855-bulk-approve-failure-reasons.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'@object-ui/console': patch
'@object-ui/i18n': patch
---

fix(console): a partly failed bulk approve or reject in the Approval Center says why each row failed

Clause-②: yes (narrowing)
Metadata-protocol: none
Skills-docs: none — no page under `skills/` or `content/docs/` names the Approval Center's bulk-failure string or teaches overriding it

<!-- adr-0087: not-required (no-migration-prescription) the narrowing is one console string retired from the approvalsInbox locale namespace of @object-ui/i18n; no packages/spec schema, registered node type, stored row or metadata key names it, nothing a metadata author writes changes, and a host that overrode it has nothing to rewrite: its override is simply no longer shown -->

**BREAKING** for a host that overrides `approvalsInbox.bulkPartial`, listed under "Removed translation keys" below: it is retired in 19.0.0, and an override of it no longer applies.

A bulk approve or reject that partly fails used to show "3 succeeded, 2 failed: Quote A, Quote B": at most three record titles, and no reason. Each failed row now keeps its refusal's text, read the way the single-row Approve reads it: the server's `userMessage` (already in the decider's language) when the refusal carries one, else the page's line for the refusal (not allowed, already decided, no longer exists), else the error's own text as the console's approvals client reports it (`CODE: message`; a server failure, for example, reads `APPROVAL_APPROVE_FAILED: ` followed by the server's text). The generic "Action failed" shows only for an error that carries no text at all.

The error toast reads "N succeeded, M failed" and lists the first three failed rows, one per line, each as "title: reason". It stays until dismissed. When more rows fail, it carries a "Show all (M)" action, which opens a dialog listing every failed row of that run with its reason, even after a later bulk run. The toasts are dismissed when the Approval Center is left.

`@object-ui/i18n`: the `approvalsInbox` namespace gains `bulkPartialSummary`, `bulkFailureLine`, `bulkFailuresShowAll`, `bulkFailuresTitle`, `bulkFailuresBody` and `close`, in every locale pack.

Removed translation keys (approvalsInbox namespace of `@object-ui/i18n`, released in 18.6.0; no code reads it since the partial-failure toast became a summary plus per-row lines). It is removed from all eleven packs it shipped in, `ar`, `de`, `en`, `es`, `fr`, `ja`, `ko`, `pt-BR`, `ru`, `zh-Hans` and `zh-Hant`:

- `approvalsInbox.bulkPartial` (ar, de, en, es, fr, ja, ko, pt-BR, ru, zh-Hans, zh-Hant)

An override of this key no longer applies; delete it, or move its wording to `approvalsInbox.bulkPartialSummary` (no `{{which}}` hole: the failed rows are listed below the summary).
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@

import '@testing-library/jest-dom/vitest';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, cleanup, waitFor, within, fireEvent } from '@testing-library/react';
import { render, screen, cleanup, waitFor, within, fireEvent, act } from '@testing-library/react';
import { MemoryRouter, Routes, Route } from 'react-router-dom';

const APP = 'com.objectstack.account';
Expand Down Expand Up @@ -71,7 +71,10 @@ const { approvalsApiStub, ADAPTER, AUTH, I18N } = vi.hoisted(() => {
};
const AUTH = { user: { id: 'u_1', email: 'approver@example.com' } };
const I18N = {
t: (key: string, options?: Record<string, unknown>) => String(options?.defaultValue ?? key),
// Interpolates like i18next, so a line built from values shows them.
t: (key: string, options?: Record<string, unknown>) =>
String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (whole, name: string) =>
options && name in options ? String(options[name]) : whole),
language: 'en',
};

Expand Down Expand Up @@ -239,3 +242,160 @@ describe('Approvals Inbox — a marked decide refusal is shown as written (objec
expect(await approveQuickFailingWith(refusal())).toBe('You are not allowed to perform this action.');
});
});

// A bulk approve that partly fails names each failed row WITH its reason —
// the refusal's own text (`userMessage` first, through the same reader the
// inline Approve uses above), else the page's generic line. When more rows
// fail than the toast lists, its "Show all" action opens a dialog listing
// every one.
describe('Approvals Inbox — a partly failed bulk approve says why each row failed', () => {
const MARKED = '此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。';
const markedRefusal = () => Object.assign(new Error('FORBIDDEN: submitter cannot approve'), {
code: 'FORBIDDEN',
status: 403,
details: { code: 'FORBIDDEN', error: 'refused', userMessage: MARKED },
});
const decidedRefusal = () => Object.assign(new Error('INVALID_STATE: already decided'), {
code: 'INVALID_STATE',
status: 409,
details: { code: 'INVALID_STATE', error: 'already decided' },
});
const ALREADY_DECIDED = 'This request was already decided. Refresh the list.';

const row = (n: number) => ({
id: `req_${n}`,
record_id: `inv_${n}`,
record_title: `Bulk Invoice ${n}`,
process_name: 'invoice_approval',
process_label: 'Invoice Approval',
object_name: 'showcase_invoice',
object_label: 'Invoice',
status: 'pending',
pending_approvers: ['u_1'],
submitter_id: 'u_2',
submitter_name: 'Sam Submitter',
// Newest first is the inbox's order: row 1 is the newest, so it lists first.
submitted_at: `2026-08-${String(30 - n).padStart(2, '0')}T00:00:00.000Z`,
});

let originalList: ReturnType<typeof approvalsApiStub.listRequests.getMockImplementation>;
beforeEach(() => { originalList = approvalsApiStub.listRequests.getMockImplementation(); });
afterEach(() => {
approvalsApiStub.listRequests.mockImplementation(originalList!);
approvalsApiStub.approve.mockReset();
approvalsApiStub.approve.mockImplementation(async () => ({ data: row(0), finalized: true }) as any);
});

/** Render `count` actionable rows; the returned function runs one bulk approve. */
async function renderRows(count: number) {
const rows = Array.from({ length: count }, (_, i) => row(i + 1));
approvalsApiStub.listRequests.mockImplementation(async () => ({ data: rows }) as any);
render(
<MemoryRouter initialEntries={[`/apps/${APP}/system/approvals`]}>
<Routes>
<Route path="/apps/:appName/system/approvals" element={<ApprovalsInboxPage />} />
</Routes>
</MemoryRouter>,
);
const box = await screen.findByTestId('approvals-inbox-table-scroller');
/** Select every row, confirm a bulk approve in which the `fail` rows are refused. */
return async (fail: Record<string, () => Error>) => {
const before = approvalsApiStub.approve.mock.calls.length;
approvalsApiStub.approve.mockImplementation((async (id: string) => {
if (fail[id]) throw fail[id]();
return { data: rows.find(r => r.id === id), finalized: true };
}) as any);
for (const r of rows) {
const link = await within(box).findByRole('link', { name: r.record_title });
const tr = link.closest('tr') as HTMLElement;
fireEvent.click(within(tr).getByRole('checkbox', { name: 'Select request' }));
}
fireEvent.click(await screen.findByRole('button', { name: `Approve ${count}` }));
const dialog = await screen.findByRole('alertdialog');
fireEvent.click(within(dialog).getByRole('button', { name: `Approve ${count}` }));
await waitFor(() => expect(approvalsApiStub.approve).toHaveBeenCalledTimes(before + count));
await waitFor(() => expect(screen.queryByRole('alertdialog')).toBeNull());
// The run is over once the selection it cleared is gone.
await waitFor(() => expect(screen.queryByRole('button', { name: `Approve ${count}` })).toBeNull());
};
}

async function bulkApprove(count: number, fail: Record<string, () => Error>) {
await (await renderRows(count))(fail);
}

it('one refused row: the toast names that row with its marked reason', async () => {
await bulkApprove(2, { req_2: markedRefusal });
await waitFor(() => expect(toasts.error).toHaveBeenCalledTimes(1));
const [title, options] = toasts.error.mock.calls[0] as [string, Record<string, any>];
expect(title).toBe('1 succeeded, 1 failed');
// The failed row, and why — the server's marked text, not a bare title.
expect(options.description).toBe(`Bulk Invoice 2: ${MARKED}`);
expect(toasts.success).not.toHaveBeenCalled();
// Everything fits in the toast: no overflow action; it still stays until
// dismissed, so the reasons can be read.
expect(options.action).toBeUndefined();
expect(options.duration).toBe(Infinity);
});

it('CONTROL: every row succeeds — a success toast and no failure feedback', async () => {
await bulkApprove(3, {});
await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1));
expect(toasts.error).not.toHaveBeenCalled();
expect(screen.queryByTestId('approvals-bulk-failures')).toBeNull();
});

it('more failures than the toast lists: "Show all" reaches every row and its reason', async () => {
await bulkApprove(6, {
req_1: markedRefusal, req_2: decidedRefusal, req_3: decidedRefusal,
req_4: markedRefusal, req_5: decidedRefusal,
});
await waitFor(() => expect(toasts.error).toHaveBeenCalledTimes(1));
const [title, options] = toasts.error.mock.calls[0] as [string, Record<string, any>];
expect(title).toBe('1 succeeded, 5 failed');
// The toast lists the first three, each with its reason …
expect(options.description).toBe([
`Bulk Invoice 1: ${MARKED}`,
`Bulk Invoice 2: ${ALREADY_DECIDED}`,
`Bulk Invoice 3: ${ALREADY_DECIDED}`,
].join('\n'));
expect(options.action.label).toBe('Show all (5)');
// The toast stays until dismissed, so its action cannot time out.
expect(options.duration).toBe(Infinity);
act(() => options.action.onClick());
const list = await screen.findByTestId('approvals-bulk-failures');
const items = within(list).getAllByRole('listitem');
expect(items).toHaveLength(5);
const expected: Array<[string, string]> = [
['Bulk Invoice 1', MARKED], ['Bulk Invoice 2', ALREADY_DECIDED], ['Bulk Invoice 3', ALREADY_DECIDED],
['Bulk Invoice 4', MARKED], ['Bulk Invoice 5', ALREADY_DECIDED],
];
for (const [title, reason] of expected) {
const item = items.find(li => li.textContent?.startsWith(title));
expect(item, title).toBeDefined();
expect(item).toHaveTextContent(reason);
}
expect(within(list).queryByText('Bulk Invoice 6')).toBeNull();
});

it("a toast's \"Show all\" opens its own run's rows, not a later run's", async () => {
const runBulk = await renderRows(6);
await runBulk({
req_1: markedRefusal, req_2: decidedRefusal, req_3: decidedRefusal,
req_4: markedRefusal, req_5: decidedRefusal,
});
await waitFor(() => expect(toasts.error).toHaveBeenCalledTimes(1));
const first = toasts.error.mock.calls[0][1] as Record<string, any>;
expect(first.action.label).toBe('Show all (5)');
// A second, clean run while the first toast is still up.
await runBulk({});
await waitFor(() => expect(toasts.success).toHaveBeenCalledTimes(1));
act(() => first.action.onClick());
const dialog = await screen.findByRole('alertdialog');
expect(within(dialog).getByText('Not decided: 5')).toBeInTheDocument();
const items = within(within(dialog).getByTestId('approvals-bulk-failures')).getAllByRole('listitem');
expect(items.map(li => li.firstElementChild?.textContent)).toEqual([
'Bulk Invoice 1', 'Bulk Invoice 2', 'Bulk Invoice 3', 'Bulk Invoice 4', 'Bulk Invoice 5',
]);
});
});
102 changes: 94 additions & 8 deletions ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,19 @@ type TabKey = InboxUrlState['tab'];
/** Server page size for the paginated tabs (submitted / all). */
const PAGE_SIZE = 50;

/** One row a bulk approve / reject could not decide, and the refusal's reason. */
interface BulkFailure {
id: string;
title: string;
reason: string;
}

/**
* How many failed rows a bulk run's toast lists before the rest move behind
* its "Show all" action (the dialog lists every one).
*/
const BULK_FAILURES_IN_TOAST = 3;

/**
* Semantic status colors (green = approved, amber = waiting, red = rejected,
* slate = recalled, violet = returned for revision) — variant-based Badge
Expand Down Expand Up @@ -1093,6 +1106,23 @@ function ApprovalsQueue() {
// Bulk selection (only meaningful on "pending" tab where the user can act)
const [selectedRowIds, setSelectedRowIds] = useState<Set<string>>(new Set());
const [bulkRunning, setBulkRunning] = useState(false);
/**
* The failed rows the "Show all" dialog lists, each with the refusal's
* reason. A toast carries the first few; its "Show all" action puts ITS OWN
* run's list here and opens the dialog, so a toast still on screen after a
* later run never shows that later run's rows (or an empty list).
*/
const [bulkFailures, setBulkFailures] = useState<BulkFailure[]>([]);
const [bulkFailuresOpen, setBulkFailuresOpen] = useState(false);
/**
* The partial-failure toasts this page raised and has not seen dismissed.
* They stay until dismissed, and their action opens this page's dialog, so
* they leave with the page.
*/
const bulkFailureToasts = useRef(new Set<string | number>());
useEffect(() => () => {
for (const id of bulkFailureToasts.current) toast.dismiss(id);
}, []);

// Inline decision confirmations (row-level quick action / mobile card /
// keyboard). BOTH decisions confirm before executing (#2762 P0-2): the
Expand Down Expand Up @@ -1473,16 +1503,23 @@ function ApprovalsQueue() {
if (targets.length === 0) return;
setBulkRunning(true);
let ok = 0;
const failures: string[] = [];
const failures: BulkFailure[] = [];
for (const r of targets) {
const pending = new Set(r.pending_approvers || []);
const actor = identities.find(i => pending.has(i)) || user?.id || '';
try {
const fn = kind === 'approve' ? approvalsApi.approve : approvalsApi.reject;
await fn(r.id, { actor_id: actor, ...decisionComment(comment) });
ok++;
} catch {
failures.push(r.record_title || formatIdentity(r.record_id));
} catch (err: any) {
// Each failure keeps its refusal's own text, read the way the
// single-row Approve reads it (`userMessage` first, else the page's
// generic line) — a bare title says which row, never why.
failures.push({
id: r.id,
title: r.record_title || formatIdentity(r.record_id),
reason: humanizeError(err, tr('actionFailed', 'Action failed')),
});
}
}
setBulkRunning(false);
Expand All @@ -1492,14 +1529,37 @@ function ApprovalsQueue() {
? tr('bulkApproved', 'Approved {{count}} requests', { count: ok })
: tr('bulkRejected', 'Rejected {{count}} requests', { count: ok }));
} else {
const shown = failures.slice(0, 3).join(', ');
toast.error(tr('bulkPartial', '{{ok}} succeeded, {{fail}} failed: {{which}}', {
ok, fail: failures.length, which: shown + (failures.length > 3 ? '…' : ''),
}));
const lines = failures.slice(0, BULK_FAILURES_IN_TOAST).map(f =>
tr('bulkFailureLine', '{{title}}: {{reason}}', { title: f.title, reason: f.reason }));
const overflow = failures.length > BULK_FAILURES_IN_TOAST;
// The toast stays until dismissed: a row per line with its reason is
// more than a few seconds' reading, and the overflow's "Show all" must
// not time out.
const toastId = toast.error(tr('bulkPartialSummary', '{{ok}} succeeded, {{fail}} failed', { ok, fail: failures.length }), {
description: lines.join('\n'),
classNames: { description: 'whitespace-pre-line' },
duration: Infinity,
closeButton: true,
onDismiss: () => { bulkFailureToasts.current.delete(toastId); },
// More failures than the toast shows: the rest are one click away.
// The action closes over THIS run's list, never the page's latest.
...(overflow
? {
action: {
label: tr('bulkFailuresShowAll', 'Show all ({{n}})', { n: failures.length }),
onClick: () => {
setBulkFailures(failures);
setBulkFailuresOpen(true);
},
},
}
: {}),
});
if (toastId != null) bulkFailureToasts.current.add(toastId);
}
void load();
refreshBadge();
}, [actionableSelectedRows, identities, user?.id, load, refreshBadge, tr]);
}, [actionableSelectedRows, identities, user?.id, load, refreshBadge, humanizeError, tr]);

/** Confirmed row-level approve (from the shared dialog). */
const inlineApprove = useCallback(async (r: ApprovalRequestRow) => {
Expand Down Expand Up @@ -2063,6 +2123,32 @@ function ApprovalsQueue() {
</div>
)}

{/* Every failed row of the last bulk run, with its reason — the
toast's "Show all" opens it when the failures overflow the toast. */}
<AlertDialog open={bulkFailuresOpen} onOpenChange={setBulkFailuresOpen}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{tr('bulkFailuresTitle', 'Not decided: {{n}}', { n: bulkFailures.length })}
</AlertDialogTitle>
<AlertDialogDescription>
{tr('bulkFailuresBody', 'These requests were left as they were. Each one says why.')}
</AlertDialogDescription>
</AlertDialogHeader>
<ul data-testid="approvals-bulk-failures" className="max-h-[50vh] overflow-y-auto space-y-2 text-sm">
{bulkFailures.map(f => (
<li key={f.id}>
<span className="font-medium">{f.title}</span>
<span className="block text-muted-foreground">{f.reason}</span>
</li>
))}
</ul>
<AlertDialogFooter>
<AlertDialogCancel>{tr('close', 'Close')}</AlertDialogCancel>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>

{loading ? (
<div className="space-y-2">
<Skeleton className="h-10 w-full" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ const LEGITIMATE_IDENTITIES: Record<string, string> = {
'collaboration.userStatusTitle': '{{name}} ({{status}}) — holes and parentheses only.',
'chatbot.build.nextStepQuote': '“{{step}}” — a hole in quote marks; ko quotes with the same curly marks as en (objectui#12724).',
'console.assignedWork.row': '{{object}} · {{field}} — two holes and a middle dot, no prose (objectstack#30205).',
'approvalsInbox.bulkFailureLine': '{{title}}: {{reason}} — holes and a colon; zh/ja set a fullwidth colon, ko/ru/ar keep `: `.',
'listConditions.chips.pattern': '{{field}}: {{value}} — holes and a colon; zh/ja set a fullwidth colon, ko/ru/ar keep `: `.',
'console.assignedWork.failure': '{{object}} {{id}}: {{message}} — holes and a colon; zh sets a fullwidth colon, ja/ko/ru/ar keep `: ` (objectstack#30205).',
};
Expand Down
Loading
Loading