Skip to content

Commit d25d912

Browse files
fix(console): the approvals inbox keeps its tab, filters, search and sort across a request page and Back (#36979)
<!-- claude-projects-attribution: {"github_login":"os-support-ai"} --> _Requested by **Yibo Wang** · [project thread](https://claude.ai/code/project/chan_01BVUyyPie8gHwoPM18iABwB?thread=cmsg_01BVUyyPie8gHwoPM18iABwBTDAJKyXUan6fJCKsZUf5Pv)_ Fixes #36966 Clause-②: no Metadata-protocol: none ## 维护者速读 - 审批人在审批收件箱里切到「全部」、按状态筛选或搜索后打开一条申请,按浏览器返回,原来回到「待我审批」且筛选全清空;现在回到离开时的标签、筛选、搜索和排序,刷新页面也保留。 - 属于审批收件箱体验改进,替逐条处理「全部 → 已撤回」或「我提交的」的审批人省去每次重建筛选。 - 出错时最坏是收件箱打开在默认状态(与改动前一样),不丢数据、不影响审批动作;可直接撤回本次合并。 - 无 ## What changes The approvals inbox (`ApprovalsQueue` in `ApprovalsInboxPage.tsx`) held its tab, status / process / object filters, search text and sort in `useState` alone, so the queue's remount on Back from a request's page reset them all. They now live in the inbox's query string, through a small codec beside the page, `approvalsInboxUrlState.ts` (the same shape as the metadata list's `metadataListState.ts`). | Param | Carries | Default (no param) | |---|---|---| | `scope` | the tab: `submitted` or `all` | `pending` | | `status` | one `APPROVAL_STATUSES` value, on tabs other than `pending` | every status | | `process` | the process label a row shows | every process | | `object` | the object machine name | every object | | `q` | the search text | no search | | `sort` | `oldest` or `amount` | `recent` | Design points the card asked to settle: - **Replace vs push.** Every write uses `setSearchParams(..., { replace: true })`, the tab change included, so filter changes add no history entries and Back leaves the inbox. Measured in the browser: after a tab switch, a sort change and a search, one Back from the inbox lands on the page before it. - **Search debounce.** The search box keeps its own draft; the draft reaches `q` after 350 ms, the same delay the server search already used (the old `serverQuery` debounce is replaced by it, and on the paginated tabs `q` IS the server query). A row opened inside the debounce first writes the pending text into the inbox's own entry, then navigates, so Back returns to it too. The draft follows the address only on a navigation the page did not write (a link here, Back / Forward), never on its own REPLACE, the rule `ResourceListPage` uses; it is applied during render, not in an effect. - **Invalid values.** Reading is strict and quiet: an unknown `scope` or `sort`, or a `status` outside `APPROVAL_STATUSES`, reads as the default. A `status` on the `pending` tab is ignored (that tab draws no status filter, so it would hide rows behind a control that is not shown). `process` and `object` name data, so they are checked once, at the first load that returns rows, and dropped only when those rows are the whole answer (the pending tab, or `rows.length >= total`) and none carries the value; otherwise the value is kept and offered in its dropdown (an object no loaded row labels shows by its machine name). A filter picked from the dropdowns is never second-guessed. - **`onTabChange`.** It writes one patch: the new `scope`, and `status`, `process`, `object`, `q`, `sort` back to their defaults (deleted from the address). Params the inbox does not own are kept. - **`?request=` deep link.** Unchanged: `ApprovalsInboxPage` still routes `?request=` to `RequestDeepLink` before the queue mounts, with or without inbox params beside it. - **Record-page round trip and full reload.** Both restore: the state is read from the address on mount, and the first server read already carries `q` and `status` (no debounce wait on a reload). Two choices worth a look: - The tab rides `scope`, not the card's suggested `tab`: `tab` is a console-reserved param (`RECORD_DETAIL_TAB_PARAM`, the record page's detail tab, in app-shell's `urlParams.ts`), which that registry says a page must never repurpose. None of the six names is in `RESERVED_URL_PARAMS`. - The state survives a reload. Object list views strip their `uf_*` state on a document reload (the list-draft rule in `listDraftStore.ts`); the inbox does not, because the card asks for reload survival and the inbox has no saved-view baseline to fall back to. If the reload reset is wanted here too, it is a follow-up, not part of this fix. The status filter accepts the full `APPROVAL_STATUSES` vocabulary, so the status select's missing `cancelled` option (#36960, the next card in this area) only needs its option added; this PR does not touch the option list. ## Tests New pin file `ApprovalsInboxPage.stateInUrl-36966.test.tsx` (8 cases, the real page under a memory router with a stub request page): 1. All + Recalled + object + sort + search, open a row, Back: same tab, selects, search, rows and address. 2. A fresh mount of the written address (a reload) opens the same inbox; the first server read already carries `q` and `status`. 3. A search typed and opened inside the debounce still comes back on Back. 4. Writes are REPLACE: after filter changes, one Back leaves the inbox. 5. Invalid control: unknown `scope` / `sort`, a `status` on the pending tab, and an unknown `status` value all read as defaults. 6. Full-set control: with every row loaded, a process / object no row carries reads as all and leaves the address; one a row carries is kept. 9. On a paginated tab whose first page lacks them, a process and object the address names are kept, in the address and in the controls (round 2, L1 S1). 7. A tab change clears the filters, search and sort from the address and keeps other params. 8. The `?request=` deep link still opens the request, with inbox params beside it, and the queue reads no list. <details><summary>Against main's page source: 7 of 8 fail (the deep-link preservation pin passes, as it should)</summary> `git restore --source=0212714711` of `ApprovalsInboxPage.tsx` (tree only, blob verified equal to the base), same test file, then restored from HEAD (blob equal to HEAD, `git diff HEAD` empty): ``` × All + Recalled + object + sort + search → open a row → Back ... AssertionError: expected [ 'INV-1001' ] to deeply equal [ 'INV-4004' ] × a reload of the written address ... × a search typed and opened within the debounce ... × writes REPLACE ... × values the inbox does not offer read as the defaults × a process or object no row carries ... × changing tab clears ... Tests 7 failed | 1 passed (8) ``` </details> <details><summary>Ablation (scripts/ablation-replace.mjs) on HEAD b84c138</summary> Mutation: the writer's `{ replace: true }` → `{ replace: false }` in `ApprovalsQueue`. The console test imports the page from `src` (no package `dist/` in the resolution path), so no rebuild or dist preflight applies. ``` ablation-replace: ok mutation landed: anchor 1 -> 0, blob c5b4e17 -> df34395b9a16 × writes REPLACE: filter changes leave one history entry, so Back leaves the inbox Tests 1 failed | 7 passed (8) ablation-replace: ok restored: blob == HEAD (c5b4e17) and `git diff HEAD` is empty ``` </details> <details><summary>Affected suites on HEAD b84c138</summary> ``` pnpm --filter @object-ui/console type-check → exit 0 pnpm --dir ui exec vitest run --maxWorkers=2 apps/console/src/pages/system/ApprovalsInboxPage \ apps/console/src/__tests__/approvalsInboxComponentRef.test.tsx \ apps/console/src/pages/consoleFaces.displayLocale-9909.test.tsx Test Files 22 passed (22) Tests 131 passed (131) ``` ESLint on the three touched source files: no new findings against the base (the page's warning counts per rule equal main's; the new files have none). </details> <details><summary>Derived gate families on HEAD b84c138: 37 of 37 run, all exit 0</summary> `node scripts/pm/dispatch-gates.mjs --commands` (tree `objectstack-ai/objectstack` at b84c138, merge base 0212714) derived 37 families; each was run and its exit code captured before any pipe. Reconciliation: `Run reconciliation — 37 derived, 37 run, 0 NOT-MEASURED, 0 UNRUN` (a derived zero: all 37 recorded an exit code). One family needed a second run: `pnpm --dir ui exec vitest run scripts/` went red in the batch on two 15 s timeouts in files this diff does not touch (`check-readme-exports.test.ts`, `select-affected-tests.test.ts`) while the box was shared; those two files re-run alone at `--maxWorkers=1` passed, `Test Files 2 passed (2)`, `Tests 161 passed (161)`. The batch run otherwise read `Tests 2 failed | 5124 passed`. CI's run of that family is the one of record. `pnpm check:new-line-citations` (under `ui/`): `0 new citation(s)`. </details> ## Acceptance notes - Server search on the paginated tabs matched only the object machine name in the showcase run (`q=invoice` found 4, `q=INV` and `q=Invoice` found 0). That is the server search, #36959's scope; noted, not touched here. - The process and object selects only draw with two or more options among the loaded rows, so a search that narrows the rows to one object hides the object select while its filter still applies (shown as "N of M"). Unchanged by this PR. ## Verification Read first, by risk: 1. `ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx`: the `openRequest` flush (writes the pending search into the current entry, then navigates) and the draft-follows-address block next to `useNavigationType`. 2. `ui/apps/console/src/pages/system/approvalsInboxUrlState.ts`: the codec and its defaults. 3. The seeded process / object check (`seedFiltersChecked`) in the page. Two-minute check: open the approvals inbox, switch to All, set the status to Recalled, open a row, press Back. Expected: the All tab, Recalled, the same rows, and an address ending `?scope=all&status=recalled`. <details><summary>Browser run (showcase on its own port, the Console from ui/ source via Vite, the issue's exact sequence)</summary> Main's page source (tree-only restore of `0212714711`): ``` [main] 1-before-open: {"url":".../system/approvals","tab":"All","combos":["Recalled","Newest first"],"rows":2} [main] 3-after-back: {"url":".../system/approvals","tab":"My Pending4","combos":["All processes","All objects","Newest first"],"rows":4} [main] 4-after-reload: {"url":".../system/approvals","tab":"My Pending4", ... "rows":4} [main] VERDICT back-restores=false reload-restores=false ``` This branch: ``` [fix] 1-before-open: {"url":".../system/approvals?scope=all&status=recalled","tab":"All","combos":["Recalled","Newest first"],"rows":2} [fix] 3-after-back: {"url":".../system/approvals?scope=all&status=recalled","tab":"All","combos":["Recalled","Newest first"],"rows":2} [fix] 4-after-reload: {"url":".../system/approvals?scope=all&status=recalled","tab":"All","combos":["Recalled","Newest first"],"rows":2} [fix] VERDICT back-restores=true reload-restores=true ``` The component route the issue names (`/component/approvals/inbox`), with sort and search: ``` after search+sort: .../component/approvals/inbox?scope=all&sort=oldest&q=invoice after Back: .../component/approvals/inbox?scope=all&sort=oldest&q=invoice tab=All search=invoice sort=Oldest first rows 4->4 one more Back: /apps/com.example.showcase/page/showcase_capability_map deep link -> .../sys_approval_request/record/areq_d081b5c8-... (asked areq_d081b5c8-...) ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01WGufziG2t1d9cfRQJDrHkB)_ <!-- signed: repo:objectstack#3 · os-support-ai · session_01WGufziG2t1d9cfRQJDrHkB --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent 8c29b81 commit d25d912

4 files changed

Lines changed: 582 additions & 34 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
---
2+
'@object-ui/console': patch
3+
'@objectstack/console': patch
4+
---
5+
6+
fix(console): the approvals inbox keeps its tab, filters, search and sort across a request's page and Back
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
Opening a request from the approvals inbox and pressing Back used to bring the inbox back on "My Pending" with every filter cleared: the tab, the status, process and object filters, the search text and the sort were held in component state only, and the inbox is rebuilt when the reader comes back. Someone working through "All" filtered to "Recalled" had to pick the tab and rebuild the filters after every request.
12+
13+
They now ride the inbox's address as page-scoped params: `scope` (the tab: `submitted` or `all`), `status`, `process`, `object`, `q` (the search text) and `sort` (`oldest` or `amount`). So Back, a reload and a copied link all reopen the inbox as the reader left it.
14+
15+
- A value at its default is left out, so an untouched inbox keeps a bare address.
16+
- Every change replaces the current history entry instead of adding one, so Back leaves the inbox rather than stepping through filter changes.
17+
- The search text reaches the address after the same short pause the server search already waited for. A search typed and opened at once is written before the request opens, so Back still returns to it.
18+
- A value the inbox does not offer (an unknown tab, sort or status, or a status on "My Pending", which has no status filter) reads as the default. A process or object the address names is checked once, when the first requests arrive, and is dropped only if those requests are the whole list (on "My Pending", or when the first page holds every request) and none of them carries it. On "Submitted by me" and "All", a value past the first page is kept and shown in its dropdown, so a filter picked after loading more pages survives Back, a reload and a copied link.
19+
- Switching tabs still clears the filters, search and sort, now in the address too. Other params are kept.
20+
- The `?request=` notification link still opens that request.
21+
22+
The tab rides `scope`, not `tab`, because `tab` is the console's reserved record-page tab param. Nothing to migrate.
Lines changed: 330 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,330 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* Approvals Inbox — the tab, the filters, the search and the sort survive a
5+
* request's page and Back (objectstack#36966).
6+
*
7+
* All of it lived in component state, so the queue's remount on Back reset it:
8+
* the inbox came back on "My Pending" with every filter cleared. It now rides
9+
* the address (`approvalsInboxUrlState.ts`), written with REPLACE.
10+
*
11+
* Pinned here, on the real page under a memory router with a stub request
12+
* page: the round trip (set → open a row → Back → restored), a reload of the
13+
* written address, the history it writes (one entry, not one per change),
14+
* values the address carries that the inbox does not offer, the tab change's
15+
* reset, and the `?request=` deep link.
16+
*/
17+
18+
import '@testing-library/jest-dom/vitest';
19+
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
20+
import { render, screen, cleanup, fireEvent, waitFor, within } from '@testing-library/react';
21+
import { MemoryRouter, Routes, Route, useLocation, useNavigate } from 'react-router-dom';
22+
23+
const APP = 'com.objectstack.account';
24+
const INBOX = `/apps/${APP}/system/approvals`;
25+
26+
const { approvalsApiStub, ADAPTER, AUTH, I18N, ROWS, listAll } = vi.hoisted(() => {
27+
const row = (id: string, status: string, process: string, object: string, title: string, at: string) => ({
28+
id,
29+
process_name: `flow:${process.toLowerCase().replace(/ /g, '_')}`,
30+
process_label: process,
31+
object_name: object,
32+
object_label: object === 'invoice' ? 'Invoice' : 'Expense',
33+
record_id: `${id}_rec`,
34+
record_title: title,
35+
status,
36+
pending_approvers: status === 'pending' ? ['u_1'] : [],
37+
submitter_id: 'u_2',
38+
submitter_name: 'Sam Submitter',
39+
submitted_at: at,
40+
updated_at: at,
41+
});
42+
const ROWS = [
43+
row('req_1', 'pending', 'Invoice Approval', 'invoice', 'INV-1001', '2026-11-04T09:00:00.000Z'),
44+
row('req_2', 'recalled', 'Expense Approval', 'expense', 'EXP-2002', '2026-11-03T09:00:00.000Z'),
45+
row('req_3', 'approved', 'Invoice Approval', 'invoice', 'INV-3003', '2026-11-02T09:00:00.000Z'),
46+
row('req_4', 'recalled', 'Invoice Approval', 'invoice', 'INV-4004', '2026-11-01T09:00:00.000Z'),
47+
];
48+
/** Every matching row in one page: the loaded rows are the whole answer. */
49+
const listAll = async (params?: Record<string, unknown>): Promise<{ data: unknown[]; total?: number }> => {
50+
if (params?.approverId) return { data: ROWS.filter((r) => r.status === 'pending') };
51+
// objectui#12608's environment count: nothing waits on anyone else here.
52+
if (params?.limit === 1) return { data: [], total: 0 };
53+
const q = typeof params?.q === 'string' ? params.q.toLowerCase() : '';
54+
const data = ROWS.filter((r) => (!params?.status || r.status === params.status)
55+
&& (!q || r.record_title.toLowerCase().includes(q)));
56+
return { data, total: data.length };
57+
};
58+
const approvalsApiStub = {
59+
listRequests: vi.fn(listAll),
60+
getRequest: vi.fn(async () => ({ data: undefined })),
61+
listActions: vi.fn(async () => ({ data: [] })),
62+
approve: vi.fn(async () => ({ data: undefined, finalized: true })),
63+
reject: vi.fn(async () => ({ data: undefined, finalized: true })),
64+
};
65+
const ADAPTER = { find: vi.fn(async () => ({ data: [] })) };
66+
const AUTH = { user: { id: 'u_1', email: 'approver@example.com' } };
67+
const I18N = {
68+
t: (key: string, options?: Record<string, unknown>) =>
69+
String(options?.defaultValue ?? key).replace(/\{\{(\w+)\}\}/g, (_, k) => String(options?.[k] ?? '')),
70+
language: 'en',
71+
};
72+
return { approvalsApiStub, ADAPTER, AUTH, I18N, ROWS, listAll };
73+
});
74+
75+
vi.mock('@object-ui/i18n', async (importOriginal) => ({
76+
...(await importOriginal<Record<string, unknown>>()),
77+
useObjectTranslation: () => I18N,
78+
}));
79+
80+
vi.mock('@object-ui/auth', async (importOriginal) => {
81+
const authFetch = vi.fn(async () => new Response('{}', { status: 200 }));
82+
return {
83+
...(await importOriginal<Record<string, unknown>>()),
84+
useAuth: () => AUTH,
85+
createAuthenticatedFetch: () => authFetch,
86+
TokenStorage: { get: () => null },
87+
};
88+
});
89+
90+
vi.mock('@object-ui/app-shell', async (importOriginal) => ({
91+
...(await importOriginal<Record<string, unknown>>()),
92+
useAdapter: () => ADAPTER,
93+
DeclaredActionsBar: () => null,
94+
isViaOverrideRow: () => false,
95+
}));
96+
97+
vi.mock('../../services/approvalsApi', async (importOriginal) => ({
98+
...(await importOriginal<Record<string, unknown>>()),
99+
approvalsApi: approvalsApiStub,
100+
}));
101+
102+
import { ApprovalsInboxPage } from './ApprovalsInboxPage';
103+
104+
/** The request page, reduced to what a round trip needs: where it is, and Back. */
105+
function RequestPageStub() {
106+
const location = useLocation();
107+
const navigate = useNavigate();
108+
return (
109+
<div>
110+
<output data-testid="request-page">{location.pathname}</output>
111+
<button type="button" onClick={() => navigate(-1)}>probe-back</button>
112+
</div>
113+
);
114+
}
115+
116+
/** Where the router is. */
117+
function LocationProbe() {
118+
const location = useLocation();
119+
return <output data-testid="where">{`${location.pathname}${location.search}`}</output>;
120+
}
121+
122+
function renderAt(entry: string) {
123+
return render(
124+
<MemoryRouter initialEntries={[entry]}>
125+
<LocationProbe />
126+
<Routes>
127+
<Route path="/apps/:appName/system/approvals" element={<ApprovalsInboxPage />} />
128+
<Route path="/apps/:appName/sys_approval_request/record/:recordId" element={<RequestPageStub />} />
129+
</Routes>
130+
</MemoryRouter>,
131+
);
132+
}
133+
134+
const where = () => screen.getByTestId('where').textContent ?? '';
135+
136+
/** The titles of the table's rows, in order. */
137+
function rowTitles(): string[] {
138+
const table = screen.queryByRole('table');
139+
if (!table) return [];
140+
return within(table).getAllByRole('row').slice(1)
141+
.map((tr) => ROWS.find((r) => tr.textContent?.includes(r.record_title))?.record_title ?? '?');
142+
}
143+
144+
function trigger(text: string | RegExp): HTMLElement {
145+
const el = screen.getAllByRole('combobox').find((c) =>
146+
typeof text === 'string' ? c.textContent?.includes(text) : text.test(c.textContent ?? ''));
147+
if (!el) throw new Error(`no select showing ${String(text)}`);
148+
return el;
149+
}
150+
151+
/** Pick an option the way a reviewer does. */
152+
async function choose(current: string, option: string): Promise<void> {
153+
fireEvent.pointerDown(trigger(current), { button: 0, ctrlKey: false, pointerType: 'mouse' });
154+
fireEvent.click(await screen.findByRole('option', { name: option }));
155+
}
156+
157+
function selectedTab(): string | undefined {
158+
return screen.getAllByRole('tab').find((t) => t.getAttribute('aria-selected') === 'true')?.textContent ?? undefined;
159+
}
160+
161+
beforeAll(() => {
162+
// Radix Select drives its trigger off pointer events, which happy-dom does
163+
// not implement — the same shim the components-side Select tests install.
164+
class MockPointerEvent extends Event {
165+
button: number;
166+
ctrlKey: boolean;
167+
pointerType: string;
168+
constructor(type: string, props: PointerEventInit = {}) {
169+
super(type, props);
170+
this.button = props.button ?? 0;
171+
this.ctrlKey = props.ctrlKey ?? false;
172+
this.pointerType = props.pointerType ?? 'mouse';
173+
}
174+
}
175+
Object.assign(window, { PointerEvent: MockPointerEvent });
176+
Object.assign(HTMLElement.prototype, {
177+
hasPointerCapture: vi.fn(),
178+
releasePointerCapture: vi.fn(),
179+
scrollIntoView: vi.fn(),
180+
});
181+
});
182+
183+
beforeEach(() => {
184+
for (const fn of Object.values(approvalsApiStub)) fn.mockClear();
185+
approvalsApiStub.listRequests.mockImplementation(listAll);
186+
});
187+
afterEach(cleanup);
188+
189+
describe('Approvals Inbox — the reading state survives a request page and Back (objectstack#36966)', () => {
190+
it('All + Recalled + object + sort + search → open a row → Back: the same tab, filters, search, sort and rows', async () => {
191+
renderAt(INBOX);
192+
await screen.findAllByText('INV-1001');
193+
194+
fireEvent.mouseDown(screen.getByRole('tab', { name: 'All' }), { button: 0 });
195+
await waitFor(() => expect(rowTitles()).toEqual(['INV-1001', 'EXP-2002', 'INV-3003', 'INV-4004']));
196+
await choose('All statuses', 'Recalled');
197+
await waitFor(() => expect(rowTitles()).toEqual(['EXP-2002', 'INV-4004']));
198+
await choose('All objects', 'Invoice');
199+
await choose('Newest first', 'Oldest first');
200+
// A search both recalled requests match, so the object select stays drawn.
201+
fireEvent.change(screen.getByPlaceholderText('Search record, process, requester…'), { target: { value: '00' } });
202+
await waitFor(() => expect(approvalsApiStub.listRequests).toHaveBeenCalledWith(
203+
expect.objectContaining({ q: '00', status: 'recalled' })));
204+
await waitFor(() => expect(rowTitles()).toEqual(['INV-4004']));
205+
206+
fireEvent.click(screen.getAllByRole('row').find((r) => r.textContent?.includes('INV-4004'))!);
207+
expect(await screen.findByTestId('request-page')).toHaveTextContent(`/apps/${APP}/sys_approval_request/record/req_4`);
208+
209+
fireEvent.click(screen.getByRole('button', { name: 'probe-back' }));
210+
await waitFor(() => expect(rowTitles()).toEqual(['INV-4004']));
211+
expect(selectedTab()).toBe('All');
212+
expect(trigger('Recalled')).toBeInTheDocument();
213+
expect(trigger('Invoice')).toBeInTheDocument();
214+
expect(trigger('Oldest first')).toBeInTheDocument();
215+
expect(screen.getByPlaceholderText('Search record, process, requester…')).toHaveValue('00');
216+
const params = new URL(where(), 'http://x').searchParams;
217+
expect(Object.fromEntries(params)).toEqual({
218+
scope: 'all', status: 'recalled', object: 'invoice', sort: 'oldest', q: '00',
219+
});
220+
});
221+
222+
it('a reload of the written address (a fresh mount) opens the same inbox, without waiting on a debounce', async () => {
223+
renderAt(`${INBOX}?scope=all&status=recalled&q=exp`);
224+
await waitFor(() => expect(rowTitles()).toEqual(['EXP-2002']));
225+
// The first server read already carries the address's query and status.
226+
const reads = approvalsApiStub.listRequests.mock.calls.map(([p]) => p).filter((p) => p?.limit === 50);
227+
expect(reads[0]).toMatchObject({ q: 'exp', status: 'recalled' });
228+
expect(selectedTab()).toBe('All');
229+
});
230+
231+
it('a search typed and opened within the debounce still comes back on Back', async () => {
232+
renderAt(`${INBOX}?scope=all`);
233+
await waitFor(() => expect(rowTitles()).toHaveLength(4));
234+
fireEvent.change(screen.getByPlaceholderText('Search record, process, requester…'), { target: { value: 'zzz' } });
235+
// Opened at once: the debounced write has not landed yet.
236+
fireEvent.click(screen.getAllByRole('row').find((r) => r.textContent?.includes('INV-3003'))!);
237+
await screen.findByTestId('request-page');
238+
fireEvent.click(screen.getByRole('button', { name: 'probe-back' }));
239+
await waitFor(() => expect(screen.getByPlaceholderText('Search record, process, requester…')).toHaveValue('zzz'));
240+
expect(new URL(where(), 'http://x').searchParams.get('q')).toBe('zzz');
241+
});
242+
243+
it('writes REPLACE: filter changes leave one history entry, so Back leaves the inbox', async () => {
244+
render(
245+
<MemoryRouter initialEntries={[`/apps/${APP}/home`, INBOX]} initialIndex={1}>
246+
<LocationProbe />
247+
<Routes>
248+
<Route path="/apps/:appName/home" element={<div>home-page</div>} />
249+
<Route path="/apps/:appName/system/approvals" element={<><ApprovalsInboxPage /><BackProbe /></>} />
250+
</Routes>
251+
</MemoryRouter>,
252+
);
253+
await screen.findAllByText('INV-1001');
254+
fireEvent.mouseDown(screen.getByRole('tab', { name: 'All' }), { button: 0 });
255+
await waitFor(() => expect(rowTitles()).toHaveLength(4));
256+
await choose('All statuses', 'Approved');
257+
await waitFor(() => expect(rowTitles()).toEqual(['INV-3003']));
258+
expect(where()).toBe(`${INBOX}?scope=all&status=approved`);
259+
260+
fireEvent.click(screen.getByRole('button', { name: 'inbox-back' }));
261+
expect(await screen.findByText('home-page')).toBeInTheDocument();
262+
});
263+
264+
it('values the inbox does not offer read as the defaults', async () => {
265+
renderAt(`${INBOX}?scope=bogus&status=approved&sort=sideways`);
266+
await screen.findAllByText('INV-1001');
267+
// An unknown tab is "My Pending"; a status there would hide rows behind a
268+
// control the tab does not draw, so it is not applied.
269+
expect(selectedTab()).toMatch(/^My Pending/);
270+
expect(rowTitles()).toEqual(['INV-1001']);
271+
expect(trigger('Newest first')).toBeInTheDocument();
272+
273+
cleanup();
274+
renderAt(`${INBOX}?scope=all&status=withdrawn`);
275+
await waitFor(() => expect(rowTitles()).toHaveLength(4));
276+
expect(trigger('All statuses')).toBeInTheDocument();
277+
const reads = approvalsApiStub.listRequests.mock.calls.map(([p]) => p).filter((p) => p?.limit === 50);
278+
expect(reads.every((p) => p?.status === undefined)).toBe(true);
279+
});
280+
281+
it('with every row loaded, a process or object no row carries reads as "all" and leaves the address; one a row carries is kept', async () => {
282+
renderAt(`${INBOX}?scope=all&object=gone_object&process=Expense%20Approval`);
283+
await waitFor(() => expect(new URL(where(), 'http://x').searchParams.get('object')).toBeNull());
284+
expect(new URL(where(), 'http://x').searchParams.get('process')).toBe('Expense Approval');
285+
await waitFor(() => expect(rowTitles()).toEqual(['EXP-2002']));
286+
});
287+
288+
it('on a paginated tab whose first page lacks them, a process and object the address names are kept, in the address and the controls', async () => {
289+
// Page 1 of 60: only invoice requests, so the expense filter sits past it.
290+
const page1 = ROWS.filter((r) => r.object_name === 'invoice' && r.status !== 'recalled');
291+
approvalsApiStub.listRequests.mockImplementation(async (params?: Record<string, unknown>) =>
292+
(params?.limit === 50 ? { data: page1, total: 60 } : listAll(params)));
293+
renderAt(`${INBOX}?scope=all&process=Expense%20Approval&object=expense`);
294+
295+
await waitFor(() => expect(approvalsApiStub.listRequests).toHaveBeenCalledWith(expect.objectContaining({ limit: 50 })));
296+
// The toolbar draws once the page lands; the filters show what is in force.
297+
expect(await screen.findByText('0 of 2')).toBeInTheDocument();
298+
expect(trigger('Expense Approval')).toBeInTheDocument();
299+
expect(trigger('expense')).toBeInTheDocument();
300+
// A drop would be a router write, which commits in a transition, a few
301+
// ticks after the page lands: give it time to land before reading.
302+
await new Promise((r) => setTimeout(r, 300));
303+
expect(Object.fromEntries(new URL(where(), 'http://x').searchParams)).toEqual({
304+
scope: 'all', process: 'Expense Approval', object: 'expense',
305+
});
306+
expect(trigger('Expense Approval')).toBeInTheDocument();
307+
});
308+
309+
it('changing tab clears the filters, search and sort from the address and keeps every other param', async () => {
310+
renderAt(`${INBOX}?scope=all&status=recalled&object=invoice&sort=oldest&q=inv&keep=1`);
311+
await waitFor(() => expect(rowTitles()).toEqual(['INV-4004']));
312+
fireEvent.mouseDown(screen.getByRole('tab', { name: 'Submitted by me' }), { button: 0 });
313+
await waitFor(() => expect(where()).toBe(`${INBOX}?scope=submitted&keep=1`));
314+
expect(screen.getByPlaceholderText('Search record, process, requester…')).toHaveValue('');
315+
fireEvent.mouseDown(screen.getByRole('tab', { name: /^My Pending/ }), { button: 0 });
316+
await waitFor(() => expect(where()).toBe(`${INBOX}?keep=1`));
317+
});
318+
319+
it('the ?request= deep link still opens the request, whatever inbox state rides beside it', async () => {
320+
renderAt(`${INBOX}?request=req_2&scope=all&status=recalled`);
321+
expect(await screen.findByTestId('request-page')).toHaveTextContent(`/apps/${APP}/sys_approval_request/record/req_2`);
322+
// The deep link replaced itself: it drew no queue and read no list.
323+
expect(approvalsApiStub.listRequests).not.toHaveBeenCalled();
324+
});
325+
});
326+
327+
function BackProbe() {
328+
const navigate = useNavigate();
329+
return <button type="button" onClick={() => navigate(-1)}>inbox-back</button>;
330+
}

0 commit comments

Comments
 (0)