Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .changeset/34060-record-lock-refusal-locale.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
---
'@objectstack/plugin-approvals': patch
'@objectstack/spec': patch
---

fix(plugin-approvals): the record-lock refusal is worded in the writer's locale

Clause-②: no
Metadata-protocol: none

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`.

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.

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`.
4 changes: 3 additions & 1 deletion packages/plugins/plugin-approvals/src/approvals-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -366,7 +366,9 @@ export class ApprovalsServicePlugin implements Plugin {
unbindAllHooks(engine);
// [#23618] The refusal's title is narrowed by the writer's served fields,
// through the same lazily-resolved authority the snapshot redaction reads.
bindApprovalLockHook(engine, ctx.logger, fieldVisibility);
// …and it is worded in the writer's locale, with the object's label in
// that locale, through the same lazily-read `i18n` service.
bindApprovalLockHook(engine, ctx.logger, fieldVisibility, i18nService);
bindRecordDeleteCancelHook(engine, this.service, ctx.logger);
bindDelegationWriteGuard(engine, ctx.logger);
// [#10749] Generic-door snapshot redaction. Registered here so the
Expand Down
82 changes: 74 additions & 8 deletions packages/plugins/plugin-approvals/src/lifecycle-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,9 @@

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

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

Expand Down Expand Up @@ -273,7 +275,8 @@ function writerEnvelope(ctx: any): unknown {
}

/**
* The END-USER sentence for a record held by a live approval (#18153).
* The END-USER sentence for a record held by a live approval (#18153), in the
* WRITER's locale.
*
* Three degradations, in the order the material runs out, and none of them
* reaches for the id or the object's API name:
Expand All @@ -286,12 +289,64 @@ function writerEnvelope(ctx: any): unknown {
* locked while an approval is in progress"), so a reader who has seen the old
* text recognises the new one; what is added is the one thing the old sentence
* never said — what has to happen before the record can be edited again.
*
* Rendered through the SHARED Operation Message Catalog
* (`@objectstack/spec/system`, the `record_locked*` keys), not a second
* mechanism: user-facing refusal text is in the request locale, and the record
* door's other refusals (`record_write_denied`, `record_access_denied`, this
* plugin's own `approval_recall_not_submitter`) already reach the user that
* way. Same `errors.<key>` override address, same resolution ladder
* (deployment override → locale catalog → `en`), so a locale the catalog does
* not carry reads the English sentence. Which degradation applies picks the
* KEY; the label and the title are its parameters, never spliced into prose
* here, so each language orders and quotes them its own way.
*/
function recordLockRefusal(
objectLabel: string | undefined,
recordTitle: string | undefined,
locale: string | undefined,
translate: ValidationMessageTranslator | undefined,
): string {
const messageKey = recordTitle
? (objectLabel ? 'record_locked' : 'record_locked_unlabeled')
: (objectLabel ? 'record_locked_untitled' : 'record_locked_opaque');
const params: Record<string, string> = {};
if (objectLabel) params.object = objectLabel;
if (recordTitle) params.title = recordTitle;
return renderOperationMessage({ messageKey, params }, { locale, translate });
}

/**
* The writer's locale and the deployment lookups the refusal is worded with.
*
* The locale is `HookContext.session.locale`, the caller's language the engine
* copies onto every hook session so a hook refusal can answer in it (the
* request's `Accept-Language`, else the `localization` settings). The `i18n`
* service, resolved lazily per refusal because it is contributed by another
* plugin that may start after this one (ADR-0029 D8), supplies two things:
* the object's label in that locale (`objects.<object>.label`, negotiated by
* {@link readerLabelsFor}, the approvals door's one reader-locale label pick)
* and the deployment's `errors.<key>` override. Absent, the built-in catalog
* still renders the writer's locale and the object keeps its declared label.
*/
function recordLockRefusal(objectLabel: string | undefined, recordTitle: string | undefined): string {
const subject = recordTitle
? (objectLabel ? `${objectLabel} '${recordTitle}'` : `'${recordTitle}'`)
: (objectLabel ? `This ${objectLabel}` : 'This record');
return `${subject} is locked while an approval is in progress, and cannot be edited until that approval is complete`;
function refusalLocalization(
ctx: any,
i18nService: (() => ReaderLabelI18n | undefined) | undefined,
): { locale: string | undefined; service: ReaderLabelI18n | undefined; translate: ValidationMessageTranslator | undefined } {
const raw = ctx?.session?.locale;
const locale = typeof raw === 'string' && raw.length > 0 ? raw : undefined;
let service: ReaderLabelI18n | undefined;
try {
service = i18nService?.();
} catch {
// i18n is optional and late-bound; a missing service degrades the wording, never the lock.
service = undefined;
}
const svc = service;
const translate: ValidationMessageTranslator | undefined = svc && typeof svc.t === 'function'
? (key, loc, params) => svc.t(key, loc, params)
: undefined;
return { locale, service, translate };
}

/**
Expand Down Expand Up @@ -529,11 +584,17 @@ async function gatingRequests(
* is narrowed by (#23618) — lazily, per refusal, because the security plugin may
* start after this one. Absent, or resolving nothing, the title is served as
* before, exactly as the payload snapshot is (`resolveReadableSnapshotFields`).
*
* `i18nService` resolves the deployment's `i18n` service the refusal is worded
* with in the writer's locale — the object's translated label and the
* `errors.record_locked*` override (see {@link refusalLocalization}). Absent,
* the sentence is still the catalog's, in the writer's locale.
*/
export function bindApprovalLockHook(
engine: MinimalEngine,
logger?: MinimalLogger,
fieldVisibility?: () => FieldVisibilitySource | undefined,
i18nService?: () => ReaderLabelI18n | undefined,
): void {
engine.registerHook('beforeUpdate', async (ctx: any) => {
const object = (ctx?.object ?? ctx?.objectName) as string | undefined;
Expand Down Expand Up @@ -602,9 +663,14 @@ export function bindApprovalLockHook(
const recordId = String(pending?.record_id ?? '');
let schema: unknown;
try { schema = engine.getSchema?.(object); } catch { /* registry unavailable — label degrades */ }
const objectLabel = typeof (schema as any)?.label === 'string' && (schema as any).label
const declaredLabel = typeof (schema as any)?.label === 'string' && (schema as any).label
? String((schema as any).label)
: undefined;
// The sentence is in the writer's locale, and so is the label it names:
// the translated `objects.<object>.label` when the pack carries one, else
// the declared label. ⛔ Never the API name.
const { locale, service, translate } = refusalLocalization(ctx, i18nService);
const objectLabel = readerLabelsFor(service, locale)?.objectLabel(object) ?? declaredLabel;
// `previous` is the pre-image the engine already read for THIS row; it is
// used only when it really is the row this pending request names, so a
// dispatch that ever carried a different row cannot title the wrong
Expand All @@ -630,7 +696,7 @@ export function bindApprovalLockHook(
`[approvals] update refused RECORD_LOCKED: record '${recordId}' of '${object}' ` +
`is held by pending approval request '${String(pending?.id ?? '')}'`,
);
lockedError(recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId)));
lockedError(recordLockRefusal(objectLabel, recordTitleOf(schema, asServed, recordId), locale, translate));
}
}, { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 });

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { SqlDriver } from '@objectstack/driver-sql';
import { ObjectStackProtocolImplementation } from '@objectstack/metadata-protocol';
import { resolveThrownHttpError } from '@objectstack/types';
import { bindApprovalLockHook } from './lifecycle-hooks.js';
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
import { installDefaultOrganization } from './default-organization.testkit.js';

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

// [#34060] The row carries the sentence in the WRITER's locale — the same
// sentence the by-id door answers (`record-lock-user-facing-message.test.ts`),
// because both are the one hook's one refusal. Only the sentence moves: the
// row's `code` and `httpStatus` are the ones pinned above, in every locale.
it('a zh-CN writer\'s row carries the Chinese sentence; an en-US writer\'s the English one', async () => {
const rowIn = async (locale: string) => {
const res: any = await protocol.updateManyData({
object: 'opportunity',
records: [{ id: lockedId, data: { amount: 999 } }],
context: { userId: 'u_writer', positions: [], permissions: [], locale },
});
expect(res.results[0].success).toBe(false);
return res.results[0].errors[0];
};
const zh = BUILTIN_OPERATION_MESSAGES['zh-CN'].record_locked
.replace('{{object}}', 'Opportunity').replace('{{title}}', 'Deal');
expect(await rowIn('zh-CN')).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 });
expect(await rowIn('en-US')).toEqual({
code: 'RECORD_LOCKED',
message: "RECORD_LOCKED: Opportunity 'Deal' is locked while an approval is in progress, and cannot be edited until that approval is complete",
httpStatus: 409,
});
const upsert: any = await protocol.batchData({
object: 'opportunity',
request: { operation: 'upsert', records: [{ id: lockedId, data: { amount: 999 } }] },
context: { userId: 'u_writer', positions: [], permissions: [], locale: 'zh-CN' },
});
expect(upsert.results[0].errors[0]).toEqual({ code: 'RECORD_LOCKED', message: `RECORD_LOCKED: ${zh}`, httpStatus: 409 });
expect((await engine.findOne('opportunity', { where: { id: lockedId } }))?.amount).toBe(100);
});

it('the batchData upsert loop answers the same way — not just updateManyData', async () => {
const res: any = await protocol.batchData({
object: 'opportunity',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { ObjectQL } from '@objectstack/objectql';
import { SqlDriver } from '@objectstack/driver-sql';
import { bindApprovalLockHook, APPROVALS_HOOK_PACKAGE } from './lifecycle-hooks.js';
import { BUILTIN_OPERATION_MESSAGES } from '@objectstack/spec/system';
import { installDefaultOrganization } from './default-organization.testkit.js';

const OPPORTUNITY = {
Expand Down Expand Up @@ -265,3 +266,151 @@ describe('[#18153] CONTROL — the operator-facing refusals are untouched', () =
expect(thrown.statusCode).toBe(409);
});
});

/**
* [#34060] The per-row refusal is in the WRITER's locale.
*
* User-facing refusal text is in the request locale (ruling C on #32440), and
* the record door's other refusals already answer that way through the shared
* Operation Message Catalog. This refusal now does too, under the
* `record_locked*` keys: the object is named by its label in the writer's
* locale (the pack's `objects.<object>.label`, else the declared label), the
* record by its title, and a locale the catalog does not carry reads English.
* The wire vocabulary does not move: `RECORD_LOCKED` / 409 and the
* `CODE: message` envelope on every leg.
*
* Same real rig as the #18153 describe above. The `i18n` service is a double
* holding one zh-CN pack, shaped as `II18nService` answers: `t()` echoes the
* key back on a miss, and `getLocales()` lists what it holds.
*/
describe('[#34060] the per-row refusal is worded in the writer\'s locale', () => {
const TAIL_EN = 'is locked while an approval is in progress, and cannot be edited until that approval is complete';
const ZH = BUILTIN_OPERATION_MESSAGES['zh-CN'];
const PACKS: Record<string, Record<string, string>> = {
'zh-CN': {
'objects.opportunity.label': '商机',
'objects.ledger_entry.label': '分类账分录',
},
};
const i18n = {
getLocales: () => Object.keys(PACKS),
t: (key: string, locale: string) => PACKS[locale]?.[key] ?? key,
};

let engine: ObjectQL;
let opportunityId: string;
let ledgerId: string;

afterEach(async () => {
try { await engine?.destroy(); } catch { /* noop */ }
});

async function rig(service: (() => any) | undefined): Promise<void> {
engine = new ObjectQL();
engine.registerDriver(new SqlDriver({
client: 'better-sqlite3',
connection: { filename: ':memory:' },
useNullAsDefault: true,
}), true);
await engine.init();
for (const o of [OPPORTUNITY, LEDGER_ENTRY, APPROVAL_REQUEST]) {
engine.registry.registerObject(o as any, 'com.objectstack.test.34060');
}
await engine.syncSchemas();
await installDefaultOrganization(engine);
opportunityId = String((await engine.insert('opportunity', { name: 'Acme renewal', amount: 100 })).id);
ledgerId = String((await engine.insert('ledger_entry', { amount: 100 })).id);
for (const [object, recordId] of [['opportunity', opportunityId], ['ledger_entry', ledgerId]] as const) {
await engine.insert('sys_approval_request', {
object_name: object, record_id: recordId, status: 'pending',
flow_run_id: 'run_1', node_config_json: NODE_CONFIG,
}, { context: { isSystem: true } } as any);
}
bindApprovalLockHook(engine as any, undefined, undefined, service);
}

/** The refusal a writer in `locale` gets; the engine copies the envelope's locale onto the hook session. */
async function refusalIn(locale: string | undefined, object: string, id: string): Promise<any> {
let thrown: any = null;
try {
await engine.update(object, { amount: 999 }, {
where: { id },
context: { userId: 'u_writer', positions: [], permissions: [], ...(locale ? { locale } : {}) },
} as any);
} catch (e) { thrown = e; }
expect(thrown).not.toBeNull();
expect(thrown.code).toBe('RECORD_LOCKED');
expect(thrown.statusCode).toBe(409);
expect(thrown.message.startsWith('RECORD_LOCKED: ')).toBe(true);
// Nothing reached the store.
expect((await engine.findOne(object, { where: { id } }))?.amount).toBe(100);
return thrown;
}

it('zh-CN: the Chinese sentence, naming the object by its zh-CN label and the record by its title', async () => {
await rig(() => i18n);
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
expect(thrown.message).toBe(
`RECORD_LOCKED: ${ZH.record_locked.replace('{{object}}', '商机').replace('{{title}}', 'Acme renewal')}`,
);
expect(thrown.message).toContain('商机「Acme renewal」');
expect(thrown.message).not.toContain(TAIL_EN);
expect(thrown.message).not.toContain(opportunityId);
});

it('zh-CN, a record with no title: the label-only sentence, still in Chinese', async () => {
await rig(() => i18n);
const thrown = await refusalIn('zh-CN', 'ledger_entry', ledgerId);
expect(thrown.message).toBe(`RECORD_LOCKED: ${ZH.record_locked_untitled.replace('{{object}}', '分类账分录')}`);
expect(thrown.message).not.toContain(ledgerId);
});

it('a bare `zh` reaches the zh-CN sentence and label', async () => {
await rig(() => i18n);
const thrown = await refusalIn('zh', 'opportunity', opportunityId);
expect(thrown.message).toContain('商机「Acme renewal」');
});

it('en-US: the English sentence, byte-identical to the one this replaced', async () => {
await rig(() => i18n);
const thrown = await refusalIn('en-US', 'opportunity', opportunityId);
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
});

it('a locale the catalog does not carry falls back to English', async () => {
await rig(() => i18n);
const thrown = await refusalIn('xx-YY', 'opportunity', opportunityId);
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
});

it('no locale on the write: English', async () => {
await rig(() => i18n);
const thrown = await refusalIn(undefined, 'opportunity', opportunityId);
expect(thrown.message).toBe(`RECORD_LOCKED: Opportunity 'Acme renewal' ${TAIL_EN}`);
});

it('no i18n service: the built-in catalog still answers zh-CN, with the declared label', async () => {
await rig(undefined);
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
expect(thrown.message).toBe(
`RECORD_LOCKED: ${ZH.record_locked.replace('{{object}}', 'Opportunity').replace('{{title}}', 'Acme renewal')}`,
);
});

it('a deployment translation of `errors.record_locked` wins, interpolated', async () => {
const override = {
getLocales: () => ['zh-CN'],
t: (key: string, locale: string) =>
key === 'errors.record_locked' && locale === 'zh-CN' ? '{{object}}《{{title}}》审批中,暂不可改' : i18n.t(key, locale),
};
await rig(() => override);
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
expect(thrown.message).toBe('RECORD_LOCKED: 商机《Acme renewal》审批中,暂不可改');
});

it('a throwing i18n service degrades the wording, never the lock', async () => {
await rig(() => { throw new Error('i18n exploded'); });
const thrown = await refusalIn('zh-CN', 'opportunity', opportunityId);
expect(thrown.message).toContain('Opportunity「Acme renewal」');
});
});
Loading
Loading