diff --git a/.changeset/36463-no-approver-text-in-reader-language.md b/.changeset/36463-no-approver-text-in-reader-language.md new file mode 100644 index 00000000000..007d1603896 --- /dev/null +++ b/.changeset/36463-no-approver-text-in-reader-language.md @@ -0,0 +1,18 @@ +--- +'@objectstack/plugin-approvals': patch +'@objectstack/rest': patch +'@object-ui/console': patch +'@object-ui/app-shell': patch +--- + +fix(plugin-approvals): the decide refusal of a submitter's own approval, and a submitter notice that names several slots, read in the reader's language + +Clause-②: yes (widening) +Metadata-protocol: none + +**Widened door response.** The approvals decide door (`packages/rest/src/approvals-routes.ts`) gains one optional member, `userMessage`, at the top level of its flat `{ code, error }` refusal body. Two rows answer it today: the two `403 FORBIDDEN` decide refusals of a submitter's own approval, the `excludeSubmitter` refusal and the administrator-override self-approve refusal. It is absent whenever no producer marked one, so every other refusal body is unchanged. + +- **The decide refusal.** When the decision door refuses a submitter's own approval (the step sets `excludeSubmitter`, or the administrator override would approve the actor's own request), the thrown error now carries a `userMessage`: the same refusal, with its remedy, in the decider's language (`approvalDecideRefused*` in every approvals message pack). A position is named by the decider's pack label, then its declared label, then its name. The error's `message` is unchanged: it stays English for the developer and the log. With no reader language, `userMessage` is English and names no user id. +- **The REST door.** The approvals routes answer a refusal the service marked with `userMessage` at the top level of their flat `{ code, error }` body, beside `error`, on every mapped row. A refusal with no marking answers exactly as before. +- **The console.** The record page's `type: 'api'` actions (the request's Approve button) read a flat body's top-level `userMessage` as well as the `error.userMessage` of the ADR-0112 envelope, and show it in place of the English `error`. The Approval Center's inline decision toast shows a marked refusal as written, before its generic line. +- **The submitter notice.** A notice for a slate of 2 to 8 slots names each slot inline, one keyed type word and value per slot (`approvalNoApproverHoldingSlots2` to `…Slots8`, derived from each pack's own `approvalNoApproverHolding`, `approvalNoApproverSlot` and `approvalNoApproverSlotSeparator`), so the messaging service renders every slot in the recipient's language at delivery. A slate of more than 8 slots still names its slots in English inside the recipient's sentence. The literal English body is unchanged. diff --git a/packages/plugins/plugin-approvals/src/admin-rescue-named-slate.integration.test.ts b/packages/plugins/plugin-approvals/src/admin-rescue-named-slate.integration.test.ts index 14333a0154f..05dd5c1ec57 100644 --- a/packages/plugins/plugin-approvals/src/admin-rescue-named-slate.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/admin-rescue-named-slate.integration.test.ts @@ -648,6 +648,27 @@ describe('an empty admin_rescue slate opens on the organization\'s administrator expect(renderer.render(notice.keyedText, notice.payload, 'zh-CN').body).toBe(holdingZh('岗位「treasury」')); }); + // [#36463] A slate of several slots is spelled inline too, one keyed + // type and value per slot, so the submitter reads every slot in their + // language: the sentence, the type words and the separator, each + // position by its pack label, else as stored. + it('the submitter\'s notice: a slate of several slots reads entirely in the recipient\'s language', async () => { + const row = await openLabelled('none_notice_two', [ + { type: 'position', value: 'sales_manager' }, { type: 'position', value: 'treasury' }, + ]); + const [notice] = told.filter((e) => e.source?.id === row.id); + expect(notice.keyedText.bodyKey).toBe('messages.approvalNoApproverHoldingSlots2'); + expect(notice.payload.body).toBe(holding("position 'Sales Manager', position 'treasury'")); + const renderer = new NotificationTextRenderer({ getData: () => undefined, getI18n: () => i18n as any }); + const zh = renderer.render(notice.keyedText, notice.payload, 'zh-CN').body; + expect(zh).toBe(holdingZh('岗位「销售经理」、岗位「treasury」')); + expect(zh).not.toMatch(/position|sales_manager/); + expect(renderer.render(notice.keyedText, notice.payload, 'ja-JP').body) + .toContain('役職「Sales Manager」、役職「treasury」を担うメンバー'); + expect(renderer.render(notice.keyedText, notice.payload, 'en').body) + .toBe(holding("position 'Sales Manager', position 'treasury'")); + }); + it('CONTROL: a note written before the slot was stored renders exactly as before', async () => { const row = await open('none_legacy', UNSTAFFED, {}, LEADERLESS_ORG); // The stored shape of a note written before #36035: `who`, pre-composed. diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index 64a0ff13ec7..cf6aeeceab1 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -148,7 +148,9 @@ import { noApproverPositions, noApproverSlots, noApproverWho, + submitterRefusalUserMessage, type NoApproverNote, + type SubmitterApprovalRefusal, } from './no-approver-note.js'; import { localizeRequestLabels, @@ -5957,21 +5959,35 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // [#36308] Composed only when it is said, naming a position as the // timeline note does: the decider's pack label, else the declared label, // else its name. The sentence stays the English the note stores. + // [#36463] Beside it, the end user's half: the same refusal in the + // decider's language, as the error's `userMessage` + // (`submitterRefusalUserMessage`), which the REST door carries to the + // wire. The `message` is unchanged byte for byte. const noOneElse = namesNoOneBut(pendingApprovers, String(raw.submitter_id ?? '')); - const noApproverRemedy = async (): Promise => { - const labels = await this.notePositionLabels(slatePositions(pendingApprovers), this.readerLabels(context)); - return noApproverNoteText({ who: noApproverWho(pendingApprovers, (name) => labels.get(name)) }); + const refuseOwnApproval = async ( + refusal: SubmitterApprovalRefusal, + message: (remedy: string | undefined) => string, + ): Promise => { + const reader = this.readerLabels(context); + const labels = noOneElse + ? await this.notePositionLabels(slatePositions(pendingApprovers), reader) + : undefined; + const labelOf = (name: string): string | undefined => labels?.get(name); + const remedy = noOneElse ? noApproverNoteText({ who: noApproverWho(pendingApprovers, labelOf) }) : undefined; + const err = new Error(message(remedy)) as Error & { userMessage?: string }; + err.userMessage = submitterRefusalUserMessage( + refusal, noOneElse ? pendingApprovers : undefined, reader?.sentence, labelOf, + ); + throw err; }; if ( input.decision === 'approve' && config.excludeSubmitter === true && raw.submitter_id && decider && decider === String(raw.submitter_id) ) { - const remedy = noOneElse ? await noApproverRemedy() : undefined; - throw new Error( + await refuseOwnApproval('excludeSubmitter', (remedy) => `FORBIDDEN: '${decider}' submitted this request, and its approval step sets excludeSubmitter, so they ` + `cannot approve it. ${remedy - ?? 'Another approver on the step decides it; if the submitter holds the only slot, reassign it to someone else.'}`, - ); + ?? 'Another approver on the step decides it; if the submitter holds the only slot, reassign it to someone else.'}`); } // [Maintainer ruling 2026-11-17, option B] The #3424 override never // approves a request its actor submitted, whatever `excludeSubmitter` @@ -5983,14 +5999,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // `attachViewers` computes `viewer.can_override_approve` from the same // predicate, so the Approve control is not offered where this refuses. if (input.decision === 'approve' && viaOverride && overrideApprovesOwnRequest(raw, decider)) { - const remedy = noOneElse ? await noApproverRemedy() : undefined; - throw new Error( + await refuseOwnApproval('override', (remedy) => `FORBIDDEN: '${decider}' submitted this request and holds no slot on it, so they cannot approve it ` + `through the administrator override. ${remedy !== undefined ? `${remedy} To withdraw it instead, reject it or recall it.` : 'An approver on the step decides it. To move it, reassign it to someone else, reject it, or recall ' - + 'it and send the record for approval again.'}`, - ); + + 'it and send the record for approval again.'}`); } // #3447 P2: decision outputs — validated BEFORE any write (audit included) diff --git a/packages/plugins/plugin-approvals/src/exclude-submitter.integration.test.ts b/packages/plugins/plugin-approvals/src/exclude-submitter.integration.test.ts index bf1896e4d0e..e8f503987f2 100644 --- a/packages/plugins/plugin-approvals/src/exclude-submitter.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/exclude-submitter.integration.test.ts @@ -483,6 +483,51 @@ describe('[#25573] excludeSubmitter keeps the submitter from approving their own .rejects.toThrow(remedy("position 'Legal Counsel', team 'ops'")); }); + // [#36463] The end user's half rides beside the English: the thrown + // error's `userMessage`, the same refusal in the decider's language (the + // REST door carries it to the wire). The `message` is the English above. + it('each refusal carries the decider\'s language as its userMessage, the message keeping its English', async () => { + const i18n = createMemoryI18n(); + for (const [locale, data] of Object.entries(ApprovalsTranslations)) { + i18n.loadTranslations(locale, data as Record); + } + i18n.loadTranslations('zh-CN', { positions: { legal: { label: '法务' } } }); + const labelled = new ApprovalService({ + engine: engine as any, + clock: { now: () => new Date(now += 1000) }, + logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any, + i18nServiceSource: () => i18n, + positionLabelSource: async (name) => (name === 'legal' ? 'Legal Counsel' : undefined), + }); + const refusalOf = (requestId: string, context: any): Promise => + labelled.decide(requestId, { decision: 'approve', actorId: 'u_sub' } as any, context).then( + () => { throw new Error('expected a refusal'); }, (err) => err); + const zhRemedy = '目前还没有其他人能审批此请求。组织管理员需要添加一名担任岗位「法务」、团队「ops」的成员,之后由该成员决定。'; + + const overridden = await open('solo_user_message', FIELD_STEP, {}, { org: SOLO_ORG }); + await engine.update('sys_approval_request', { id: overridden.id, pending_approvers: 'position:legal,team:ops' }, + { context: SYSTEM } as any); + const zhOverride = await refusalOf(overridden.id, { ...soloAdmin, locale: 'zh-CN' }); + expect(zhOverride.message).toBe("FORBIDDEN: 'u_sub' submitted this request and holds no slot on it, so they cannot " + + 'approve it through the administrator override. No one else can approve this request yet. An organization ' + + "administrator must add a member who holds position '法务', team 'ops'; that member can then decide it. To " + + 'withdraw it instead, reject it or recall it.'); + expect(zhOverride.userMessage).toBe(`此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。${zhRemedy}如需撤销,请驳回或撤回该请求。`); + + const excluded = await open('solo_user_message_excluded', FIELD_STEP, ON, { org: SOLO_ORG }); + await engine.update('sys_approval_request', { id: excluded.id, pending_approvers: 'position:legal,team:ops' }, + { context: SYSTEM } as any); + expect((await refusalOf(excluded.id, { ...soloAdmin, locale: 'zh-CN' })).userMessage) + .toBe(`此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。${zhRemedy}`); + + // A decider who asked in no language reads the English, which names no id. + const plain = await refusalOf(overridden.id, soloAdmin); + expect(plain.userMessage).toBe('You submitted this request and hold no slot on it, so you cannot approve it ' + + 'through the administrator override. No one else can approve this request yet. An organization administrator ' + + "must add a member who holds position 'Legal Counsel', team 'ops'; that member can then decide it. To withdraw " + + 'it instead, reject it or recall it.'); + }); + it('the excludeSubmitter refusal names a labelled position the same way', async () => { const labelled = new ApprovalService({ engine: engine as any, @@ -513,6 +558,11 @@ describe('[#25573] excludeSubmitter keeps the submitter from approving their own { context: SYSTEM } as any); await expect(svc.decide(overridden.id, { decision: 'approve', actorId: 'u_sub' } as any, soloAdmin)) .rejects.toThrow('through the administrator override. An approver on the step decides it. To move it'); + // [#36463] …and the end user's half names that approver too (a service with no i18n reads the English). + await expect(svc.decide(excluded.id, { decision: 'approve', actorId: 'u_sub' } as any, SUB)).rejects.toMatchObject({ + userMessage: 'You submitted this request, and its approval step keeps its submitter from approving it, so you ' + + 'cannot approve it. Another approver on the step decides it; if you hold the only slot, reassign it to someone else.', + }); expect(sent.filter((e) => e.source?.id === excluded.id && e.topic === 'approval.comment')).toEqual([]); }); }); diff --git a/packages/plugins/plugin-approvals/src/no-approver-note.test.ts b/packages/plugins/plugin-approvals/src/no-approver-note.test.ts index 490b31db63a..874db4e51e0 100644 --- a/packages/plugins/plugin-approvals/src/no-approver-note.test.ts +++ b/packages/plugins/plugin-approvals/src/no-approver-note.test.ts @@ -11,10 +11,10 @@ */ import { describe, it, expect } from 'vitest'; -import { noApproverNoteText, noApproverNotice, noApproverWho } from './no-approver-note.js'; +import { noApproverNoteText, noApproverNotice, noApproverWho, submitterRefusalUserMessage } from './no-approver-note.js'; import { interpolate, type ApprovalTextParam } from './approval-notification-text.js'; import type { ApprovalSentenceRender } from './admin-rescue-note.js'; -import { approvalMessages, enMessages } from './translations/messages.js'; +import { approvalMessages, enMessages, NO_APPROVER_NOTICE_MAX_SLOTS } from './translations/messages.js'; type Locale = keyof typeof approvalMessages; @@ -128,11 +128,105 @@ describe('[#36308] the submitter\'s notice', () => { } }); - it('several slots ride as one English `who`, each position by its declared label; none and a stored `who` as before', () => { - expect(noApproverNotice({ slots: ['position:legal', 'team:ops'] }, (name) => (name === 'legal' ? 'Legal Counsel' : undefined))) - .toEqual({ id: 'approvalNoApproverHolding', params: { who: "position 'Legal Counsel', team 'ops'" } }); + it('none and a stored `who` as before', () => { expect(noApproverNotice({})).toEqual({ id: 'approvalNoApprover', params: {} }); expect(noApproverNotice({ who: "position 'legal'" })) .toEqual({ id: 'approvalNoApproverHolding', params: { who: "position 'legal'" } }); }); }); + +describe('[#36463] the submitter\'s notice names several slots in the reader\'s language', () => { + const declared = (name: string) => (name === 'legal' ? 'Legal Counsel' : undefined); + + it('a slate of two slots spells each inline, keyed, in the slate\'s order', () => { + const notice = noApproverNotice({ slots: ['position:legal', 'team:ops'] }, declared); + expect(notice).toEqual({ + id: 'approvalNoApproverHoldingSlots2', + params: { + type1: { key: 'messages.approvalApproverTypePosition', fallback: 'position' }, + value1: { key: 'positions.legal.label', fallback: 'Legal Counsel' }, + type2: { key: 'messages.approvalApproverTypeTeam', fallback: 'team' }, + value2: 'ops', + }, + }); + // The acceptance: a zh-CN submitter reads it entirely in Chinese, the + // position by its pack label, else as stored (its declared label). + expect(deliveredIn('zh-CN', notice, { 'positions.legal.label': '法务' })).toBe( + '目前还没有其他人能审批此请求。组织管理员需要添加一名担任岗位「法务」、团队「ops」的成员,之后由该成员决定。', + ); + const asStored = deliveredIn('zh-CN', notice); + expect(asStored).toContain('担任岗位「Legal Counsel」、团队「ops」的成员'); + expect(asStored).not.toMatch(/position|team/); + // The English a recipient with no pack reads is the sentence the row stores, the declared label inside it. + expect(deliveredIn('en', notice)).toBe('No one else can approve this request yet. An organization administrator ' + + "must add a member who holds position 'Legal Counsel', team 'ops'; that member can then decide it."); + }); + + it('for every slate size it spells, in every pack, the notice reads the timeline\'s sentence for the same slate', () => { + const kinds = ['position:legal', 'team:ops', 'department:west', 'org_membership_level:admin', 'role:admin']; + for (let n = 2; n <= NO_APPROVER_NOTICE_MAX_SLOTS; n++) { + const slate = Array.from({ length: n }, (_, i) => `${kinds[i % kinds.length]}_${i}`); + for (const locale of Object.keys(approvalMessages) as Locale[]) { + expect(deliveredIn(locale, noApproverNotice({ slots: slate })), `${locale} ${n}`) + .toBe(noApproverNoteText({ slots: slate }, renderIn(locale))); + } + } + }); + + it('a slate of more slots than it spells keeps one English `who` inside the reader\'s sentence', () => { + const slate = Array.from({ length: NO_APPROVER_NOTICE_MAX_SLOTS + 1 }, (_, i) => `team:t${i}`); + const notice = noApproverNotice({ slots: slate }); + expect(notice.id).toBe('approvalNoApproverHolding'); + expect(notice.params).toEqual({ who: noApproverWho(slate) }); + }); +}); + +describe('[#36463] the decision door\'s refusal of a submitter\'s own approval, as the end user reads it', () => { + const label = (name: string) => (name === 'legal' ? '法务' : undefined); + const SLATE = ['position:legal', 'team:ops']; + + it('a zh-CN decider reads each refusal entirely in Chinese, the position by its label', () => { + const excluded = submitterRefusalUserMessage('excludeSubmitter', SLATE, renderIn('zh-CN'), label); + expect(excluded).toBe('此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。' + + '目前还没有其他人能审批此请求。组织管理员需要添加一名担任岗位「法务」、团队「ops」的成员,之后由该成员决定。'); + const override = submitterRefusalUserMessage('override', SLATE, renderIn('zh-CN'), label); + expect(override).toBe('此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。' + + '目前还没有其他人能审批此请求。组织管理员需要添加一名担任岗位「法务」、团队「ops」的成员,之后由该成员决定。' + + '如需撤销,请驳回或撤回该请求。'); + // No English word but the team's stored value. + for (const text of [excluded, override]) expect(text.replace('ops', '')).not.toMatch(/[A-Za-z]/); + }); + + it('with another approver on the slate, the remedy names that approver; a slate with no literal names the plain remedy', () => { + expect(submitterRefusalUserMessage('excludeSubmitter', undefined, renderIn('zh-CN'))) + .toBe('此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。' + + '由该步骤的其他审批人决定;如果只有您持有审批席位,请将其转交给其他人。'); + expect(submitterRefusalUserMessage('override', undefined, renderIn('zh-CN'))) + .toMatch(/^此请求由您提交,且您不在其审批人之列.*由该步骤的审批人决定。/); + expect(submitterRefusalUserMessage('excludeSubmitter', ['u_sub'], renderIn('zh-CN'))) + .toContain(approvalMessages['zh-CN'].approvalNoApprover); + }); + + it('every shipped pack composes every refusal in its own language, with no hole left', () => { + for (const locale of Object.keys(approvalMessages) as Locale[]) { + for (const refusal of ['excludeSubmitter', 'override'] as const) { + for (const slate of [SLATE, undefined]) { + const text = submitterRefusalUserMessage(refusal, slate, renderIn(locale), label); + expect(text, `${locale} ${refusal}`).not.toMatch(/\{\{/); + if (locale !== 'en') expect(text, `${locale} ${refusal}`).not.toContain('You submitted'); + } + } + } + }); + + it('with no reader language, and when the pack lacks a sentence, the whole text is English, never half of each', () => { + const english = submitterRefusalUserMessage('override', ['position:legal'], undefined, (n) => (n === 'legal' ? 'Legal Counsel' : undefined)); + expect(english).toBe('You submitted this request and hold no slot on it, so you cannot approve it through the ' + + 'administrator override. No one else can approve this request yet. An organization administrator must add a ' + + "member who holds position 'Legal Counsel'; that member can then decide it. To withdraw it instead, reject it or recall it."); + for (const dropped of ['approvalDecideRefusedOverrideOwnRequest', 'approvalDecideRefusedOverrideWithdraw', 'approvalNoApproverHolding']) { + expect(submitterRefusalUserMessage('override', ['position:legal'], renderIn('zh-CN', [dropped]), (n) => (n === 'legal' ? 'Legal Counsel' : undefined)), dropped) + .toBe(english); + } + }); +}); diff --git a/packages/plugins/plugin-approvals/src/no-approver-note.ts b/packages/plugins/plugin-approvals/src/no-approver-note.ts index 9957834f7db..b17052b3f88 100644 --- a/packages/plugins/plugin-approvals/src/no-approver-note.ts +++ b/packages/plugins/plugin-approvals/src/no-approver-note.ts @@ -23,7 +23,7 @@ */ import { approvalMessageKey, interpolate, type ApprovalTextParam } from './approval-notification-text.js'; -import { enMessages, type ApprovalMessageId } from './translations/messages.js'; +import { enMessages, noApproverHoldingSlotsId, type ApprovalMessageId } from './translations/messages.js'; import { slatePositions, type ApprovalSentenceRender, type PositionLabelOf } from './admin-rescue-note.js'; import { isPlatformAdminAddress, slateNamesAPerson } from './approver-address.js'; import { positionLabelKey } from './reader-locale-labels.js'; @@ -128,6 +128,23 @@ export function namesNoOneBut(slate: readonly string[], submitter: string): bool return !slateNamesAPerson(slate.filter((slot) => slot !== submitter)); } +/** + * One slot of the submitter's notice as the messaging service fills it per + * recipient: `type` the approver type's word as a key, and a position's + * `value` its reader-language label as a key (`positions..label`) + * falling back to `declaredLabel`, else the name. + */ +function slotParams(slot: Slot, declaredLabel: PositionLabelOf | undefined): { + type: ApprovalTextParam; value: ApprovalTextParam; +} { + const word = APPROVER_TYPE_WORDS[slot.type]; + const value = slotValue(slot, declaredLabel); + return { + type: word ? { key: approvalMessageKey(word), fallback: enMessages[word] } : slot.type, + value: slot.type === 'position' ? { key: positionLabelKey(slot.value), fallback: value } : value, + }; +} + /** * The submitter's notice body for the note: its catalog sentence and the * params the messaging service fills per recipient, at delivery @@ -139,25 +156,30 @@ export function namesNoOneBut(slate: readonly string[], submitter: string): bool * the approver type's word as a key, and a position's `value` is its * reader-language label as a key (`positions..label`, the key the * timeline reads) falling back to `declaredLabel`, else the name — the order - * the timeline note names it in. A slate of several slots names them in - * English inside the reader's sentence, each position by `declaredLabel`; a - * note that stored `who` keeps it as written. + * the timeline note names it in. [#36463] A slate of 2 to + * `NO_APPROVER_NOTICE_MAX_SLOTS` slots is spelled inline the same way, in + * `approvalNoApproverHoldingSlots`, slot `i` under `type` / `value` + * in the slate's order. A slate of more slots names them in English inside + * the reader's sentence, each position by `declaredLabel`; a note that stored + * `who` keeps it as written. */ export function noApproverNotice(note: Pick, declaredLabel?: PositionLabelOf): { id: ApprovalMessageId; params: Record; } { const slots = note.slots ? slotsOf(note.slots) : []; if (slots.length === 1) { - const [slot] = slots; - const word = APPROVER_TYPE_WORDS[slot.type]; - const value = slotValue(slot, declaredLabel); - return { - id: 'approvalNoApproverHoldingSlot', - params: { - type: word ? { key: approvalMessageKey(word), fallback: enMessages[word] } : slot.type, - value: slot.type === 'position' ? { key: positionLabelKey(slot.value), fallback: value } : value, - }, - }; + const { type, value } = slotParams(slots[0], declaredLabel); + return { id: 'approvalNoApproverHoldingSlot', params: { type, value } }; + } + const listed = noApproverHoldingSlotsId(slots.length); + if (listed) { + const params: Record = {}; + slots.forEach((slot, i) => { + const { type, value } = slotParams(slot, declaredLabel); + params[`type${i + 1}`] = type; + params[`value${i + 1}`] = value; + }); + return { id: listed, params }; } const who = note.slots ? noApproverWho(note.slots, declaredLabel) : note.who; return who @@ -193,6 +215,66 @@ export function noApproverNoteText( : interpolate(enMessages.approvalNoApproverHolding, { who }); } +/** The decision door's two refusals of a submitter's own approval. */ +export type SubmitterApprovalRefusal = 'excludeSubmitter' | 'override'; + +/** + * [#36463] The end user's half of the decision door's refusal of a + * submitter's own approval: the text the thrown error carries as its + * `userMessage` (`ApiErrorSchema.userMessage`, composed where it is produced, + * in the request's language), beside a `message` that keeps its English for + * the developer and the log. + * + * `refusal` names which refusal it is: `excludeSubmitter` (the step keeps its + * submitter from approving) or `override` (the administrator override never + * approves a request its actor submitted, maintainer ruling 2026-11-17, + * option B). `noOneElseOn` is the slate when no one but the submitter is on + * it: the remedy is then the no-approver sentence the timeline note names, a + * position named by `positionLabel`; absent, the remedy names the approver + * who decides it. With `render`, every sentence is the reader's language; a + * pack that lacks one of them answers the whole text in English, never a + * sentence of each. + */ +export function submitterRefusalUserMessage( + refusal: SubmitterApprovalRefusal, + noOneElseOn: readonly string[] | undefined, + render?: ApprovalSentenceRender, + positionLabel?: PositionLabelOf, +): string { + const compose = ( + sentence: (id: ApprovalMessageId, params: Readonly>) => string | undefined, + noApprover: () => string | undefined, + ): string | undefined => { + let remedy: string | undefined; + if (noOneElseOn) { + const named = noApprover(); + remedy = named === undefined || refusal === 'excludeSubmitter' + ? named + : sentence('approvalDecideRefusedOverrideWithdraw', { remedy: named }); + } else { + remedy = sentence( + refusal === 'excludeSubmitter' ? 'approvalDecideRefusedAnotherApprover' : 'approvalDecideRefusedOverrideAnotherApprover', + {}, + ); + } + if (remedy === undefined) return undefined; + return sentence( + refusal === 'excludeSubmitter' ? 'approvalDecideRefusedSubmitterExcluded' : 'approvalDecideRefusedOverrideOwnRequest', + { remedy }, + ); + }; + const inReader = render + ? compose( + (id, params) => render(approvalMessageKey(id), params), + () => noApproverNoteText({ slots: noOneElseOn ?? [] }, render, positionLabel), + ) + : undefined; + return inReader ?? compose( + (id, params) => interpolate(enMessages[id], params), + () => noApproverNoteText({ who: noApproverWho(noOneElseOn ?? [], positionLabel) }), + )!; +} + /** * The note a parsed node-config snapshot carries, or `undefined` when it * carries none or one this module did not write (the stored comment stands). diff --git a/packages/plugins/plugin-approvals/src/translations/messages.ts b/packages/plugins/plugin-approvals/src/translations/messages.ts index d3a19781cd6..ce01b03c5db 100644 --- a/packages/plugins/plugin-approvals/src/translations/messages.ts +++ b/packages/plugins/plugin-approvals/src/translations/messages.ts @@ -71,7 +71,18 @@ * of one slot as `approvalNoApproverHoldingSlot`, the same sentence with the * slot spelled inline, because a notice is rendered per recipient at delivery, * where a hole is filled by one text or one hole-free key and never by a - * composed sentence. + * composed sentence. [#36463] A slate of several slots rides the derived + * `approvalNoApproverHoldingSlots` (`slotListSentences` below), each slot + * spelled inline the same way. + * + * `approvalDecideRefused*` are the decision door's refusal of a submitter's + * own approval, as the end user reads it (the thrown error's `userMessage`): + * `SubmitterExcluded` when the step sets `excludeSubmitter`, `OverrideOwnRequest` + * when the administrator override would approve the actor's own request. Their + * `{{remedy}}` is the no-approver sentence above when no one else is on the + * slate (after the override, inside `OverrideWithdraw`), else + * `AnotherApprover` / `OverrideAnotherApprover`. The error's `message` keeps + * its English for the developer and the log. * * `approvalPlatformAdminSlotLabel` is not a sentence: it is the display label * of the platform administrators' slot (`platform_admin:*`), which names no @@ -82,8 +93,8 @@ import type { TranslationData } from '@objectstack/spec/system'; type Messages = NonNullable; -/** The ids, as `en` spells them — every other locale carries exactly these. */ -export const enMessages = { +/** The authored ids, as `en` spells them — every other locale carries exactly these. */ +const enSentences = { approvalRequestedTitle: 'Approval requested', approvalRequestedBody: 'A decision on {{object}} {{record}} is waiting on you.', approvalReminderTitle: 'Approval reminder', @@ -134,13 +145,76 @@ export const enMessages = { approvalNoApproverSlot: "{{type}} '{{value}}'", approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: "No one else can approve this request yet. An organization administrator must add a member who holds {{type}} '{{value}}'; that member can then decide it.", + approvalDecideRefusedSubmitterExcluded: 'You submitted this request, and its approval step keeps its submitter from approving it, so you cannot approve it. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'You submitted this request and hold no slot on it, so you cannot approve it through the administrator override. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'Another approver on the step decides it; if you hold the only slot, reassign it to someone else.', + approvalDecideRefusedOverrideAnotherApprover: 'An approver on the step decides it. To move it, reassign it to someone else, reject it, or recall it and send the record for approval again.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} To withdraw it instead, reject it or recall it.', approvalPlatformAdminSlotLabel: 'Platform administrators', } as const satisfies Messages; +/** An authored sentence's id: one every pack below spells by hand. */ +type AuthoredMessageId = keyof typeof enSentences; + +type ApprovalMessages = Readonly>; + +/** + * [#36463] The most slots the submitter's notice names one by one in the + * reader's language. A notice is rendered per recipient at delivery, where a + * hole takes one text or one hole-free key, so a list of slot clauses cannot + * ride as one param: a slate of `n` slots is spelled inline instead, in + * `approvalNoApproverHoldingSlots`, whose `{{type}}` / `{{value}}` + * holes are each one such param. A slate of more slots than this names them + * in English inside the reader's sentence (`noApproverNotice`). + */ +export const NO_APPROVER_NOTICE_MAX_SLOTS = 8; + +/** The derived id of the notice sentence for a slate of `n` slots, 2 to {@link NO_APPROVER_NOTICE_MAX_SLOTS}. */ +export type NoApproverHoldingSlotsId = `approvalNoApproverHoldingSlots${2 | 3 | 4 | 5 | 6 | 7 | 8}`; + +/** The derived id for a slate of `n` slots, or `undefined` outside 2 to {@link NO_APPROVER_NOTICE_MAX_SLOTS}. */ +export function noApproverHoldingSlotsId(n: number): NoApproverHoldingSlotsId | undefined { + return Number.isInteger(n) && n >= 2 && n <= NO_APPROVER_NOTICE_MAX_SLOTS + ? `approvalNoApproverHoldingSlots${n}` as NoApproverHoldingSlotsId + : undefined; +} + +/** + * [#36463] A pack's notice sentences for a slate of 2 to + * {@link NO_APPROVER_NOTICE_MAX_SLOTS} slots, derived from the three entries + * the timeline note composes the same sentence from: `approvalNoApproverHolding` + * with its `{{who}}` spelled as `n` `approvalNoApproverSlot` clauses (holes + * numbered from 1) joined by `approvalNoApproverSlotSeparator`. Derived, never + * hand-spelled, so the notice reads exactly what the timeline reads for the same + * slate and no translation is written twice. + */ +function slotListSentences( + pack: Pick, +): Record { + const out = {} as Record; + for (let n = 2; n <= NO_APPROVER_NOTICE_MAX_SLOTS; n++) { + const clauses = Array.from({ length: n }, (_, i) => pack.approvalNoApproverSlot + .replace('{{type}}', () => `{{type${i + 1}}}`) + .replace('{{value}}', () => `{{value${i + 1}}}`)); + const who = clauses.join(pack.approvalNoApproverSlotSeparator); + out[noApproverHoldingSlotsId(n)!] = pack.approvalNoApproverHolding.replace('{{who}}', () => who); + } + return out; +} + +/** A pack with its derived notice sentences. */ +function withSlotLists(pack: T): T & Record { + return { ...pack, ...slotListSentences(pack) }; +} + +/** The ids, as `en` spells them — every other locale carries exactly these. */ +export const enMessages = withSlotLists(enSentences); + /** One approval notification sentence's id. */ export type ApprovalMessageId = keyof typeof enMessages; -type ApprovalMessages = Readonly>; +/** A shipped locale's sentences: the authored ones and the derived ones. */ +type ShippedMessages = Readonly>; export const zhCNMessages: ApprovalMessages = { approvalRequestedTitle: '新的审批请求', @@ -193,6 +267,11 @@ export const zhCNMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}}「{{value}}」', approvalNoApproverSlotSeparator: '、', approvalNoApproverHoldingSlot: '目前还没有其他人能审批此请求。组织管理员需要添加一名担任{{type}}「{{value}}」的成员,之后由该成员决定。', + approvalDecideRefusedSubmitterExcluded: '此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。{{remedy}}', + approvalDecideRefusedOverrideOwnRequest: '此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。{{remedy}}', + approvalDecideRefusedAnotherApprover: '由该步骤的其他审批人决定;如果只有您持有审批席位,请将其转交给其他人。', + approvalDecideRefusedOverrideAnotherApprover: '由该步骤的审批人决定。如需改由他人处理,可将其转交给其他人、驳回它,或撤回后重新提交审批。', + approvalDecideRefusedOverrideWithdraw: '{{remedy}}如需撤销,请驳回或撤回该请求。', approvalPlatformAdminSlotLabel: '平台管理员', }; @@ -247,6 +326,11 @@ export const jaJPMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}}「{{value}}」', approvalNoApproverSlotSeparator: '、', approvalNoApproverHoldingSlot: 'このリクエストを承認できる人はまだ他にいません。組織の管理者が{{type}}「{{value}}」を担うメンバーを追加する必要があります。追加されたメンバーが判断できます。', + approvalDecideRefusedSubmitterExcluded: 'このリクエストはあなたが申請したもので、その承認ステップでは申請者が自分のリクエストを承認できないため、あなたは承認できません。{{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'このリクエストはあなたが申請したもので、あなたはその承認者に含まれていないため、管理者権限で代わりに承認することはできません。{{remedy}}', + approvalDecideRefusedAnotherApprover: 'このステップの他の承認者が判断します。承認枠を持つのがあなただけの場合は、他の人に再割り当てしてください。', + approvalDecideRefusedOverrideAnotherApprover: 'このステップの承認者が判断します。担当を変えるには、他の人に再割り当てするか、却下するか、取り下げてからレコードを再度承認に回してください。', + approvalDecideRefusedOverrideWithdraw: '{{remedy}}代わりに取りやめるには、却下するか取り下げてください。', approvalPlatformAdminSlotLabel: 'プラットフォーム管理者', }; @@ -301,6 +385,11 @@ export const esESMessages: ApprovalMessages = { approvalNoApproverSlot: "{{type}} '{{value}}'", approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: "Nadie más puede aprobar esta solicitud todavía. Un administrador de la organización debe añadir un miembro que ocupe {{type}} '{{value}}'; ese miembro podrá entonces decidirla.", + approvalDecideRefusedSubmitterExcluded: 'Usted envió esta solicitud y su paso de aprobación no permite que quien la envía la apruebe, así que no puede aprobarla. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'Usted envió esta solicitud y no ocupa ningún puesto de aprobación en ella, así que no puede aprobarla mediante la anulación de administrador. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'La decide otro aprobador del paso; si usted ocupa el único puesto, reasígnela a otra persona.', + approvalDecideRefusedOverrideAnotherApprover: 'La decide un aprobador del paso. Para moverla, reasígnela a otra persona, recházela o retírela y vuelva a enviar el registro a aprobación.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} Para retirarla en su lugar, recházela o retírela.', approvalPlatformAdminSlotLabel: 'Administradores de la plataforma', }; @@ -355,6 +444,11 @@ export const zhHantMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}}「{{value}}」', approvalNoApproverSlotSeparator: '、', approvalNoApproverHoldingSlot: '目前還沒有其他人能核准此請求。組織管理員需要新增一名擔任{{type}}「{{value}}」的成員,之後由該成員決定。', + approvalDecideRefusedSubmitterExcluded: '此請求由你提交,而其核准步驟不允許提交人核准自己的請求,因此你不能核准它。{{remedy}}', + approvalDecideRefusedOverrideOwnRequest: '此請求由你提交,且你不在其核准人之列,因此不能以管理員身分代為核准它。{{remedy}}', + approvalDecideRefusedAnotherApprover: '由該步驟的其他核准人決定;如果只有你持有核准席位,請將其轉交給其他人。', + approvalDecideRefusedOverrideAnotherApprover: '由該步驟的核准人決定。如需改由他人處理,可將其轉交給其他人、駁回它,或撤回後重新送出核准。', + approvalDecideRefusedOverrideWithdraw: '{{remedy}}如需撤銷,請駁回或撤回該請求。', approvalPlatformAdminSlotLabel: '平台管理員', }; @@ -409,6 +503,11 @@ export const arMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}} «{{value}}»', approvalNoApproverSlotSeparator: '، ', approvalNoApproverHoldingSlot: 'لا يمكن لأحد آخر الموافقة على هذا الطلب بعد. يجب على مسؤول المؤسسة إضافة عضو يشغل {{type}} «{{value}}»؛ وعندها يمكن لهذا العضو البتّ فيه.', + approvalDecideRefusedSubmitterExcluded: 'لقد قدّمت هذا الطلب، وخطوة الموافقة فيه لا تسمح لمقدّمه بالموافقة عليه، لذا لا يمكنك الموافقة عليه. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'لقد قدّمت هذا الطلب ولا تشغل أي مقعد موافقة فيه، لذا لا يمكنك الموافقة عليه عبر صلاحية تجاوز المسؤول. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'يبتّ فيه موافِق آخر في الخطوة؛ وإن كنت تشغل المقعد الوحيد، فأعد تعيينه إلى شخص آخر.', + approvalDecideRefusedOverrideAnotherApprover: 'يبتّ فيه موافِق في الخطوة. لنقله، أعد تعيينه إلى شخص آخر أو ارفضه أو استرجعه ثم أرسل السجل للموافقة مجددًا.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} لسحبه بدلًا من ذلك، ارفضه أو استرجعه.', approvalPlatformAdminSlotLabel: 'مسؤولو المنصة', }; @@ -463,6 +562,11 @@ export const frMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}} « {{value}} »', approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: 'Personne d’autre ne peut encore approuver cette demande. Un administrateur de l’organisation doit ajouter un membre qui occupe {{type}} « {{value}} » ; ce membre pourra alors la décider.', + approvalDecideRefusedSubmitterExcluded: 'Vous avez soumis cette demande, et son étape d’approbation interdit à son demandeur de l’approuver ; vous ne pouvez donc pas l’approuver. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'Vous avez soumis cette demande et n’y occupez aucun poste d’approbation ; vous ne pouvez donc pas l’approuver par la dérogation administrateur. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'Un autre approbateur de l’étape la décide ; si vous occupez le seul poste, réattribuez-la à quelqu’un d’autre.', + approvalDecideRefusedOverrideAnotherApprover: 'Un approbateur de l’étape la décide. Pour la déplacer, réattribuez-la à quelqu’un d’autre, rejetez-la, ou rappelez-la et renvoyez l’enregistrement en approbation.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} Pour la retirer plutôt, rejetez-la ou rappelez-la.', approvalPlatformAdminSlotLabel: 'Administrateurs de la plateforme', }; @@ -517,6 +621,11 @@ export const ptBRMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}} "{{value}}"', approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: 'Ninguém mais pode aprovar esta solicitação ainda. Um administrador da organização precisa adicionar um membro que ocupe {{type}} "{{value}}"; esse membro poderá então decidi-la.', + approvalDecideRefusedSubmitterExcluded: 'Você enviou esta solicitação, e a etapa de aprovação dela não permite que quem a enviou a aprove, então você não pode aprová-la. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'Você enviou esta solicitação e não ocupa nenhuma vaga de aprovação nela, então não pode aprová-la pela substituição de administrador. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'Outro aprovador da etapa a decide; se você ocupa a única vaga, reatribua-a a outra pessoa.', + approvalDecideRefusedOverrideAnotherApprover: 'Um aprovador da etapa a decide. Para movê-la, reatribua-a a outra pessoa, rejeite-a ou recolha-a e envie o registro para aprovação novamente.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} Para retirá-la em vez disso, rejeite-a ou recolha-a.', approvalPlatformAdminSlotLabel: 'Administradores da plataforma', }; @@ -571,6 +680,11 @@ export const ruMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}} «{{value}}»', approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: 'Пока больше никто не может согласовать этот запрос. Администратор организации должен добавить участника, занимающего {{type}} «{{value}}»; затем этот участник сможет принять решение.', + approvalDecideRefusedSubmitterExcluded: 'Вы отправили этот запрос, а его шаг согласования не позволяет отправителю согласовать его, поэтому вы не можете его согласовать. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'Вы отправили этот запрос и не занимаете в нём места согласующего, поэтому не можете согласовать его через права администратора. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'Решение принимает другой согласующий шага; если единственное место занимаете вы, переназначьте его на кого-то другого.', + approvalDecideRefusedOverrideAnotherApprover: 'Решение принимает согласующий шага. Чтобы передать запрос, переназначьте его на кого-то другого, отклоните его или отзовите и отправьте запись на согласование заново.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} Чтобы вместо этого отозвать его, отклоните или отзовите запрос.', approvalPlatformAdminSlotLabel: 'Администраторы платформы', }; @@ -625,6 +739,11 @@ export const deMessages: ApprovalMessages = { approvalNoApproverSlot: '{{type}} „{{value}}“', approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: 'Noch kann niemand sonst diese Anfrage genehmigen. Ein Administrator der Organisation muss ein Mitglied hinzufügen, das {{type}} „{{value}}“ innehat; dieses Mitglied kann dann darüber entscheiden.', + approvalDecideRefusedSubmitterExcluded: 'Sie haben diese Anfrage eingereicht, und ihr Genehmigungsschritt lässt den Einreicher sie nicht genehmigen, daher können Sie sie nicht genehmigen. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: 'Sie haben diese Anfrage eingereicht und haben keinen Platz darin inne, daher können Sie sie nicht über die Administratorüberschreibung genehmigen. {{remedy}}', + approvalDecideRefusedAnotherApprover: 'Ein anderer Genehmiger des Schritts entscheidet darüber; wenn Sie den einzigen Platz innehaben, weisen Sie ihn jemand anderem zu.', + approvalDecideRefusedOverrideAnotherApprover: 'Ein Genehmiger des Schritts entscheidet darüber. Um sie zu verschieben, weisen Sie sie jemand anderem zu, lehnen Sie sie ab, oder rufen Sie sie zurück und reichen Sie den Datensatz erneut zur Genehmigung ein.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} Um sie stattdessen zurückzuziehen, lehnen Sie sie ab oder rufen Sie sie zurück.', approvalPlatformAdminSlotLabel: 'Plattformadministratoren', }; @@ -679,20 +798,25 @@ export const koMessages: ApprovalMessages = { approvalNoApproverSlot: "{{type}} '{{value}}'", approvalNoApproverSlotSeparator: ', ', approvalNoApproverHoldingSlot: "아직 다른 누구도 이 요청을 승인할 수 없습니다. 조직 관리자가 {{type}} '{{value}}'을(를) 맡은 구성원을 추가해야 하며, 그러면 그 구성원이 결정할 수 있습니다.", + approvalDecideRefusedSubmitterExcluded: '이 요청은 회원님이 제출한 것이며, 해당 승인 단계는 제출자가 자신의 요청을 승인하지 못하게 하므로 회원님은 승인할 수 없습니다. {{remedy}}', + approvalDecideRefusedOverrideOwnRequest: '이 요청은 회원님이 제출한 것이며 회원님은 이 요청의 승인자가 아니므로, 관리자 재정의로 승인할 수 없습니다. {{remedy}}', + approvalDecideRefusedAnotherApprover: '이 단계의 다른 승인자가 결정합니다. 회원님만 승인 자리를 맡고 있다면 다른 사람에게 재할당하세요.', + approvalDecideRefusedOverrideAnotherApprover: '이 단계의 승인자가 결정합니다. 옮기려면 다른 사람에게 재할당하거나, 반려하거나, 회수한 뒤 레코드를 다시 승인 요청하세요.', + approvalDecideRefusedOverrideWithdraw: '{{remedy}} 대신 철회하려면 반려하거나 회수하세요.', approvalPlatformAdminSlotLabel: '플랫폼 관리자', }; /** The shipped locales, keyed as the bundle beside this file keys them. */ -export const approvalMessages: Readonly> = { +export const approvalMessages: Readonly> = { en: enMessages, - 'zh-CN': zhCNMessages, - 'ja-JP': jaJPMessages, - 'es-ES': esESMessages, - 'zh-Hant': zhHantMessages, - ar: arMessages, - fr: frMessages, - 'pt-BR': ptBRMessages, - ru: ruMessages, - de: deMessages, - ko: koMessages, + 'zh-CN': withSlotLists(zhCNMessages), + 'ja-JP': withSlotLists(jaJPMessages), + 'es-ES': withSlotLists(esESMessages), + 'zh-Hant': withSlotLists(zhHantMessages), + ar: withSlotLists(arMessages), + fr: withSlotLists(frMessages), + 'pt-BR': withSlotLists(ptBRMessages), + ru: withSlotLists(ruMessages), + de: withSlotLists(deMessages), + ko: withSlotLists(koMessages), }; diff --git a/packages/rest/src/approvals-routes.ts b/packages/rest/src/approvals-routes.ts index b02a20c10eb..08134961997 100644 --- a/packages/rest/src/approvals-routes.ts +++ b/packages/rest/src/approvals-routes.ts @@ -47,7 +47,7 @@ // `handleApprovalError` below. Constructor and reader share one module in // `@objectstack/types` because the producer is a PLUGIN and rest cannot // import one. -import { strandedDecisionDetails, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; +import { declaredUserMessage, strandedDecisionDetails, sendError as sendEnvelopeError, sendOk } from '@objectstack/types'; // [#29880] The declared value set of `sys_approval_request.status`. The // object's select options are built FROM this list (#3786), so it is the // object's own declaration, read where the object reads it, and not a second @@ -284,6 +284,16 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s // a `RESUME_FAILED` from a caller with no decision to report must // not be dressed up as one. const stranded = strandedDecisionDetails(err); + // [#36463] The refusal's end-user text, when the service marked one + // on the thrown error (`ApiErrorSchema.userMessage`: presence is the + // marking, read once through `declaredUserMessage`). At the top level + // of this flat body, the member the stranded envelope below already + // carries its own `userMessage` in, and the one `@objectstack/client` + // lifts from this dialect. Status-agnostic, as the contract declares + // it: every row answers it when the producer marked one, and none + // invents one. The decide refusal of a submitter's own approval is + // its producer, in the decider's language. + const marked = declaredUserMessage(err); for (const [re, status, code] of mapping) { if (re.test(msg)) { // [#13095] The strip is anchored to the CODE this row just @@ -300,6 +310,7 @@ export function registerApprovalsEndpoints(this: ApprovalsRouteHost, basePath: s res.status(status).json({ code, error: msg.replace(new RegExp(`^${code}:\\s*`), ''), + ...(marked !== undefined ? { userMessage: marked } : {}), // Anchored to the code the envelope describes, for the // same reason the strip above is: these four facts are // about a recorded-decision-with-stranded-run and diff --git a/packages/rest/src/rest-approvals-wire-codes.test.ts b/packages/rest/src/rest-approvals-wire-codes.test.ts index 9ec8ee68d27..ee11a1af234 100644 --- a/packages/rest/src/rest-approvals-wire-codes.test.ts +++ b/packages/rest/src/rest-approvals-wire-codes.test.ts @@ -504,3 +504,32 @@ describe('approvals wire codes are registered vocabulary (#8885)', () => { } }); }); + +// [#36463] A refusal the approvals service marks for the end user (the thrown +// error's `userMessage`, `ApiErrorSchema.userMessage`) reaches the wire at the +// top level of this door's flat body, beside the English `error` — the member +// `@objectstack/client` lifts from this dialect. The decide refusal of a +// submitter's own approval is its producer, in the decider's language. +describe('a refusal the approvals service marks for the end user carries its userMessage (#36463)', () => { + const ENGLISH = "'u_sub' submitted this request and holds no slot on it, so they cannot approve it through the " + + 'administrator override. No one else can approve this request yet.'; + const MARKED = '此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。'; + + it('the decide refusal answers 403 FORBIDDEN, its English as `error` and the marked text as `userMessage`', async () => { + const decide = vi.fn().mockRejectedValue(Object.assign(new Error(`FORBIDDEN: ${ENGLISH}`), { userMessage: MARKED })); + const answer = await drive(boot({ decide }), 'POST', `${REQ}/approve`); + expect(answer.status).toBe(403); + expect(answer.body).toEqual({ code: 'FORBIDDEN', error: ENGLISH, userMessage: MARKED }); + expect(ApiErrorSchema.safeParse({ + code: answer.body?.code, message: answer.body?.error, userMessage: answer.body?.userMessage, + }).success).toBe(true); + }); + + it('CONTROL: an unmarked refusal and a blank marking carry no userMessage member', async () => { + for (const thrown of [new Error(`FORBIDDEN: ${ENGLISH}`), Object.assign(new Error(`FORBIDDEN: ${ENGLISH}`), { userMessage: ' ' })]) { + const answer = await drive(boot({ decide: vi.fn().mockRejectedValue(thrown) }), 'POST', `${REQ}/approve`); + expect(answer.status).toBe(403); + expect(answer.body).toEqual({ code: 'FORBIDDEN', error: ENGLISH }); + } + }); +}); diff --git a/ui/apps/console/src/pages/system/ApprovalsInboxPage.inlineActionsVisible-34587.test.tsx b/ui/apps/console/src/pages/system/ApprovalsInboxPage.inlineActionsVisible-34587.test.tsx index c0ef524f95f..7a66ef9db8a 100644 --- a/ui/apps/console/src/pages/system/ApprovalsInboxPage.inlineActionsVisible-34587.test.tsx +++ b/ui/apps/console/src/pages/system/ApprovalsInboxPage.inlineActionsVisible-34587.test.tsx @@ -22,7 +22,7 @@ import '@testing-library/jest-dom/vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, cleanup, waitFor, within } from '@testing-library/react'; +import { render, screen, cleanup, waitFor, within, fireEvent } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; const APP = 'com.objectstack.account'; @@ -78,6 +78,13 @@ const { approvalsApiStub, ADAPTER, AUTH, I18N } = vi.hoisted(() => { return { approvalsApiStub, ADAPTER, AUTH, I18N }; }); +// objectstack#36463: the inline decision's failure toast is read off sonner. +const toasts = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() })); +vi.mock('sonner', async (importOriginal) => { + const real = await importOriginal>(); + return { ...real, toast: Object.assign((...args: unknown[]) => real.toast(...args), real.toast, toasts) }; +}); + vi.mock('@object-ui/i18n', async (importOriginal) => ({ ...(await importOriginal>()), useObjectTranslation: () => I18N, @@ -143,6 +150,8 @@ function hidingClasses(el: Element | null): string[] { beforeEach(() => { for (const fn of Object.values(approvalsApiStub)) fn.mockClear(); + toasts.error.mockClear(); + toasts.success.mockClear(); }); afterEach(cleanup); @@ -196,3 +205,37 @@ describe('Approvals Inbox — inline Approve / Reject shown by default (objectst } }); }); + +// objectstack#36463 — a decide refusal the server marked for the end user +// (`userMessage`, the decider's language) is the inline Approve's failure +// toast, ahead of the page's generic "not allowed" line; an unmarked refusal +// keeps that line. `approvalsApi.call` parks the body on `err.details`. +describe('Approvals Inbox — a marked decide refusal is shown as written (objectstack#36463)', () => { + const MARKED = '此请求由您提交,而其审批步骤不允许提交人批准自己的请求,因此您不能批准它。'; + const refusal = (userMessage?: string) => Object.assign( + new Error("FORBIDDEN: 'u_1' submitted this request, and its approval step sets excludeSubmitter, so they cannot approve it."), + { + code: 'FORBIDDEN', + status: 403, + details: { code: 'FORBIDDEN', error: 'refused', ...(userMessage !== undefined ? { userMessage } : {}) }, + }, + ); + + async function approveQuickFailingWith(err: Error) { + approvalsApiStub.approve.mockRejectedValueOnce(err); + const rowFor = await renderInbox(); + fireEvent.click(rowFor('Quick Invoice').approve); + const dialog = await screen.findByRole('alertdialog'); + fireEvent.click(within(dialog).getByRole('button', { name: 'Approve' })); + await waitFor(() => expect(toasts.error).toHaveBeenCalledTimes(1)); + return toasts.error.mock.calls[0][0]; + } + + it('the marked text is the toast', async () => { + expect(await approveQuickFailingWith(refusal(MARKED))).toBe(MARKED); + }); + + it('CONTROL: an unmarked refusal keeps the generic line', async () => { + expect(await approveQuickFailingWith(refusal())).toBe('You are not allowed to perform this action.'); + }); +}); diff --git a/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx b/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx index 5dd0e40064a..cc61321c02e 100644 --- a/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx +++ b/ui/apps/console/src/pages/system/ApprovalsInboxPage.tsx @@ -78,6 +78,7 @@ import { } from '@object-ui/components'; import { toast } from 'sonner'; import { useAuth } from '@object-ui/auth'; +import { declaredUserMessage } from '@object-ui/react'; import { useDisplayLocale, useObjectTranslation } from '@object-ui/i18n'; import { APPROVAL_STATUS_LABELS } from '@objectstack/spec/contracts'; import { @@ -877,6 +878,12 @@ function ApprovalsQueue() { /** Map raw API errors to business-readable toasts (no `HTTP_404: Not found`). */ const humanizeError = useCallback((err: any, fallback: string): string => { + // A refusal the server marked for the end user (`userMessage`, already in + // the request's language) is shown as written, before any generic line: + // the decide refusal of a submitter's own approval names what to do + // instead (objectstack#36463). `call` parks the body on `err.details`. + const marked = declaredUserMessage(err); + if (marked) return marked; const code = err?.code ?? ''; const status = err?.status ?? 0; if (code === 'NOT_IMPLEMENTED' || status === 501) { diff --git a/ui/packages/app-shell/src/utils/__tests__/flowLaunch.preDispatchRefusal-36390.test.tsx b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.preDispatchRefusal-36390.test.tsx index ce6e0dbd346..9219e90f731 100644 --- a/ui/packages/app-shell/src/utils/__tests__/flowLaunch.preDispatchRefusal-36390.test.tsx +++ b/ui/packages/app-shell/src/utils/__tests__/flowLaunch.preDispatchRefusal-36390.test.tsx @@ -140,3 +140,27 @@ describe('the api and script types reach the same door and show the same line', expect(await toastedBy(action, dispatchWith(recordNotFound()))).toEqual([MESSAGE]); }); }); + +// objectstack#36463 — the approvals door answers its refusals in the flat +// `{ code, error }` dialect, and a decide refusal of a submitter's own approval +// marks the decider's language at that body's top level. The `type: 'api'` +// Approve action on the request's page reads it there, as `@objectstack/client` +// does, so the toast is the decider's language rather than the English `error`. +describe('a flat approvals refusal shows its top-level userMessage (objectstack#36463)', () => { + const ACTION = { name: 'approval_approve', type: 'api', target: '/api/v1/approvals/requests/{id}/approve' } as ActionDef; + const ENGLISH = "'u_sub' submitted this request and holds no slot on it, so they cannot approve it through the administrator override."; + const MARKED = '此请求由您提交,且您不在其审批人之列,因此不能以管理员身份代为批准它。'; + + it('the marked text is the toast; the English error is not', async () => { + const shown = await toastedBy(ACTION, async () => + apiActionRefusalResult({ status: 403 }, { code: 'FORBIDDEN', error: ENGLISH, userMessage: MARKED }, 'HTTP 403', 'zh-CN')); + expect(shown).toEqual([MARKED]); + }); + + it('CONTROL: unmarked, or marked blank, the toast reads the error as before', async () => { + for (const body of [{ code: 'FORBIDDEN', error: ENGLISH }, { code: 'FORBIDDEN', error: ENGLISH, userMessage: ' ' }]) { + const shown = await toastedBy(ACTION, async () => apiActionRefusalResult({ status: 403 }, body, 'HTTP 403', 'zh-CN')); + expect(shown).toEqual([ENGLISH]); + } + }); +}); diff --git a/ui/packages/app-shell/src/utils/flowResponse.ts b/ui/packages/app-shell/src/utils/flowResponse.ts index 0204b934f10..b16a5b5f03b 100644 --- a/ui/packages/app-shell/src/utils/flowResponse.ts +++ b/ui/packages/app-shell/src/utils/flowResponse.ts @@ -433,12 +433,25 @@ function refusalEnvelopeMessage( locale: string | undefined, ): string { return flowFailureMessage( - { userMessage: declaredUserMessage((json as { error?: unknown } | null | undefined)?.error) }, + { userMessage: refusalBodyUserMessage(json) }, actionErrorDetail(json, fallback), locale, ); } +/** + * A refusal body's producer-marked `userMessage`, from the two members + * `@objectstack/client` lifts it from: the ADR-0112 envelope's + * `error.userMessage`, else the top level of a flat `{ code, error }` body — + * the dialect the approvals door answers, where a decide refusal carries the + * decider's own language (objectstack#36463). One predicate for both: + * `declaredUserMessage`, so a blank or non-string value is no marking. + */ +function refusalBodyUserMessage(json: unknown): string | null { + const body = json as { error?: unknown; userMessage?: unknown } | null | undefined; + return declaredUserMessage(body?.error) ?? declaredUserMessage({ userMessage: body?.userMessage }); +} + /** * The error a `type: 'api'` action shows for a non-2xx answer (objectstack#27487 * — see the header). A `400 FLOW_FAILED` is a flow the endpoint ran, and reads