Skip to content

Commit 3a08833

Browse files
fix(plugin-approvals): word the record-lock refusal in the writer's locale (#34449)
Fixes #34060 Clause-②: no Metadata-protocol: none ## 维护者速读 - 改了什么:审批锁定记录时的拒绝提示(409 RECORD_LOCKED)改为按请求语言输出,中文用户看到「项目「华东仓储客服平台实施」正在审批中,已被锁定,审批完成前无法编辑」。 - 为什么改:其它记录拒绝提示早已按请求语言返回,唯独这句永远是英文,用户在被拦住的那一刻读不懂原因。 - 风险与回滚:只换句子,错误码、409、`RECORD_LOCKED: ` 前缀和英文原句逐字不变;回滚即还原本 PR。 - 先看:`packages/plugins/plugin-approvals/src/lifecycle-hooks.ts`(`recordLockRefusal` 与 `refusalLocalization`)、`packages/spec/src/system/operation-message.ts`(四个新键的四种语言文案)、`packages/plugins/plugin-approvals/src/approvals-plugin.ts`(把 i18n 服务传给锁钩子)。 - 两分钟验证:`pnpm --filter @objectstack/plugin-approvals exec vitest run src/record-lock-user-facing-message.test.ts`,预期全部通过,其中 zh-CN 用例断言中文句子。 - 需要你做的:无,席位落地。 ## What changes The approval record lock's per-row refusal is rendered through the shared Operation Message Catalog (`renderOperationMessage`, `@objectstack/spec/system`), the catalog the record door's other refusals already use (`record_write_denied`, `record_access_denied`, and this plugin's own `approval_recall_not_submitter`). No new mechanism. - `packages/spec/src/system/operation-message.ts`: four keys, one wire code, picked by what the hook has in hand: `record_locked` (`{{object}}` and `{{title}}`), `record_locked_untitled` (`{{object}}`), `record_locked_unlabeled` (`{{title}}`) and `record_locked_opaque` (nothing). They ship in every locale the catalog carries (`en`, `zh-CN`, `ja-JP`, `es-ES`), the same set as the sibling record-door refusals. English is byte-identical to the old template literal. - `lifecycle-hooks.ts`: `recordLockRefusal` picks the key and passes the label and title as parameters. The locale is `HookContext.session.locale`, which the engine copies from the request envelope. The object label is `objects.OBJECT.label` in that locale, read through the plugin's existing `readerLabelsFor` (negotiated, so a bare `zh` reaches `zh-CN`). It falls back to the declared label and never to the API name. A deployment `errors.record_locked*` override wins, as for every catalog key. - `approvals-plugin.ts`: `bindApprovalLockHook` takes the lazily read `i18n` service as a new optional fourth parameter. Absent, the built-in catalog still answers in the writer's locale. - Unchanged: `code: RECORD_LOCKED`, `statusCode: 409`, the `RECORD_LOCKED: ` prefix, the error's own property set, and the three operator-facing lock refusals. - Changeset: patch for `@objectstack/plugin-approvals` and `@objectstack/spec`. ## Tests - `record-lock-user-facing-message.test.ts`: a new top-level describe on the real rig (ObjectQL, sqlite, real hook). It covers zh-CN titled and untitled, a bare `zh`, en-US, an unknown `xx-YY` falling back to English, no locale, no i18n service, a deployment override, and a throwing i18n service. Each case asserts `code`, `statusCode` 409, the prefix, and that nothing reached the store. - `record-lock-batch-row-status.integration.test.ts`: the bulk-row path through the real `updateManyData` and `batchData` upsert loops. The zh-CN row carries the Chinese sentence and the en-US row carries the existing English sentence. Both rows keep `code` and `httpStatus` 409. - `operation-message.test.ts`: a new top-level describe. Every locale defines the four keys with exactly their placeholders, the English is byte-identical, and an unknown locale falls back to `en`. ## Acceptance notes - The re-measure used a throwaway REST-level boot (`bootStack`, real approvals and trigger plugins, a locking approval flow, a zh-CN pack labelling the object 项目). It was run on main and on this branch and is not committed. - `check:platform-checklist` (red on main before #34435) is not among this diff's derived gates. #34435 is in this branch's base, a121e29. ## Verification <details><summary>Re-measure on main a121e29 (REST, Accept-Language)</summary> ```text PATCH zh-CN -> 409 {"error":"Project '华东仓储客服平台实施' is locked while an approval is in progress, and cannot be edited until that approval is complete","code":"RECORD_LOCKED",...} updateMany zh-CN -> 207 ... "message":"RECORD_LOCKED: Project '华东仓储客服平台实施' is locked while an approval is in progress, ...","httpStatus":409 PATCH en-US -> 409 (same English sentence) PATCH xx-YY -> 409 (same English sentence) ``` </details> <details><summary>Same boot on this branch</summary> ```text PATCH zh-CN -> 409 {"error":"项目「华东仓储客服平台实施」正在审批中,已被锁定,审批完成前无法编辑","code":"RECORD_LOCKED","object":"m34060_project"} updateMany zh-CN -> 207 ... {"code":"RECORD_LOCKED","message":"RECORD_LOCKED: 项目「华东仓储客服平台实施」正在审批中,已被锁定,审批完成前无法编辑","httpStatus":409} PATCH en-US -> 409 {"error":"Project '华东仓储客服平台实施' is locked while an approval is in progress, and cannot be edited until that approval is complete","code":"RECORD_LOCKED",...} PATCH xx-YY -> 409 (English, as en-US) updateMany en-US / xx-YY -> 207, row 409, English sentence ``` </details> <details><summary>Ablation (one-off, not committed)</summary> `node scripts/ablation-replace.mjs` replaced the hook's `locale` argument to `recordLockRefusal` with `undefined` (anchor 1 -> 0, blob 4278df5 -> 297b98bb7ab7). It then ran both plugin test files: **7 failed | 14 passed**. All seven were the zh/zh-CN cases plus the batch-row locale case. The English cases stayed green, as expected. The subject is imported from `src` by relative path, so no rebuild was needed. Restore: blob == HEAD (4278df5) and `git diff HEAD` empty. </details> <details><summary>Local test and gate readings at head b5c0292</summary> - `pnpm --filter @objectstack/plugin-approvals exec vitest run --maxWorkers=2`: Test Files 121 passed (121), Tests 1714 passed (1714). - `pnpm --filter @objectstack/spec exec vitest run --maxWorkers=2 src/system/operation-message.test.ts`: Tests 50 passed (50). - `pnpm --filter @objectstack/plugin-approvals typecheck` (includes `check:test-typecheck`): exit 0. `pnpm --filter @objectstack/spec typecheck`: exit 0. - `node scripts/pm/dispatch-gates.mjs --commands`: 93 commands, run in this worktree at b5c0292. 91 exited 0 on the first pass. Two first answered PREREQUISITE NOT MET (exit 3): `check:dual-build-cjs-loads` (no `dist/` yet) and `check:type-check-debt` (verify-lock queue timeout). Both were re-run: `check:type-check-debt` under the lock gave exit 0 (128/131 type-checked, 0 in DEBT), and `check:dual-build-cjs-loads` after the full build gave exit 0 (124 entry points across 72 packages load). - `node scripts/pm/dispatch-gates.mjs --ran`: 93 derived, 93 run, 0 NOT-MEASURED, 0 UNRUN. </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01FEkQ5kgF3mo9f7LXuv5hac)_ <!-- signed: repo:objectstack#1 · os-project-manager · session_01FEkQ5kgF3mo9f7LXuv5hac --> --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent d5e6b20 commit 3a08833

7 files changed

Lines changed: 360 additions & 10 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/plugin-approvals': patch
3+
'@objectstack/spec': patch
4+
---
5+
6+
fix(plugin-approvals): the record-lock refusal is worded in the writer's locale
7+
8+
Clause-②: no
9+
Metadata-protocol: none
10+
11+
A user who saved a record held by an approval in progress was refused `409 RECORD_LOCKED` with an English sentence in every locale, while the other refusals on the same request answered in the request locale. A zh-CN writer read `Project '华东仓储客服平台实施' is locked while an approval is in progress, and cannot be edited until that approval is complete`.
12+
13+
The sentence is now rendered through the shared Operation Message Catalog (`@objectstack/spec/system`, `renderOperationMessage`), the catalog the record door's other refusals use. Four new keys cover what the lock hook has in hand: `record_locked` (object label and record title), `record_locked_untitled` (label only), `record_locked_unlabeled` (title only) and `record_locked_opaque` (neither). They ship in `en`, `zh-CN`, `ja-JP` and `es-ES`. The object is named by its label in the writer's locale (`objects.<object>.label` from the deployment's language pack, else the declared label), never by its API name. The same zh-CN writer now reads `项目「华东仓储客服平台实施」正在审批中,已被锁定,审批完成前无法编辑`. Batch rows (`updateMany`, `batch` upsert) carry the same sentence.
14+
15+
Unchanged: the English sentence is byte-identical, a locale the catalog does not carry reads English, and the wire code `RECORD_LOCKED`, the 409 status and the `RECORD_LOCKED: ` message prefix do not move. A deployment can override each sentence under `errors.record_locked`, `errors.record_locked_untitled`, `errors.record_locked_unlabeled` and `errors.record_locked_opaque`.

‎packages/plugins/plugin-approvals/src/approvals-plugin.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,9 @@ export class ApprovalsServicePlugin implements Plugin {
366366
unbindAllHooks(engine);
367367
// [#23618] The refusal's title is narrowed by the writer's served fields,
368368
// through the same lazily-resolved authority the snapshot redaction reads.
369-
bindApprovalLockHook(engine, ctx.logger, fieldVisibility);
369+
// …and it is worded in the writer's locale, with the object's label in
370+
// that locale, through the same lazily-read `i18n` service.
371+
bindApprovalLockHook(engine, ctx.logger, fieldVisibility, i18nService);
370372
bindRecordDeleteCancelHook(engine, this.service, ctx.logger);
371373
bindDelegationWriteGuard(engine, ctx.logger);
372374
// [#10749] Generic-door snapshot redaction. Registered here so the

‎packages/plugins/plugin-approvals/src/lifecycle-hooks.ts‎

Lines changed: 74 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,9 @@
131131

132132
import { withoutOperationPrivateKeys } from '@objectstack/core';
133133
import { resolveDisplayField } from '@objectstack/spec/data';
134+
import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system';
134135
import { redactSnapshot, resolveReadableSnapshotFields, type FieldVisibilitySource } from './payload-redaction.js';
136+
import { readerLabelsFor, type ReaderLabelI18n } from './reader-locale-labels.js';
135137

136138
export const APPROVALS_HOOK_PACKAGE = 'plugin-approvals:lock';
137139

@@ -273,7 +275,8 @@ function writerEnvelope(ctx: any): unknown {
273275
}
274276

275277
/**
276-
* The END-USER sentence for a record held by a live approval (#18153).
278+
* The END-USER sentence for a record held by a live approval (#18153), in the
279+
* WRITER's locale.
277280
*
278281
* Three degradations, in the order the material runs out, and none of them
279282
* reaches for the id or the object's API name:
@@ -286,12 +289,64 @@ function writerEnvelope(ctx: any): unknown {
286289
* locked while an approval is in progress"), so a reader who has seen the old
287290
* text recognises the new one; what is added is the one thing the old sentence
288291
* never said — what has to happen before the record can be edited again.
292+
*
293+
* Rendered through the SHARED Operation Message Catalog
294+
* (`@objectstack/spec/system`, the `record_locked*` keys), not a second
295+
* mechanism: user-facing refusal text is in the request locale, and the record
296+
* door's other refusals (`record_write_denied`, `record_access_denied`, this
297+
* plugin's own `approval_recall_not_submitter`) already reach the user that
298+
* way. Same `errors.<key>` override address, same resolution ladder
299+
* (deployment override → locale catalog → `en`), so a locale the catalog does
300+
* not carry reads the English sentence. Which degradation applies picks the
301+
* KEY; the label and the title are its parameters, never spliced into prose
302+
* here, so each language orders and quotes them its own way.
303+
*/
304+
function recordLockRefusal(
305+
objectLabel: string | undefined,
306+
recordTitle: string | undefined,
307+
locale: string | undefined,
308+
translate: ValidationMessageTranslator | undefined,
309+
): string {
310+
const messageKey = recordTitle
311+
? (objectLabel ? 'record_locked' : 'record_locked_unlabeled')
312+
: (objectLabel ? 'record_locked_untitled' : 'record_locked_opaque');
313+
const params: Record<string, string> = {};
314+
if (objectLabel) params.object = objectLabel;
315+
if (recordTitle) params.title = recordTitle;
316+
return renderOperationMessage({ messageKey, params }, { locale, translate });
317+
}
318+
319+
/**
320+
* The writer's locale and the deployment lookups the refusal is worded with.
321+
*
322+
* The locale is `HookContext.session.locale`, the caller's language the engine
323+
* copies onto every hook session so a hook refusal can answer in it (the
324+
* request's `Accept-Language`, else the `localization` settings). The `i18n`
325+
* service, resolved lazily per refusal because it is contributed by another
326+
* plugin that may start after this one (ADR-0029 D8), supplies two things:
327+
* the object's label in that locale (`objects.<object>.label`, negotiated by
328+
* {@link readerLabelsFor}, the approvals door's one reader-locale label pick)
329+
* and the deployment's `errors.<key>` override. Absent, the built-in catalog
330+
* still renders the writer's locale and the object keeps its declared label.
289331
*/
290-
function recordLockRefusal(objectLabel: string | undefined, recordTitle: string | undefined): string {
291-
const subject = recordTitle
292-
? (objectLabel ? `${objectLabel} '${recordTitle}'` : `'${recordTitle}'`)
293-
: (objectLabel ? `This ${objectLabel}` : 'This record');
294-
return `${subject} is locked while an approval is in progress, and cannot be edited until that approval is complete`;
332+
function refusalLocalization(
333+
ctx: any,
334+
i18nService: (() => ReaderLabelI18n | undefined) | undefined,
335+
): { locale: string | undefined; service: ReaderLabelI18n | undefined; translate: ValidationMessageTranslator | undefined } {
336+
const raw = ctx?.session?.locale;
337+
const locale = typeof raw === 'string' && raw.length > 0 ? raw : undefined;
338+
let service: ReaderLabelI18n | undefined;
339+
try {
340+
service = i18nService?.();
341+
} catch {
342+
// i18n is optional and late-bound; a missing service degrades the wording, never the lock.
343+
service = undefined;
344+
}
345+
const svc = service;
346+
const translate: ValidationMessageTranslator | undefined = svc && typeof svc.t === 'function'
347+
? (key, loc, params) => svc.t(key, loc, params)
348+
: undefined;
349+
return { locale, service, translate };
295350
}
296351

297352
/**
@@ -529,11 +584,17 @@ async function gatingRequests(
529584
* is narrowed by (#23618) — lazily, per refusal, because the security plugin may
530585
* start after this one. Absent, or resolving nothing, the title is served as
531586
* before, exactly as the payload snapshot is (`resolveReadableSnapshotFields`).
587+
*
588+
* `i18nService` resolves the deployment's `i18n` service the refusal is worded
589+
* with in the writer's locale — the object's translated label and the
590+
* `errors.record_locked*` override (see {@link refusalLocalization}). Absent,
591+
* the sentence is still the catalog's, in the writer's locale.
532592
*/
533593
export function bindApprovalLockHook(
534594
engine: MinimalEngine,
535595
logger?: MinimalLogger,
536596
fieldVisibility?: () => FieldVisibilitySource | undefined,
597+
i18nService?: () => ReaderLabelI18n | undefined,
537598
): void {
538599
engine.registerHook('beforeUpdate', async (ctx: any) => {
539600
const object = (ctx?.object ?? ctx?.objectName) as string | undefined;
@@ -602,9 +663,14 @@ export function bindApprovalLockHook(
602663
const recordId = String(pending?.record_id ?? '');
603664
let schema: unknown;
604665
try { schema = engine.getSchema?.(object); } catch { /* registry unavailable — label degrades */ }
605-
const objectLabel = typeof (schema as any)?.label === 'string' && (schema as any).label
666+
const declaredLabel = typeof (schema as any)?.label === 'string' && (schema as any).label
606667
? String((schema as any).label)
607668
: undefined;
669+
// The sentence is in the writer's locale, and so is the label it names:
670+
// the translated `objects.<object>.label` when the pack carries one, else
671+
// the declared label. ⛔ Never the API name.
672+
const { locale, service, translate } = refusalLocalization(ctx, i18nService);
673+
const objectLabel = readerLabelsFor(service, locale)?.objectLabel(object) ?? declaredLabel;
608674
// `previous` is the pre-image the engine already read for THIS row; it is
609675
// used only when it really is the row this pending request names, so a
610676
// dispatch that ever carried a different row cannot title the wrong
@@ -630,7 +696,7 @@ export function bindApprovalLockHook(
630696
`[approvals] update refused RECORD_LOCKED: record '${recordId}' of '${object}' ` +
631697
`is held by pending approval request '${String(pending?.id ?? '')}'`,
632698
);
633-
lockedError(recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId)));
699+
lockedError(recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate));
634700
}
635701
}, { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 });
636702

‎packages/plugins/plugin-approvals/src/record-lock-batch-row-status.integration.test.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ import { SqlDriver } from '@objectstack/driver-sql';
5050
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
5151
import { resolveThrownHttpError } from '@objectstack/types';
5252
import { bindApprovalLockHook } from './lifecycle-hooks.js';
53+
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
5354
import { installDefaultOrganization } from './default-organization.testkit.js';
5455

5556
const opportunity = {
@@ -192,6 +193,37 @@ describe('[#8570] a locked record\'s batch row carries the 409 the hook declared
192193
expect((await engine.findOne('opportunity', { where: { id: freeId } }))?.amount).toBe(555);
193194
});
194195

196+
// [#34060] The row carries the sentence in the WRITER's locale — the same
197+
// sentence the by-id door answers (`record-lock-user-facing-message.test.ts`),
198+
// because both are the one hook's one refusal. Only the sentence moves: the
199+
// row's `code` and `httpStatus` are the ones pinned above, in every locale.
200+
it('a zh-CN writer\'s row carries the Chinese sentence; an en-US writer\'s the English one', async () => {
201+
const rowIn = async (locale: string) => {
202+
const res: any = await protocol.updateManyData({
203+
object: 'opportunity',
204+
records: [{ id: lockedId, data: { amount: 999 } }],
205+
context: { userId: 'u_writer', positions: [], permissions: [], locale },
206+
});
207+
expect(res.results[0].success).toBe(false);
208+
return res.results[0].errors[0];
209+
};
210+
const zh = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_locked
211+
.replace('{{object}}', 'Opportunity').replace('{{title}}', 'Deal');
212+
expect(await rowIn('zh-CN')).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 });
213+
expect(await rowIn('en-US')).toEqual({
214+
code: 'RECORD_LOCKED',
215+
message: "RECORD_LOCKED: Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete",
216+
httpStatus: 409,
217+
});
218+
const upsert: any = await protocol.batchData({
219+
object: 'opportunity',
220+
request: { operation: 'upsert', records: [{ id: lockedId, data: { amount: 999 } }] },
221+
context: { userId: 'u_writer', positions: [], permissions: [], locale: 'zh-CN' },
222+
});
223+
expect(upsert.results[0].errors[0]).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 });
224+
expect((await engine.findOne('opportunity', { where: { id: lockedId } }))?.amount).toBe(100);
225+
});
226+
195227
it('the batchData upsert loop answers the same way — not just updateManyData', async () => {
196228
const res: any = await protocol.batchData({
197229
object: 'opportunity',

‎packages/plugins/plugin-approvals/src/record-lock-user-facing-message.test.ts‎

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
4343
import { ObjectQL } from '@objectstack/objectql';
4444
import { SqlDriver } from '@objectstack/driver-sql';
4545
import { bindApprovalLockHook, APPROVALS_HOOK_PACKAGE } from './lifecycle-hooks.js';
46+
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
4647
import { installDefaultOrganization } from './default-organization.testkit.js';
4748

4849
const OPPORTUNITY = {
@@ -265,3 +266,151 @@ describe('[#18153] CONTROL — the operator-facing refusals are untouched', () =
265266
expect(thrown.statusCode).toBe(409);
266267
});
267268
});
269+
270+
/**
271+
* [#34060] The per-row refusal is in the WRITER's locale.
272+
*
273+
* User-facing refusal text is in the request locale (ruling C on #32440), and
274+
* the record door's other refusals already answer that way through the shared
275+
* Operation Message Catalog. This refusal now does too, under the
276+
* `record_locked*` keys: the object is named by its label in the writer's
277+
* locale (the pack's `objects.<object>.label`, else the declared label), the
278+
* record by its title, and a locale the catalog does not carry reads English.
279+
* The wire vocabulary does not move: `RECORD_LOCKED` / 409 and the
280+
* `CODE: message` envelope on every leg.
281+
*
282+
* Same real rig as the #18153 describe above. The `i18n` service is a double
283+
* holding one zh-CN pack, shaped as `II18nService` answers: `t()` echoes the
284+
* key back on a miss, and `getLocales()` lists what it holds.
285+
*/
286+
describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => {
287+
const TAIL_EN = 'is locked while an approval is in progress, and cannot be edited until that approval is complete';
288+
const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'];
289+
const PACKS: Record<string, Record<string, string>> = {
290+
'zh-CN': {
291+
'objects.opportunity.label': '商机',
292+
'objects.ledger_entry.label': '分类账分录',
293+
},
294+
};
295+
const i18n = {
296+
getLocales: () => Object.keys(PACKS),
297+
t: (key: string, locale: string) => PACKS[locale]?.[key] ?? key,
298+
};
299+
300+
let engine: ObjectQL;
301+
let opportunityId: string;
302+
let ledgerId: string;
303+
304+
afterEach(async () => {
305+
try { await engine?.destroy(); } catch { /* noop */ }
306+
});
307+
308+
async function rig(service: (() => any) | undefined): Promise<void> {
309+
engine = new ObjectQL();
310+
engine.registerDriver(new SqlDriver({
311+
client: 'better-sqlite3',
312+
connection: { filename: ':memory:' },
313+
useNullAsDefault: true,
314+
}), true);
315+
await engine.init();
316+
for (const o of [OPPORTUNITY, LEDGER_ENTRY, APPROVAL_REQUEST]) {
317+
engine.registry.registerObject(o as any, 'com.objectstack.test.34060');
318+
}
319+
await engine.syncSchemas();
320+
await installDefaultOrganization(engine);
321+
opportunityId = String((await engine.insert('opportunity', { name: 'Acme renewal', amount: 100 })).id);
322+
ledgerId = String((await engine.insert('ledger_entry', { amount: 100 })).id);
323+
for (const [object, recordId] of [['opportunity', opportunityId], ['ledger_entry', ledgerId]] as const) {
324+
await engine.insert('sys_approval_request', {
325+
object_name: object, record_id: recordId, status: 'pending',
326+
flow_run_id: 'run_1', node_config_json: NODE_CONFIG,
327+
}, { context: { isSystem: true } } as any);
328+
}
329+
bindApprovalLockHook(engine as any, undefined, undefined, service);
330+
}
331+
332+
/** The refusal a writer in `locale` gets; the engine copies the envelope's locale onto the hook session. */
333+
async function refusalIn(locale: string | undefined, object: string, id: string): Promise<any> {
334+
let thrown: any = null;
335+
try {
336+
await engine.update(object, { amount: 999 }, {
337+
where: { id },
338+
context: { userId: 'u_writer', positions: [], permissions: [], ...(locale ? { locale } : {}) },
339+
} as any);
340+
} catch (e) { thrown = e; }
341+
expect(thrown).not.toBeNull();
342+
expect(thrown.code).toBe('RECORD_LOCKED');
343+
expect(thrown.statusCode).toBe(409);
344+
expect(thrown.message.startsWith('RECORD_LOCKED: ')).toBe(true);
345+
// Nothing reached the store.
346+
expect((await engine.findOne(object, { where: { id } }))?.amount).toBe(100);
347+
return thrown;
348+
}
349+
350+
it('zh-CN: the Chinese sentence, naming the object by its zh-CN label and the record by its title', async () => {
351+
await rig(() => i18n);
352+
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
353+
expect(thrown.message).toBe(
354+
`RECORD_LOCKED: ${ZH.record_locked.replace('{{object}}', '商机').replace('{{title}}', 'Acme renewal')}`,
355+
);
356+
expect(thrown.message).toContain('商机「Acme renewal」');
357+
expect(thrown.message).not.toContain(TAIL_EN);
358+
expect(thrown.message).not.toContain(opportunityId);
359+
});
360+
361+
it('zh-CN, a record with no title: the label-only sentence, still in Chinese', async () => {
362+
await rig(() => i18n);
363+
const thrown = await refusalIn('zh-CN', 'ledger_entry', ledgerId);
364+
expect(thrown.message).toBe(`RECORD_LOCKED: ${ZH.record_locked_untitled.replace('{{object}}', '分类账分录')}`);
365+
expect(thrown.message).not.toContain(ledgerId);
366+
});
367+
368+
it('a bare `zh` reaches the zh-CN sentence and label', async () => {
369+
await rig(() => i18n);
370+
const thrown = await refusalIn('zh', 'opportunity', opportunityId);
371+
expect(thrown.message).toContain('商机「Acme renewal」');
372+
});
373+
374+
it('en-US: the English sentence, byte-identical to the one this replaced', async () => {
375+
await rig(() => i18n);
376+
const thrown = await refusalIn('en-US', 'opportunity', opportunityId);
377+
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
378+
});
379+
380+
it('a locale the catalog does not carry falls back to English', async () => {
381+
await rig(() => i18n);
382+
const thrown = await refusalIn('xx-YY', 'opportunity', opportunityId);
383+
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
384+
});
385+
386+
it('no locale on the write: English', async () => {
387+
await rig(() => i18n);
388+
const thrown = await refusalIn(undefined, 'opportunity', opportunityId);
389+
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
390+
});
391+
392+
it('no i18n service: the built-in catalog still answers zh-CN, with the declared label', async () => {
393+
await rig(undefined);
394+
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
395+
expect(thrown.message).toBe(
396+
`RECORD_LOCKED: ${ZH.record_locked.replace('{{object}}', 'Opportunity').replace('{{title}}', 'Acme renewal')}`,
397+
);
398+
});
399+
400+
it('a deployment translation of `errors.record_locked` wins, interpolated', async () => {
401+
const override = {
402+
getLocales: () => ['zh-CN'],
403+
t: (key: string, locale: string) =>
404+
key === 'errors.record_locked' && locale === 'zh-CN' ? '{{object}}《{{title}}》审批中,暂不可改' : i18n.t(key, locale),
405+
};
406+
await rig(() => override);
407+
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
408+
expect(thrown.message).toBe('RECORD_LOCKED: 商机《Acme renewal》审批中,暂不可改');
409+
});
410+
411+
it('a throwing i18n service degrades the wording, never the lock', async () => {
412+
await rig(() => { throw new Error('i18n exploded'); });
413+
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
414+
expect(thrown.message).toContain('Opportunity「Acme renewal」');
415+
});
416+
});

0 commit comments

Comments
 (0)