diff --git a/.changeset/34588-approval-request-full-record.md b/.changeset/34588-approval-request-full-record.md new file mode 100644 index 00000000000..7cae8b4aaa4 --- /dev/null +++ b/.changeset/34588-approval-request-full-record.md @@ -0,0 +1,18 @@ +--- +'@objectstack/plugin-approvals': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +feat(approvals): the approval request page shows the whole business record, not a six-field summary + +Clause-②: yes (widening — new @object-ui/i18n locale keys only; no metadata or schema accept set) +Metadata-protocol: none + +An approver used to see the request's amount and at most six fields under "As submitted", and had to open the business record to read the rest. The request page (`sys_approval_request_detail`) now draws the request whole, with no tabs: the header, the highlights, then the decision panel (`record:approval_decision`), last. + +- **On top:** the deciding comment on a decided request, and the request's declared decision actions, unchanged. +- **Left, "As submitted":** every field of the request's snapshot the reader may read, in the sections and order of the target object's default record page, each through the record page's own cell. Field-level security is unchanged: the service's per-reader redaction and the client's field verdicts both apply. The panel reads the target record once (`findOne`, no params). A field whose current value differs from the submitted one is marked "Changed" with its current value. If the record cannot be read, nothing is marked and the card says so. Below the card are the record's child tables (owned `master_detail` children and `relatedList: 'primary'` tables). They are read-only and show CURRENT rows, with a note saying so, because the snapshot keeps the record's own row only. +- **Right rail, in this order:** approval progress (the step line, the decision tally, and who the request waits on), the record's attachment fields, and the request's activity (its `sys_approval_action` thread, newest first). The activity is read only when the reader's verdict allows reading that object. In the console the approvals route answers that read for every party to the request. + +Nothing is editable on the page, and the snapshot's storage is unchanged. The record approvals panel and the request page now share one action-timeline component. New `approvalsInbox.*` keys in all eleven `@object-ui/i18n` packs: `snapshotChanged`, `snapshotCurrentValue`, `snapshotOpenRecord`, `snapshotCurrentUnreadable`, `snapshotChildCurrent`, `progressTitle`, `attachmentsTitle`. diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request-page.test.ts b/packages/plugins/plugin-approvals/src/sys-approval-request-page.test.ts index 07b6f499869..484213bd647 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request-page.test.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request-page.test.ts @@ -11,13 +11,11 @@ * * 1. the plugin's manifest carries the page, so the registry — and the * metadata API reading it — has it; - * 2. the page body is the one the ruling's build list names (a slotted page - * until the `tabs` slot retired, objectstack#27053; rebuilt as the same - * nodes in a `kind: 'full'` page): a header, one - * `record:approval_decision` node, `record:details`, `sys_approval_action` - * as the related list, no discussion thread, and a highlights strip that - * leaves `record_id` to the details grid (the seat's choice on the ui - * seat's design input `6081889955`) and names nothing by a machine name; + * 2. the page body: a header, a highlights strip that leaves `record_id` + * out and names nothing by a machine name, and ONE + * `record:approval_decision` node that draws the rest of the page, the + * business record as submitted and the rail of progress, attachments and + * activity (objectstack#34588); no tabs and no discussion thread; * 3. the page passes what `os validate` judges a page by — the parse, the * component-type vocabulary, the props rows and the build rules — with a * control for each half that can go red; @@ -49,8 +47,7 @@ const PAGE = SysApprovalRequestDetailPage as AnyRec; const COMPONENTS = (PAGE.regions?.[0]?.components ?? []) as AnyRec[]; const nodeOf = (type: string): AnyRec | undefined => COMPONENTS.find((c) => c.type === type); const HIGHLIGHTS = (nodeOf('record:highlights') ?? {}) as AnyRec; -const TAB_ITEMS = (nodeOf('page:tabs')?.properties?.items ?? []) as AnyRec[]; -/** Where the decision panel sits in the region: after the header, before the highlights. */ +/** Where the decision panel sits in the region: after the header and the highlights, last. */ const DECISION_AT = COMPONENTS.findIndex((c) => c.type === 'record:approval_decision'); /** The plugin's one manifest, as `init` registers it. */ @@ -134,15 +131,15 @@ describe('sys_approval_request detail page — served through the manifest', () }); describe('sys_approval_request detail page — the page body', () => { - it('authors exactly the header, the decision panel, the highlights and the tabs, in the slotted order', () => { - // The nodes the slotted page rendered, in the synthesizer's order: the - // header it fell through to, its `actions` slot, its `highlights` slot and - // its tab strip, whose first tab is the details body. Its `discussion` - // slot was empty, so there is no discussion node. The header reads the - // object's placed header actions live, as the synthesized one did: a bare - // `page:header` drew none, so an action another package places on the - // object at `record_header` was dropped (#29951). - expect(COMPONENTS.map((c) => c.type)).toEqual(['page:header', 'record:approval_decision', 'record:highlights', 'page:tabs']); + it('authors exactly the header, the highlights and the decision panel, the panel last (objectstack#34588)', () => { + // The panel draws the rest of the page: the business record as submitted, + // whole, and the rail of progress, attachments and activity, the activity + // last (maintainer 2026-11-17). The header reads the object's placed + // header actions live: a bare `page:header` drew none, so an action + // another package places on the object at `record_header` was dropped + // (#29951). + expect(COMPONENTS.map((c) => c.type)).toEqual(['page:header', 'record:highlights', 'record:approval_decision']); + expect(DECISION_AT).toBe(COMPONENTS.length - 1); expect(nodeOf('page:header')).toEqual({ type: 'page:header', properties: { placedActions: true } }); }); @@ -153,10 +150,10 @@ describe('sys_approval_request detail page — the page body', () => { }); it('highlights the object\'s highlightFields minus record_id, which the object itself keeps', () => { - // The seat's choice on the ui seat's design input: the page's strip drops - // `record_id` so the details grid keeps it (that grid is where the console - // draws the target-record card of the `record_id` / `object_name` pointer - // pair), and the object's `highlightFields` keeps it. + // The page reaches the record the `record_id` / `object_name` pointer pair + // names through the decision panel, which draws that record whole and + // links to it, so the strip leaves the pair out; the object's + // `highlightFields` keeps `record_id` for the other surfaces that read it. const declared = SysApprovalRequest.highlightFields ?? []; expect(declared).toContain('record_id'); expect(HIGHLIGHTS.type).toBe('record:highlights'); @@ -167,9 +164,7 @@ describe('sys_approval_request detail page — the page body', () => { it('names the flow by its label, process_label, in the strip and in the object\'s list alike', () => { // `process_name` is the machine source (`flow:NAME`); `process_label` is the // flow's label, served under that name by the approvals get. The object's - // list moves with the strip: the Details tab's bare `record:details` node - // draws the object's `highlightFields` minus the strip, so a strip-only - // change would put `process_name` in that tab. + // list moves with the strip, never the strip alone. const strip = HIGHLIGHTS.properties.fields as string[]; const declared = SysApprovalRequest.highlightFields ?? []; expect(strip[0]).toBe('process_label'); @@ -197,23 +192,16 @@ describe('sys_approval_request detail page — the page body', () => { expect(fields.current_step).toMatchObject({ type: 'text' }); }); - it('draws no Object chip: object_name, the target\'s API name, is in neither list, and the Details tab is the pointer pair\'s card', () => { + it('draws no Object chip: object_name, the target\'s API name, is in neither list', () => { // `object_name` holds the target object's API name (`showcase_announcement`) - // and the object declares no field holding that object's label. The page - // names the target object on the card the console draws for the - // `record_id` / `object_name` pair in the Details tab, which heads the - // record with its object's label. The object's list moves with the strip - // for the reason the flow chip's does: dropped from the strip alone, - // `object_name` would be drawn as a row in that tab. + // and the object declares no field holding that object's label. The + // decision panel names the target object beside the submitted record's + // heading, read from the object's definition. const strip = HIGHLIGHTS.properties.fields as string[]; const declared = SysApprovalRequest.highlightFields ?? []; const fields = SysApprovalRequest.fields as AnyRec; expect({ strip: strip.includes('object_name'), declared: declared.includes('object_name') }) .toEqual({ strip: false, declared: false }); - // The Details tab's bare `record:details` node draws the object's list - // minus the strip: the id half of the pair, whose type half names the - // target object. - expect(TAB_ITEMS[0].children).toEqual([{ type: 'record:details' }]); expect(declared.filter((f: string) => !strip.includes(f))).toEqual(['record_id']); expect(fields.record_id?.referenceVia).toBe('object_name'); // Control: the type half stays a declared, required field. It is dropped @@ -221,42 +209,18 @@ describe('sys_approval_request detail page — the page body', () => { expect(fields.object_name).toMatchObject({ type: 'text', required: true }); }); - it('tabs: Details is record:details, Timeline is sys_approval_action as a related list on request_id', () => { - expect(TAB_ITEMS.map((t) => t.label?.en)).toEqual(['Details', 'Timeline']); - expect(TAB_ITEMS[0].children).toEqual([{ type: 'record:details' }]); - const [timeline] = TAB_ITEMS[1].children as AnyRec[]; - expect(timeline.type).toBe('record:related_list'); - expect(timeline.properties).toMatchObject({ objectName: 'sys_approval_action', relationshipField: 'request_id' }); - // The relationship really points back at this object. + it('has no tabs: the panel draws the record and, last in its rail, the request\'s thread (objectstack#34588)', () => { + // The page had two tabs, Details (the pointer pair's card) and Timeline + // (`sys_approval_action` as a related list). Neither is a node any more. + const types = nodesOf(COMPONENTS).map((n) => n.type); + expect(types.filter((t) => t === 'page:tabs' || t === 'record:details' || t === 'record:related_list')).toEqual([]); + // The thread the panel reads really points back at this object. expect((SysApprovalAction.fields as AnyRec).request_id).toMatchObject({ type: 'lookup', reference: 'sys_approval_request' }); }); - it('names each Timeline step by its label, step_label, never by the node\'s machine id, step_name', () => { - // Both are stored on every `sys_approval_action` row: `step_name` is the - // Approval node's id (`dual_signoff`), `step_label` the step's label the - // service copies from the request (`actionRow`). The existence check below - // cannot tell them apart, since both are declared fields, so the choice is - // pinned here, the way the strip's `current_step_label` is. - const [timeline] = TAB_ITEMS[1].children as AnyRec[]; - const columns = timeline.properties.columns as string[]; - const fields = SysApprovalAction.fields as AnyRec; - expect({ label: columns.includes('step_label'), machine: columns.includes('step_name') }) - .toEqual({ label: true, machine: false }); - expect(fields.step_label).toMatchObject({ type: 'text', label: 'Approval Step' }); - // Control: the machine id stays a declared field. It is dropped from the - // Timeline, not from the object. - expect(fields.step_name).toMatchObject({ type: 'text' }); - }); - it('every field the page names exists on its object', () => { const requestFields = Object.keys(SysApprovalRequest.fields); - const actionFields = Object.keys(SysApprovalAction.fields); - const [timeline] = TAB_ITEMS[1].children as AnyRec[]; - const missing = [ - ...(HIGHLIGHTS.properties.fields as string[]).filter((f) => !requestFields.includes(f)).map((f) => `request.${f}`), - ...(timeline.properties.columns as string[]).filter((f) => !actionFields.includes(f)).map((f) => `action.${f}`), - ...(timeline.properties.sort as AnyRec[]).map((s) => s.field).filter((f) => !actionFields.includes(f)).map((f) => `action.${f}`), - ]; + const missing = (HIGHLIGHTS.properties.fields as string[]).filter((f) => !requestFields.includes(f)).map((f) => `request.${f}`); expect(missing).toEqual([]); }); diff --git a/packages/plugins/plugin-approvals/src/sys-approval-request.page.ts b/packages/plugins/plugin-approvals/src/sys-approval-request.page.ts index 458549cdc63..066dfa92191 100644 --- a/packages/plugins/plugin-approvals/src/sys-approval-request.page.ts +++ b/packages/plugins/plugin-approvals/src/sys-approval-request.page.ts @@ -17,32 +17,30 @@ import type { Page } from '@objectstack/spec/ui'; * * Strategy * -------- - * - `kind: 'full'` + `isDefault: true`: the page owns its tab strip, so it is - * drawn as authored at every width. It was a `kind: 'slotted'` page until - * the `tabs` slot retired (#27053); the rebuild renders the same nodes in - * the same order. Its `page:header` is the one the synthesizer supplied: + * - `kind: 'full'` + `isDefault: true`: the page is drawn as authored at + * every width. It was a `kind: 'slotted'` page until the `tabs` slot + * retired (#27053). Its `page:header` is the one the synthesizer supplied: * the request's title, and the object's placed header actions read live * (`placedActions: true`, #29951). The object places none of its own (its * decision actions are `record_section` ones, drawn by the panel below), so * the header draws only what an installed package places on * `sys_approval_request` at `record_header` / `record_more`. - * - After the header, ONE `record:approval_decision` node: the request's - * decision progress and its declared decision actions, the reply - * (`approval_comment`) included, in one panel. The type is declared with an - * empty strict props row, so the node carries no `properties` at all; the - * panel reads the bound request and the object's own actions. - * - The highlight strip is the object's `highlightFields` WITHOUT `record_id`. The - * details grid hides every field a mounted highlights strip shows, and - * `record_id` / `object_name` is a declared `referenceVia` pointer pair that - * the console draws as a card of the target record IN THE DETAILS GRID — a - * strip carrying `record_id` would take the card off the page. The object's - * own `highlightFields` keeps `record_id`: other surfaces read it, and only - * this page has a grid the pair must stay in. - * - The strip and the object's list change together, never the strip alone. - * The Details tab's `record:details` node authors neither `sections` nor - * `fields`, so it draws the object's `highlightFields` (the spec's declared - * fallback) minus the strip: a field the object lists and the strip drops - * moves into that tab. + * - Then the highlight strip: the object's `highlightFields` WITHOUT + * `record_id`. `record_id` / `object_name` is a declared `referenceVia` + * pointer pair, and the page reaches the record it points at through the + * panel below, which draws that record whole and links to it. The object's + * own `highlightFields` keeps `record_id`: other surfaces read it. The + * strip and the object's list change together, never the strip alone. + * - Then ONE `record:approval_decision` node, the rest of the page + * (#34588; maintainer 2026-11-17: 「审批页应该直接显示完整的记录;「动态」在 + * 最后」): the request's declared decision actions, the reply + * (`approval_comment`) included; the business record as submitted, whole, + * in its default record page's sections, with what changed since + * submission marked, and its child tables; and a right rail of approval + * progress, attachments and activity, the activity last. The type is + * declared with an empty strict props row, so the node carries no + * `properties` at all; the panel reads the bound request, its record and + * the object's own actions. * - The flow chip is `process_label` (the flow's label), not `process_name` * (the machine source, `flow:NAME`). The console reads a request through * the approvals get, which serves `process_label` by the one display-label @@ -57,30 +55,21 @@ import type { Page } from '@objectstack/spec/ui'; * no step at all serves neither field, and the strip draws no step chip. * - There is no Object chip. `object_name` is the target object's API name * as stored (`showcase_announcement`), and the object declares no field - * that holds that object's label. The page names the target object in the - * Details tab instead: the `record_id` / `object_name` pair's card heads the - * target record with its object's label, translated and read from the - * object's definition when the page draws, so a relabelled object reads its - * new label. Where the card cannot read the target (the reader may not - * read it, or the platform deleted it), the page names no object at all. - * `object_name` leaves the object's `highlightFields` too, by the rule - * above, so the Details tab does not draw it as a row. - * - The tab strip is authored: Details (`record:details`, a bare node: see - * the strip above) and Timeline — `sys_approval_action` as a - * related list keyed on `request_id`, newest first. Its step column is - * `step_label` (the step's label, stored on every row), not `step_name` - * (the node's machine id, such as `dual_signoff`), as the strip's step - * chip is `current_step_label`. + * that holds that object's label. The panel names the target object + * beside the submitted record's heading, translated and read from the + * object's definition when the page draws. + * - There are no tabs. The page had two: Details (the pointer pair's card) + * and Timeline (`sys_approval_action` as a related list). The panel now + * draws the record itself and, last in its rail, the request's thread. * - There is no `record:discussion` node: the generic discussion thread has - * no place here. A request's thread is its timeline, and its reply is the + * no place here. A request's thread is its activity, and its reply is the * declared `approval_comment` action, which the service stores as a - * `sys_approval_action` row the Timeline tab lists. - * - There is no aside: the page places only its `main` region. + * `sys_approval_action` row the activity lists. + * - There is no aside region: the panel lays out its own rail, so the rail + * and the record stack in one order on a narrow screen. * - * Copy inside the components is authored as inline locale maps, the ruled route for - * page prose; the page-level `label` is the one key a translation bundle - * reaches (`pages.sys_approval_request_detail.label`, in - * `translations/pages.ts`). + * The page-level `label` is the one key a translation bundle reaches + * (`pages.sys_approval_request_detail.label`, in `translations/pages.ts`). */ export const SysApprovalRequestDetailPage: Page = { name: 'sys_approval_request_detail', @@ -103,10 +92,7 @@ export const SysApprovalRequestDetailPage: Page = { // dropped it, #29951); the host appends its system actions. { type: 'page:header', properties: { placedActions: true } }, - // ── The decision panel ──────────────────────────────────────── - { type: 'record:approval_decision' }, - - // ── Highlight chips, `record_id` left to the details grid ───── + // ── Highlight chips, `record_id` left out (see the header) ───── { type: 'record:highlights', properties: { @@ -114,39 +100,9 @@ export const SysApprovalRequestDetailPage: Page = { }, }, - // ── Tabs: the request's fields, then its timeline ───────────── - { - type: 'page:tabs', - properties: { - tabStyle: 'line', - position: 'top', - items: [ - { - label: { en: 'Details', 'zh-CN': '详情', 'ja-JP': '詳細', 'es-ES': 'Detalles', 'zh-Hant': '詳細資料', 'ar': 'التفاصيل', 'fr': 'Détails', 'pt-BR': 'Detalhes', 'ru': 'Подробности', 'de': 'Details', 'ko': '세부 정보' }, - icon: 'file-text', - children: [{ type: 'record:details' }], - }, - { - label: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología', 'zh-Hant': '時間軸', 'ar': 'المخطط الزمني', 'fr': 'Chronologie', 'pt-BR': 'Linha do tempo', 'ru': 'Хронология', 'de': 'Verlauf', 'ko': '타임라인' }, - icon: 'history', - children: [ - { - type: 'record:related_list', - properties: { - objectName: 'sys_approval_action', - relationshipField: 'request_id', - columns: ['created_at', 'action', 'actor_id', 'step_label', 'comment', 'attachments'], - sort: [{ field: 'created_at', order: 'desc' }], - limit: 50, - showViewAll: true, - title: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología', 'zh-Hant': '時間軸', 'ar': 'المخطط الزمني', 'fr': 'Chronologie', 'pt-BR': 'Linha do tempo', 'ru': 'Хронология', 'de': 'Verlauf', 'ko': '타임라인' }, - }, - }, - ], - }, - ], - }, - }, + // ── The request, whole: decisions, the record as submitted, and the + // rail of progress, attachments and activity (objectstack#34588) ── + { type: 'record:approval_decision' }, // No `record:discussion` node: the reply is `approval_comment`. ], diff --git a/packages/spec/liveness/field.json b/packages/spec/liveness/field.json index 6525313fff9..e31930cc71b 100644 --- a/packages/spec/liveness/field.json +++ b/packages/spec/liveness/field.json @@ -156,7 +156,7 @@ "status": "live", "verifiedAt": "2026-10-27", "evidenceScope": "in-repo", - "evidence": "ui/packages/core/src/evaluator/deadlineSettled.ts#isDeadlineSettled (the one host helper: `true` only when the field declares `dueLike: true` and a `settledWhen` that holds for the row, evaluated through `evalRowPredicate` with `record` bound; a predicate that fails to evaluate answers not settled); ui/packages/fields/src/index.tsx#resolveDueLike (the date and datetime cells take the host's verdict as `deadlineSettled`, and a settled deadline paints as a non-deadline: no overdue wording, no overdue colour); ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx#useObjectGridGenerateColumns (the grid asks the helper per row and hands each date cell its answer); ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.tsx#FieldFace (the approval snapshot judges the predicate against the snapshot's own values)", + "evidence": "ui/packages/core/src/evaluator/deadlineSettled.ts#isDeadlineSettled (the one host helper: `true` only when the field declares `dueLike: true` and a `settledWhen` that holds for the row, evaluated through `evalRowPredicate` with `record` bound; a predicate that fails to evaluate answers not settled); ui/packages/fields/src/index.tsx#resolveDueLike (the date and datetime cells take the host's verdict as `deadlineSettled`, and a settled deadline paints as a non-deadline: no overdue wording, no overdue colour); ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx#useObjectGridGenerateColumns (the grid asks the helper per row and hands each date cell its answer); ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx#FieldFace (the approval request page judges the predicate against the row the value comes from: the snapshot's own values for a submitted value, the current row for a changed field's current value)", "producer": "ui/packages/plugin-grid/src/objectGridGenerateColumns.tsx#useObjectGridGenerateColumns copies the object definition's `settledWhen` onto the column's field metadata beside `dueLike` on each of its three column paths; ui/packages/plugin-detail/src/fieldEnrichment.ts#ENRICHED_FIELD_METADATA_KEYS copies it onto a detail-view field; ui/packages/plugin-grid/src/objectGridRowLoad.ts#useObjectGridRowLoad and ui/packages/plugin-list/src/ListView.tsx#ListView fetch the predicate's operands for a shown deadline, so a list that does not show the column the predicate reads still judges the row", "note": "Deadline settle predicate, `date` / `datetime` with `dueLike: true` only (the parse door refuses it off type or without `dueLike`; lint's field-rule pass judges the CEL at `os build`, `os validate` and the object save door, the way it judges `visibleWhen`). LIVE in the console since objectui#11815 landed: while the predicate holds for a record, that record's deadline shows no overdue wording and no overdue colour. Readers beyond the four in the evidence ask the same helper per row and hand its answer to the same cell: the record detail sections (plugin-detail DetailSection, HeaderHighlight and RelatedList), the kanban card (plugin-kanban ObjectKanban), the gallery and compact list (plugin-list ObjectGallery, ListViewCompact) and the tree (plugin-tree ObjectTree); each surface is pinned by its own `deadlineSettled-11815` test under ui/packages. CORRECTED 2026-10-27 from `planned`: the row was written ahead of that landing and not flipped when it came. Display only: nothing on the write path reads it. No `authorWarn` was ever set, so none is dropped." }, diff --git a/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummary-12483.test.tsx b/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummary-12483.test.tsx index 9804f43fa28..be87dad6daa 100644 --- a/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummary-12483.test.tsx +++ b/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummary-12483.test.tsx @@ -2,12 +2,20 @@ * ObjectUI * Copyright (c) 2024-present ObjectStack Inc. * - * objectui#12483 (face 2 of ruling C on objectui#12438): the page objectstack - * serves for an approval request shows the request's declared amount and a - * summary of its record snapshot, under the target object's declared labels, - * each value through the record page's own cell, with the object's - * `hidden: true` fields trimmed and a field the reader may not read never - * drawn, as the approvals inbox's request sheet shows them. + * The page objectstack serves for an approval request draws the business + * record WHOLE (objectstack#34588; maintainer 2026-11-17: 「审批页应该直接显示 + * 完整的记录」): every field of the request's snapshot the reader may read, + * under the target object's declared labels, each value through the record + * page's own cell, with the object's `hidden: true` fields trimmed and a field + * the reader may not read never drawn. A field changed after submission is + * marked, with its current value. + * + * This file pinned the summary that came before it (objectui#12483, face 2 of + * ruling C on objectui#12438): the declared amount as a lead, then at most six + * rows, with no read of the record. #34588 retires the lead, the six-row cut + * and the no-read rule; the faces it keeps (declared labels, the record page's + * cell, the hidden trim, field permissions, an undeclared key takes no row, + * labels told apart) are pinned here against the full record. * * Mounted as `approvalRequestsDataSource.servedPageApprovers-12482.test.tsx` * mounts it: the REAL `RecordDetailView`, opened by the generic record route @@ -16,17 +24,6 @@ * is objectstack `plugin-approvals`' `sys_approval_request_detail` copied * whole. Only the HTTP transport, the console adapter and the metadata store * are doubled. - * - * The sheet's pins were the spec of the face, matched by assertion and not by - * markup, and the first two retired with the sheet (objectui#12484), against - * this file: `ApprovalsInboxPage.summaryFaces-11677.test.tsx` (declared labels, - * the record page's cell, an undeclared key takes no row, labels told apart), - * `ApprovalsInboxPage.hiddenFieldTrim.test.tsx` (a hidden field is dropped - * before the row cut and never leads) and - * `ApprovalsInboxPage.queueHiddenAmount.test.tsx` (a hidden amount is not - * shown). The amount here is the DECLARED one, a `currency` field: the sheet's - * key-name guess is deliberately not ported, and the last describe block pins - * that boundary. */ import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, within, waitFor } from '@testing-library/react'; @@ -194,7 +191,7 @@ const DEFS: Record = { invoice: INVOICE_DEF, }; -/** objectstack `plugin-approvals`' `SysApprovalRequestDetailPage`, whole (as of objectstack `09dd537193`). */ +/** objectstack `plugin-approvals`' `SysApprovalRequestDetailPage`, whole (as of objectstack#34588). */ const SERVED_PAGE = { name: 'sys_approval_request_detail', label: 'Approval Request', @@ -208,46 +205,14 @@ const SERVED_PAGE = { name: 'main', width: 'full', components: [ - { type: 'page:header' }, - { type: 'record:approval_decision' }, + { type: 'page:header', properties: { placedActions: true } }, { type: 'record:highlights', properties: { fields: ['process_label', 'status', 'current_step_label', 'submitter_id', 'updated_at'], }, }, - { - type: 'page:tabs', - properties: { - tabStyle: 'line', - position: 'top', - items: [ - { - label: { en: 'Details', 'zh-CN': '详情', 'ja-JP': '詳細', 'es-ES': 'Detalles' }, - icon: 'file-text', - children: [{ type: 'record:details' }], - }, - { - label: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología' }, - icon: 'history', - children: [ - { - type: 'record:related_list', - properties: { - objectName: 'sys_approval_action', - relationshipField: 'request_id', - columns: ['created_at', 'action', 'actor_id', 'step_name', 'comment', 'attachments'], - sort: [{ field: 'created_at', order: 'desc' }], - limit: 50, - showViewAll: true, - title: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología' }, - }, - }, - ], - }, - ], - }, - }, + { type: 'record:approval_decision' }, ], }, ], @@ -260,6 +225,9 @@ function json(status: number, body: unknown): Response { /** The row the approvals get serves for this case. */ let served: Record = BASE_ROW; +/** The target record as it reads now; null reads as not found. */ +let current: Record | null = null; + const transport = vi.fn(async (input: RequestInfo | URL, init?: RequestInit): Promise => { const raw = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url; const url = new URL(raw, 'http://test.local'); @@ -272,7 +240,7 @@ vi.stubGlobal('fetch', transport); const host = { find: vi.fn(async (_resource: string, _params?: unknown) => ({ data: [], total: 0 })), - findOne: vi.fn(async (_resource: string, _id: string) => null), + findOne: vi.fn(async (resource: string, id: string) => (resource === 'invoice' && id === 'inv_1' ? current : null)), create: vi.fn(), update: vi.fn(), delete: vi.fn(), getObjectSchema: vi.fn(async (name: string) => DEFS[name] ?? null), }; @@ -340,34 +308,28 @@ async function openServedPage( return panel; } -/** The summary once the target's definition answered. */ -async function summaryOf(panel: HTMLElement): Promise { - return within(panel).findByTestId('record-snapshot-summary', undefined, { timeout: 8000 }); +/** The record card once the target's definition answered. */ +async function recordOf(panel: HTMLElement): Promise { + return within(panel).findByTestId('submitted-record', undefined, { timeout: 8000 }); } -/** The summary's rows, as `{ field key -> { label, value } }`. */ -function summaryRows(panel: HTMLElement): Map { +/** The card's fields, in drawn order, as `{ field key -> { label, value } }`. */ +function recordFields(panel: HTMLElement): Map { const out = new Map(); - for (const row of panel.querySelectorAll('[data-summary-field]')) { - const [label, value] = Array.from(row.children); - out.set(row.getAttribute('data-summary-field') as string, { + for (const row of panel.querySelectorAll('[data-submitted-field]')) { + const label = row.querySelector('dt'); + const value = row.querySelector('dd'); + // The value as submitted; a "Changed" note under it is read separately. + const note = value?.querySelector('[data-submitted-current]'); + const text = (value?.textContent ?? '').replace(note?.textContent ?? '\u0000', ''); + out.set(row.getAttribute('data-submitted-field') as string, { label: (label?.textContent ?? '').trim(), - value: (value?.textContent ?? '').trim(), + value: text.trim(), }); } return out; } -function lead(panel: HTMLElement): { key: string | null; label: string; value: string } | null { - const el = panel.querySelector('[data-summary-lead]'); - if (!el) return null; - return { - key: el.getAttribute('data-summary-lead'), - label: (el.children[0]?.textContent ?? '').trim(), - value: (el.children[1]?.textContent ?? '').trim(), - }; -} - /** What the record page draws for this declaration and stored value, standalone. */ function recordPageFace(field: string, value: unknown): string { const def = { ...INVOICE_FIELDS[field], name: field }; @@ -383,22 +345,29 @@ const pageText = () => document.body.textContent ?? ''; afterEach(() => { cleanup(); served = BASE_ROW; + current = null; defs = DEFS; + host.findOne.mockClear(); getItem.mockClear(); transport.mockClear(); }); -describe('the served request page shows the declared amount and a summary of the snapshot (objectui#12483)', () => { - it('the served page parses as a spec page, with no node or prop added for the summary', () => { +/** Every declared, visible, non-bookkeeping field of `PAYLOAD`, in the object's declared order. */ +const ALL_DRAWN = ['name', 'account', 'contact', 'cost_center', 'region', 'status', 'issued_on', 'amount', 'total_amount', 'tax_rate']; + +describe('the served request page draws the submitted record whole (objectstack#34588, was objectui#12483)', () => { + it('the served page parses as a spec page, and the decision panel is its last node, with no prop', () => { const parsed = PageSchema.safeParse(SERVED_PAGE); expect(parsed.success, JSON.stringify(parsed.error?.issues ?? [])).toBe(true); - expect(SERVED_PAGE.regions[0].components[1]).toEqual({ type: 'record:approval_decision' }); + const components = SERVED_PAGE.regions[0].components; + expect(components[components.length - 1]).toEqual({ type: 'record:approval_decision' }); + expect(JSON.stringify(SERVED_PAGE)).not.toContain('page:tabs'); }); it('declared labels and the record page\'s faces: option labels, the date face, a resolved reference by its name', async () => { const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - const rows = summaryRows(panel); + await recordOf(panel); + const rows = recordFields(panel); expect(rows.get('region')).toEqual({ label: 'Region', value: recordPageFace('region', 'emea') }); expect(rows.get('region')?.value).toBe('EMEA'); @@ -410,92 +379,118 @@ describe('the served request page shows the declared amount and a summary of the const labels = [...rows.values()].map((r) => r.label); expect(new Set(labels).size).toBe(labels.length); - // Bookkeeping columns and the unresolved reference take no row, and no id is printed. - for (const key of ['id', 'owner_id', 'created_at', 'contact']) expect(rows.has(key)).toBe(false); - for (const raw of ['con_x8Pq2LmN4pR7tZk3', 'acc_7Hq2LmN4pR7tZk91', '2026-07-23']) { - expect(within(panel).queryByText(raw)).toBeNull(); - } + // Bookkeeping columns take no row. + for (const key of ['id', 'owner_id', 'created_at']) expect(rows.has(key)).toBe(false); + // A reference the service did not resolve for this reader is drawn as the + // record page draws it: the lookup cell's unresolved-reference face. The + // summary dropped it to fit six rows; the whole record keeps it. + expect(rows.get('contact')).toEqual({ label: 'Contact', value: recordPageFace('contact', 'con_x8Pq2LmN4pR7tZk3') }); + for (const raw of ['acc_7Hq2LmN4pR7tZk91', '2026-07-23']) expect(within(panel).queryByText(raw)).toBeNull(); }); - it('the declared amount leads, under its declared label, through the currency face, and is not repeated as a row', async () => { + it('the amount is an ordinary field in its place, through the currency face, drawn once', async () => { const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - expect(lead(panel)).toEqual({ key: 'amount', label: 'Invoice Amount', value: recordPageFace('amount', 12500) }); - expect(lead(panel)?.value).toContain('12,500'); - expect(summaryRows(panel).has('amount')).toBe(false); + await recordOf(panel); + expect(panel.querySelector('[data-summary-lead]')).toBeNull(); + expect(recordFields(panel).get('amount')).toEqual({ label: 'Invoice Amount', value: recordPageFace('amount', 12500) }); + expect(panel.querySelectorAll('[data-submitted-field="amount"]')).toHaveLength(1); }); - it('a hidden field takes no row and the next field takes its slot', async () => { + it('a hidden field takes no row, and every other field is drawn: no row cut', async () => { const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - const rows = summaryRows(panel); - expect([...rows.keys()]).toEqual(['name', 'account', 'cost_center', 'region', 'status', 'issued_on']); + await recordOf(panel); + const rows = recordFields(panel); + expect([...rows.keys()]).toEqual(ALL_DRAWN); expect(rows.has('internal_score')).toBe(false); expect(pageText()).not.toContain('87,654'); expect(pageText()).not.toContain('87654'); }); - it('COUNTER-PROBE: the same snapshot with nothing declared hidden draws that field, and the last row is cut', async () => { + it('COUNTER-PROBE: the same snapshot with nothing declared hidden draws that field, and nothing is cut', async () => { const shown = { ...INVOICE_FIELDS, internal_score: { type: 'number', label: 'Internal Score' } }; defs = { ...DEFS, invoice: { ...INVOICE_DEF, fields: shown } }; const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - const rows = summaryRows(panel); - expect([...rows.keys()]).toEqual(['name', 'account', 'cost_center', 'internal_score', 'region', 'status']); + await recordOf(panel); + const rows = recordFields(panel); expect(rows.get('internal_score')?.label).toBe('Internal Score'); + expect(rows.size).toBe(ALL_DRAWN.length + 1); + expect(rows.has('tax_rate')).toBe(true); }); - it('a hidden amount never leads, and is shown nowhere', async () => { + it('a hidden amount is shown nowhere', async () => { const hiddenAmount = { ...INVOICE_FIELDS, amount: { ...INVOICE_FIELDS.amount, hidden: true } }; defs = { ...DEFS, invoice: { ...INVOICE_DEF, fields: hiddenAmount } }; const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - expect(lead(panel)).toBeNull(); - expect(summaryRows(panel).has('amount')).toBe(false); + await recordOf(panel); + expect(recordFields(panel).has('amount')).toBe(false); expect(pageText()).not.toContain('12,500'); }); - it('a field the reader may not read is never drawn, and its slot goes to the next field', async () => { + it('a field the reader may not read is never drawn', async () => { const panel = await openServedPage(BASE_ROW, readerWithout('cost_center', 'amount')); - await summaryOf(panel); - const rows = summaryRows(panel); - expect(rows.has('cost_center')).toBe(false); - expect(lead(panel)).toBeNull(); + await recordOf(panel); + const rows = recordFields(panel); expect(pageText()).not.toContain('CC-LEDGER-SECRET'); expect(pageText()).not.toContain('12,500'); - expect([...rows.keys()]).toEqual(['name', 'account', 'region', 'status', 'issued_on', 'total_amount']); + expect([...rows.keys()]).toEqual(ALL_DRAWN.filter((k) => k !== 'cost_center' && k !== 'amount')); }); - it('COUNTER-PROBE: the same reader allowed every field sees the cost center', async () => { + it('COUNTER-PROBE: the same reader allowed every field sees the cost center and the amount', async () => { const panel = await openServedPage(BASE_ROW, readerWithout()); - await summaryOf(panel); - expect(summaryRows(panel).get('cost_center')).toEqual({ label: 'Cost Center', value: 'CC-LEDGER-SECRET' }); - expect(lead(panel)?.key).toBe('amount'); + await recordOf(panel); + expect(recordFields(panel).get('cost_center')).toEqual({ label: 'Cost Center', value: 'CC-LEDGER-SECRET' }); + expect(recordFields(panel).has('amount')).toBe(true); }); - it('the summary costs no read beyond the approvals get: the snapshot is in the row, the definition in the metadata store', async () => { + it('the record is read once, through the console adapter, to mark what changed after submission', async () => { + current = { ...PAYLOAD, amount: 13250, account: { id: 'acc_7Hq2LmN4pR7tZk91', name: 'Fabrikam' } }; const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - expect(getItem).toHaveBeenCalledWith('object', 'invoice'); + await recordOf(panel); + await waitFor(() => expect(panel.querySelector('[data-submitted-field="amount"][data-changed="true"]')).not.toBeNull(), { timeout: 8000 }); + const invoiceReads = host.findOne.mock.calls.filter(([resource]) => resource === 'invoice'); + expect(invoiceReads.map(([resource, id]) => [resource, id])).toEqual([['invoice', 'inv_1']]); + // No params: the read the record page sends, not a narrowed one. + expect((invoiceReads[0] as unknown[])[2]).toBeUndefined(); + // The submitted value stays the value; the current one is beside it. + expect(recordFields(panel).get('amount')?.value).toBe(recordPageFace('amount', 12500)); + const amount = panel.querySelector('[data-submitted-field="amount"]') as HTMLElement; + expect(within(amount).getByTestId('submitted-field-changed').textContent).toBe('Changed'); + expect(amount.querySelector('[data-submitted-current]')?.textContent).toContain(recordPageFace('amount', 13250)); + // The same account, served expanded, is not a change. + expect(panel.querySelector('[data-submitted-field="account"]')?.getAttribute('data-changed')).not.toBe('true'); + expect(panel.querySelectorAll('[data-changed="true"]')).toHaveLength(1); + // The approvals get stays the only read of the request; no invoice path reaches the transport. const paths = transport.mock.calls.map(([input]) => new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, 'http://test.local').pathname); expect(paths.filter((p) => p.includes('invoice'))).toEqual([]); }); + + it('CONTROL: a record that does not read marks nothing, says so, and still draws the snapshot', async () => { + current = null; + const panel = await openServedPage(BASE_ROW); + await recordOf(panel); + expect(await within(panel).findByTestId('submitted-record-current-unreadable', undefined, { timeout: 8000 })).toBeTruthy(); + expect(panel.querySelectorAll('[data-changed="true"]')).toHaveLength(0); + expect([...recordFields(panel).keys()]).toEqual(ALL_DRAWN); + }); }); -describe('controls (objectui#12483)', () => { - it('CONTROL: a request with no payload draws no summary, and still its decisions', async () => { +describe('controls (objectui#12483, kept by objectstack#34588)', () => { + it('CONTROL: a request with no payload draws no record card, asks for neither its definition nor its record, and still decides', async () => { const { payload: _p, payload_display: _d, ...bare } = BASE_ROW; const panel = await openServedPage(bare); - await waitFor(() => expect(getItem).toHaveBeenCalledWith('object', 'invoice')); - expect(within(panel).queryByTestId('record-snapshot-summary')).toBeNull(); + // The panel has settled on the request: its rail is drawn. + await within(panel).findByTestId('approval-decision-progress', undefined, { timeout: 8000 }); + expect(within(panel).queryByTestId('submitted-record')).toBeNull(); + expect(getItem).not.toHaveBeenCalledWith('object', 'invoice'); + expect(host.findOne.mock.calls.filter(([resource]) => resource === 'invoice')).toEqual([]); expect(within(panel).getByTestId('declared-action-approval_reject')).toBeTruthy(); }); - it('CONTROL: a payload key the object does not declare takes no row, as the sheet drops it', async () => { + it('CONTROL: a payload key the object does not declare takes no row', async () => { const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - expect(summaryRows(panel).has('legacy_note')).toBe(false); + await recordOf(panel); + expect(recordFields(panel).has('legacy_note')).toBe(false); expect(pageText()).not.toContain('snapshot-era column'); }); @@ -503,40 +498,38 @@ describe('controls (objectui#12483)', () => { const clash = { ...INVOICE_FIELDS, region: { ...INVOICE_FIELDS.region, label: 'Status' } }; defs = { ...DEFS, invoice: { ...INVOICE_DEF, fields: clash } }; const panel = await openServedPage(BASE_ROW); - await summaryOf(panel); - const rows = summaryRows(panel); + await recordOf(panel); + const rows = recordFields(panel); expect(rows.get('region')?.label).not.toBe(rows.get('status')?.label); expect(rows.get('region')?.label).toContain('Status'); expect(rows.get('status')?.label).toContain('Status'); }); - it('CONTROL: without the target object\'s definition nothing is summarized, and the panel still decides', async () => { + it('CONTROL: without the target object\'s definition nothing is drawn of the record, and the panel still decides', async () => { defs = { ...DEFS, invoice: null }; const panel = await openServedPage(BASE_ROW); await waitFor(() => expect(getItem).toHaveBeenCalledWith('object', 'invoice')); - expect(within(panel).queryByTestId('record-snapshot-summary')).toBeNull(); + expect(within(panel).queryByTestId('submitted-record')).toBeNull(); expect(pageText()).not.toContain('CC-LEDGER-SECRET'); expect(within(panel).getByTestId('declared-action-approval_approve')).toBeTruthy(); }); }); -describe('the amount is the declared one; a key name is not read (objectui#12483)', () => { - it('a roll-up the sheet\'s name guess would match is an ordinary row, not the amount', async () => { - // No currency field in the snapshot; `cost_center` is left out too, so the - // roll-up falls inside the six rows rather than being cut. - const { amount: _a, cost_center: _c, ...noCurrency } = PAYLOAD; +describe('a key name is not read as the amount (objectui#12483, kept by objectstack#34588)', () => { + it('a roll-up the sheet\'s name guess would match is an ordinary row, through its own cell', async () => { + const { amount: _a, ...noCurrency } = PAYLOAD; const panel = await openServedPage({ ...BASE_ROW, payload: noCurrency }); - await summaryOf(panel); - expect(lead(panel)).toBeNull(); - expect(summaryRows(panel).get('total_amount')).toEqual({ + await recordOf(panel); + expect(panel.querySelector('[data-summary-lead]')).toBeNull(); + expect(recordFields(panel).get('total_amount')).toEqual({ label: 'Line Total', value: recordPageFace('total_amount', 4321), }); }); - it('a declared amount of zero still leads: it is the record\'s amount', async () => { + it('a declared amount of zero is drawn: zero is a value, not an empty field', async () => { const panel = await openServedPage({ ...BASE_ROW, payload: { ...PAYLOAD, amount: 0 } }); - await summaryOf(panel); - expect(lead(panel)).toEqual({ key: 'amount', label: 'Invoice Amount', value: recordPageFace('amount', 0) }); + await recordOf(panel); + expect(recordFields(panel).get('amount')).toEqual({ label: 'Invoice Amount', value: recordPageFace('amount', 0) }); }); }); diff --git a/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummaryAmount-12534.test.tsx b/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummaryAmount-12534.test.tsx index fa9baf83486..64d4f63aaa7 100644 --- a/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummaryAmount-12534.test.tsx +++ b/ui/apps/console/src/services/approvalRequestsDataSource.servedPageSummaryAmount-12534.test.tsx @@ -2,13 +2,16 @@ * ObjectUI * Copyright (c) 2024-present ObjectStack Inc. * - * objectui#12534 (the summed-currency half of objectui#12483's declared - * amount): on the page objectstack serves for an approval request, the - * snapshot summary also leads with a `summary` field whose spec - * `summaryOperations` is a `sum` over a field the summarized object declares - * `type: 'currency'`, so the showcase's expense-report and invoice roll-up - * totals lead. The summarized object's definition is read through the same - * metadata-store path as the target's, once, for one object. + * Roll-up totals on the page objectstack serves for an approval request + * (objectstack#34588, was objectui#12534). The page used to summarize the + * snapshot under a lead amount, and objectui#12534 let a `summary` field whose + * `summaryOperations` is a `sum` over a `currency` field take that lead, which + * cost a read of the summarized object's definition. #34588 draws the record + * WHOLE (maintainer 2026-11-17: 「审批页应该直接显示完整的记录」), so there is + * no lead to take: every roll-up is an ordinary field in its place, through + * its own field's cell, and no summarized object's definition is read for it. + * The record's child lines are drawn instead, as a read-only table of the + * CURRENT rows (the snapshot keeps the record's own row only). * * Mounted as `approvalRequestsDataSource.servedPageSummary-12483.test.tsx` * mounts it (the REAL `RecordDetailView`, opened by the generic record route @@ -20,10 +23,9 @@ * declarations (`examples/app-showcase`, objectstack `9e0945cf4`): * `showcase_expense_report` with its `showcase_expense_line` roll-ups, * `showcase_invoice.total` over `showcase_invoice_line.amount`, and - * `showcase_product.unit_price` for the currency-only CONTROL. Only the HTTP - * transport, the console adapter and the metadata store are doubled. - */ -import { describe, it, expect, vi, afterEach } from 'vitest'; + * `showcase_product.unit_price`. Only the HTTP transport, the console adapter + * and the metadata store are doubled. + */import { describe, it, expect, vi, afterEach } from 'vitest'; import { render, screen, cleanup, within } from '@testing-library/react'; import { MemoryRouter, Routes, Route } from 'react-router-dom'; import type { ReactNode } from 'react'; @@ -227,7 +229,7 @@ const DEFS: Record = { showcase_product: PRODUCT_DEF, }; -/** objectstack `plugin-approvals`' `SysApprovalRequestDetailPage`, whole (as of objectstack `9e0945cf4`). */ +/** objectstack `plugin-approvals`' `SysApprovalRequestDetailPage`, whole (as of objectstack#34588). */ const SERVED_PAGE = { name: 'sys_approval_request_detail', label: 'Approval Request', @@ -241,46 +243,14 @@ const SERVED_PAGE = { name: 'main', width: 'full', components: [ - { type: 'page:header' }, - { type: 'record:approval_decision' }, + { type: 'page:header', properties: { placedActions: true } }, { type: 'record:highlights', properties: { fields: ['process_label', 'status', 'current_step_label', 'submitter_id', 'updated_at'], }, }, - { - type: 'page:tabs', - properties: { - tabStyle: 'line', - position: 'top', - items: [ - { - label: { en: 'Details', 'zh-CN': '详情', 'ja-JP': '詳細', 'es-ES': 'Detalles' }, - icon: 'file-text', - children: [{ type: 'record:details' }], - }, - { - label: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología' }, - icon: 'history', - children: [ - { - type: 'record:related_list', - properties: { - objectName: 'sys_approval_action', - relationshipField: 'request_id', - columns: ['created_at', 'action', 'actor_id', 'step_name', 'comment', 'attachments'], - sort: [{ field: 'created_at', order: 'desc' }], - limit: 50, - showViewAll: true, - title: { en: 'Timeline', 'zh-CN': '时间线', 'ja-JP': 'タイムライン', 'es-ES': 'Cronología' }, - }, - }, - ], - }, - ], - }, - }, + { type: 'record:approval_decision' }, ], }, ], @@ -350,9 +320,19 @@ const transport = vi.fn(async (input: RequestInfo | URL, init?: RequestInit): Pr }); vi.stubGlobal('fetch', transport); +/** The target record as it reads now; null reads as not found. */ +let current: Record | null = null; + +/** The expense report's lines as they read now. */ +const EXPENSE_LINES = [ + { id: 'line_1', expense_report: 'exp_1', merchant: 'Deutsche Bahn', amount: 240.5, billable: false, incurred_on: '2026-10-01' }, + { id: 'line_2', expense_report: 'exp_1', merchant: 'Hotel Adlon', amount: 1600, billable: false, incurred_on: '2026-10-02' }, +]; + const host = { - find: vi.fn(async (_resource: string, _params?: unknown) => ({ data: [], total: 0 })), - findOne: vi.fn(async (_resource: string, _id: string) => null), + find: vi.fn(async (resource: string, _params?: unknown) => + resource === 'showcase_expense_line' ? { data: EXPENSE_LINES, total: EXPENSE_LINES.length } : { data: [], total: 0 }), + findOne: vi.fn(async (_resource: string, id: string) => (current && current.id === id ? current : null)), create: vi.fn(), update: vi.fn(), delete: vi.fn(), getObjectSchema: vi.fn(async (name: string) => DEFS[name] ?? null), }; @@ -361,7 +341,7 @@ const host = { let defs: Record = DEFS; const getItem = vi.fn(async (type: string, name: string) => (type === 'object' ? (defs[name] ?? null) : null)); const metadata = { - apps: [], objects: [REQUEST_DEF, ACTION_DEF, USER_DEF], dashboards: [], reports: [], + apps: [], objects: [REQUEST_DEF, ACTION_DEF, USER_DEF] as unknown[], dashboards: [], reports: [], pages: [SERVED_PAGE], loading: false, error: null, refresh: async () => {}, invalidate: () => {}, ensureType: async () => [], getItem, @@ -419,33 +399,24 @@ async function openServedPage(row: Record, permissions?: MePerm return panel; } -async function summaryOf(panel: HTMLElement): Promise { - return within(panel).findByTestId('record-snapshot-summary', undefined, { timeout: 8000 }); +async function recordOf(panel: HTMLElement): Promise { + return within(panel).findByTestId('submitted-record', undefined, { timeout: 8000 }); } -/** The summary's rows, as `{ field key -> { label, value } }`. */ -function summaryRows(panel: HTMLElement): Map { +/** The card's fields, in drawn order, as `{ field key -> { label, value } }`. */ +function recordFields(panel: HTMLElement): Map { const out = new Map(); - for (const row of panel.querySelectorAll('[data-summary-field]')) { - const [label, value] = Array.from(row.children); - out.set(row.getAttribute('data-summary-field') as string, { - label: (label?.textContent ?? '').trim(), - value: (value?.textContent ?? '').trim(), + for (const row of panel.querySelectorAll('[data-submitted-field]')) { + const value = row.querySelector('dd'); + const note = value?.querySelector('[data-submitted-current]'); + out.set(row.getAttribute('data-submitted-field') as string, { + label: (row.querySelector('dt')?.textContent ?? '').trim(), + value: (value?.textContent ?? '').replace(note?.textContent ?? '\u0000', '').trim(), }); } return out; } -function lead(panel: HTMLElement): { key: string | null; label: string; value: string } | null { - const el = panel.querySelector('[data-summary-lead]'); - if (!el) return null; - return { - key: el.getAttribute('data-summary-lead'), - label: (el.children[0]?.textContent ?? '').trim(), - value: (el.children[1]?.textContent ?? '').trim(), - }; -} - /** What the record page draws for this declaration and stored value, standalone. */ function recordPageFace(def: Record, field: string, value: unknown): string { const declared = { ...(def.fields as Record>)[field], name: field }; @@ -464,12 +435,16 @@ const pageText = () => document.body.textContent ?? ''; afterEach(() => { cleanup(); served = requestRow('showcase_expense_report', EXPENSE_PAYLOAD); + current = null; defs = DEFS; + metadata.objects = [REQUEST_DEF, ACTION_DEF, USER_DEF]; + host.find.mockClear(); + host.findOne.mockClear(); getItem.mockClear(); transport.mockClear(); }); -describe('a `sum` summary over a currency field leads the served request page (objectui#12534)', () => { +describe('roll-up totals are ordinary fields of the whole record (objectstack#34588, was objectui#12534)', () => { it('the showcase declarations parse as spec objects, and the served page as a spec page', () => { for (const def of [EXPENSE_REPORT_DEF, EXPENSE_LINE_DEF, INVOICE_DEF, INVOICE_LINE_DEF, PRODUCT_DEF]) { const { owner_id: _o, created_at: _c, ...authored } = def.fields as Record; @@ -479,101 +454,79 @@ describe('a `sum` summary over a currency field leads the served request page (o expect(PageSchema.safeParse(SERVED_PAGE).success).toBe(true); }); - it('the expense report\'s total leads, under its declared label, through its own field\'s cell, and is not repeated as a row', async () => { + it("the expense report's total is drawn in its place, under its declared label, through its own field's cell, once", async () => { const panel = await openServedPage(requestRow('showcase_expense_report', EXPENSE_PAYLOAD)); - await summaryOf(panel); - expect(lead(panel)).toEqual({ - key: 'total_amount', + await recordOf(panel); + expect(panel.querySelector('[data-summary-lead]')).toBeNull(); + const rows = recordFields(panel); + expect(rows.get('total_amount')).toEqual({ label: 'Total', value: recordPageFace(EXPENSE_REPORT_DEF, 'total_amount', 1840.5), }); - expect(lead(panel)?.value).toContain('1,840.5'); - const rows = summaryRows(panel); - expect(rows.has('total_amount')).toBe(false); - // The other roll-ups of the same child are ordinary rows below it. - expect([...rows.keys()]).toEqual(['name', 'employee', 'status', 'submitted_on', 'approved_amount', 'reimbursable_amount']); + // Every roll-up of the same child, `sum` and `count` alike, in declared order. + expect([...rows.keys()]).toEqual([ + 'name', 'employee', 'status', 'submitted_on', + 'total_amount', 'approved_amount', 'reimbursable_amount', 'line_count', 'rejected_count', 'over_limit_count', + ]); + expect(rows.get('line_count')).toEqual({ label: 'Lines', value: recordPageFace(EXPENSE_REPORT_DEF, 'line_count', 4) }); }); - it('the invoice, which declares no currency field of its own, leads with its subtotal', async () => { + it("the invoice's subtotal is an ordinary field", async () => { const panel = await openServedPage(requestRow('showcase_invoice', INVOICE_PAYLOAD)); - await summaryOf(panel); - expect(lead(panel)).toEqual({ - key: 'total', - label: 'Subtotal', - value: recordPageFace(INVOICE_DEF, 'total', 9876.25), - }); - expect(summaryRows(panel).has('total')).toBe(false); + await recordOf(panel); + expect(recordFields(panel).get('total')).toEqual({ label: 'Subtotal', value: recordPageFace(INVOICE_DEF, 'total', 9876.25) }); }); - it('the summarized object\'s definition is read once, through the metadata store, and no record is read', async () => { + it("no summarized object's definition is read to draw a roll-up", async () => { const panel = await openServedPage(requestRow('showcase_expense_report', EXPENSE_PAYLOAD)); - await summaryOf(panel); + await recordOf(panel); const reads = definitionsRead(); - expect(reads.filter((n) => n === 'showcase_expense_report').length).toBeGreaterThan(0); - // Three `sum`s over one child, one read of that child. - expect(reads.filter((n) => n === 'showcase_expense_line')).toEqual(['showcase_expense_line']); - const paths = transport.mock.calls.map(([input]) => - new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url, 'http://test.local').pathname); - expect(paths.filter((p) => p.includes('expense'))).toEqual([]); - expect(host.findOne.mock.calls.filter(([resource]) => resource === 'showcase_expense_line')).toEqual([]); + expect(reads).toContain('showcase_expense_report'); + expect(reads).not.toContain('showcase_expense_line'); }); - it('a field the reader may not read is never drawn: without the total, the next `sum` leads', async () => { + it('a field the reader may not read is never drawn; the other roll-ups still are', async () => { const panel = await openServedPage(requestRow('showcase_expense_report', EXPENSE_PAYLOAD), readerWithout('total_amount')); - await summaryOf(panel); - expect(lead(panel)?.key).toBe('approved_amount'); - expect(summaryRows(panel).has('total_amount')).toBe(false); + await recordOf(panel); + const rows = recordFields(panel); + expect(rows.has('total_amount')).toBe(false); + expect(rows.has('approved_amount')).toBe(true); expect(pageText()).not.toContain('1,840.5'); }); -}); - -describe('controls (objectui#12534)', () => { - it('CONTROL: a summary that is not a `sum` is an ordinary row, and no other definition is read', async () => { - const { total_amount: _t, approved_amount: _a, reimbursable_amount: _r, ...counts } = EXPENSE_PAYLOAD; - const panel = await openServedPage(requestRow('showcase_expense_report', counts)); - await summaryOf(panel); - expect(lead(panel)).toBeNull(); - const rows = summaryRows(panel); - expect(rows.get('line_count')).toEqual({ label: 'Lines', value: recordPageFace(EXPENSE_REPORT_DEF, 'line_count', 4) }); - expect(rows.has('rejected_count')).toBe(true); - expect(definitionsRead()).not.toContain('showcase_expense_line'); - }); - - it('CONTROL: a `sum` over a field the summarized object declares `number` is an ordinary row', async () => { - const overQuantity = { - ...INVOICE_DEF, - fields: { - ...INVOICE_DEF.fields, - total: { ...INVOICE_DEF.fields.total, summaryOperations: { object: 'showcase_invoice_line', field: 'quantity', function: 'sum' } }, - }, - }; - defs = { ...DEFS, showcase_invoice: overQuantity }; - const panel = await openServedPage(requestRow('showcase_invoice', INVOICE_PAYLOAD)); - await summaryOf(panel); - expect(lead(panel)).toBeNull(); - expect(summaryRows(panel).get('total')).toEqual({ label: 'Subtotal', value: recordPageFace(INVOICE_DEF, 'total', 9876.25) }); - }); - it('CONTROL: the currency-only case keeps objectui#12483\'s amount, and reads no other definition', async () => { + it("the product's unit price, a plain currency field, is an ordinary field", async () => { const product = { id: 'prd_1', created_at: '2026-10-06T06:44:23.359Z', name: 'Widget', sku: 'W-1', unit_price: 49.5 }; const panel = await openServedPage(requestRow('showcase_product', product)); - await summaryOf(panel); - expect(lead(panel)).toEqual({ - key: 'unit_price', + await recordOf(panel); + expect(recordFields(panel).get('unit_price')).toEqual({ label: 'Unit Price', value: recordPageFace(PRODUCT_DEF, 'unit_price', 49.5), }); - expect(definitionsRead().every((n) => !n.endsWith('_line'))).toBe(true); }); +}); - it('CONTROL: when the summarized object\'s definition cannot be read, the total is an ordinary row', async () => { - defs = { ...DEFS, showcase_expense_line: null }; +describe("the record's child lines (objectstack#34588)", () => { + it('are drawn once the record reads: its current lines, read-only, headed as current rows', async () => { + metadata.objects = [REQUEST_DEF, ACTION_DEF, USER_DEF, EXPENSE_REPORT_DEF, EXPENSE_LINE_DEF]; + current = { ...EXPENSE_PAYLOAD }; const panel = await openServedPage(requestRow('showcase_expense_report', EXPENSE_PAYLOAD)); - await summaryOf(panel); - expect(lead(panel)).toBeNull(); - expect(summaryRows(panel).get('total_amount')).toEqual({ - label: 'Total', - value: recordPageFace(EXPENSE_REPORT_DEF, 'total_amount', 1840.5), - }); + const child = await within(panel).findByTestId('submitted-child-tables', undefined, { timeout: 8000 }); + const lines = child.querySelector('[data-submitted-child="showcase_expense_line"]') as HTMLElement; + expect(lines).not.toBeNull(); + expect(lines.querySelector('[data-submitted-child-note]')?.textContent) + .toBe('Current rows: the submission does not keep child rows.'); + expect(await within(lines).findByText('Hotel Adlon', undefined, { timeout: 8000 })).toBeTruthy(); + // Read-only: no New or Add. + expect(within(lines).queryByRole('button', { name: /^New$|Add/ })).toBeNull(); + expect(host.find.mock.calls.some(([resource]) => resource === 'showcase_expense_line')).toBe(true); + }); + + it('CONTROL: a record that does not read draws no child lines, and asks for none', async () => { + metadata.objects = [REQUEST_DEF, ACTION_DEF, USER_DEF, EXPENSE_REPORT_DEF, EXPENSE_LINE_DEF]; + current = null; + const panel = await openServedPage(requestRow('showcase_expense_report', EXPENSE_PAYLOAD)); + await within(panel).findByTestId('submitted-record-current-unreadable', undefined, { timeout: 8000 }); + expect(within(panel).queryByTestId('submitted-child-tables')).toBeNull(); + expect(host.find.mock.calls.some(([resource]) => resource === 'showcase_expense_line')).toBe(false); }); }); diff --git a/ui/packages/app-shell/README.md b/ui/packages/app-shell/README.md index f467e773a18..5c36ff07225 100644 --- a/ui/packages/app-shell/README.md +++ b/ui/packages/app-shell/README.md @@ -1267,48 +1267,49 @@ registers: ``` The block takes no props — its `properties` bag accepts only `{}`. It draws -from the request record the page binds: the server-computed decision progress -(when the request is pending and aggregates more than one decision) above the -request's own declared decision actions at `record_section`, each shown or -hidden by its `visible` predicate over the request's `viewer` block. A decided -request, or a viewer who may not decide, gets no decision buttons. After a -decision the request record and its timeline are re-read in place. Placed on -any other page, the block draws a short notice that it works only on approval -request pages. `className` styles the wrapper. - -Above the progress, the block shows what was submitted, from the request row's -record snapshot (`payload`) and the server's display values -(`payload_display`), against the target object's declared fields: the -declared amount (the first non-zero field declared `type: 'currency'`, or -declared `type: 'summary'` with a `summaryOperations` `sum` over a field the -summarized object declares `type: 'currency'`; else the first such field), -then the first six business fields, each under its declared label and through -the record page's own cell. Telling a roll-up total apart reads the -summarized object's definition from the metadata store, for one object at -most; if that definition cannot be read, the roll-up is an ordinary row. A -key that only looks like an amount by its name never leads. A key the object -does not declare, a framework column, an -unresolved reference id, a field declared `hidden: true` and a field the -reader may not read take no row. Without the target object's definition, the -summary is not drawn. The summary is headed "As submitted" -(`approvalsInbox.snapshotAsSubmitted`): the snapshot is the target record as it -was submitted, not its current state, so after a decision its values can -differ from the request's status in the page's highlights. The record's -current values are the Details tab's record card. - -Two more parts come from the same request row. A request no person submitted -(its `submitter_id` absent or null, as the approvals get serves a request a -flow run opened with no user context) is marked "Flow-initiated", above the -summary; a request a person submitted carries no marker. Below the summary, -the block draws the vertical step line of the request's own route -(`flow_route`, served by the approvals get) when it has more than one step, -at any status: the steps the request's flow run passed, its own step, and, -while it is pending, the steps ahead that the flow's graph alone decides. -Past an undecided branch nothing is drawn. The line is the same stepper the -record approvals panel draws, it never scrolls sideways, and it never draws -the row's `flow_steps`, the flow graph's first branch at every decision. The -marker and the line's accessible name are the Approval Center's -`approvalsInbox.*` rows. +the whole request from the request record the page binds, and objectstack's +request page (`sys_approval_request_detail`) puts it last, below the header +and the highlights, with no tabs (objectstack#34588). Placed on any other +page, the block draws a short notice that it works only on approval request +pages. `className` styles the wrapper. + +On top: a "Flow-initiated" marker when no person submitted the request (its +`submitter_id` absent or null), the deciding action's comment on a decided +request, and the request's own declared decision actions at +`record_section`, each shown or hidden by its `visible` predicate over the +request's `viewer` block. A decided request, or a viewer who may not decide, +gets no decision buttons. After a decision the request record and its thread +are re-read in place. + +Below, two columns (one on a narrow page): + +- **The record, as submitted** (`approvalsInbox.snapshotAsSubmitted`): every + field of the request's record snapshot (`payload`) the reader may read, in + the sections and order of the target object's default record page, each + under its declared label and through the record page's own cell, with the + server's display values (`payload_display`) for references. A field the + object does not declare, a framework column, a field declared + `hidden: true` and a field the reader may not read are not drawn. The block + also reads the target record once (`findOne`, no params): a field whose + current value differs from the submitted one is marked "Changed" + (`approvalsInbox.snapshotChanged`) with its current value beside it. If the + record cannot be read, nothing is marked and the card says so. Below the + card, the record's child tables (owned `master_detail` children and + `relatedList: 'primary'` tables), read-only, with their CURRENT rows and a + note saying so: the snapshot keeps the record's own row only. Without the + target object's definition, or with no snapshot, the record is not drawn. +- **The right rail**, in this order: approval progress (the vertical step line + of the request's own route, `flow_route`, when it has more than one step; + the server-computed decision tally when the request is pending and + aggregates more than one decision; who it waits on), the record's + attachment fields, and the request's activity: its thread + (`sys_approval_action`), newest first, read through the page's data source, + only for a reader whose verdict allows reading `sys_approval_action`. + +The step line is the same stepper the record approvals panel draws, it never +scrolls sideways, and it never draws the row's `flow_steps`, the flow graph's +first branch at every decision. Past an undecided branch nothing is drawn. +Copy is the Approval Center's `approvalsInbox.*` rows. ## User-scoped state (favorites, recent items) diff --git a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts index d335c88e2a3..83865e021ff 100644 --- a/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts +++ b/ui/packages/app-shell/src/console/__tests__/openPathObjectReaders-12811.test.ts @@ -105,6 +105,7 @@ const OBJECTS_READERS: Record = { }, 'packages/app-shell/src/views/RecordFormPage.tsx': { kind: 'off', why: 'a record form route' }, 'packages/app-shell/src/views/SearchResultsPage.tsx': { kind: 'off', why: 'the search route: every searchable object' }, + 'packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx': { kind: 'off', why: "the approval request page's child tables: the record's owned children from every object" }, 'packages/app-shell/src/views/global-search-renderer.tsx': { kind: 'action', why: 'the global search block reads every object only once the user types, after ensureType(\'object\') (objectui#12980)', diff --git a/ui/packages/app-shell/src/views/RecordApprovalsPanel.tsx b/ui/packages/app-shell/src/views/RecordApprovalsPanel.tsx index 8c404012dbc..e173cfd83e2 100644 --- a/ui/packages/app-shell/src/views/RecordApprovalsPanel.tsx +++ b/ui/packages/app-shell/src/views/RecordApprovalsPanel.tsx @@ -7,21 +7,17 @@ */ import * as React from 'react'; -import { useDisplayLocale } from '@object-ui/i18n'; import { cn, Badge, Button, useIsMobile } from '@object-ui/components'; -import { Stamp, Paperclip, Loader2, Send, ShieldAlert } from 'lucide-react'; +import { Stamp, Loader2, Send } from 'lucide-react'; import { toast } from 'sonner'; -import { createAuthenticatedFetch } from '@object-ui/auth'; import { useObjectTranslation } from '@object-ui/react'; import { isSubmitterOf, listApprovalActions, remindApprovalRequest, type ApprovalActionLite, - type ApprovalActionAttachmentLite, type ApprovalRequestLite, } from '../hooks/useRecordApprovals.js'; -import { isViaOverrideRow } from '../utils/approvalOverride.js'; import { approverCopyFrom, approverDisplay, @@ -38,6 +34,7 @@ import { import { ApprovalStepLine } from './approval-progress/ApprovalStepLine.js'; import { DecisionProgressIndicator } from './approval-progress/DecisionProgressIndicator.js'; import { eligibleApproverCount } from './approval-progress/eligibleApprovers.js'; +import { ApprovalActionTimeline } from './approval-progress/ApprovalActionTimeline.js'; /** * RecordApprovalsPanel — the record page's read-only approval surface @@ -101,20 +98,6 @@ const STATUS_CLASSES: Record = { returned: 'border-violet-200 bg-violet-50 text-violet-700 dark:border-violet-500/30 dark:bg-violet-500/10 dark:text-violet-400', }; -/** Timeline dot color per action kind — same palette as the Approval Center. */ -const ACTION_DOT: Record = { - approve: 'bg-emerald-500', - reject: 'bg-destructive', - submit: 'bg-blue-500', - reassign: 'bg-indigo-500', - remind: 'bg-amber-500', - request_info: 'bg-amber-500', - comment: 'bg-slate-400', - escalate: 'bg-red-500', - revise: 'bg-violet-500', - resubmit: 'bg-blue-500', -}; - /** * Identity formatting moved to `utils/approverIdentity` in `77f846a8b` — the * panel, the merged timeline and the admin-override dialog must not each own a @@ -189,16 +172,6 @@ export function approverChips( return order.map((k) => byKey.get(k)!); } -/** - * `locale` is REQUIRED: the timeline's action times used to be formatted with - * no tag, i.e. in the MACHINE's locale (objectui#9909). The panel passes - * `useDisplayLocale()`. - */ -function formatDate(s: string | null | undefined, locale: string): string { - if (!s) return '—'; - try { return new Date(s).toLocaleString(locale); } catch { return s; } -} - /** * The step a request or a timeline row names, as a reader should see it: the * authored step label when there is one, else the node's machine name @@ -229,7 +202,6 @@ export const RecordApprovalsPanel: React.FC = ({ className, }) => { const { t } = useObjectTranslation(); - const displayLocale = useDisplayLocale(); // objectstack#29070: on a phone Send reminder is a 44 px target (`lg`), not // the 24 px chip it is beside the approver chips on a desktop. const isMobile = useIsMobile(); @@ -330,30 +302,6 @@ export const RecordApprovalsPanel: React.FC = ({ } }, [pendingRequest, reloadActions, tr]); - /** - * Open a timeline attachment via its short-lived signed URL — same - * user-gesture-preserving dance as the Approval Center (framework#3266 - * follow-up): open the tab synchronously, then point it at the URL. - */ - const authFetch = React.useMemo(() => createAuthenticatedFetch(), []); - const openAttachment = React.useCallback(async (att: ApprovalActionAttachmentLite) => { - const win = window.open('', '_blank', 'noopener'); - try { - const base = String((import.meta as any).env?.VITE_SERVER_URL || '').replace(/\/$/, ''); - const res = await authFetch(`${base}/api/v1/storage/files/${encodeURIComponent(att.id)}/url`); - if (!res.ok) throw new Error(`HTTP_${res.status}`); - const body = await res.json().catch(() => null); - const raw = body?.data?.url ?? body?.url; - if (!raw) throw new Error('NO_URL'); - const url = /^https?:\/\//i.test(raw) ? raw : `${base}${raw}`; - if (win) win.location.href = url; - else window.open(url, '_blank', 'noopener'); - } catch { - win?.close(); - toast.error(tr('attachmentOpenFailed', 'Could not open the attachment — please try again')); - } - }, [authFetch, tr]); - // After all hooks: an unavailable plugin or a record with no requests // renders no chrome at all. if (!available || requests.length === 0 || !headline) return null; @@ -369,25 +317,6 @@ export const RecordApprovalsPanel: React.FC = ({ } }; - const actionText = (a: ApprovalActionLite): string => - a.action === 'submit' ? tr('actSubmit', 'Submitted') - : a.action === 'approve' ? tr('actApprove', 'Approved') - : a.action === 'reject' ? tr('actReject', 'Rejected') - : a.action === 'recall' ? tr('actRecall', 'Recalled') - : a.action === 'reassign' ? tr('actReassign', 'Reassigned') - : a.action === 'remind' ? tr('actRemind', 'Reminder sent') - : a.action === 'request_info' ? tr('actRequestInfo', 'Requested more info') - : a.action === 'comment' ? tr('actComment', 'Commented') - : a.action === 'escalate' ? tr('actEscalate', 'SLA escalated') - : a.action === 'revise' ? tr('actRevise', 'Sent back for revision') - : a.action === 'resubmit' ? tr('actResubmit', 'Resubmitted') - : a.action; - - const actorName = (a: ApprovalActionLite): string => - a.actor_id === 'system:sla' - ? tr('systemSlaActor', 'System (SLA)') - : a.actor_name ?? formatIdentity(a.actor_id); - /** * A timeline row's step label is its request's (objectui#13248). The server * writes `sys_approval_action.step_label` as a copy of the owning request's @@ -502,88 +431,7 @@ export const RecordApprovalsPanel: React.FC = ({
{tr('history', 'Activity')}
- {actionsLoading && actions.length === 0 ? ( -
- - {tr('loadingMore', 'Loading…')} -
- ) : actions.length === 0 ? ( -
{tr('noActions', 'No actions yet.')}
- ) : ( -
    - {actions.map((a) => ( -
  1. - {/* objectui#5178 — an admin override does not wear the ordinary - decision's dot. `approve` is emerald here, which is exactly - the "byte-for-byte like an ordinary approval" the card - reports; an override gets the amber attention dot instead, - so the distinction survives a glance down the timeline. */} - -
    - {actionText(a)} - · - {actorName(a)} - {/* The marker framework#4466 wrote and nothing read. Only an - explicit `via_override: true` earns it — see - `isViaOverrideRow` for why "not recorded" must not - render as either answer. */} - {isViaOverrideRow(a) && ( - - - {tr('viaOverrideChip', 'Admin override')} - - )} - {actionStepText(a) && ( - - · {actionStepText(a)} - - )} - - {formatDate(a.created_at, displayLocale)} - -
    - {a.action === 'reassign' && (a.reassign_from || a.reassign_to) && ( -
    - {tr('reassignFromTo', 'from {{from}} to {{to}}', { - from: a.reassign_from_name ?? formatIdentity(a.reassign_from), - to: a.reassign_to_name ?? formatIdentity(a.reassign_to), - })} -
    - )} - {a.comment && ( -
    "{a.comment}"
    - )} - {Array.isArray(a.attachments) && a.attachments.length > 0 && ( -
    - {a.attachments.map((att, i) => ( - - ))} -
    - )} -
  2. - ))} -
- )} + diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.decidedSnapshot-27502.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.decidedSnapshot-27502.test.tsx index 1690ced17b0..3a2ce4b5d81 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.decidedSnapshot-27502.test.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.decidedSnapshot-27502.test.tsx @@ -10,7 +10,8 @@ * After a decision, the approval request page must not tell two stories * (objectstack#27502, ruling record 6499914328). The page's highlights read the * REQUEST row, whose status moves to approved; the decision panel's summary - * reads the request's `payload`, the target record as it was SUBMITTED, which + * (since objectstack#34588 the whole submitted record, which used to be a + * six-field summary) reads the request's `payload`, the target record as it was SUBMITTED, which * keeps its submitted status (objectstack#10749, ruling record 5377367175: the * snapshot is kept as the evidence of what was submitted). So the summary is * labelled as the submitted values: a section whose accessible name is the @@ -117,22 +118,22 @@ function mount(data: Record): HTMLElement { describe('ApprovalDecisionPanel — the summary is labelled as the submitted values (objectstack#27502)', () => { it('a decided request: the snapshot keeps its submitted status, under the heading, and nobody is waited on', async () => { const panel = mount(requestRow('approved')); - const summary = await within(panel).findByTestId('record-snapshot-summary'); + const summary = await within(panel).findByTestId('submitted-record'); // The decided state the reload serves: nobody is waited on any more. expect(within(panel).queryByTestId('approval-decision-pending-approvers')).toBeNull(); // The summary is the region the heading names, and the heading is the pack row. expect(HEADING).not.toBe(HEADING_KEY); expect(within(panel).getByRole('region', { name: HEADING })).toBe(summary); - expect(summary.querySelector('[data-summary-heading]')?.textContent).toBe(HEADING); + expect(summary.querySelector('[data-submitted-heading]')?.textContent).toBe(HEADING); // What the section holds is the snapshot as submitted, under the declared select field. - const status = summary.querySelector('[data-summary-field="status"]'); + const status = summary.querySelector('[data-submitted-field="status"]'); expect(status?.textContent).toBe('StatusSubmitted'); }); it('a pending request carries the heading too: it names the source, not a status', async () => { const panel = mount(requestRow('pending')); - const summary = await within(panel).findByTestId('record-snapshot-summary'); + const summary = await within(panel).findByTestId('submitted-record'); expect(within(panel).getByTestId('approval-decision-pending-approvers')).toBeTruthy(); expect(within(panel).getByRole('region', { name: HEADING })).toBe(summary); @@ -144,7 +145,7 @@ describe('ApprovalDecisionPanel — the summary is labelled as the submitted val await waitFor(() => expect(seen).toContain(`object:${EXPENSE_REPORT.name}`)); await new Promise((r) => setTimeout(r, 0)); - expect(within(panel).queryByTestId('record-snapshot-summary')).toBeNull(); + expect(within(panel).queryByTestId('submitted-record')).toBeNull(); expect(within(panel).queryByText(HEADING)).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.fullRecord-34588.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.fullRecord-34588.test.tsx new file mode 100644 index 00000000000..8ebdc0986b1 --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.fullRecord-34588.test.tsx @@ -0,0 +1,263 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The approval request page shows the business record whole (objectstack#34588; + * maintainer 2026-11-17: 「审批页应该直接显示完整的记录;「动态」在最后」), pinned + * against the card's acceptance: + * + * 1. a request on a record with more than ten fields and a child table shows + * every field and the child rows without leaving the page; + * 2. a field changed after submission is marked "Changed", with its current value; + * 3. a field the approver may not read appears nowhere; + * + * and its layout: the fields in the object's default record page sections, and + * the right rail in the order progress, attachments, activity. + * + * The declared actions bar is doubled: what is under test is the page body. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'; +import { cleanup, render, screen, waitFor, within } from '@testing-library/react'; + +vi.mock('../DeclaredActionsBar.js', () => ({ + DeclaredActionsBar: () =>
, +})); + +/** The approver may read every field but the margin. */ +const DENIED = new Set(['purchase_request.internal_margin']); +vi.mock('@object-ui/permissions', async (importOriginal) => { + const actual = await importOriginal(); + const perms = { + isLoaded: true, + can: () => true, + check: () => ({ allowed: true }), + checkField: (object: string, field: string) => !DENIED.has(`${object}.${field}`), + getFieldPermissions: () => ({ readable: true, writable: false }), + }; + return { ...actual, usePermissions: () => perms }; +}); + +import { AdapterCtx, MetadataCtx, RecordContextProvider } from '@object-ui/react'; +import { ApprovalDecisionRenderer } from './ApprovalDecisionPanel'; +import { resetApproverDirectoryCache } from '../../hooks/useApproverDirectory'; + +const PURCHASE_REQUEST = { + name: 'purchase_request', + label: 'Purchase Request', + fieldGroups: [ + { key: 'request', label: 'Request' }, + { key: 'delivery', label: 'Delivery' }, + ], + fields: { + name: { type: 'text', label: 'Request No', group: 'request' }, + amount: { type: 'currency', label: 'Amount', group: 'request' }, + vendor: { type: 'text', label: 'Vendor', group: 'request' }, + category: { + type: 'select', + label: 'Category', + group: 'request', + options: [{ value: 'it', label: 'IT equipment' }, { value: 'office', label: 'Office supplies' }], + }, + cost_center: { type: 'text', label: 'Cost Center', group: 'request' }, + budget_code: { type: 'text', label: 'Budget Code', group: 'request' }, + requested_on: { type: 'date', label: 'Requested On', group: 'request' }, + internal_margin: { type: 'number', label: 'Internal Margin', group: 'request' }, + ship_to: { type: 'text', label: 'Ship To', group: 'delivery' }, + needed_by: { type: 'date', label: 'Needed By', group: 'delivery' }, + carrier: { type: 'text', label: 'Carrier', group: 'delivery' }, + contact_phone: { type: 'text', label: 'Contact Phone', group: 'delivery' }, + justification: { type: 'textarea', label: 'Justification', group: 'delivery' }, + quote: { type: 'file', label: 'Quote', group: 'delivery' }, + secret_flag: { type: 'text', label: 'Secret Flag', hidden: true }, + }, +}; + +const PURCHASE_LINE = { + name: 'purchase_line', + label: 'Purchase Line', + pluralLabel: 'Purchase Lines', + fields: { + request: { type: 'master_detail', reference: 'purchase_request', label: 'Request' }, + item: { type: 'text', label: 'Item' }, + qty: { type: 'number', label: 'Qty' }, + }, +}; + +/** The record as submitted: the request's `payload`. */ +const SUBMITTED = { + id: 'pr_1', + name: 'PR-002', + amount: 800, + vendor: 'Contoso', + category: 'it', + cost_center: 'CC-10', + budget_code: 'B-77', + requested_on: '2026-11-10', + internal_margin: 0.42, + ship_to: 'Building 4', + needed_by: '2026-12-01', + carrier: 'DHL', + contact_phone: '555-0100', + justification: 'New laptops for the design team', + quote: 'file_quote_1', + secret_flag: 'hidden-value-xyz', +}; + +/** The record as it reads now: the vendor changed after submission. */ +const CURRENT = { ...SUBMITTED, vendor: 'Fabrikam', internal_margin: 0.5 }; + +const LINES = [ + { id: 'l1', request: 'pr_1', item: 'Laptop 14-inch', qty: 4 }, + { id: 'l2', request: 'pr_1', item: 'Docking station', qty: 4 }, +]; + +const THREAD = [ + { id: 'a1', request_id: 'areq_1', action: 'submit', actor_id: 'u9', actor_name: 'JIANGUO Zhuang', comment: 'Please approve', created_at: '2026-11-10T09:00:00Z' }, +]; + +const REQUEST = { + id: 'areq_1', + process_name: 'flow:purchase_approval', + object_name: 'purchase_request', + record_id: 'pr_1', + status: 'pending', + submitter_id: 'u9', + pending_approvers: ['u1'], + pending_approver_names: { u1: 'Ada Approver' }, + viewer: { can_act: true, is_submitter: false, can_override: false }, + payload: SUBMITTED, +}; + +function makeAdapter(current: Record | null) { + return { + getObjectSchema: vi.fn(async (name: string) => [PURCHASE_REQUEST, PURCHASE_LINE].find((o) => o.name === name) ?? null), + findOne: vi.fn(async (object: string, id: string) => { + if (object === 'purchase_request' && id === 'pr_1' && current) return current; + throw Object.assign(new Error('not found'), { status: 404 }); + }), + find: vi.fn(async (object: string) => { + if (object === 'sys_approval_action') return { data: THREAD }; + if (object === 'purchase_line') return { data: LINES, total: LINES.length }; + return { data: [] }; + }), + }; +} + +function mount(current: Record | null = CURRENT) { + const adapter = makeAdapter(current); + const metadata = { + objects: [PURCHASE_REQUEST, PURCHASE_LINE], + getItem: async (type: string, name: string) => + type === 'object' ? ([PURCHASE_REQUEST, PURCHASE_LINE].find((o) => o.name === name) ?? null) : null, + }; + render( + + + + + + + , + ); + return { adapter, panel: screen.getByTestId('approval-decision-panel') }; +} + +const fieldKeys = (root: HTMLElement) => + [...root.querySelectorAll('[data-submitted-field]')].map((el) => el.getAttribute('data-submitted-field')); + +beforeEach(() => resetApproverDirectoryCache()); +afterEach(cleanup); + +describe('the request page shows the business record whole (objectstack#34588)', () => { + it('acceptance 1: every readable field, past the old six, in the default record page\'s sections, and the child rows', async () => { + const { panel } = mount(); + const record = await within(panel).findByTestId('submitted-record'); + await waitFor(() => expect(record.getAttribute('data-current')).toBe('readable')); + expect(fieldKeys(record)).toEqual([ + 'name', 'amount', 'vendor', 'category', 'cost_center', 'budget_code', 'requested_on', + 'ship_to', 'needed_by', 'carrier', 'contact_phone', 'justification', + ]); + // The object's field groups, in declared order, under their labels. + const sections = [...record.querySelectorAll('[data-submitted-section]')]; + expect(sections.map((s) => s.getAttribute('data-submitted-section'))).toEqual(['group:request', 'group:delivery']); + expect(sections.map((s) => s.firstElementChild?.textContent)).toEqual(['Request', 'Delivery']); + // Through the record page's faces: an option by its label, a reference-free text as is. + expect(record.querySelector('[data-submitted-field="category"]')?.textContent).toContain('IT equipment'); + // The child table's current rows, on this page. + const children = await within(panel).findByTestId('submitted-child-tables'); + await waitFor(() => expect(children.textContent).toContain('Laptop 14-inch')); + expect(children.textContent).toContain('Docking station'); + }); + + it('acceptance 2: a field changed after submission is marked, with its current value; the rest are not', async () => { + const { panel } = mount(); + const record = await within(panel).findByTestId('submitted-record'); + await waitFor(() => expect(record.querySelector('[data-submitted-field="vendor"]')?.getAttribute('data-changed')).toBe('true')); + const vendor = record.querySelector('[data-submitted-field="vendor"]') as HTMLElement; + expect(vendor.textContent).toContain('Contoso'); + expect(within(vendor).getByTestId('submitted-field-changed').textContent).toBe('Changed'); + expect(vendor.textContent).toContain('Fabrikam'); + expect(record.querySelectorAll('[data-changed="true"]')).toHaveLength(1); + }); + + it('acceptance 3: a field the approver may not read appears nowhere, from either row; a hidden one neither', async () => { + const { panel } = mount(); + const record = await within(panel).findByTestId('submitted-record'); + await waitFor(() => expect(record.getAttribute('data-current')).toBe('readable')); + expect(fieldKeys(record)).not.toContain('internal_margin'); + expect(panel.textContent).not.toContain('Internal Margin'); + expect(panel.textContent).not.toContain('0.42'); + expect(panel.textContent).not.toContain('Secret Flag'); + expect(panel.textContent).not.toContain('hidden-value-xyz'); + }); + + it('the rail reads progress, attachments, activity, in that order, the activity last; the record sits beside it', async () => { + const { panel } = mount(); + const rail = within(panel).getByTestId('approval-decision-rail'); + await within(rail).findByTestId('submitted-attachments'); + await waitFor(() => expect(within(rail).getByTestId('approval-decision-activity').textContent).toContain('JIANGUO Zhuang')); + const order = [...rail.children].map((el) => el.getAttribute('data-testid')); + expect(order).toEqual(['approval-decision-progress', 'submitted-attachments', 'approval-decision-activity']); + // The attachment is in the rail, not in the field grid. + expect(within(rail).getByTestId('submitted-attachments').querySelector('[data-submitted-attachment="quote"]')).toBeTruthy(); + expect(fieldKeys(within(panel).getByTestId('approval-decision-record'))).not.toContain('quote'); + // The decisions sit above both columns. + const actions = within(panel).getByTestId('declared-actions-probe'); + expect(actions.compareDocumentPosition(rail) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + }); + + it('the child table says its rows are current and offers no way to change them', async () => { + const { panel } = mount(); + const children = await within(panel).findByTestId('submitted-child-tables'); + const table = children.querySelector('[data-submitted-child="purchase_line"]') as HTMLElement; + expect(table.querySelector('[data-submitted-child-note]')?.textContent).toContain('Current rows'); + expect(within(table).queryByRole('button', { name: /^new$/i })).toBeNull(); + expect(within(table).queryByRole('button', { name: /^add/i })).toBeNull(); + }); + + it('the record is read once, by id, with no params: the read the record page sends', async () => { + const { adapter, panel } = mount(); + await within(panel).findByTestId('submitted-record'); + await waitFor(() => expect(adapter.findOne).toHaveBeenCalled()); + expect(adapter.findOne.mock.calls).toEqual([['purchase_request', 'pr_1']]); + }); + + it('CONTROL: a record the approver cannot read now marks nothing, says so, and draws no child table; the snapshot still shows whole', async () => { + const { panel } = mount(null); + const record = await within(panel).findByTestId('submitted-record'); + await waitFor(() => expect(record.getAttribute('data-current')).toBe('unreadable')); + expect(within(record).getByTestId('submitted-record-current-unreadable')).toBeTruthy(); + expect(record.querySelectorAll('[data-changed="true"]')).toHaveLength(0); + expect(fieldKeys(record)).toHaveLength(12); + expect(record.querySelector('[data-submitted-field="vendor"]')?.textContent).toContain('Contoso'); + expect(within(panel).queryByTestId('submitted-child-tables')).toBeNull(); + expect(within(record).queryByTestId('submitted-record-open')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx index 81b45b3b1c1..e4eb46a8da7 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.stepLine-12491.test.tsx @@ -155,13 +155,14 @@ describe('ApprovalDecisionPanel — the step line draws the served route (object expect(within(panel).getByTestId('declared-actions-probe')).toBeTruthy(); }); - it('the line sits above the tally, and the tally above the decisions', () => { + it('the decisions sit on top; the line sits above the tally, both in the progress card of the rail (objectstack#34588)', () => { const panel = mount(requestRow({ decision_progress: { behavior: 'quorum', got: 1, need: 2 } })); - const line = within(panel).getByLabelText(STEP_LINE_NAME); - const bar = within(panel).getByRole('progressbar'); + const progressCard = within(panel).getByTestId('approval-decision-progress'); + const line = within(progressCard).getByLabelText(STEP_LINE_NAME); + const bar = within(progressCard).getByRole('progressbar'); const actions = within(panel).getByTestId('declared-actions-probe'); // DOCUMENT_POSITION_FOLLOWING: the argument comes after the receiver. + expect(actions.compareDocumentPosition(line) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); expect(line.compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); - expect(bar.compareDocumentPosition(actions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); }); }); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.test.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.test.tsx index a209276f9ad..797c6643f49 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.test.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.test.tsx @@ -293,7 +293,9 @@ describe('names who the pending step waits on (objectui#12482)', () => { expect(screen.getByTitle('position:sales_manager').textContent).toBe('Regional Sales Manager· Grace Hopper'), ); expect(ensureType).toHaveBeenCalledWith('position'); - expect(adapter.find.mock.calls.map(([object]) => object)).toEqual(['sys_user_position', 'sys_user']); + // The request's own thread is the activity card's read (objectstack#34588), not the directory's. + const directoryReads = adapter.find.mock.calls.map(([object]) => object).filter((object) => object !== 'sys_approval_action'); + expect(directoryReads).toEqual(['sys_user_position', 'sys_user']); expect(panelText()).not.toContain('position:'); expect(panelText()).not.toContain('positi…'); }); @@ -306,7 +308,8 @@ describe('names who the pending step waits on (objectui#12482)', () => { }); expect(screen.getByTitle('position:sales_manager').textContent).toBe('Sales Manager (served)'); expect(ensureType).not.toHaveBeenCalled(); - expect(adapter.find).not.toHaveBeenCalled(); + // Only the request's own thread is read (the activity card, objectstack#34588). + expect(adapter.find.mock.calls.map(([object]) => object).filter((object) => object !== 'sys_approval_action')).toEqual([]); }); it('CONTROL: an id nothing can name keeps the face the inbox sheet draws for it, the raw id on hover only', () => { @@ -403,7 +406,7 @@ describe("a decided request's own decision comment is on the panel the reader la expect(comment.textContent).toContain('Split the claim by month'); }); - it('CONTROL: a pending request reads no thread and shows no decision comment', () => { + it('CONTROL: a pending request reads its thread once, for the activity card, and shows no decision comment (objectstack#34588)', async () => { timeline([{ id: 'a1', request_id: REQUEST.id, action: 'comment', actor_id: 'u1', comment: 'Looking into it' }]); render( @@ -412,8 +415,9 @@ describe("a decided request's own decision comment is on the panel the reader la , ); - expect(screen.getByTestId('approval-decision-panel')).toBeTruthy(); - expect(threadReads()).toHaveLength(0); + const activity = screen.getByTestId('approval-decision-activity'); + await waitFor(() => expect(activity.textContent).toContain('Looking into it')); + expect(threadReads()).toHaveLength(1); expect(screen.queryByTestId('approval-decision-comment')).toBeNull(); }); diff --git a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx index 01ed5573df3..d8de7260d64 100644 --- a/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx +++ b/ui/packages/app-shell/src/views/approval-decision/ApprovalDecisionPanel.tsx @@ -11,7 +11,15 @@ * of objectui#2763; ruling 6079807016, letter 乙), the page component type * `record:approval_decision`. * - * One node, seven parts, each drawn by a piece already shipped: + * One node, the whole request page below its header (objectstack#34588): + * the decision row on top, then the business record on the left and a right + * rail of approval progress, attachments and activity, in that order + * (maintainer 2026-11-17: 「审批页应该直接显示完整的记录;「动态」在最后」). The + * rail is a column beside the record from the `@4xl` container width up; + * narrower, the parts stack in the same order, so the activity is last there + * too. + * + * The parts, each drawn by a piece already shipped: * * 0. **Where the request came from** (objectui#12491) — a request no person * submitted (opened by a flow run with no user context, such as a @@ -20,19 +28,16 @@ * origin" below. * 0b. **Why it was decided** (objectstack#32667) — on a request that was * rejected, sent back for revision or approved, the comment the deciding - * action was recorded with, and who recorded it. See "The decision - * comment" below. - * 1. **What was submitted** (objectui#12483) — the declared amount and a - * summary of the request's record snapshot, under the target object's - * declared labels and through the record page's own cells, with the - * object's `hidden: true` fields and the reader's unreadable fields left - * out. `RecordSnapshotSummary` draws it from the bound row's `payload` - * and `payload_display`: the target record as SUBMITTED, kept as the - * request's evidence of what was submitted (objectstack#10749), never a - * live read. It is headed "As submitted" so a decided request's snapshot - * never reads as the record's current state (objectstack#27502); the - * current record is the Details tab's pointer card. See its header for - * what it reads. + * action was recorded with, and who recorded it. See "The request's + * thread" below. + * 1. **What was submitted** (objectstack#34588, replacing objectui#12483's + * six-field summary) — the business record whole, as SUBMITTED: every + * field the reader may read, in the sections of the object's default + * record page, a field changed after submission marked with its current + * value, the record's child tables as current rows, and its attachment + * fields in the rail. `./SubmittedRecord.tsx` draws it from the bound + * row's `payload` and `payload_display` (objectstack#10749) and one read + * of the record; see its header for what it reads. * 2. **Where the flow stands** (objectui#12491, objectstack#26668) — the * vertical step line of this request's own route, the bound row's * `flow_route` as the approvals get serves it: the steps its run passed, @@ -101,21 +106,28 @@ * origin, like the names, are drawn where no tally exists, so each is its own * part under its own gate. * - * ## The decision comment (objectstack#32667) + * ## The request's thread (objectstack#32667, objectstack#34588) + * + * The rail ends with the request's activity: its thread + * (`sys_approval_action`), newest first, drawn by `ApprovalActionTimeline`, + * the markup the business record's approvals panel draws its timeline with. + * It took the place of the page's Timeline tab. The request row carries no + * thread, so the panel reads it the way that tab read it: a `find` of + * `sys_approval_action` scoped to the request (`{ request_id }`), through the + * page's data source, which the console routes to + * `GET /approvals/requests/:id/actions`. One read, again when a decision + * invalidates the timeline; with no data source it reads nothing. Like that + * tab's related list, it reads only on a read verdict for the object: a + * reader refused `sys_approval_action` sends no read and gets no activity + * card (objectui#13324). * - * The reader a decision reaches lands on this page, on its Details tab; the - * applicant of a rejected request comes here to learn what to fix. The reason - * lives only on the request's thread (`sys_approval_action.comment`), which - * the Timeline tab lists, so the panel draws the deciding action's comment - * itself. The request row carries no comment, so the panel reads the thread - * the way the Timeline tab reads it: a `find` of `sys_approval_action` scoped - * to the request (`{ request_id }`), through the page's data source, which the - * console routes to `GET /approvals/requests/:id/actions`. It reads once, only - * on a request whose status a decision set, and again when a decision - * invalidates the timeline; with no data source it reads nothing. The deciding - * action is the latest of the kind the status names: `reject` for `rejected`, - * `revise` for `returned`, `approve` for `approved`. A decision recorded - * without a comment, and a read that fails, draw nothing. + * The reader a decision reaches lands on this page; the applicant of a + * rejected request comes here to learn what to fix. So on a request whose + * status a decision set, the deciding action's comment is also drawn on top, + * from the same read: the latest action of the kind the status names + * (`reject` for `rejected`, `revise` for `returned`, `approve` for + * `approved`). A decision recorded without a comment, and a read that fails, + * draw nothing there. * * ## No authorable props * @@ -167,13 +179,20 @@ import { useRecordContext, } from '@object-ui/react'; import { cn, Badge } from '@object-ui/components'; -import { Workflow } from 'lucide-react'; +import { usePermissions } from '@object-ui/permissions'; +import { History, Stamp, Workflow } from 'lucide-react'; +import { ApprovalActionTimeline } from '../approval-progress/ApprovalActionTimeline.js'; import { ApprovalStepLine } from '../approval-progress/ApprovalStepLine.js'; import { DecisionProgressIndicator } from '../approval-progress/DecisionProgressIndicator.js'; import { eligibleApproverCount } from '../approval-progress/eligibleApprovers.js'; import { DeclaredActionsBar } from '../DeclaredActionsBar.js'; import { approverChips } from '../RecordApprovalsPanel.js'; -import { RecordSnapshotSummary } from './RecordSnapshotSummary.js'; +import { + SubmittedAttachmentsCard, + SubmittedChildTables, + SubmittedRecordCard, + useSubmittedRecord, +} from './SubmittedRecord.js'; import { RECORD_APPROVAL_ACTION_LOCATION, SYS_APPROVAL_REQUEST_OBJECT } from '../recordApprovalActions.js'; import type { ApprovalActionLite, ApprovalRequestLite } from '../../hooks/useRecordApprovals.js'; import type { ApprovalRequestRow } from '@objectstack/spec/contracts'; @@ -285,50 +304,66 @@ const DECIDING_ACTION: Readonly> = { approved: 'approve', }; -/** The read of one request's thread, newest first: the Timeline tab's scope and order. */ +/** The read of one request's thread, newest first: the order the activity card draws it in. */ function timelineQuery(requestId: string) { return { $filter: { request_id: requestId }, $orderby: [{ field: 'created_at', order: 'desc' as const }] }; } -/** The first `kind` row of a thread read newest first. */ -function latestOfKind(rows: unknown, kind: string): ApprovalActionLite | null { - if (!Array.isArray(rows)) return null; - const row = rows.find((r) => (r as ApprovalActionLite | null)?.action === kind); - return (row as ApprovalActionLite | undefined) ?? null; -} - /** - * Why a decided request was decided: the deciding action's comment and who - * recorded it, on the request's own page; nothing on a pending request, or - * for a decision recorded without a comment. + * The request's thread, newest first: ONE read that the activity card and the + * decision comment share (see "The request's thread" above). `loaded` turns + * true once the read answered, a failure included. + * + * Read through the adapter the PAGE is bound to (the record context's), which + * the console routes to the request's actions route, and only on a read + * verdict, as the Timeline related list it replaces was: a reader whose + * verdict refuses `sys_approval_action` sends no read and sees no rows. Under + * the console's `ApprovalRecordReads` the verdict for both approval objects + * is the server's, so a party to the request reads its thread. */ -function DecisionComment({ request }: { request: ApprovalRequestLite }) { - const { t } = useObjectTranslation(); - const dataSource = useAdapter(); - const kind = DECIDING_ACTION[request.status]; - const requestId = String(request.id); - const timelineChanged = useDataInvalidation(kind ? APPROVAL_ACTION_OBJECT : undefined); - const [answer, setAnswer] = React.useState<{ key: string; action: ApprovalActionLite | null } | null>(null); - const key = kind ? `${requestId}::${kind}` : null; +function useRequestThread(requestId: string): { rows: ApprovalActionLite[]; loaded: boolean; readable: boolean } { + const adapter = useAdapter(); + const dataSource = useRecordContext()?.dataSource ?? adapter; + const perms = usePermissions(); + const timelineChanged = useDataInvalidation(APPROVAL_ACTION_OBJECT); + const [answer, setAnswer] = React.useState<{ key: string; rows: ApprovalActionLite[] } | null>(null); + const permitted = perms?.isLoaded ? perms.can(APPROVAL_ACTION_OBJECT, 'read') : true; + const canRead = permitted && typeof dataSource?.find === 'function'; React.useEffect(() => { - if (!kind || key === null || typeof dataSource?.find !== 'function') return; + if (!canRead) return; let cancelled = false; // The executor runs synchronously, so a source that THROWS lands with a rejection. - new Promise((resolve) => resolve(dataSource.find(APPROVAL_ACTION_OBJECT, timelineQuery(requestId)))).then( + new Promise((resolve) => resolve(dataSource!.find(APPROVAL_ACTION_OBJECT, timelineQuery(requestId)))).then( (out) => { - if (!cancelled) setAnswer({ key, action: latestOfKind((out as { data?: unknown } | null)?.data, kind) }); + const rows = (out as { data?: unknown } | null)?.data; + if (!cancelled) setAnswer({ key: requestId, rows: Array.isArray(rows) ? (rows as ApprovalActionLite[]) : [] }); }, () => { - if (!cancelled) setAnswer({ key, action: null }); + if (!cancelled) setAnswer({ key: requestId, rows: [] }); }, ); return () => { cancelled = true; }; - }, [kind, key, requestId, dataSource, timelineChanged]); + }, [requestId, canRead, dataSource, timelineChanged]); - const action = answer && answer.key === key ? answer.action : null; + if (!canRead) return { rows: [], loaded: true, readable: permitted }; + return answer && answer.key === requestId + ? { rows: answer.rows, loaded: true, readable: true } + : { rows: [], loaded: false, readable: true }; +} + +/** + * Why a decided request was decided: the deciding action's comment and who + * recorded it, on the request's own page; nothing on a pending request, or + * for a decision recorded without a comment. + */ +function DecisionComment({ request, thread }: { request: ApprovalRequestLite; thread: readonly ApprovalActionLite[] }) { + const { t } = useObjectTranslation(); + const kind = DECIDING_ACTION[request.status]; + // The thread is newest first, so the first row of the kind is the deciding one. + const action = kind ? thread.find((row) => row?.action === kind) ?? null : null; const comment = typeof action?.comment === 'string' ? action.comment.trim() : ''; if (!action || !comment) return null; const tr = (k: string, defaultValue: string) => String(t(`approvalsInbox.${k}`, { defaultValue })); @@ -351,38 +386,85 @@ function DecisionComment({ request }: { request: ApprovalRequestLite }) { ); } +/** A titled card of the page's right rail. */ +function RailCard({ icon: Icon, title, testId, children }: { + icon: React.ComponentType<{ className?: string; 'aria-hidden'?: boolean }>; + title: string; + testId: string; + children: React.ReactNode; +}) { + return ( +
+
+ + {title} +
+
{children}
+
+ ); +} + /** The parts over one request row. Module-internal: no package export. */ export function ApprovalDecisionPanel({ request, className }: ApprovalDecisionPanelProps) { + const { t } = useObjectTranslation(); const progress = request.decision_progress; const eligible = eligibleApproverCount(request); const requestId = String(request.id); + const thread = useRequestThread(requestId); + const submitted = useSubmittedRecord(request); + const stepLabel = (request as { current_step_label?: unknown }).current_step_label; + // A row names its own step when the read serves `step_label`; else every + // row of this request is on the request's step (one request, one node). + const stepText = React.useCallback( + (action: ApprovalActionLite) => { + const own = (action as { step_label?: unknown }).step_label; + if (typeof own === 'string' && own !== '') return own; + return typeof stepLabel === 'string' && stepLabel !== '' ? stepLabel : null; + }, + [stepLabel], + ); const handleDecided = React.useCallback(() => { notifyDataChanged({ objectName: SYS_APPROVAL_REQUEST_OBJECT, recordId: requestId }); notifyDataChanged({ objectName: APPROVAL_ACTION_OBJECT }); }, [requestId]); + const tr = (key: string, defaultValue: string) => String(t(`approvalsInbox.${key}`, { defaultValue })); + return ( -
- - - - - {progress && } - - {/* The approver's band, the same one the business record page draws - (objectstack#34361). */} - +
+
+ + + {/* The approver's band, the same one the business record page draws + (objectstack#34361). */} + +
+
+
+ {submitted && } + {submitted && } +
+ +
); } diff --git a/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.test.tsx b/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.test.tsx deleted file mode 100644 index 676a9b4ba01..00000000000 --- a/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.test.tsx +++ /dev/null @@ -1,409 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * The snapshot summary the decision panel draws (objectui#12483): which keys - * of a record snapshot it draws, and that it draws them only against the - * object's DECLARED fields. The same face on the real record page, over the - * console's routed approvals source and objectstack's served page, is pinned - * in the console's `approvalRequestsDataSource.servedPageSummary-12483.test.tsx`. - */ - -import * as React from 'react'; -import { describe, it, expect, afterEach } from 'vitest'; -import { cleanup, render, screen, waitFor } from '@testing-library/react'; -import { MetadataCtx } from '@object-ui/react'; -import { RecordSnapshotSummary } from './RecordSnapshotSummary'; -import { distinctLabels, planSnapshotSummary } from './snapshotSummaryPlan'; - -afterEach(cleanup); - -const FIELDS: Record> = { - owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner', system: true }, - name: { type: 'text', label: 'Name' }, - account: { type: 'lookup', reference: 'account', label: 'Account' }, - secret: { type: 'text', label: 'Secret', hidden: true }, - budget: { type: 'number', label: 'Budget' }, - fee: { type: 'currency', label: 'Fee' }, - amount: { type: 'currency', label: 'Amount' }, - note: { type: 'text', label: 'Note' }, -}; - -describe('planSnapshotSummary (objectui#12483)', () => { - it('reads the declared shape only: undeclared, hidden, bookkeeping, empty and unresolved-reference keys take no row', () => { - const plan = planSnapshotSummary( - { - id: 'r1', owner_id: 'u_1', name: 'N', account: 'acc_1', secret: 's', budget: 5, - legacy: 'x', note: ' ', amount: 10, - }, - FIELDS, - undefined, - ); - expect(plan).toEqual({ lead: 'amount', rows: ['name', 'budget'], attachments: [], summed: null }); - }); - - it('a reference the service resolved is a row', () => { - expect(planSnapshotSummary({ account: 'acc_1' }, FIELDS, { account: 'Fabrikam' }).rows).toEqual(['account']); - }); - - it('the first non-zero declared currency leads, else the first declared currency; a name never does', () => { - expect(planSnapshotSummary({ fee: 0, amount: 7 }, FIELDS, undefined).lead).toBe('amount'); - expect(planSnapshotSummary({ fee: 0, amount: 0 }, FIELDS, undefined)).toEqual({ lead: 'fee', rows: ['amount'], attachments: [], summed: null }); - // `budget` is a key the sheet's name guess matches, declared `number`. - expect(planSnapshotSummary({ budget: 900 }, FIELDS, undefined)).toEqual({ lead: null, rows: ['budget'], attachments: [], summed: null }); - }); - - it('a hidden field is dropped before the row cut, so the next one takes its slot', () => { - const plan = planSnapshotSummary({ name: 'N', secret: 's', budget: 1, note: 'z' }, FIELDS, undefined, null, 2); - expect(plan.rows).toEqual(['name', 'budget']); - }); -}); - -describe('distinctLabels (objectui#12483)', () => { - it('qualifies only the shared labels, and every label when a qualified one still collides', () => { - expect(distinctLabels([{ key: 'a', label: 'X' }, { key: 'b', label: 'X' }, { key: 'c', label: 'Y' }])) - .toEqual(['X (a)', 'X (b)', 'Y']); - expect(distinctLabels([{ key: 'a', label: 'X' }, { key: 'b', label: 'X' }, { key: 'c', label: 'X (a)' }])) - .toEqual(['X (a)', 'X (b)', 'X (a) (c)']); - }); -}); - -function mount(defs: Record, props: React.ComponentProps) { - const metadata = { getItem: async (type: string, name: string) => (type === 'object' ? (defs[name] ?? null) : null) }; - return render( - - - , - ); -} - -describe('RecordSnapshotSummary (objectui#12483)', () => { - it('draws the lead and the rows under the declared labels once the definition answers', async () => { - mount({ invoice: { name: 'invoice', fields: FIELDS } }, { - objectName: 'invoice', - snapshot: { name: 'INV-1', account: 'acc_1', amount: 0 }, - display: { account: 'Fabrikam' }, - }); - const summary = await screen.findByTestId('record-snapshot-summary'); - expect(summary.querySelector('[data-summary-lead]')?.getAttribute('data-summary-lead')).toBe('amount'); - const rows = [...summary.querySelectorAll('[data-summary-field]')].map((r) => r.textContent); - expect(rows).toEqual(['NameINV-1', 'AccountFabrikam']); - }); - - it('CONTROL: draws nothing without the definition, without a snapshot, or for a definition of another object', async () => { - const seen: string[] = []; - const defs = { other: { name: 'other', fields: FIELDS } }; - const metadata = { - getItem: async (_t: string, name: string) => { - seen.push(name); - return name === 'invoice' ? { name: 'other', fields: FIELDS } : null; - }, - }; - render( - - - , - ); - await waitFor(() => expect(seen).toContain('invoice')); - expect(screen.queryByTestId('record-snapshot-summary')).toBeNull(); - cleanup(); - mount(defs, { objectName: 'other', snapshot: undefined }); - mount(defs, { objectName: 'missing', snapshot: { name: 'INV-1' } }); - await new Promise((r) => setTimeout(r, 0)); - expect(screen.queryByTestId('record-snapshot-summary')).toBeNull(); - }); -}); - -/** - * objectui#12534: a `summary` that declares a `sum` over a field its summarized - * object declares `currency` is the declared amount too, read from the spec's - * `summaryOperations` declaration and the summarized object's definition. - */ -const ROLLUPS: Record> = { - ...FIELDS, - total: { type: 'summary', label: 'Total', summaryOperations: { object: 'line', field: 'amount', function: 'sum' } }, - approved: { - type: 'summary', label: 'Approved', - summaryOperations: { object: 'line', field: 'amount', function: 'sum', filter: { status: 'approved' } }, - }, - qty: { type: 'summary', label: 'Quantity', summaryOperations: { object: 'line', field: 'quantity', function: 'sum' } }, - lines: { type: 'summary', label: 'Lines', summaryOperations: { object: 'line', field: 'amount', function: 'count' } }, - peak: { type: 'summary', label: 'Peak', summaryOperations: { object: 'line', field: 'amount', function: 'max' } }, - other: { type: 'summary', label: 'Other', summaryOperations: { object: 'other_line', field: 'amount', function: 'sum' } }, -}; -const LINE = { name: 'line', fields: { amount: { type: 'currency', label: 'Amount' }, quantity: { type: 'number' } } }; -const OTHER_LINE = { name: 'other_line', fields: { amount: { type: 'currency', label: 'Amount' } } }; - -describe('planSnapshotSummary: a `sum` over a currency field is the amount (objectui#12534)', () => { - it('leads once the summarized definition is given; before, it is a row and the plan names that one object', () => { - expect(planSnapshotSummary({ name: 'N', total: 40 }, ROLLUPS, undefined)) - .toEqual({ lead: null, rows: ['name', 'total'], attachments: [], summed: 'line' }); - expect(planSnapshotSummary({ name: 'N', total: 40 }, ROLLUPS, undefined, LINE)) - .toEqual({ lead: 'total', rows: ['name'], attachments: [], summed: 'line' }); - }); - - it('CONTROL: a summary that is not a `sum` is a row and asks for no definition', () => { - expect(planSnapshotSummary({ lines: 3, peak: 9 }, ROLLUPS, undefined, LINE)) - .toEqual({ lead: null, rows: ['lines', 'peak'], attachments: [], summed: null }); - }); - - it('CONTROL: a `sum` over a field the summarized object does not declare `currency` is a row', () => { - const plan = planSnapshotSummary({ qty: 12 }, ROLLUPS, undefined, LINE); - expect(plan.lead).toBeNull(); - expect(plan.rows).toEqual(['qty']); - }); - - it('CONTROL: a definition of another object is not read as the summarized one', () => { - expect(planSnapshotSummary({ total: 40 }, ROLLUPS, undefined, OTHER_LINE).lead).toBeNull(); - }); - - it('the order is unchanged across both kinds: the first non-zero amount, else the first one', () => { - // A non-zero currency ahead of the roll-up leads, and no definition is asked for. - expect(planSnapshotSummary({ amount: 7, total: 40 }, ROLLUPS, undefined)) - .toEqual({ lead: 'amount', rows: ['total'], attachments: [], summed: null }); - expect(planSnapshotSummary({ amount: 0, total: 40 }, ROLLUPS, undefined, LINE).lead).toBe('total'); - expect(planSnapshotSummary({ total: 0, amount: 5 }, ROLLUPS, undefined, LINE).lead).toBe('amount'); - expect(planSnapshotSummary({ total: 0, amount: 0 }, ROLLUPS, undefined, LINE).lead).toBe('total'); - // A filtered `sum` is a `sum`. - expect(planSnapshotSummary({ total: 0, approved: 25 }, ROLLUPS, undefined, LINE).lead).toBe('approved'); - }); - - it('only the first `sum`\'s object is read: a `sum` over another object stays a row', () => { - const plan = planSnapshotSummary({ other: 9, total: 40 }, ROLLUPS, undefined, OTHER_LINE); - expect(plan).toEqual({ lead: 'other', rows: ['total'], attachments: [], summed: 'other_line' }); - expect(planSnapshotSummary({ other: 0, total: 40 }, ROLLUPS, undefined, OTHER_LINE).lead).toBe('other'); - }); -}); - -describe('RecordSnapshotSummary: the summarized object\'s definition (objectui#12534)', () => { - function mountRollups(answer: (name: string) => Promise, snapshot: Record) { - const asked: string[] = []; - const metadata = { - getItem: async (type: string, name: string) => { - asked.push(name); - return type === 'object' ? answer(name) : null; - }, - }; - render( - - - , - ); - return asked; - } - const defs: Record = { invoice: { name: 'invoice', fields: ROLLUPS }, line: LINE }; - const leadOf = (summary: HTMLElement) => summary.querySelector('[data-summary-lead]')?.getAttribute('data-summary-lead') ?? null; - - it('reads the one summarized definition once, and the roll-up leads', async () => { - const asked = mountRollups(async (name) => defs[name] ?? null, { name: 'INV-1', total: 40, approved: 25 }); - const summary = await screen.findByTestId('record-snapshot-summary'); - expect(leadOf(summary)).toBe('total'); - expect(asked).toEqual(['invoice', 'line']); - }); - - it('CONTROL: a non-zero currency ahead of the roll-up leads, and no other definition is read', async () => { - const asked = mountRollups(async (name) => defs[name] ?? null, { amount: 7, total: 40 }); - const summary = await screen.findByTestId('record-snapshot-summary'); - expect(leadOf(summary)).toBe('amount'); - expect(asked).toEqual(['invoice']); - }); - - it('CONTROL: an unreadable summarized definition leaves the roll-up an ordinary row', async () => { - mountRollups(async (name) => (name === 'line' ? null : defs[name] ?? null), { name: 'INV-1', total: 40 }); - const summary = await screen.findByTestId('record-snapshot-summary'); - expect(leadOf(summary)).toBeNull(); - expect(summary.querySelector('[data-summary-field="total"]')).not.toBeNull(); - }); - - it('waits for the summarized definition, so the amount does not move in after the rows', async () => { - let release: (def: unknown) => void = () => {}; - const childAnswer = new Promise((resolve) => { release = resolve; }); - const asked = mountRollups((name) => (name === 'line' ? childAnswer : Promise.resolve(defs[name] ?? null)), { - name: 'INV-1', total: 40, - }); - await waitFor(() => expect(asked).toEqual(['invoice', 'line'])); - expect(screen.queryByTestId('record-snapshot-summary')).toBeNull(); - release(LINE); - const summary = await screen.findByTestId('record-snapshot-summary'); - expect(leadOf(summary)).toBe('total'); - }); -}); - -/** - * objectui#11815 (ruling D): a declared deadline is judged against the - * snapshot the face draws, so a done snapshot's past deadline reads neutral - * and an open one's reads overdue. The snapshot's date and status were frozen - * together; its own state is the consistent reading. - */ -describe('RecordSnapshotSummary — a declared deadline is judged against the snapshot (objectui#11815)', () => { - const daysAgo = (n: number): string => { - const d = new Date(); - d.setDate(d.getDate() - n); - return d.toISOString().slice(0, 10); - }; - const TASK = { - name: 'task', - fields: { - name: { type: 'text', label: 'Name' }, - status: { type: 'text', label: 'Status' }, - due_date: { type: 'date', label: 'Due', dueLike: true, settledWhen: "record.status == 'done'" }, - }, - }; - const dueCell = async () => { - const summary = await screen.findByTestId('record-snapshot-summary'); - return summary.querySelector('[data-summary-field="due_date"]')?.children[1] as HTMLElement | undefined; - }; - - it("a snapshot whose `settledWhen` holds draws its past deadline neutral", async () => { - mount({ task: TASK }, { objectName: 'task', snapshot: { name: 'T', status: 'done', due_date: daysAgo(5) } }); - const cell = await dueCell(); - expect(cell?.textContent).toBe('5 days ago'); - expect(cell?.querySelector('.text-red-600')).toBeNull(); - }); - - it("a snapshot whose `settledWhen` does not hold draws its past deadline overdue", async () => { - mount({ task: TASK }, { objectName: 'task', snapshot: { name: 'T', status: 'open', due_date: daysAgo(5) } }); - const cell = await dueCell(); - expect(cell?.textContent).toBe('Overdue 5d'); - expect(cell?.querySelector('.text-red-600')).not.toBeNull(); - }); -}); - -/** - * Object and list values (objectstack#32854): an attachment, a field whose - * type is in the spec's media family `FILE_REFERENCE_TYPES`, is drawn through - * its own cell, openable, after the rows and outside the row cut; every other - * object or list value is left out. The rule is in `RecordSnapshotSummary.tsx`'s - * header. - */ -const ID_A = 'fil_a1b2c3'; -const ID_B = 'fil_d4e5f6'; -const CLAIM: Record> = { - title: { type: 'text', label: 'Title' }, - amount: { type: 'currency', label: 'Amount' }, - category: { type: 'text', label: 'Category' }, - reason: { type: 'text', label: 'Reason' }, - invoice_no: { type: 'text', label: 'Invoice number' }, - status: { type: 'text', label: 'Status' }, - invoices: { type: 'file', label: 'E-invoices', multiple: true }, - receipt: { type: 'file', label: 'Receipt' }, - photo: { type: 'image', label: 'Photo' }, - badge: { type: 'avatar', label: 'Badge' }, - clip: { type: 'video', label: 'Clip' }, - memo: { type: 'audio', label: 'Memo' }, - private_scan: { type: 'file', label: 'Private scan', hidden: true }, - address: { type: 'address', label: 'Address' }, - spot: { type: 'location', label: 'Spot' }, - extra: { type: 'json', label: 'Extra' }, - labels: { type: 'multiselect', label: 'Labels', options: [{ label: 'A', value: 'a' }] }, - watchers: { type: 'lookup', reference: 'sys_user', label: 'Watchers', multiple: true }, -}; -const LEFT_OUT = { - address: { street: '1 Main St', city: 'Springfield' }, - spot: { latitude: 1, longitude: 2 }, - extra: { a: 1 }, - labels: ['a'], - watchers: ['u_1', 'u_2'], -}; - -describe('planSnapshotSummary: object and list values (objectstack#32854)', () => { - it('a `multiple` file field is an attachment, outside the row cut and never the lead', () => { - const plan = planSnapshotSummary( - { amount: 120, title: 'Trip', category: 'Travel', reason: 'Visit', invoice_no: 'F-1', status: 'open', invoices: [ID_A, ID_B] }, - CLAIM, undefined, null, 2, - ); - expect(plan).toEqual({ lead: 'amount', rows: ['title', 'category'], attachments: ['invoices'], summed: null }); - }); - - it.each([ - ['file (single, stored id)', 'receipt', ID_A], - ['file (single, expanded)', 'receipt', { id: ID_A, name: 'r.pdf', url: '/api/v1/storage/files/fil_a1b2c3' }], - ['image', 'photo', ID_A], - ['avatar', 'badge', ID_A], - ['video', 'clip', [ID_A]], - ['audio', 'memo', ID_A], - ])('a %s field is an attachment', (_kind, key, value) => { - expect(planSnapshotSummary({ title: 'T', [key]: value }, CLAIM, undefined)).toEqual( - { lead: null, rows: ['title'], attachments: [key], summed: null }, - ); - }); - - it('CONTROL: every other object or list value is left out, a row and an attachment alike', () => { - expect(planSnapshotSummary({ title: 'T', ...LEFT_OUT }, CLAIM, undefined)).toEqual( - { lead: null, rows: ['title'], attachments: [], summed: null }, - ); - }); - - it('CONTROL: an empty, hidden or undeclared attachment takes no row', () => { - const plan = planSnapshotSummary( - { title: 'T', invoices: [], receipt: ' ', photo: {}, clip: null, private_scan: ID_A, legacy_file: [ID_B] }, - CLAIM, undefined, - ); - expect(plan).toEqual({ lead: null, rows: ['title'], attachments: [], summed: null }); - }); -}); - -describe('RecordSnapshotSummary: attachments are drawn and open (objectstack#32854)', () => { - const claim = { name: 'expense_claim', fields: CLAIM }; - const draw = async (snapshot: Record) => { - mount({ expense_claim: claim }, { objectName: 'expense_claim', snapshot }); - return screen.findByTestId('record-snapshot-summary'); - }; - const linksOf = (el: Element | null | undefined) => - [...(el?.querySelectorAll('a[data-slot="file-download-link"]') ?? [])].map((a) => ({ - href: a.getAttribute('href'), - target: a.getAttribute('target'), - name: a.textContent, - })); - - it('a `multiple` file field draws each file as a link that opens it, after the six rows', async () => { - const summary = await draw({ - amount: 120, title: 'Trip', category: 'Travel', reason: 'Visit', invoice_no: 'F-1', status: 'open', - invoices: [ID_A, { id: ID_B, name: 'invoice-2.pdf', url: '/api/v1/storage/files/fil_d4e5f6' }], - }); - expect([...summary.querySelectorAll('[data-summary-field]')].map((r) => r.getAttribute('data-summary-field'))) - .toEqual(['title', 'category', 'reason', 'invoice_no', 'status']); - const row = summary.querySelector('[data-summary-attachment="invoices"]'); - expect(row?.firstElementChild?.textContent).toBe('E-invoices'); - expect(linksOf(row)).toEqual([ - { href: `/api/v1/storage/files/${ID_A}`, target: '_blank', name: 'File' }, - { href: '/api/v1/storage/files/fil_d4e5f6', target: '_blank', name: 'invoice-2.pdf' }, - ]); - }); - - it('a single file field draws its file as a link that opens it', async () => { - const summary = await draw({ title: 'Trip', receipt: { id: ID_A, name: 'receipt.pdf', url: '/api/v1/storage/files/fil_a1b2c3' } }); - expect(linksOf(summary.querySelector('[data-summary-attachment="receipt"]'))).toEqual([ - { href: `/api/v1/storage/files/${ID_A}`, target: '_blank', name: 'receipt.pdf' }, - ]); - }); - - it.each([['video', 'clip'], ['audio', 'memo']])('the %s field draws its file as a link that opens it', async (_kind, key) => { - const summary = await draw({ title: 'Trip', [key]: [ID_A] }); - expect(linksOf(summary.querySelector(`[data-summary-attachment="${key}"]`))).toEqual([ - { href: `/api/v1/storage/files/${ID_A}`, target: '_blank', name: 'File' }, - ]); - }); - - it.each([['image', 'photo'], ['avatar', 'badge']])('an %s field draws its thumbnail from the download endpoint', async (_kind, key) => { - const summary = await draw({ title: 'Trip', [key]: ID_A }); - const img = summary.querySelector(`[data-summary-attachment="${key}"] img`); - expect(img?.getAttribute('src')).toBe(`/api/v1/storage/files/${ID_A}`); - }); - - it('CONTROL: a left-out kind draws nothing, and the scalar rows are unchanged', async () => { - const summary = await draw({ title: 'Trip', status: 'open', ...LEFT_OUT }); - expect([...summary.querySelectorAll('[data-summary-field]')].map((r) => r.textContent)).toEqual(['TitleTrip', 'Statusopen']); - expect(summary.querySelectorAll('[data-summary-attachment]')).toHaveLength(0); - }); - - it('a snapshot holding only an attachment still draws the section', async () => { - const summary = await draw({ invoices: [ID_A] }); - expect(linksOf(summary.querySelector('[data-summary-attachment="invoices"]'))).toHaveLength(1); - }); -}); diff --git a/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.tsx b/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.tsx deleted file mode 100644 index 30c3c6c52e0..00000000000 --- a/ui/packages/app-shell/src/views/approval-decision/RecordSnapshotSummary.tsx +++ /dev/null @@ -1,249 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * A record snapshot summarized against its object's DECLARED fields - * (objectui#12483): the declared amount, then the first business fields, each - * under its declared label and drawn through the record page's own cell. - * - * The decision panel draws it from the request row the served page binds: the - * snapshot is the row's `payload` (already redacted for the reader by the - * approvals service), `payload_display` is the service's display value for a - * reference, and the target object is the row's `object_name`. So the face - * needs no prop, no page edit and no spec row. - * - * ## Only the declared shape is read - * - * - **The amount** is a field the object declares `type: 'currency'`, or a - * `type: 'summary'` whose `summaryOperations` (the spec's roll-up - * declaration) is a `sum` over a field the summarized object declares - * `type: 'currency'` (objectui#12534): a roll-up total such as an expense - * report's or an invoice's. Of both kinds, in snapshot order, the first - * non-zero one leads, else the first one, because a declared amount's zero - * is the record's amount. It is drawn through its own field's cell, as the - * record page draws it. ⛔ No guess from a key's NAME: a key that only looks - * like an amount is an ordinary row here, and so is a summary that is not a - * `sum`, a `sum` over a field that is not `currency`, and a `sum` whose - * summarized object's definition cannot be read. - * - **A key the object does not declare** gets no row: it has no label and no - * face to show. - * - **A field the object declares `hidden: true`** gets no row and never leads - * (`hidden` is the UI contract "hidden from the default UI"), and it is - * dropped BEFORE the row cut, so the next field takes its slot. - * - **A framework-managed column** (`isSystemManagedField`) is bookkeeping, not - * a business field, and gets no row. - * - **A reference the service did not resolve** gets no row: its value is an - * id. - * - **A field the reader may not read** is never drawn. The service already - * redacts the snapshot per reader; the snapshot also passes through - * `withoutDeniedFields` with the reader's field permissions, as every surface - * that draws a display value from a whole row does (objectui#10594). - * - * ## Object and list values: attachments are drawn, the rest is left out - * - * A field whose value is an object or a list is drawn only when it is an - * attachment, and by this rule alone: - * - * - **Attachments are drawn**: a declared field whose type is in the spec's - * media family `FILE_REFERENCE_TYPES` (`file`, single or `multiple`, - * `image`, `avatar`, `video`, `audio`), whichever form the snapshot holds - * (the stored `sys_file` id, the expanded `{ id, name, url }` object, a list - * of either). Each is drawn through the field's own cell, the record page's: - * a file is a link to the platform's download endpoint, an image a - * thumbnail that opens. The summary adds no download channel; the endpoint - * judges the reader's access. Attachments are drawn full width after the - * rows and are never cut by `SNAPSHOT_SUMMARY_ROWS`, because they are what - * the approver decides on. An empty one (no id, an empty list) gets no row. - * - **Every other object or list value is left out**, whatever its type: an - * address, a location, `json` / `object`, `composite`, `record`, - * `repeater`, `grid`, `vector`, a multi-value option list (`multiselect`, - * `checkboxes`, `tags`) and a multi-value reference. Their faces are - * blocks, maps or chip lists that a one-line glance row cannot hold without - * cutting them, and the record itself, a click away, draws them whole. - * - * Until the object's definition answers, or when it cannot (no definition, a - * refused read), nothing is drawn: without the declarations there is no - * declared label, no face and no `hidden` to honour. - * - * ## Labelled as the submitted values (objectstack#27502) - * - * The snapshot is the record as it was SUBMITTED, kept at rest as the - * request's evidence of what was submitted and served redacted per reader - * (objectstack#10749, ruling record 5377367175, Option B). It is not the - * record's current state: after a decision the record's own status moves on - * while the snapshot's stays. So the summary is a section headed "As - * submitted" (`approvalsInbox.snapshotAsSubmitted`, in the muted label style - * of the panel's "Waiting on"), its accessible name, and a snapshot value - * never reads as the record's current one beside the page's highlights, which - * read the request row (ruling record 6499914328 on objectstack#27502). The - * heading names the source, not a status, so a pending request carries it - * too; a summary that draws nothing draws no heading. The record's current - * values are the Details tab's pointer card's to show, a live read of the - * target that the reader may be refused; this face reads no record. - * - * ## Cost - * - * A row with no snapshot asks for nothing. Otherwise the definition is - * `useMetadataItem('object', name)`: a cache hit when the - * console already holds the object, else one by-name read that the metadata - * provider de-duplicates and caches, shared with the record card the details - * grid draws for the same target. No record read: the snapshot is in the row. - * - * One more definition is read only when a `sum` summary is drawn ahead of a - * non-zero `currency` field: the summarized object's, through the same - * `useMetadataItem` path, and only ONE such object, the one the first such - * summary rolls up. A `sum` over another object stays an ordinary row. The - * summary first draws once that answer is in, so the amount does not move in - * after the rows are drawn; a definition answered for another object is never - * read as this one's. - * - * Module-internal: nothing re-exports it from the package entry. - */ - -import * as React from 'react'; -import { isDeadlineSettled, withoutDeniedFields } from '@object-ui/core'; -import { getCellRenderer, resolveCellRendererType } from '@object-ui/fields'; -import { useSafeFieldLabel } from '@object-ui/i18n'; -import { usePermissions } from '@object-ui/permissions'; -import { useMetadataItem, useObjectTranslation, usePredicateScope } from '@object-ui/react'; -import type { FieldMetadata } from '@object-ui/types'; -import { distinctLabels, planSnapshotSummary, type FieldDef } from './snapshotSummaryPlan.js'; - -/** - * A declared field's stored value, through the record page's own cell. - * - * A declared deadline is judged against `snapshot`, the same record values the - * face draws `value` from (objectui#11815): the snapshot's date and its status - * were frozen together, so its `settledWhen` is read off the snapshot's own - * state, never the live record's. - */ -function FieldFace({ objectName, def, value, snapshot, fields }: { - objectName: string; - def: FieldDef; - value: unknown; - snapshot: Record; - fields: Record; -}) { - const { translateOptions } = useSafeFieldLabel(); - const predicateScope = usePredicateScope(); - const options = def.options; - const field = Array.isArray(options) && options.length > 0 - ? { ...def, options: translateOptions(objectName, def.name as string, options) } - : def; - const Cell = getCellRenderer(resolveCellRendererType(field as { type?: string; format?: string })); - const deadlineSettled = isDeadlineSettled(def, snapshot, { scope: predicateScope, fields }); - // eslint-disable-next-line react-hooks/static-components -- getCellRenderer returns the registry's module-level renderer for the type, not a component created during render - return ; -} - -export interface RecordSnapshotSummaryProps { - /** The snapshot's object. */ - objectName: string | null | undefined; - /** The snapshot: one record's stored values, keyed by field name. */ - snapshot: unknown; - /** The service's display value per reference key. */ - display?: Record; -} - -/** An object's declared fields from its definition, when this one is `name`'s. */ -function declaredFields(item: unknown, name: string): Record | null { - if (!item || typeof item !== 'object') return null; - const def = item as { name?: unknown; fields?: unknown }; - // A definition answered for the PREVIOUS name is not drawn against this one. - if (def.name !== undefined && def.name !== name) return null; - const declared = def.fields; - if (!declared || typeof declared !== 'object' || Array.isArray(declared)) return null; - return declared as Record; -} - -export function RecordSnapshotSummary({ objectName, snapshot, display }: RecordSnapshotSummaryProps) { - const target = typeof objectName === 'string' && objectName !== '' ? objectName : null; - const hasSnapshot = !!snapshot && typeof snapshot === 'object' && !Array.isArray(snapshot); - // No snapshot, nothing to summarize: the definition is not asked for. - const { item } = useMetadataItem('object', hasSnapshot ? target : null); - const perms = usePermissions(); - - const fields = target === null ? null : declaredFields(item, target); - if (target === null || !fields || !hasSnapshot) return null; - - const shown = withoutDeniedFields(snapshot as Record, perms, target); - return ; -} - -/** - * The summary once the target's definition answered. Mounted then, so the - * summarized object's read below starts out loading and the summary waits for - * it. - */ -function DeclaredSummary({ target, fields, shown, display }: { - target: string; - fields: Record; - shown: Record; - display: Record | undefined; -}) { - const summed = planSnapshotSummary(shown, fields, display).summed; - const child = useMetadataItem('object', summed); - const { fieldLabel } = useSafeFieldLabel(); - const { t } = useObjectTranslation(); - const headingId = React.useId(); - if (summed !== null && child.loading) return null; - - // An unreadable definition leaves every `sum` an ordinary row. - const childFields = summed === null ? null : declaredFields(child.item, summed); - const summarized = summed !== null && childFields ? { name: summed, fields: childFields } : null; - const plan = planSnapshotSummary(shown, fields, display, summarized); - const keys = [...(plan.lead ? [plan.lead] : []), ...plan.rows, ...plan.attachments]; - if (keys.length === 0) return null; - - const declaredLabel = (key: string) => { - const label = fields[key]?.label; - return fieldLabel(target, key, typeof label === 'string' && label !== '' ? label : key); - }; - const labels = distinctLabels(keys.map((key) => ({ key, label: declaredLabel(key) }))); - const labelOf = new Map(keys.map((key, i) => [key, labels[i]])); - const valueOf = (key: string) => - display?.[key] ?? ( - - ); - - return ( -
-
- {String(t('approvalsInbox.snapshotAsSubmitted', { defaultValue: 'As submitted' }))} -
- {plan.lead && ( -
-
{labelOf.get(plan.lead)}
-
- {valueOf(plan.lead)} -
-
- )} - {plan.rows.length > 0 && ( -
- {plan.rows.map((key) => ( -
-
{labelOf.get(key)}
-
{valueOf(key)}
-
- ))} -
- )} - {plan.attachments.length > 0 && ( -
- {plan.attachments.map((key) => ( -
-
{labelOf.get(key)}
- -
- ))} -
- )} -
- ); -} diff --git a/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx b/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx new file mode 100644 index 00000000000..13d109658c4 --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-decision/SubmittedRecord.tsx @@ -0,0 +1,538 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The business record an approval request is about, drawn whole on the + * request's page (objectstack#34588; maintainer 2026-11-17: 「审批页应该直接显示 + * 完整的记录;「动态」在最后」). It replaces the "As submitted" summary that drew + * the amount and at most six fields (objectui#12483), so the approver no longer + * leaves the page to read the rest of the record. + * + * Three faces, each drawn by the decision panel where the page puts it: + * + * - {@link SubmittedRecordCard}: every field the reader may read, in the + * sections and the order of the object's DEFAULT record page. + * - {@link SubmittedChildTables}: the record's child tables, read-only. + * - {@link SubmittedAttachmentsCard}: the record's attachment fields, in the + * page's right rail. + * + * ## The values are the submitted ones + * + * The values are the request's snapshot: the row's `payload`, the record as it + * was SUBMITTED, kept at rest as the request's evidence (objectstack#10749) and + * served redacted per reader. So the card stays headed "As submitted" + * (`approvalsInbox.snapshotAsSubmitted`, ruling record 6499914328 on + * objectstack#27502): a snapshot value never reads as the record's current one. + * + * A field changed after submission is marked "Changed", with its current value + * beside it. The current values come from ONE read of the record + * (`findOne`, no params, the read the record page sends), re-read when the + * record is invalidated on the data bus. A read that is refused, fails or finds + * nothing marks nothing, and the card says the current record could not be + * read; it never says why (the platform answers a record outside the reader's + * rows with the same 404 it gives a deleted one). How two values compare is + * `valuesDiffer` in `./submittedRecordPlan`. + * + * ## The layout is the object's default record page + * + * The sections are `deriveRecordDetailSections`, the one derivation every + * surface that builds the object's default record page reads (objectui#12442): + * the object's field groups in declared order, else the primary section and + * "More details". A `{ group }` section is resolved through + * `deriveFieldGroupDetailSections`, the resolved form `record:details` draws, + * and headed through the same per-object `sectionLabel` convention. Every + * section is drawn open: the approver decides on all of it, so a group + * declared collapsed is not folded here, and a group's `visibleWhen` is not + * evaluated (it judges the live record's state, not the submitted one). + * + * ## Which fields are drawn + * + * A field is drawn when the object declares it, it is not `hidden: true`, it + * is not framework bookkeeping (`isSystemManagedField`), and at least one of + * the two rows serves it to this reader. Both rows pass through + * `withoutDeniedFields` with the reader's field permissions first, as every + * surface that draws a whole row does (objectui#10594), and the service has + * already redacted the snapshot per reader. So a field the reader may not read + * is never drawn, from either row. A field whose value is empty is drawn with + * the empty placeholder, so the reader sees that it was submitted empty. + * + * Each value is drawn through the record page's own cell for its type. A + * reference the service resolved is drawn by `payload_display`, the name the + * service read for this reader; any other reference through the lookup cell, + * which names it the way the record page does. Long-form types span the row + * (`isWideFieldType`, the record page's own rule). + * + * ## Child tables are current values + * + * The snapshot keeps the record's own row only (the card's 不做: no change to + * the snapshot's storage). So the child tables are the record's CURRENT rows, + * each headed with that fact. They are the object's owned children + * (`master_detail`) and its body tables (`relatedList: 'primary'`), from + * `deriveRelatedLists`, the record page's derivation, gated on the reader's + * read of the child object. Each is the plugin's `RelatedList` with no New, + * Add, edit, delete or row action: the request page never edits the record. + * They are drawn only once the record itself read. + * + * Module-internal: nothing re-exports it from the package entry. + */ + +import * as React from 'react'; +import { Badge, EmptyValue, cn } from '@object-ui/components'; +import { isDeadlineSettled, withoutDeniedFields } from '@object-ui/core'; +import { getCellRenderer, resolveCellRendererType } from '@object-ui/fields'; +import { useSafeFieldLabel } from '@object-ui/i18n'; +import { usePermissions } from '@object-ui/permissions'; +import { deriveFieldGroupDetailSections, isWideFieldType, RelatedList } from '@object-ui/plugin-detail'; +import { + useAdapter, + useDataInvalidation, + useMetadata, + useMetadataItem, + useObjectTranslation, + usePredicateScope, + useRelatedRecordActions, +} from '@object-ui/react'; +import type { FieldMetadata } from '@object-ui/types'; +import { ExternalLink, Paperclip } from 'lucide-react'; +import { deriveRecordDetailSections } from '../recordDetailSections.js'; +import { deriveRelatedLists } from '../../utils/deriveRelatedLists.js'; +import { servedObjectLabel, servedObjectPluralLabel } from '../../hooks/servedObjectLabel.js'; +import { + distinctLabels, + planSubmittedRecord, + type FieldDef, + type SubmittedField, + type SubmittedRecordPlan, + type SubmittedSectionInput, +} from './submittedRecordPlan.js'; + +/** Rows each child table shows per page. */ +const CHILD_TABLE_PAGE_SIZE = 10; + +/** The record's current state, as one read answered it. */ +export type CurrentRecordState = + | { status: 'loading' } + | { status: 'readable'; row: Record } + | { status: 'unreadable' }; + +/** Everything the three faces draw, from one definition read and one record read. */ +export interface SubmittedRecordModel { + objectName: string; + recordId: string | null; + objectDef: { name: string; label?: unknown; fields: Record } & Record; + /** The snapshot narrowed for this reader: the values the faces draw. */ + snapshot: Record; + display: Record | undefined; + plan: SubmittedRecordPlan; + current: CurrentRecordState; +} + +/** An object's definition, when the one answered is `name`'s. */ +function definitionOf(item: unknown, name: string): SubmittedRecordModel['objectDef'] | null { + if (!item || typeof item !== 'object') return null; + const def = item as { name?: unknown; fields?: unknown }; + // A definition answered for the PREVIOUS name is not drawn against this one. + if (def.name !== undefined && def.name !== name) return null; + const fields = def.fields; + if (!fields || typeof fields !== 'object' || Array.isArray(fields)) return null; + return { ...(item as Record), name, fields: fields as Record }; +} + +/** + * One read of the record as it is now. `findOne` with no params, the request + * the record page sends, re-read in place when the record is invalidated. + */ +function useCurrentRecord(objectName: string | null, recordId: string | null): CurrentRecordState { + const dataSource = useAdapter(); + const invalidation = useDataInvalidation(objectName ?? undefined); + const key = objectName !== null && recordId !== null ? `${objectName}::${recordId}` : null; + const canRead = typeof dataSource?.findOne === 'function'; + const [answer, setAnswer] = React.useState<{ key: string; row: Record | null } | null>(null); + + React.useEffect(() => { + if (key === null || objectName === null || recordId === null || !canRead) return; + let cancelled = false; + // The executor runs synchronously, so a source that THROWS lands with a rejection. + new Promise((resolve) => resolve(dataSource!.findOne(objectName, recordId))).then( + (row) => { + if (cancelled) return; + setAnswer({ + key, + row: row && typeof row === 'object' && !Array.isArray(row) ? (row as Record) : null, + }); + }, + () => { + if (!cancelled) setAnswer({ key, row: null }); + }, + ); + return () => { + cancelled = true; + }; + }, [key, objectName, recordId, canRead, dataSource, invalidation]); + + if (key === null || !canRead) return { status: 'unreadable' }; + if (!answer || answer.key !== key) return { status: 'loading' }; + return answer.row ? { status: 'readable', row: answer.row } : { status: 'unreadable' }; +} + +/** + * The submitted record of a request: its object's definition, the snapshot + * and the current row narrowed for the reader, and the plan of what to draw. + * Null until the definition answers, and when there is no snapshot or no + * definition: without the declarations there is no label, face or `hidden` + * to honour. + */ +export function useSubmittedRecord(request: { + object_name?: string | null; + record_id?: string | null; + payload?: unknown; + payload_display?: Record | null; +}): SubmittedRecordModel | null { + const target = typeof request.object_name === 'string' && request.object_name !== '' ? request.object_name : null; + const recordId = typeof request.record_id === 'string' && request.record_id !== '' ? request.record_id : null; + const payload = request.payload; + const hasSnapshot = !!payload && typeof payload === 'object' && !Array.isArray(payload); + // No snapshot, nothing to draw: neither the definition nor the record is asked for. + const { item } = useMetadataItem('object', hasSnapshot ? target : null); + const current = useCurrentRecord(hasSnapshot ? target : null, hasSnapshot ? recordId : null); + const perms = usePermissions(); + const { t } = useObjectTranslation(); + const { sectionLabel } = useSafeFieldLabel(); + + const objectDef = target === null ? null : definitionOf(item, target); + const display = request.payload_display ?? undefined; + + return React.useMemo(() => { + if (target === null || objectDef === null || !hasSnapshot) return null; + const snapshot = withoutDeniedFields(payload as Record, perms, target); + const currentRow = current.status === 'readable' ? withoutDeniedFields(current.row, perms, target) : null; + const sections = resolveSections(objectDef, sectionLabel, t); + const plan = planSubmittedRecord(sections, objectDef.fields, snapshot, currentRow); + return { objectName: target, recordId, objectDef, snapshot, display, plan, current }; + }, [target, recordId, objectDef, hasSnapshot, payload, perms, current, sectionLabel, t, display]); +} + +/** + * The object's default record page sections, resolved to headings and field + * names (see "The layout is the object's default record page" above). + */ +function resolveSections( + objectDef: SubmittedRecordModel['objectDef'], + sectionLabel: (objectName: string, sectionName: string, fallback: string) => string, + t: (key: string, options?: Record) => unknown, +): SubmittedSectionInput[] { + const tr = (key: string, defaultValue: string) => String(t(key, { defaultValue })); + const derived = deriveRecordDetailSections(objectDef, { + moreDetails: sectionLabel(objectDef.name, 'details', tr('detail.sectionMoreDetails', 'More details')), + ungrouped: tr('common.ungroupedSection', 'Other'), + }); + const groups = new Map>( + (deriveFieldGroupDetailSections(objectDef as never) ?? []).map((s) => [String(s.name), s]), + ); + const names = (list: unknown): string[] => + (Array.isArray(list) ? list : []) + .map((f) => (typeof f === 'string' ? f : (f as { name?: unknown } | null)?.name)) + .filter((n): n is string => typeof n === 'string' && n !== ''); + const columnsOf = (value: unknown) => (typeof value === 'number' && value > 0 ? value : undefined); + + return derived.map((section, i) => { + if (typeof section.group === 'string') { + const group = groups.get(section.group); + const fallback = typeof group?.label === 'string' ? group.label : section.group; + return { + key: `group:${section.group}`, + label: sectionLabel(objectDef.name, section.group, fallback), + columns: columnsOf(section.columns ?? group?.columns), + fields: names(group?.fields), + }; + } + const label = typeof section.label === 'string' && section.label !== '' ? section.label : undefined; + return { + key: typeof section.name === 'string' ? section.name : `section:${i}`, + ...(label ? { label } : {}), + columns: columnsOf(section.columns), + fields: names(section.fields), + }; + }); +} + +/** + * A declared field's value, through the record page's own cell. A declared + * deadline's `settledWhen` is judged against `record`, the row the value comes from + * (objectui#11815): the snapshot's date against the snapshot's own state, the + * current date against the current row's. + */ +function FieldFace({ objectName, def, value, record, fields }: { + objectName: string; + def: FieldDef; + value: unknown; + record: Record; + fields: Record; +}) { + const { translateOptions } = useSafeFieldLabel(); + const predicateScope = usePredicateScope(); + const options = def.options; + const field = Array.isArray(options) && options.length > 0 + ? { ...def, options: translateOptions(objectName, def.name as string, options) } + : def; + const Cell = getCellRenderer(resolveCellRendererType(field as { type?: string; format?: string })); + const deadlineSettled = isDeadlineSettled(def, record, { scope: predicateScope, fields }); + // eslint-disable-next-line react-hooks/static-components -- getCellRenderer returns the registry's module-level renderer for the type, not a component created during render + return ; +} + +function isBlank(value: unknown): boolean { + if (value === undefined || value === null) return true; + if (typeof value === 'string') return value.trim() === ''; + return Array.isArray(value) && value.length === 0; +} + +/** The labels every drawn field is shown under, told apart where they collide. */ +function useFieldLabels(model: SubmittedRecordModel): Map { + const { fieldLabel } = useSafeFieldLabel(); + return React.useMemo(() => { + const keys = [ + ...model.plan.sections.flatMap((s) => s.fields.map((f) => f.key)), + ...model.plan.attachments.map((f) => f.key), + ]; + const declared = (key: string) => { + const label = model.objectDef.fields[key]?.label; + return fieldLabel(model.objectName, key, typeof label === 'string' && label !== '' ? label : key); + }; + const labels = distinctLabels(keys.map((key) => ({ key, label: declared(key) }))); + return new Map(keys.map((key, i) => [key, labels[i]])); + }, [model, fieldLabel]); +} + +/** One field: its submitted value, and when it changed, the mark and the current value. */ +function SubmittedValue({ model, field }: { model: SubmittedRecordModel; field: SubmittedField }) { + const { t } = useObjectTranslation(); + const def = { ...(model.objectDef.fields[field.key] as FieldDef), name: field.key }; + const submitted = isBlank(field.value) + ? + : model.display?.[field.key] ?? ( + + ); + if (!field.changed) return <>{submitted}; + const currentRow = model.current.status === 'readable' ? model.current.row : {}; + return ( + <> + {submitted} +
+ + {String(t('approvalsInbox.snapshotChanged', { defaultValue: 'Changed' }))} + + + {String(t('approvalsInbox.snapshotCurrentValue', { defaultValue: 'Current value' }))}: + + + {isBlank(field.current) + ? + : } + +
+ + ); +} + +/** The grid's column classes for a section's declared column count, clamped by the container's width. */ +function gridColumns(columns: number | undefined): string { + const n = Math.min(Math.max(columns ?? 3, 1), 4); + if (n === 1) return 'grid-cols-1'; + if (n === 2) return 'grid-cols-1 @md:grid-cols-2'; + if (n === 3) return 'grid-cols-1 @md:grid-cols-2 @3xl:grid-cols-3'; + return 'grid-cols-1 @md:grid-cols-2 @3xl:grid-cols-3 @5xl:grid-cols-4'; +} + +/** + * The record as submitted, in its default record page's sections, headed "As + * submitted" with the object's label, and a link to the record when it read. + */ +export function SubmittedRecordCard({ model, className }: { model: SubmittedRecordModel; className?: string }) { + const { t, language } = useObjectTranslation(); + const { objectLabel } = useSafeFieldLabel() as unknown as { + objectLabel: (def: { name: string; label: string }) => string; + }; + const labels = useFieldLabels(model); + const recordLinks = useRelatedRecordActions(); + const headingId = React.useId(); + const { plan, current } = model; + if (plan.sections.length === 0) return null; + + const objectName = servedObjectLabel(model.objectDef, language, objectLabel, model.objectName); + const href = + current.status === 'readable' && model.recordId !== null && recordLinks?.recordHref + ? recordLinks.recordHref(model.objectName, model.recordId) + : null; + + return ( +
+ + {current.status === 'unreadable' && ( +

+ {String(t('approvalsInbox.snapshotCurrentUnreadable', { + defaultValue: 'The current record cannot be read, so changes made after submission are not marked.', + }))} +

+ )} +
+ {plan.sections.map((section) => ( +
+ {section.label && ( +
{section.label}
+ )} +
+ {section.fields.map((field) => { + const type = model.objectDef.fields[field.key]?.type; + return ( +
+
{labels.get(field.key)}
+
+ +
+
+ ); + })} +
+
+ ))} +
+
+ ); +} + +/** The record's attachment fields as submitted, for the page's right rail; nothing when none holds a file. */ +export function SubmittedAttachmentsCard({ model, className }: { model: SubmittedRecordModel; className?: string }) { + const { t } = useObjectTranslation(); + const labels = useFieldLabels(model); + const { attachments } = model.plan; + if (attachments.length === 0) return null; + return ( +
+
+ + {String(t('approvalsInbox.attachmentsTitle', { defaultValue: 'Attachments' }))} + {attachments.length} +
+
+ {attachments.map((field) => ( +
+
{labels.get(field.key)}
+ +
+ ))} +
+
+ ); +} + +/** + * The record's child tables, current rows, read-only (see "Child tables are + * current values" above). Drawn once the record itself read. + */ +export function SubmittedChildTables({ model, className }: { model: SubmittedRecordModel; className?: string }) { + const { t, language } = useObjectTranslation(); + const { objectPluralLabel } = useSafeFieldLabel() as unknown as { + objectPluralLabel: (def: { name: string; label: string; pluralLabel?: string }) => string; + }; + const { objects } = useMetadata(); + const perms = usePermissions(); + const dataSource = useAdapter(); + const readable = model.current.status === 'readable' && model.recordId !== null; + + const tables = React.useMemo(() => { + if (!readable) return []; + const derived = deriveRelatedLists(model.objectDef as never, objects as never, { + canRead: perms?.isLoaded ? (name: string) => perms.can(name, 'read') : undefined, + listLabel: (child) => servedObjectPluralLabel(child as never, language, objectPluralLabel, child.name), + }); + const children = derived.filter((relation) => relation.isPrimary || relation.isOwned); + return [...children.filter((r) => r.isPrimary), ...children.filter((r) => !r.isPrimary)]; + }, [readable, model.objectDef, objects, perms, language, objectPluralLabel]); + + if (!readable || tables.length === 0 || !dataSource) return null; + const note = String(t('approvalsInbox.snapshotChildCurrent', { + defaultValue: 'Current rows: the submission does not keep child rows.', + })); + return ( +
+ {tables.map((relation) => { + const childDef = (objects as Array<{ name?: string }>).find((o) => o?.name === relation.childObject) as + | { name: string; label?: unknown; pluralLabel?: unknown } + | undefined; + const title = relation.title + || (childDef ? servedObjectPluralLabel(childDef, language, objectPluralLabel, relation.childLabel) : relation.childLabel); + return ( +
+

{note}

+ 0 ? { columns: relation.columns } : {})} + {...(relation.sort && relation.sort.length > 0 ? { defaultSort: relation.sort } : {})} + {...(relation.filter ? { filter: relation.filter as never } : {})} + /> +
+ ); + })} +
+ ); +} diff --git a/ui/packages/app-shell/src/views/approval-decision/snapshotSummaryPlan.ts b/ui/packages/app-shell/src/views/approval-decision/snapshotSummaryPlan.ts deleted file mode 100644 index b8c7ef74881..00000000000 --- a/ui/packages/app-shell/src/views/approval-decision/snapshotSummaryPlan.ts +++ /dev/null @@ -1,150 +0,0 @@ -/** - * ObjectUI - * Copyright (c) 2024-present ObjectStack Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -/** - * Which keys of a record snapshot `RecordSnapshotSummary` draws, and the - * labels it draws them under (objectui#12483). Pure: the reader's field - * permissions are applied to the snapshot before it gets here. The rules are - * in `RecordSnapshotSummary.tsx`'s header. - */ - -import { FILE_REFERENCE_TYPES } from '@objectstack/spec/data'; -import { isExpandableFieldType } from '@object-ui/core'; -import { isSystemManagedField, type SummaryFieldMetadata } from '@object-ui/types'; - -/** One field's declaration as the object definition serves it. */ -export type FieldDef = Readonly>; - -/** An object's declared fields, keyed by field name. */ -type FieldDefs = Readonly>; - -/** The rows a snapshot draws: the declared amount, then the business fields. */ -export interface SnapshotSummaryPlan { - lead: string | null; - rows: string[]; - /** - * The attachment fields the snapshot holds, in snapshot order: declared - * fields whose type is a `FILE_REFERENCE_TYPES` member (the spec's media - * family, `file` single and `multiple` included). Drawn after the rows and - * never cut by `max`: an attachment is what the approver decides on. - */ - attachments: string[]; - /** - * The object a `sum` summary ahead of the amount rolls up, whose definition - * decides whether that summary is the amount (objectui#12534); null when no - * such summary is drawn. At most one, so a page reads at most one more - * definition. - */ - summed: string | null; -} - -/** A roll-up as `@objectstack/spec`'s `FieldSchema.summaryOperations` declares it. */ -type SummaryOperations = NonNullable; - -/** The roll-up a field declares when it is a `summary` whose function is `sum`. */ -function declaredSum(def: FieldDef | undefined): SummaryOperations | null { - if (def?.type !== 'summary') return null; - const ops = def.summaryOperations as SummaryOperations | undefined; - return ops?.function === 'sum' ? ops : null; -} - -/** - * Does an attachment field's stored value hold a file: a non-empty id or URL, - * a non-empty list, or an object with any member (the expanded or refused - * form). Each entry is the field cell's to read. - */ -function holdsAttachment(value: unknown): boolean { - if (typeof value === 'string') return value.trim() !== ''; - if (Array.isArray(value)) return value.length > 0; - return !!value && typeof value === 'object' && Object.keys(value).length > 0; -} - -/** How many business-field rows the summary draws below the amount. */ -export const SNAPSHOT_SUMMARY_ROWS = 6; - -function numeric(value: unknown): number | null { - if (typeof value === 'number') return Number.isFinite(value) ? value : null; - if (typeof value === 'string' && value.trim() !== '' && Number.isFinite(Number(value))) return Number(value); - return null; -} - -/** - * Which keys of `snapshot` are drawn, in snapshot order. Pure: the reader's - * field permissions are applied to `snapshot` before it gets here. - * - * `summarized` is the definition of the object the plan's `summed` names, once - * it answered, else null: a `sum` summary is the amount only when that object - * declares the summed field `type: 'currency'`, and without its definition the - * summary is an ordinary row. - */ -export function planSnapshotSummary( - snapshot: Readonly>, - fields: FieldDefs, - display: Readonly> | undefined, - summarized: { name: string; fields: FieldDefs } | null = null, - max: number = SNAPSHOT_SUMMARY_ROWS, -): SnapshotSummaryPlan { - const candidates: string[] = []; - const attachments: string[] = []; - for (const [key, value] of Object.entries(snapshot)) { - const def = fields[key]; - if (!def || typeof def !== 'object') continue; // not a field of this object - if (def.hidden === true) continue; // hidden from the default UI - if (isSystemManagedField(key, def as { system?: boolean })) continue; // bookkeeping - if (typeof def.type === 'string' && FILE_REFERENCE_TYPES.has(def.type)) { - if (holdsAttachment(value)) attachments.push(key); - continue; - } - // Every other object or list value is left out (the rule is in - // `RecordSnapshotSummary.tsx`'s header). - if (value == null || typeof value === 'object') continue; - if (String(value).trim() === '') continue; - if (!display?.[key] && isExpandableFieldType(def)) continue; // an unresolved reference id - candidates.push(key); - } - - let lead: string | null = null; - let leadZero: string | null = null; - let summed: string | null = null; - for (const key of candidates) { - const n = numeric(snapshot[key]); - if (n === null) continue; - if (fields[key]?.type !== 'currency') { - const sum = declaredSum(fields[key]); - if (!sum) continue; - // The first `sum` ahead of the amount names the one definition read; - // a sum over any other object stays an ordinary row. - summed ??= sum.object; - if (sum.object !== summed || summarized?.name !== summed) continue; - // A `sum` always names its field (only a `count` may omit it). - if (sum.field === undefined || summarized.fields[sum.field]?.type !== 'currency') continue; - } - if (n !== 0) { - lead = key; - break; - } - leadZero ??= key; - } - lead ??= leadZero; - - return { lead, rows: candidates.filter((key) => key !== lead).slice(0, max), attachments, summed }; -} - -/** - * Two rows never share a label: every row whose label is shared names its - * field key as well, and if a qualified label still matches another row's - * plain label, every row is qualified. Field keys are unique, so the result is. - */ -export function distinctLabels(rows: ReadonlyArray<{ key: string; label: string }>): string[] { - const qualify = (pick: (r: { key: string; label: string }) => boolean) => - rows.map((r) => (pick(r) ? `${r.label} (${r.key})` : r.label)); - const count = new Map(); - for (const r of rows) count.set(r.label, (count.get(r.label) ?? 0) + 1); - const once = qualify((r) => (count.get(r.label) ?? 0) > 1); - return new Set(once).size === once.length ? once : qualify(() => true); -} diff --git a/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.test.ts b/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.test.ts new file mode 100644 index 00000000000..a307cce101a --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.test.ts @@ -0,0 +1,136 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * What the request page draws of a submitted record (objectstack#34588): which + * fields, in which section, which changed after submission, and how two values + * compare. The faces over the real panel are pinned in + * `ApprovalDecisionPanel.fullRecord-34588.test.tsx`. + */ + +import { describe, it, expect } from 'vitest'; +import { distinctLabels, planSubmittedRecord, valuesDiffer } from './submittedRecordPlan'; + +const FIELDS: Record> = { + name: { type: 'text', label: 'Name' }, + amount: { type: 'currency', label: 'Amount' }, + account: { type: 'lookup', reference: 'account', label: 'Account' }, + due_on: { type: 'date', label: 'Due On' }, + tags: { type: 'multiselect', label: 'Tags' }, + note: { type: 'textarea', label: 'Note' }, + secret: { type: 'text', label: 'Secret', hidden: true }, + owner_id: { type: 'lookup', reference: 'sys_user', label: 'Owner', system: true }, + receipt: { type: 'file', label: 'Receipt' }, + photo: { type: 'image', label: 'Photo' }, +}; + +const SECTIONS = [ + { key: 'main', fields: ['name', 'amount', 'account', 'due_on', 'tags', 'secret', 'owner_id', 'receipt', 'photo', 'legacy'] }, + { key: 'details', label: 'More details', fields: ['note', 'name'] }, +]; + +describe('planSubmittedRecord (objectstack#34588)', () => { + it('draws every declared, visible, non-bookkeeping field either row serves, in section order, each once', () => { + const plan = planSubmittedRecord( + SECTIONS, + FIELDS, + { name: 'PO-1', amount: 800, account: 'acc_1', due_on: null, tags: [], secret: 's', owner_id: 'u1', legacy: 'x', note: 'n' }, + null, + ); + expect(plan.sections.map((s) => [s.key, s.fields.map((f) => f.key)])).toEqual([ + ['main', ['name', 'amount', 'account', 'due_on', 'tags']], + ['details', ['note']], + ]); + expect(plan.sections[1].label).toBe('More details'); + expect(plan.changedCount).toBe(0); + }); + + it('a field neither row serves is not drawn: the reader may not read it', () => { + const plan = planSubmittedRecord(SECTIONS, FIELDS, { name: 'PO-1' }, { id: 'r1', name: 'PO-1', amount: 800 }); + expect(plan.sections[0].fields.map((f) => f.key)).toEqual(['name', 'amount']); + expect(plan.sections).toHaveLength(1); + }); + + it('marks a field changed only when the current row holds it and it differs, and carries the current value', () => { + const plan = planSubmittedRecord( + SECTIONS, + FIELDS, + { name: 'PO-1', amount: 800, account: 'acc_1', note: 'n' }, + { name: 'PO-1', amount: 950, account: { id: 'acc_1', name: 'Fabrikam' } }, + ); + const byKey = new Map(plan.sections.flatMap((s) => s.fields).map((f) => [f.key, f])); + expect(byKey.get('amount')).toEqual({ key: 'amount', value: 800, changed: true, current: 950 }); + expect(byKey.get('account')?.changed).toBe(false); // the same record, expanded + expect(byKey.get('note')?.changed).toBe(false); // the current row does not serve it + expect(byKey.get('name')?.changed).toBe(false); + expect(plan.changedCount).toBe(1); + }); + + it('a field set after submission is drawn from the current row and marked changed', () => { + const plan = planSubmittedRecord(SECTIONS, FIELDS, { name: 'PO-1' }, { name: 'PO-1', due_on: '2026-12-01' }); + const due = plan.sections[0].fields.find((f) => f.key === 'due_on'); + expect(due).toEqual({ key: 'due_on', value: undefined, changed: true, current: '2026-12-01' }); + }); + + it('attachments go to their own list, after the grid, only when a file is held', () => { + const plan = planSubmittedRecord(SECTIONS, FIELDS, { name: 'PO-1', receipt: 'file_1', photo: [] }, null); + expect(plan.attachments.map((f) => f.key)).toEqual(['receipt']); + expect(plan.sections[0].fields.map((f) => f.key)).toEqual(['name']); + }); + + it('an attachment removed after submission stays listed, marked changed', () => { + const plan = planSubmittedRecord(SECTIONS, FIELDS, { receipt: ['file_1'] }, { receipt: [] }); + expect(plan.attachments).toEqual([{ key: 'receipt', value: ['file_1'], changed: true, current: [] }]); + expect(plan.changedCount).toBe(1); + }); +}); + +describe('valuesDiffer (objectstack#34588)', () => { + it('empty is one value: absent, null, blank and an empty list', () => { + for (const [a, b] of [[undefined, null], [null, ''], [' ', []], [[], undefined]] as const) { + expect(valuesDiffer(FIELDS.name, a, b)).toBe(false); + } + expect(valuesDiffer(FIELDS.name, null, 'x')).toBe(true); + }); + + it('numbers compare by value, a numeric string included on a numeric field', () => { + expect(valuesDiffer(FIELDS.amount, 800, '800.00')).toBe(false); + expect(valuesDiffer(FIELDS.amount, 800, 801)).toBe(true); + }); + + it('a reference compares by the record it names, stored or expanded', () => { + expect(valuesDiffer(FIELDS.account, 'acc_1', { id: 'acc_1', name: 'Fabrikam' })).toBe(false); + expect(valuesDiffer(FIELDS.account, { _id: 'acc_1' }, { id: 'acc_2' })).toBe(true); + }); + + it('a date compares by its instant; a list as a set', () => { + expect(valuesDiffer(FIELDS.due_on, '2026-07-23', '2026-07-23T00:00:00.000Z')).toBe(false); + expect(valuesDiffer(FIELDS.due_on, '2026-07-23', '2026-07-24')).toBe(true); + expect(valuesDiffer(FIELDS.tags, ['a', 'b'], ['b', 'a'])).toBe(false); + expect(valuesDiffer(FIELDS.tags, ['a'], ['a', 'c'])).toBe(true); + }); + + it('CONTROL: text that only looks like a date or a number on a text field compares as text', () => { + expect(valuesDiffer(FIELDS.name, '1', '01')).toBe(true); + expect(valuesDiffer(FIELDS.name, 'x', 'x')).toBe(false); + }); + + it('an object without an id compares by its content, key order aside', () => { + expect(valuesDiffer(FIELDS.note, { a: 1, b: { c: 2 } }, { b: { c: 2 }, a: 1 })).toBe(false); + expect(valuesDiffer(FIELDS.note, { a: 1 }, { a: 2 })).toBe(true); + }); +}); + +describe('distinctLabels (objectui#12483)', () => { + it('qualifies only the shared labels, and every label when a qualified one still collides', () => { + expect(distinctLabels([{ key: 'a', label: 'X' }, { key: 'b', label: 'X' }, { key: 'c', label: 'Y' }])) + .toEqual(['X (a)', 'X (b)', 'Y']); + expect(distinctLabels([{ key: 'a', label: 'X' }, { key: 'b', label: 'X' }, { key: 'c', label: 'X (a)' }])) + .toEqual(['X (a)', 'X (b)', 'X (a) (c)']); + }); +}); diff --git a/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.ts b/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.ts new file mode 100644 index 00000000000..f55f28c881b --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-decision/submittedRecordPlan.ts @@ -0,0 +1,208 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * Which fields of a submitted record the request page draws, in which + * section, and which of them changed after submission (objectstack#34588). + * Pure: the reader's field permissions are applied to both rows before they + * get here. The rules are in `SubmittedRecord.tsx`'s header. + */ + +import { FILE_REFERENCE_TYPES } from '@objectstack/spec/data'; +import { isSystemManagedField } from '@object-ui/types'; + +/** One field's declaration as the object definition serves it. */ +export type FieldDef = Readonly>; + +/** An object's declared fields, keyed by field name. */ +export type FieldDefs = Readonly>; + +/** + * One section of the object's default record page, already resolved: its + * heading (absent for the untitled primary section), its column count when + * the derivation names one, and its member field names in page order. + */ +export interface SubmittedSectionInput { + key: string; + label?: string; + columns?: number; + fields: readonly string[]; +} + +/** One drawn field: the submitted value and, when it changed, the current one. */ +export interface SubmittedField { + key: string; + /** The value as submitted (`undefined` when the snapshot holds no such key). */ + value: unknown; + /** True only when the current row was read, holds the key, and differs. */ + changed: boolean; + /** The current value; read only when `changed`. */ + current: unknown; +} + +export interface SubmittedSection { + key: string; + label?: string; + columns?: number; + fields: SubmittedField[]; +} + +export interface SubmittedRecordPlan { + sections: SubmittedSection[]; + /** + * The attachment fields (`FILE_REFERENCE_TYPES`) that hold a file in the + * snapshot or in the current row, in page order. Drawn in the page's + * attachments card, not in the field grid. + */ + attachments: SubmittedField[]; + /** How many drawn fields (attachments included) changed after submission. */ + changedCount: number; +} + +/** Field types whose values are numbers, compared as numbers. */ +const NUMERIC_TYPES: ReadonlySet = new Set([ + 'number', 'currency', 'percent', 'rating', 'slider', 'autonumber', 'summary', 'formula', +]); + +/** Field types whose values are instants or days, compared as instants. */ +const TEMPORAL_TYPES: ReadonlySet = new Set(['date', 'datetime', 'time']); + +function isEmpty(value: unknown): boolean { + if (value === undefined || value === null) return true; + if (typeof value === 'string') return value.trim() === ''; + if (Array.isArray(value)) return value.length === 0; + return false; +} + +/** Keys sorted at every depth, so two equal objects serialize alike. */ +function stableStringify(value: unknown): string { + if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`; + if (value && typeof value === 'object') { + const entries = Object.keys(value as Record) + .sort() + .map((k) => `${JSON.stringify(k)}:${stableStringify((value as Record)[k])}`); + return `{${entries.join(',')}}`; + } + return JSON.stringify(value) ?? 'null'; +} + +/** + * One value's comparable form. A reference is compared by the record it + * names, whether it is stored as an id or served expanded (`{ id, … }`); a + * number by its numeric value; a date by its instant; a list as a set of its + * members' forms; empty (absent, null, blank, an empty list) as one value. + */ +function comparable(def: FieldDef | undefined, value: unknown): string | null { + if (isEmpty(value)) return null; + if (Array.isArray(value)) { + const members = value + .map((member) => comparable(def, member)) + .filter((m): m is string => m !== null) + .sort(); + return members.length === 0 ? null : `[${members.join(',')}]`; + } + if (typeof value === 'object') { + const ref = (value as { id?: unknown; _id?: unknown }).id ?? (value as { _id?: unknown })._id; + if (typeof ref === 'string' || typeof ref === 'number') return `ref:${ref}`; + return `obj:${stableStringify(value)}`; + } + const type = typeof def?.type === 'string' ? def.type : ''; + if (TEMPORAL_TYPES.has(type) && typeof value === 'string') { + const at = Date.parse(value); + if (Number.isFinite(at)) return `t:${at}`; + } + if (typeof value === 'number' || (NUMERIC_TYPES.has(type) && typeof value === 'string')) { + const n = Number(value); + if (Number.isFinite(n)) return `n:${n}`; + } + // A bare id or name compares with its expanded form's id above. + return typeof value === 'string' ? `ref:${value}` : `v:${String(value)}`; +} + +/** Whether a field's current value differs from its submitted one. */ +export function valuesDiffer(def: FieldDef | undefined, submitted: unknown, current: unknown): boolean { + return comparable(def, submitted) !== comparable(def, current); +} + +function isAttachmentField(def: FieldDef): boolean { + return typeof def.type === 'string' && FILE_REFERENCE_TYPES.has(def.type); +} + +/** + * The plan for one submitted record. + * + * - `snapshot` is the request's `payload`, already narrowed for the reader by + * the service and by the reader's field permissions. + * - `current` is the record as it reads now, narrowed the same way, or null + * when it was not read (no data source, refused, gone, still loading): then + * nothing is marked changed and only the snapshot's keys are drawn. + */ +export function planSubmittedRecord( + sections: readonly SubmittedSectionInput[], + fields: FieldDefs, + snapshot: Readonly>, + current: Readonly> | null, +): SubmittedRecordPlan { + const seen = new Set(); + const attachments: SubmittedField[] = []; + let changedCount = 0; + + const fieldOf = (key: string): SubmittedField | null => { + if (seen.has(key)) return null; // one field, one place + const def = fields[key]; + if (!def || typeof def !== 'object') return null; // not a field of this object + if (def.hidden === true) return null; // hidden from the default UI + if (isSystemManagedField(key, def as { system?: boolean })) return null; // bookkeeping + const inSnapshot = Object.prototype.hasOwnProperty.call(snapshot, key); + const inCurrent = current !== null && Object.prototype.hasOwnProperty.call(current, key); + // Neither answer serves the key to this reader: nothing to draw. + if (!inSnapshot && !inCurrent) return null; + seen.add(key); + const value = inSnapshot ? snapshot[key] : undefined; + const changed = inCurrent && valuesDiffer(def, value, current![key]); + if (changed) changedCount += 1; + return { key, value, changed, current: changed ? current![key] : undefined }; + }; + + const planned: SubmittedSection[] = []; + for (const section of sections) { + const drawn: SubmittedField[] = []; + for (const key of section.fields) { + const field = fieldOf(key); + if (!field) continue; + if (isAttachmentField(fields[key]!)) { + if (!isEmpty(field.value) || field.changed) attachments.push(field); + continue; + } + drawn.push(field); + } + if (drawn.length > 0) { + planned.push({ + key: section.key, + ...(section.label ? { label: section.label } : {}), + ...(section.columns ? { columns: section.columns } : {}), + fields: drawn, + }); + } + } + return { sections: planned, attachments, changedCount }; +} + +/** + * Two rows never share a label: every row whose label is shared names its + * field key as well, and if a qualified label still matches another row's + * plain label, every row is qualified. Field keys are unique, so the result is. + */ +export function distinctLabels(rows: ReadonlyArray<{ key: string; label: string }>): string[] { + const qualify = (pick: (r: { key: string; label: string }) => boolean) => + rows.map((r) => (pick(r) ? `${r.label} (${r.key})` : r.label)); + const count = new Map(); + for (const r of rows) count.set(r.label, (count.get(r.label) ?? 0) + 1); + const once = qualify((r) => (count.get(r.label) ?? 0) > 1); + return new Set(once).size === once.length ? once : qualify(() => true); +} diff --git a/ui/packages/app-shell/src/views/approval-progress/ApprovalActionTimeline.tsx b/ui/packages/app-shell/src/views/approval-progress/ApprovalActionTimeline.tsx new file mode 100644 index 00000000000..51025c57efa --- /dev/null +++ b/ui/packages/app-shell/src/views/approval-progress/ApprovalActionTimeline.tsx @@ -0,0 +1,205 @@ +/** + * ObjectUI + * Copyright (c) 2024-present ObjectStack Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +/** + * The approval action timeline: one entry per `sys_approval_action` row, its + * kind, who acted, the step, when, a reassignment's from and to, the comment + * and the attachments (each opened through its short-lived signed URL). + * + * One markup for both places that tell an approval's story, so the two cannot + * drift: the business record's approvals panel (`RecordApprovalsPanel`, the + * merged threads of every request on the record) and the approval request's + * own page, whose right rail ends with it (objectstack#34588). Each caller + * reads its rows and passes them in the order it draws them; the step each + * row names is the caller's to resolve (`stepText`), because the actions + * route does not serve a row's step label (objectui#13248). + * + * Copy is the Approval Center's `approvalsInbox.*` keys, verbatim. + */ + +import * as React from 'react'; +import { toast } from 'sonner'; +import { Badge } from '@object-ui/components'; +import { createAuthenticatedFetch } from '@object-ui/auth'; +import { useDisplayLocale } from '@object-ui/i18n'; +import { useObjectTranslation } from '@object-ui/react'; +import { Loader2, Paperclip, ShieldAlert } from 'lucide-react'; +import type { ApprovalActionAttachmentLite, ApprovalActionLite } from '../../hooks/useRecordApprovals.js'; +import { isViaOverrideRow } from '../../utils/approvalOverride.js'; +import { formatIdentity } from '../../utils/approverIdentity.js'; + +/** Timeline dot color per action kind — same palette as the Approval Center. */ +const ACTION_DOT: Record = { + approve: 'bg-emerald-500', + reject: 'bg-destructive', + submit: 'bg-blue-500', + reassign: 'bg-indigo-500', + remind: 'bg-amber-500', + request_info: 'bg-amber-500', + comment: 'bg-slate-400', + escalate: 'bg-red-500', + revise: 'bg-violet-500', + resubmit: 'bg-blue-500', +}; + +/** + * `locale` is REQUIRED: the timeline's action times used to be formatted with + * no tag, i.e. in the MACHINE's locale (objectui#9909). The timeline passes + * `useDisplayLocale()`. + */ +function formatDate(s: string | null | undefined, locale: string): string { + if (!s) return '—'; + try { return new Date(s).toLocaleString(locale); } catch { return s; } +} + +export interface ApprovalActionTimelineProps { + /** The rows, in the order they are drawn. */ + actions: readonly ApprovalActionLite[]; + /** True while the first read has not answered: a spinner instead of "No actions yet." */ + loading?: boolean; + /** The step a row names, as a reader should see it; null names none. */ + stepText?: (action: ApprovalActionLite) => string | null; +} + +export function ApprovalActionTimeline({ actions, loading = false, stepText }: ApprovalActionTimelineProps) { + const { t } = useObjectTranslation(); + const displayLocale = useDisplayLocale(); + const tr = React.useCallback( + (key: string, defaultValue: string, opts?: Record) => + String(t(`approvalsInbox.${key}`, { defaultValue, ...opts })), + [t], + ); + + /** + * Open a timeline attachment via its short-lived signed URL — same + * user-gesture-preserving dance as the Approval Center (framework#3266 + * follow-up): open the tab synchronously, then point it at the URL. + */ + const authFetch = React.useMemo(() => createAuthenticatedFetch(), []); + const openAttachment = React.useCallback(async (att: ApprovalActionAttachmentLite) => { + const win = window.open('', '_blank', 'noopener'); + try { + const base = String((import.meta as any).env?.VITE_SERVER_URL || '').replace(/\/$/, ''); + const res = await authFetch(`${base}/api/v1/storage/files/${encodeURIComponent(att.id)}/url`); + if (!res.ok) throw new Error(`HTTP_${res.status}`); + const body = await res.json().catch(() => null); + const raw = body?.data?.url ?? body?.url; + if (!raw) throw new Error('NO_URL'); + const url = /^https?:\/\//i.test(raw) ? raw : `${base}${raw}`; + if (win) win.location.href = url; + else window.open(url, '_blank', 'noopener'); + } catch { + win?.close(); + toast.error(tr('attachmentOpenFailed', 'Could not open the attachment — please try again')); + } + }, [authFetch, tr]); + + const actionText = (a: ApprovalActionLite): string => + a.action === 'submit' ? tr('actSubmit', 'Submitted') + : a.action === 'approve' ? tr('actApprove', 'Approved') + : a.action === 'reject' ? tr('actReject', 'Rejected') + : a.action === 'recall' ? tr('actRecall', 'Recalled') + : a.action === 'reassign' ? tr('actReassign', 'Reassigned') + : a.action === 'remind' ? tr('actRemind', 'Reminder sent') + : a.action === 'request_info' ? tr('actRequestInfo', 'Requested more info') + : a.action === 'comment' ? tr('actComment', 'Commented') + : a.action === 'escalate' ? tr('actEscalate', 'SLA escalated') + : a.action === 'revise' ? tr('actRevise', 'Sent back for revision') + : a.action === 'resubmit' ? tr('actResubmit', 'Resubmitted') + : a.action; + + const actorName = (a: ApprovalActionLite): string => + a.actor_id === 'system:sla' + ? tr('systemSlaActor', 'System (SLA)') + : a.actor_name ?? formatIdentity(a.actor_id); + + const actionStepText = (a: ApprovalActionLite): string | null => stepText?.(a) ?? null; + + return loading && actions.length === 0 ? ( +
+ + {tr('loadingMore', 'Loading…')} +
+ ) : actions.length === 0 ? ( +
{tr('noActions', 'No actions yet.')}
+ ) : ( +
    + {actions.map((a) => ( +
  1. + {/* objectui#5178 — an admin override does not wear the ordinary + decision's dot. `approve` is emerald here, which is exactly + the "byte-for-byte like an ordinary approval" the card + reports; an override gets the amber attention dot instead, + so the distinction survives a glance down the timeline. */} + +
    + {actionText(a)} + · + {actorName(a)} + {/* The marker framework#4466 wrote and nothing read. Only an + explicit `via_override: true` earns it — see + `isViaOverrideRow` for why "not recorded" must not + render as either answer. */} + {isViaOverrideRow(a) && ( + + + {tr('viaOverrideChip', 'Admin override')} + + )} + {actionStepText(a) && ( + + · {actionStepText(a)} + + )} + + {formatDate(a.created_at, displayLocale)} + +
    + {a.action === 'reassign' && (a.reassign_from || a.reassign_to) && ( +
    + {tr('reassignFromTo', 'from {{from}} to {{to}}', { + from: a.reassign_from_name ?? formatIdentity(a.reassign_from), + to: a.reassign_to_name ?? formatIdentity(a.reassign_to), + })} +
    + )} + {a.comment && ( +
    "{a.comment}"
    + )} + {Array.isArray(a.attachments) && a.attachments.length > 0 && ( +
    + {a.attachments.map((att, i) => ( + + ))} +
    + )} +
  2. + ))} +
+ ); +} diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 4b1596590fd..13b33b54dc5 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -4762,6 +4762,13 @@ const ar = { openNextAfterDecision: 'فتح التالي بعد اتخاذ القرار', queueDone: 'لا توجد طلبات معلقة أخرى في هذه القائمة.', snapshotAsSubmitted: 'كما قُدِّم', + snapshotChanged: 'تم التغيير', + snapshotCurrentValue: 'القيمة الحالية', + snapshotOpenRecord: 'فتح السجل', + snapshotCurrentUnreadable: 'تتعذر قراءة السجل الحالي، لذا لا تُعلَّم التغييرات التي تمت بعد الإرسال.', + snapshotChildCurrent: 'الصفوف الحالية: لا يحفظ الإرسال الصفوف الفرعية.', + progressTitle: 'تقدم الموافقة', + attachmentsTitle: 'المرفقات', attachmentChip: 'مرفق', attachmentOpenFailed: 'تعذّر فتح المرفق — يرجى المحاولة مرة أخرى', approveOneTitle: 'الموافقة على "{{title}}"؟', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 3aff599be24..cbfa95731ad 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -4365,6 +4365,13 @@ const de = { openNextAfterDecision: 'Nach der Entscheidung die nächste öffnen', queueDone: 'In dieser Liste sind keine offenen Anfragen mehr.', snapshotAsSubmitted: 'Wie eingereicht', + snapshotChanged: 'Geändert', + snapshotCurrentValue: 'Aktueller Wert', + snapshotOpenRecord: 'Datensatz öffnen', + snapshotCurrentUnreadable: 'Der aktuelle Datensatz kann nicht gelesen werden, daher sind Änderungen nach der Einreichung nicht markiert.', + snapshotChildCurrent: 'Aktuelle Zeilen: Die Einreichung speichert keine untergeordneten Zeilen.', + progressTitle: 'Genehmigungsfortschritt', + attachmentsTitle: 'Anhänge', attachmentChip: 'Anhang', attachmentOpenFailed: 'Anhang konnte nicht geöffnet werden – bitte erneut versuchen', approveOneTitle: '„{{title}}“ genehmigen?', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index fa35746d39f..0b49bb28a48 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -5301,6 +5301,13 @@ const en = { openNextAfterDecision: 'Open next after deciding', queueDone: 'No more pending requests in this list.', snapshotAsSubmitted: 'As submitted', + snapshotChanged: 'Changed', + snapshotCurrentValue: 'Current value', + snapshotOpenRecord: 'Open record', + snapshotCurrentUnreadable: 'The current record cannot be read, so changes made after submission are not marked.', + snapshotChildCurrent: 'Current rows: the submission does not keep child rows.', + progressTitle: 'Approval progress', + attachmentsTitle: 'Attachments', attachmentChip: 'Attachment', attachmentOpenFailed: 'Could not open the attachment — please try again', approveOneTitle: 'Approve "{{title}}"?', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index c3479cb9adf..9e2bddad223 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -4465,6 +4465,13 @@ const es = { openNextAfterDecision: 'Abrir la siguiente tras decidir', queueDone: 'No quedan solicitudes pendientes en esta lista.', snapshotAsSubmitted: 'Tal como se envió', + snapshotChanged: 'Modificado', + snapshotCurrentValue: 'Valor actual', + snapshotOpenRecord: 'Abrir registro', + snapshotCurrentUnreadable: 'No se puede leer el registro actual, así que los cambios posteriores al envío no se marcan.', + snapshotChildCurrent: 'Filas actuales: el envío no guarda las filas secundarias.', + progressTitle: 'Progreso de la aprobación', + attachmentsTitle: 'Adjuntos', attachmentChip: 'Adjunto', attachmentOpenFailed: 'No se pudo abrir el archivo adjunto: inténtalo de nuevo', approveOneTitle: '¿Aprobar «{{title}}»?', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index b8e05cddcb8..3fb6139b7c3 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -4461,6 +4461,13 @@ const fr = { openNextAfterDecision: 'Ouvrir la suivante après décision', queueDone: 'Plus aucune demande en attente dans cette liste.', snapshotAsSubmitted: 'Tel que soumis', + snapshotChanged: 'Modifié', + snapshotCurrentValue: 'Valeur actuelle', + snapshotOpenRecord: 'Ouvrir l’enregistrement', + snapshotCurrentUnreadable: 'L’enregistrement actuel est illisible ; les modifications après la soumission ne sont donc pas signalées.', + snapshotChildCurrent: 'Lignes actuelles : la soumission ne conserve pas les lignes enfants.', + progressTitle: 'Avancement de l’approbation', + attachmentsTitle: 'Pièces jointes', attachmentChip: 'Pièce jointe', attachmentOpenFailed: "Impossible d'ouvrir la pièce jointe — veuillez réessayer", approveOneTitle: 'Approuver « {{title}} » ?', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index c2803463061..ca46d9936b9 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -4367,6 +4367,13 @@ const ja = { openNextAfterDecision: '決定後に次を開く', queueDone: 'このリストの保留中のリクエストはすべて処理済みです。', snapshotAsSubmitted: '申請時の内容', + snapshotChanged: '変更あり', + snapshotCurrentValue: '現在の値', + snapshotOpenRecord: 'レコードを開く', + snapshotCurrentUnreadable: '現在のレコードを読み取れないため、申請後の変更は表示されません。', + snapshotChildCurrent: '現在の値:申請時の明細行は保存されていません。', + progressTitle: '承認の進捗', + attachmentsTitle: '添付ファイル', attachmentChip: '添付ファイル', attachmentOpenFailed: '添付ファイルを開けませんでした。もう一度お試しください', approveOneTitle: '「{{title}}」を承認しますか?', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 608fa308ac9..8e11cbbaf5e 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -4364,6 +4364,13 @@ const ko = { openNextAfterDecision: '결정 후 다음 열기', queueDone: '이 목록에 대기 중인 요청이 더 이상 없습니다.', snapshotAsSubmitted: '제출 당시 내용', + snapshotChanged: '변경됨', + snapshotCurrentValue: '현재 값', + snapshotOpenRecord: '레코드 열기', + snapshotCurrentUnreadable: '현재 레코드를 읽을 수 없어 제출 후 변경 사항을 표시하지 않습니다.', + snapshotChildCurrent: '현재 값: 제출 당시 하위 행은 저장되지 않습니다.', + progressTitle: '승인 진행 상황', + attachmentsTitle: '첨부 파일', attachmentChip: '첨부 파일', attachmentOpenFailed: '첨부 파일을 열 수 없습니다. 다시 시도해 주세요', approveOneTitle: '"{{title}}"을(를) 승인할까요?', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 51879402d21..c9c290f9ae7 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -4460,6 +4460,13 @@ const pt = { openNextAfterDecision: 'Abrir a próxima após decidir', queueDone: 'Não há mais solicitações pendentes nesta lista.', snapshotAsSubmitted: 'Conforme enviado', + snapshotChanged: 'Alterado', + snapshotCurrentValue: 'Valor atual', + snapshotOpenRecord: 'Abrir registro', + snapshotCurrentUnreadable: 'Não é possível ler o registro atual, então as alterações após o envio não são marcadas.', + snapshotChildCurrent: 'Linhas atuais: o envio não guarda as linhas filhas.', + progressTitle: 'Progresso da aprovação', + attachmentsTitle: 'Anexos', attachmentChip: 'Anexo', attachmentOpenFailed: 'Não foi possível abrir o anexo — tente novamente', approveOneTitle: 'Aprovar "{{title}}"?', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 862b290130a..a5ce4a5a359 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -4574,6 +4574,13 @@ const ru = { openNextAfterDecision: 'Открывать следующий после решения', queueDone: 'В этом списке больше нет ожидающих запросов.', snapshotAsSubmitted: 'На момент подачи', + snapshotChanged: 'Изменено', + snapshotCurrentValue: 'Текущее значение', + snapshotOpenRecord: 'Открыть запись', + snapshotCurrentUnreadable: 'Не удаётся прочитать текущую запись, поэтому изменения после подачи не отмечены.', + snapshotChildCurrent: 'Текущие строки: при подаче дочерние строки не сохраняются.', + progressTitle: 'Ход согласования', + attachmentsTitle: 'Вложения', attachmentChip: 'Вложение', attachmentOpenFailed: 'Не удалось открыть вложение — попробуйте ещё раз', approveOneTitle: 'Согласовать «{{title}}»?', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 228ef8997c1..e67c9b1af74 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -4614,6 +4614,13 @@ const zh = { openNextAfterDecision: '处理后打开下一条', queueDone: '这个列表里的待审请求已全部处理完。', snapshotAsSubmitted: '提交时的内容', + snapshotChanged: '已改动', + snapshotCurrentValue: '当前值', + snapshotOpenRecord: '打开记录', + snapshotCurrentUnreadable: '无法读取当前记录,提交后的改动无法标出。', + snapshotChildCurrent: '当前值:提交时未保存子表数据。', + progressTitle: '审批进度', + attachmentsTitle: '附件', attachmentChip: '附件', attachmentOpenFailed: '无法打开附件,请重试', approveOneTitle: '通过“{{title}}”?', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 37b28b743c5..9e046fcdc4a 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -4614,6 +4614,13 @@ const zhHant = { openNextAfterDecision: '處理後開啟下一條', queueDone: '這個列表裡的待審請求已全部處理完。', snapshotAsSubmitted: '提交時的內容', + snapshotChanged: '已改動', + snapshotCurrentValue: '當前值', + snapshotOpenRecord: '開啟記錄', + snapshotCurrentUnreadable: '無法讀取當前記錄,提交後的改動無法標出。', + snapshotChildCurrent: '當前值:提交時未儲存子表資料。', + progressTitle: '審批進度', + attachmentsTitle: '附件', attachmentChip: '附件', attachmentOpenFailed: '無法開啟附件,請重試', approveOneTitle: '通過“{{title}}”?',