Skip to content

Commit 4eeb174

Browse files
fix(app-shell): refuse a toolbar flow's row count before its dialog, and translate the newTabUrl refusal (objectui#13397) (#13428)
Closes #13397 Clause-②: no ## What changed A record-scoped `type: 'flow'` action launched from a list toolbar with 0 or 2+ rows selected is now refused before its param dialog opens. The toast is in the session's language and nothing is sent. With exactly one row the flow behaves as before. This is the flow-action half that objectui#13384 (PR #13395) left out. - **`useConsoleActionRuntime` `flowHandler`**: the registered handler now carries `refuseBeforeInput`, the optional `ActionRunnerHandler` member from PR #13395. It is `serverActionHandler`'s own member: core's `createServerActionHandler` builds it and the console wrapper forwards it. That handler is built in this hook with no `resolveRecordId`, so the member runs `resolveServerActionRecordId`, the resolver the flow dispatch already runs. It also skips an action whose dialog itself collects `recordId`. No second copy of the rule is written. The dispatch itself is renamed `flowDispatch`. `flowHandler` wraps it in a `useMemo` with the member attached. - **Dispatch-time refusal**: a direct `flowHandler` call refused by the resolver now shows the refusal through its `errorKey` (`t(errorKey, { defaultValue: error })`), with the English as fallback for an empty answer. These are the same pack keys the runner's translator reads for the early refusal. - **`createConsoleServerActionHandler` `newTabUrl` fast path**: - The "no record id available" refusal moves to a pack key, `console.serverAction.noRecordId`, through the wrapper's existing `t`. - The resolver's own refusal on that path is shown through its `errorKey` too. - With no `t`, both stay English, as before. - **`@object-ui/i18n`**: `console.serverAction.noRecordId` is added to all ten packs, each with its own translation. - The `ConsoleActionRuntime.flowHandler` type now also declares `refuseBeforeInput`, as `Pick` of `ServerActionHandler`. - One changeset: app-shell and i18n, patch. ## Tests Run on head `90f61b9e7c`: - `pnpm exec vitest run --maxWorkers=2` over every test file that names `flowHandler`, `refuseBeforeInput`, `resolveServerActionRecordId`, `newTabUrl` or `consoleServerAction` (git grep: 28 files outside i18n), plus all of `packages/i18n/` (the key-parity suites included). Result: **114/114 files, 1713 passed, 13 skipped**. - New `useConsoleActionRuntime.flowRowGuard-13397.test.tsx`. The session reads zh-CN: the translator answers from the shipped zh pack. - `flowHandler.refuseBeforeInput`, 0 and 2 rows: it returns the resolver's `error` with `actions.selectRowFirst` / `actions.selectExactlyOneRow`. With 1 row it returns nothing. - Controls: an object-level toolbar flow with 0 rows is not refused. A dialog that collects `recordId` is not judged early. - Through `ConsoleActionRuntimeProvider` and a real runner, 0 and 2 rows: no param dialog opens, and no request is sent. The toast reads `此操作针对单条记录,请先选择一行。` / `此操作针对单条记录,请只选择一行。`. - 1 row: the dialog opens, as today. Control: an object-level toolbar flow with 0 rows still opens its dialog. - A direct call with 0 and 2 rows returns the zh-CN refusal, and nothing is sent. - `consoleServerAction.test.tsx`, a new `newTabUrl` block: - No record id: the refusal reads `此操作针对单条记录,但没有可用的记录 ID。` and no tab opens. Control: with no `t` it stays English. - 2 rows: the resolver's refusal reads zh-CN. Control: 1 row still opens the tab. - New `consoleNoRecordId-13397.test.ts` (i18n): pins the zh-CN and en text. Every other pack defines the key with its own text. - Type-check, `NODE_OPTIONS=--max-old-space-size=8192 pnpm exec turbo run type-check --concurrency=2 --filter=@object-ui/app-shell --filter=@object-ui/i18n`: 31/31 tasks. That includes `tsc -p tsconfig.test.json` for both packages. The test-file tsconfig was re-run on the final head. - `pnpm check:i18n-keys`, `check:i18n-drift`, `check:i18n-dead-keys`: exit 0. - eslint on the touched files: 0 errors. No warning is added: the counts match `origin/main` for the two edited files that had warnings, and the new test files have none. - `check:new-line-citations`: 0 new. `check-changeset-presence`: pass. ### Ablation Each run used `ablation-replace` with on-disk proof, and was restored to `git diff HEAD` empty. Each ran the new flow suite, `consoleServerAction.test.tsx` and `useConsoleActionRuntime.test.tsx` (92 tests). | Mutation | Result | |---|---| | `flowHandler`'s `refuseBeforeInput` set to `undefined` | 4 red: both member cases (0 and 2 rows) and both end-to-end cases (0 and 2 rows). The 1-row and control cases stay green. | | Dispatch-time `errorKey` translation dropped in `flowDispatch` | 2 red (the direct-call cases, 0 and 2 rows) | | `newTabUrl` "no record id" back to the hard-coded English | 1 red (the zh-CN case). The English control stays green. | | `newTabUrl` resolver refusal shown without its `errorKey` | 1 red | ## Acceptance notes - **Judgment call**: the flow member reuses `serverActionHandler.refuseBeforeInput` rather than calling core directly. Core's `collectsRecordIdParam` is not exported, and core is outside this card's surface. Reusing the member keeps one copy of the rule. The coupling holds while this hook builds `serverActionHandler` with no `resolveRecordId`. The member pins in the new suite compare the flow's answer with `resolveServerActionRecordId`'s, so a change there goes red. - **Out of scope, still open**: core's own dispatch-time refusal (`createServerActionHandler`, for a caller that invokes the handler directly, outside the runner) still returns the English `error`, because its result carries no `errorKey`. Through the runner it is never reached for a row-count refusal, because the early refusal comes first. Carrier: none. - `RecordDetailView`'s copy of the flow handler is not touched. It resolves against its own record, so a row count never applies there. - [x] Adds no product-specific widget, dialog, hook or string (see AGENTS.md › Product-neutral renderer) 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01WJozybDmRH8z2c5SD7vJkj --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent b317942 commit 4eeb174

16 files changed

Lines changed: 382 additions & 8 deletions

File tree

‎.changeset/13397-flow-row-guard.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@object-ui/i18n': patch
3+
'@object-ui/app-shell': patch
4+
---
5+
6+
A record-scoped flow action launched from a list toolbar with 0 or several rows selected is refused before its param dialog opens, and its refusal is translated (objectui#13397).
7+
8+
The console's `flowHandler` now carries `refuseBeforeInput`, the early refusal objectui#13384 gave the `script` handler, answered by the same resolver its dispatch runs. The runner asks it before the confirmation and the param dialog, so "select a row first" and "select exactly one row" show in the session's language before the user fills anything in, and nothing is sent. With exactly one row the flow behaves as before. A direct call that is refused at dispatch time is shown through the refusal's pack key too.
9+
10+
The console server-action wrapper's `newTabUrl` refusal ("no record id available") now has a pack key, `console.serverAction.noRecordId`, defined in every shipped pack, and the wrapper's fast path shows the resolver's own refusal through its pack key.
Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
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+
* objectui#13397 — a record-scoped `type: 'flow'` action launched from a list
11+
* toolbar with a row count other than 1 is refused BEFORE its param dialog,
12+
* with a translated toast and no request. objectui#13384 gave the `script`
13+
* handler that early refusal (`refuseBeforeInput`); the console `flowHandler`
14+
* ran the same resolver only at dispatch time, after the whole dialog, and
15+
* showed its English `error`.
16+
*
17+
* The session here reads zh-CN: the translator answers from the shipped zh
18+
* pack, so a refusal that reaches the toast untranslated reads English and
19+
* fails the text pin.
20+
*/
21+
22+
import { describe, it, expect, beforeEach, vi } from 'vitest';
23+
import { render, screen, fireEvent, waitFor, renderHook, act } from '@testing-library/react';
24+
import React from 'react';
25+
26+
const navigateSpy = vi.fn();
27+
vi.mock('react-router-dom', () => ({ useNavigate: () => navigateSpy }));
28+
29+
const authFetchSpy = vi.fn();
30+
vi.mock('@object-ui/auth', async (importOriginal) => ({
31+
...(await importOriginal<Record<string, unknown>>()),
32+
useAuth: () => ({ user: { id: 'u1', name: 'User', image: null }, activeOrganization: null }),
33+
createAuthenticatedFetch: () => authFetchSpy,
34+
}));
35+
36+
vi.mock('@object-ui/i18n', async (importOriginal) => {
37+
const { builtInLocales } = await import('@object-ui/i18n/locales');
38+
// The zh-CN pack, read by dotted key; a key it lacks answers its default.
39+
const zhT = (key: string, options?: { defaultValue?: string }) => {
40+
const hit = key.split('.').reduce<unknown>(
41+
(node, part) => (node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined),
42+
builtInLocales.zh,
43+
);
44+
return typeof hit === 'string' ? hit : String(options?.defaultValue ?? key);
45+
};
46+
return {
47+
...(await importOriginal<Record<string, unknown>>()),
48+
useObjectLabel: () => ({
49+
fieldLabel: (_o: unknown, _n: unknown, l: string) => l,
50+
fieldOptionLabel: (_o: unknown, _f: unknown, _v: unknown, l: string) => l,
51+
actionParamText: (_o: unknown, _a: unknown, _p: unknown, _attr: unknown, fallback: string) => fallback,
52+
actionParamOptionLabel: (_o: unknown, _a: unknown, _p: unknown, _v: unknown, fallback: string) => fallback,
53+
actionDescription: (_o: unknown, _a: unknown, fallback: string) => fallback,
54+
}),
55+
useObjectTranslation: () => ({ t: zhT, language: 'zh' }),
56+
};
57+
});
58+
59+
vi.mock('../useActionModal', () => ({
60+
useActionModal: () => ({
61+
modalHandler: vi.fn(async () => ({ success: true })),
62+
modalElement: null,
63+
closeModal: () => {},
64+
resolveModalTarget: vi.fn(async () => null),
65+
}),
66+
}));
67+
68+
// The param dialog renders a marker while it is open — the "did a dialog open"
69+
// probe. The other dialogs stay inert.
70+
vi.mock('../../views/ActionParamDialog', () => ({
71+
ActionParamDialog: ({ state }: { state: { open?: boolean } }) =>
72+
state?.open ? <div data-testid="param-dialog" /> : null,
73+
}));
74+
vi.mock('../../views/ActionConfirmDialog', () => ({ ActionConfirmDialog: () => null }));
75+
vi.mock('../../views/ActionResultDialog', () => ({ ActionResultDialog: () => null }));
76+
vi.mock('../../views/FlowRunner', () => ({ FlowRunner: () => null }));
77+
78+
vi.mock('sonner', () => ({ toast: Object.assign(vi.fn(), { error: vi.fn(), success: vi.fn() }) }));
79+
80+
import { toast } from 'sonner';
81+
import { useConsoleActionRuntime, ConsoleActionRuntimeProvider } from '../useConsoleActionRuntime';
82+
import { useAction } from '@object-ui/react';
83+
import { resolveServerActionRecordId, type ActionContext, type ActionDef } from '@object-ui/core';
84+
85+
const ZH_SELECT_ROW_FIRST = '此操作针对单条记录,请先选择一行。';
86+
const ZH_SELECT_EXACTLY_ONE_ROW = '此操作针对单条记录,请只选择一行。';
87+
88+
/** A record-scoped flow with a param dialog, mounted on rows AND the toolbar. */
89+
const REASSIGN = {
90+
type: 'flow',
91+
name: 'reassign',
92+
target: 'reassign_wizard',
93+
locations: ['list_item', 'list_toolbar'],
94+
params: [{ name: 'owner', label: 'Owner', type: 'text', required: true }],
95+
};
96+
const launch = (extra: Record<string, unknown> = {}): ActionDef => ({ ...JSON.parse(JSON.stringify(REASSIGN)), ...extra });
97+
const rowsContext = (rows: Record<string, unknown>[]): ActionContext => ({ selectedRecords: rows });
98+
const toastError = vi.mocked(toast.error);
99+
100+
beforeEach(() => {
101+
authFetchSpy.mockReset();
102+
toastError.mockClear();
103+
vi.mocked(toast.success).mockClear();
104+
});
105+
106+
describe('flowHandler.refuseBeforeInput — the resolver its dispatch runs (objectui#13397)', () => {
107+
const runtime = () => renderHook(() => useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' })).result.current;
108+
109+
it.each([
110+
['0 rows', [] as Record<string, unknown>[], 'actions.selectRowFirst'],
111+
['2 rows', [{ id: 'a' }, { id: 'b' }], 'actions.selectExactlyOneRow'],
112+
])('%s: answers the resolver\'s refusal with its pack key', (_label, rows, errorKey) => {
113+
const context = rowsContext(rows);
114+
const rule = resolveServerActionRecordId(launch(), context);
115+
116+
expect(runtime().flowHandler.refuseBeforeInput?.(launch(), context)).toEqual({ error: rule.error, errorKey });
117+
});
118+
119+
it('1 row: no refusal', () => {
120+
expect(runtime().flowHandler.refuseBeforeInput?.(launch(), rowsContext([{ id: 'a' }])))
121+
.toBeUndefined();
122+
});
123+
124+
it('control: an object-level toolbar flow with 0 rows is not refused', () => {
125+
expect(runtime().flowHandler.refuseBeforeInput?.(
126+
launch({ locations: ['list_toolbar'] }),
127+
rowsContext([]),
128+
)).toBeUndefined();
129+
});
130+
131+
it('control: a dialog that itself collects `recordId` is not judged before it runs', () => {
132+
const collectsRecordId = launch({ params: [{ name: 'recordId', label: 'Record', type: 'text' }] });
133+
134+
expect(runtime().flowHandler.refuseBeforeInput?.(collectsRecordId, rowsContext([])))
135+
.toBeUndefined();
136+
});
137+
});
138+
139+
describe('a toolbar flow launch through the console runtime (objectui#13397)', () => {
140+
function Probe({ rows, action }: { rows: Record<string, unknown>[]; action: ActionDef }) {
141+
const { execute, updateContext } = useAction();
142+
return (
143+
<button
144+
onClick={() => {
145+
updateContext({ selectedRecords: rows });
146+
void execute(action);
147+
}}
148+
>
149+
run-flow
150+
</button>
151+
);
152+
}
153+
const mount = (rows: Record<string, unknown>[], action: ActionDef = launch()) => {
154+
render(
155+
<ConsoleActionRuntimeProvider dataSource={{}} objects={[]} objectName="inv">
156+
<Probe rows={rows} action={action} />
157+
</ConsoleActionRuntimeProvider>,
158+
);
159+
fireEvent.click(screen.getByText('run-flow'));
160+
};
161+
162+
it.each([
163+
['0 rows', [] as Record<string, unknown>[], ZH_SELECT_ROW_FIRST],
164+
['2 rows', [{ id: 'a' }, { id: 'b' }], ZH_SELECT_EXACTLY_ONE_ROW],
165+
])('%s: refused before the param dialog, with a zh-CN toast and no request', async (_label, rows, zh) => {
166+
mount(rows);
167+
168+
await waitFor(() => expect(toastError).toHaveBeenCalledWith(zh));
169+
expect(screen.queryByTestId('param-dialog')).toBeNull();
170+
expect(authFetchSpy).not.toHaveBeenCalled();
171+
});
172+
173+
it('1 row: the param dialog opens, as today, and nothing is refused', async () => {
174+
mount([{ id: 'rec_1' }]);
175+
176+
await screen.findByTestId('param-dialog');
177+
expect(toastError).not.toHaveBeenCalled();
178+
expect(authFetchSpy).not.toHaveBeenCalled();
179+
});
180+
181+
it('control: an object-level toolbar flow with 0 rows still opens its dialog', async () => {
182+
mount([], launch({ locations: ['list_toolbar'] }));
183+
184+
await screen.findByTestId('param-dialog');
185+
expect(toastError).not.toHaveBeenCalled();
186+
});
187+
});
188+
189+
describe('flowHandler called directly: the dispatch-time refusal is translated (objectui#13397)', () => {
190+
it.each([
191+
['0 rows', [] as Record<string, unknown>[], ZH_SELECT_ROW_FIRST],
192+
['2 rows', [{ id: 'a' }, { id: 'b' }], ZH_SELECT_EXACTLY_ONE_ROW],
193+
])('%s: refuses in zh-CN through the pack key, with no request', async (_label, rows, zh) => {
194+
const { result } = renderHook(() => useConsoleActionRuntime({ dataSource: {}, objects: [], objectName: 'inv' }));
195+
196+
let res: unknown;
197+
await act(async () => {
198+
res = await result.current.flowHandler(launch({ params: {} }), rowsContext(rows));
199+
});
200+
201+
expect(res).toEqual({ success: false, error: zh });
202+
expect(authFetchSpy).not.toHaveBeenCalled();
203+
});
204+
});

‎packages/app-shell/src/hooks/useConsoleActionRuntime.tsx‎

Lines changed: 51 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import type {
3737
NavigationHandler,
3838
ParamCollectionHandler,
3939
ResultDialogHandler,
40+
ServerActionHandler,
4041
ToastHandler,
4142
} from '@object-ui/core';
4243
import { actionErrorDetail, captureUpdateUndoData, resolveRecordIdParamSeed, resolveServerActionRecordId } from '@object-ui/core';
@@ -92,7 +93,14 @@ export interface ConsoleActionRuntime {
9293
// narrower restatement that nothing could catch while the tests calling it
9394
// with two arguments were unchecked (objectui#4040).
9495
apiHandler: (action: ActionDef, context?: ActionContext) => Promise<ActionResult>;
95-
flowHandler: (action: ActionDef, context?: ActionContext) => Promise<ActionResult>;
96+
/**
97+
* Carries `refuseBeforeInput` (objectui#13397), so the runner refuses a
98+
* single-record flow launched with 0 or several rows selected before its
99+
* param dialog opens — the member `serverActionHandler` carries since
100+
* objectui#13384, answered by the same resolver.
101+
*/
102+
flowHandler: ((action: ActionDef, context?: ActionContext) => Promise<ActionResult>)
103+
& Pick<ServerActionHandler, 'refuseBeforeInput'>;
96104
serverActionHandler: (action: ActionDef, context?: ActionContext) => Promise<ActionResult>;
97105
/** `type: 'modal'` — opens `target` as a page/object form, else runs the action server-side. */
98106
modalActionHandler: (action: ActionDef, context?: ActionContext) => Promise<ActionResult>;
@@ -636,8 +644,11 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons
636644
*
637645
* `context` is the shared ActionRunner context (registered handlers are
638646
* invoked as `handler(action, runnerContext)`).
647+
*
648+
* This is the dispatch only; the registered `flowHandler` below wraps it
649+
* with the early row-count refusal (objectui#13397).
639650
*/
640-
const flowHandler = useCallback(async (action: ActionDef, context?: ActionContext): Promise<ActionResult> => {
651+
const flowDispatch = useCallback(async (action: ActionDef, context?: ActionContext): Promise<ActionResult> => {
641652
const flowName = action.target || action.name;
642653
if (!flowName) {
643654
return { success: false, error: 'No flow target provided for flow action' };
@@ -659,8 +670,20 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons
659670
// ID"); a pure object-level toolbar flow keeps triggering with no record.
660671
// This handler used to hold a second copy of that rule, worded for flows.
661672
// ⛔ Never re-add one here: a rule written twice drifts.
673+
//
674+
// A launch through the runner is refused before its dialog by
675+
// `flowHandler.refuseBeforeInput` below; this check stays for a caller
676+
// that invokes the handler directly. Its refusal is shown through its
677+
// pack key, as the runner shows the early one (objectui#13397), with
678+
// the English source as the default and the fallback for an empty
679+
// answer.
662680
const resolution = resolveServerActionRecordId(action, context);
663-
if (resolution.error) return { success: false, error: resolution.error };
681+
if (resolution.error) {
682+
const error = resolution.errorKey
683+
? String(t(resolution.errorKey, { defaultValue: resolution.error })) || resolution.error
684+
: resolution.error;
685+
return { success: false, error };
686+
}
664687
const recordId = resolution.recordId;
665688
if (recordId != null && params.recordId == null) params.recordId = recordId;
666689
// Ask the store for the object type BEFORE the lookup, as the param
@@ -710,7 +733,7 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons
710733
} catch (error) {
711734
return { success: false, error: (error as Error).message };
712735
}
713-
}, [authFetch, objApiName, objects, metadata, refresh, i18n, language]);
736+
}, [authFetch, objApiName, objects, metadata, refresh, i18n, language, t]);
714737

715738
// Server-side action handler — POST /api/v1/actions/{object}/{action}, built
716739
// from @object-ui/core's `createServerActionHandler` via the shared console
@@ -746,6 +769,30 @@ export function useConsoleActionRuntime(opts: ConsoleActionRuntimeOptions): Cons
746769
[authFetch],
747770
);
748771

772+
/**
773+
* The registered flow handler: {@link flowDispatch}, plus the early
774+
* row-count refusal the runner asks before its confirmation and param
775+
* dialog (`ActionRunnerHandler`'s `refuseBeforeInput`, objectui#13397).
776+
* Without it a single-record flow launched from a list toolbar with 0 or
777+
* several rows ran its whole param dialog and was refused only after
778+
* Confirm, in English.
779+
*
780+
* The member is `serverActionHandler`'s own — core's
781+
* `createServerActionHandler` builds it (objectui#13384) and the console
782+
* wrapper forwards it. That handler is built here with no `resolveRecordId`,
783+
* so its member runs `resolveServerActionRecordId`, the resolver
784+
* `flowDispatch` runs, and skips an action whose dialog itself collects
785+
* `recordId`. ⛔ Never write a flow copy of that rule: a rule written twice
786+
* drifts.
787+
*/
788+
const flowHandler = useMemo(
789+
() => Object.assign(
790+
(action: ActionDef, context?: ActionContext) => flowDispatch(action, context),
791+
{ refuseBeforeInput: serverActionHandler.refuseBeforeInput },
792+
),
793+
[flowDispatch, serverActionHandler],
794+
);
795+
749796
// Client-side modal transport, shared with RecordDetailView so a
750797
// `type: 'modal'` action behaves the SAME on a list page, an SDUI page, a
751798
// declared-actions bar and a record page. Before this, only RecordDetailView

‎packages/app-shell/src/utils/__tests__/consoleServerAction.test.tsx‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ vi.mock('sonner', () => {
2121
});
2222

2323
import { toast } from 'sonner';
24-
import { ActionRunner } from '@object-ui/core';
24+
import { ActionRunner, type ActionDef } from '@object-ui/core';
25+
import { builtInLocales } from '@object-ui/i18n/locales';
2526
import { createConsoleServerActionHandler } from '../consoleServerAction';
2627

2728
/** A pre-openable tab stub with the surface the wrapper drives. */
@@ -492,3 +493,55 @@ describe('the early record-id refusal is forwarded to the runner (objectui#13384
492493
});
493494
});
494495
});
496+
497+
describe('the newTabUrl fast path refuses in the session language (objectui#13397)', () => {
498+
// The zh-CN pack as the wrapper's `t`, read by dotted key; a key it lacks
499+
// answers the English default, as `useObjectTranslation().t` does.
500+
const zhT = (key: string, englishDefault: string) => {
501+
const hit = key.split('.').reduce<unknown>(
502+
(node, part) => (node && typeof node === 'object' ? (node as Record<string, unknown>)[part] : undefined),
503+
builtInLocales.zh,
504+
);
505+
return typeof hit === 'string' ? hit : englishDefault;
506+
};
507+
const SSO: ActionDef = { type: 'script', name: 'sso_as_owner', opensInNewTab: true, newTabUrl: '/sso-open/{recordId}' };
508+
509+
it('no resolvable record id: the refusal reads zh-CN, with no tab', async () => {
510+
const openSpy = vi.spyOn(window, 'open');
511+
const { handler, fetch } = makeHandler({ t: zhT });
512+
513+
const res = await handler({ ...SSO });
514+
515+
expect(res).toEqual({ success: false, error: '此操作针对单条记录,但没有可用的记录 ID。' });
516+
expect(openSpy).not.toHaveBeenCalled();
517+
expect(fetch).not.toHaveBeenCalled();
518+
});
519+
520+
it('control: with no `t` the same refusal stays English', async () => {
521+
const { handler } = makeHandler();
522+
523+
expect(await handler({ ...SSO })).toEqual({
524+
success: false,
525+
error: 'This action runs on a single record — no record id available.',
526+
});
527+
});
528+
529+
it("the resolver's own refusal reads zh-CN through its pack key, with no tab", async () => {
530+
const openSpy = vi.spyOn(window, 'open');
531+
const { handler } = makeHandler({ t: zhT });
532+
533+
const res = await handler({ ...SSO }, { selectedRecords: [{ id: 'a' }, { id: 'b' }] });
534+
535+
expect(res).toEqual({ success: false, error: '此操作针对单条记录,请只选择一行。' });
536+
expect(openSpy).not.toHaveBeenCalled();
537+
});
538+
539+
it('control: with one row the fast path still opens the tab', async () => {
540+
const tab = makeTab();
541+
vi.spyOn(window, 'open').mockReturnValue(tab);
542+
const { handler } = makeHandler({ t: zhT });
543+
544+
expect(await handler({ ...SSO }, { selectedRecords: [{ id: 'e1' }] })).toEqual({ success: true });
545+
expect(tab.location.href).toBe('https://api.test/sso-open/e1');
546+
});
547+
});

0 commit comments

Comments
 (0)