diff --git a/.changeset/35599-record-page-edit-state.md b/.changeset/35599-record-page-edit-state.md new file mode 100644 index 00000000000..9237444777c --- /dev/null +++ b/.changeset/35599-record-page-edit-state.md @@ -0,0 +1,21 @@ +--- +'@objectstack/plugin-approvals': patch +'@object-ui/plugin-form': patch +'@object-ui/i18n': patch +'@object-ui/plugin-detail': patch +--- + +feat: edit a record and its line tables together, and lock a record's lines while an approval locks the record + +Clause-②: no +Metadata-protocol: none + +**A locked record's lines are locked too.** While a record is held by an approval that locks it, writes to its master-detail child rows are refused with `RECORD_LOCKED` (409), the same answer a write to the record itself gets: inserting a row under it, updating or deleting one of its rows, and moving a row into it or out of it (both ends of a reparent are checked). A multi-row write that touches any such row is refused as a whole, and a row whose parent cannot be read is refused when the parent object has a locking approval the writer's run does not own. The approval's own exemptions carry over: system writes and the flow run that opened the approval still write. The refusal names the record by its object's label ("This Opportunity is locked while an approval is in progress, …"). Lookup children are not affected. `@objectstack/plugin-approvals` binds the new `bindDetailRowLockHook` beside the record lock it already binds. + +**`@object-ui/plugin-form` exports the record-page body-table editor.** `RecordBodyTableEditor` draws a master-detail body table as editable lines (the `LineItemsField` grid, with the child columns, field permissions and add / remove rules the master-detail form uses) for a host's edit session (`RecordEditSessionContext`). `buildRecordEditBatch` folds a record's field changes and every table's lines into one batch (the `buildMasterDetailEditBatch` diff, table by table), and `attributeRecordEditRefusal` places a refused batch's reasons on the record's field or on the line whose write carried the refused field. + +**`@object-ui/i18n`** adds `detail.bodyTableRow`, `detail.bodyTablesReadOnlyBulk` and `detail.discardInlineEditsMessage` to every built-in pack. + +**`@object-ui/plugin-detail`** exports `RecordBodyTableEditorSlotContext`: while a host provides it, a `record:related_list` whose relationship id (`CHILD_OBJECT.FK_FIELD`) is in the slot's set draws the host's element in its place instead of the read-only list. The record page's edit state draws its body-table editors through it; no new node type is registered. + +In the console, Edit on a record page that draws master-detail body tables now opens the page's edit state: the fields become inputs, the body tables editable lines, and one Save writes all of it in one batch. Per-field inline edit stays on every record page, those included, and saves the record alone through its save bar. One mode runs at a time: the edit state offers no per-field inline edit, and pressing Edit while inline changes are unsaved first asks whether to discard them. diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 111f4c645c9..ca1d7e590f8 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -182,7 +182,7 @@ One of the largest consumers of the flag; | # | Behaviour when `isSystem` | Package | What you get / what you lose | Symbol | |:--|:---|:---|:---|:---| -| 41 | **Approval record lock released** — a locked record is writable | plugin-approvals | Get: engine self-writes (the status mirror) pass. Lose: the lock that stops edits while an approval is live. Note there is deliberately **no admin exemption** here — only `isSystem` | `bindApprovalLockHook` | +| 41 | **Approval record lock released** — a locked record, and its master-detail rows, are writable | plugin-approvals | Get: engine self-writes (the status mirror) pass, and so do system writes to a locked master's detail rows. Lose: the lock that stops edits to the record and its detail rows while an approval is live. Note there is deliberately **no admin exemption** here — only `isSystem` | `bindApprovalLockHook`, `bindDetailRowLockHook` | | 42 | Delegation write guard bypassed | plugin-approvals | Get: service / seed / import may write delegation rows naming another delegator | `bindDelegationWriteGuard` | | 43 | Approval actor / submitter / pending-approver checks bypassed (9 sites) | plugin-approvals | Get: approve, reject, recall, reassign without being a pending approver or the submitter, and a decision or comment that attaches files the actor did not upload (every other caller attaches only files it uploaded, in the request's organization) | `isOverrideActor`, `resolveActor`, `sendBack`, `resubmit`, `reassign`, `remind`, `requestInfo`, `comment`, `assertAttachmentsUploadedByCaller` | | 44 | Attachment access hooks return early (insert + update + delete, the referenced-file check on insert + update, and the read AST) | service-storage | Lose: attachment visibility scoping | `installAttachmentAccessHooks`, `installAttachmentFileReferenceGate`, `installAttachmentReadVisibility` | @@ -579,6 +579,7 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-approvals/src/approval-service.ts#sendBack` | 1 | 43 | | `packages/plugins/plugin-approvals/src/lifecycle-hooks.ts#bindApprovalLockHook` | 1 | 41 | | `packages/plugins/plugin-approvals/src/lifecycle-hooks.ts#bindDelegationWriteGuard` | 1 | 42 | +| `packages/plugins/plugin-approvals/src/lifecycle-hooks.ts#bindDetailRowLockHook` | 1 | 41 | | `packages/plugins/plugin-approvals/src/payload-predicate-guard.ts#bindSnapshotPredicateGuard` | 1 | 17 | | `packages/plugins/plugin-approvals/src/payload-redaction-middleware.ts#bindSnapshotRedactionMiddleware` | 1 | 17 | | `packages/plugins/plugin-approvals/src/reader-locale-labels-middleware.ts#bindReaderLocaleLabelsMiddleware` | 1 | 17 | diff --git a/docs/qa/platform-checklist/areas/records-forms.json b/docs/qa/platform-checklist/areas/records-forms.json index 9bd0e37d541..bb9b556be5f 100644 --- a/docs/qa/platform-checklist/areas/records-forms.json +++ b/docs/qa/platform-checklist/areas/records-forms.json @@ -1523,7 +1523,7 @@ "title": "Master + line items save as one atomic batch, with server-side roll-up", "since": "v16", "status": "active", - "revision": 10, + "revision": 11, "priority": "P1", "surface": "browser", "personas": [ @@ -1546,7 +1546,9 @@ "re-read master + lines via GET /api/v1/data/showcase_invoice?$filter=[[\"name\",\"=\",\"os-qa-\"]] and the lines by the returned invoice id; check invoice.total against the sum of line amounts", "add a third line via the edit form and save; re-read invoice.total; delete that line; re-read total again", "repeat the create with one child made deliberately invalid (product empty on a line); attempt save; capture the failure", - "verify no partial writes: filtered GET for the failed invoice name returns 0 rows and no orphan lines exist" + "verify no partial writes: filtered GET for the failed invoice name returns 0 rows and no orphan lines exist", + "record-page edit (#35599): open a saved invoice's record page (its Line Items draw as a body table) and press Edit: the fields become inputs, the body table becomes editable lines, and the header shows Cancel and Save in Edit's place. Change the invoice name, one line's quantity, add a line in the trailing blank row and remove another line; Save ONCE; capture the network trace of the save and re-read the invoice and its lines", + "on the same page, Edit again, clear one line's product and Save: capture the error and where it is drawn; re-read the invoice and lines; then press Cancel and check the page reads as stored" ], "acceptance": [ { @@ -1584,11 +1586,18 @@ "oracle": "api", "verify": "change qty, watch amount update without save; after save the API row carries qty × unit_price", "evidence": "screenshot + line read" + }, + { + "clause": "the record page's edit state saves the record's changes and every body table's line creates, updates and deletes in ONE POST /api/v1/batch, one transaction; a refused save writes nothing, keeps every edit on screen, and draws the reason on the line whose write carried the refused field; Cancel discards every edit", + "oracle": "network", + "verify": "the save sends exactly one batch call whose payload opens with the invoice update (only the changed fields) and carries the line create, update and delete; after the invalid-line save the re-read shows the invoice and lines unchanged and the line's error sits under the table naming that line; after Cancel the lines and fields read as stored", + "evidence": "the batch payload, the two re-reads, the error screenshot" } ], "negative": [ "the invalid-child case must not partially commit: ANY surviving master or sibling row after the failed save is a FAIL — check by API read, not by the grid", - "a save that issues one write per row (N requests) is a FAIL of the atomicity clause even when all rows land" + "a save that issues one write per row (N requests) is a FAIL of the atomicity clause even when all rows land", + "a record-page save that sends the record update and the line writes as separate requests (or one request per line) is a FAIL of the edit-state clause even when every row lands" ], "traps": [ "automation-input", @@ -1596,7 +1605,7 @@ ], "automated": { "kind": "e2e", - "ref": "objectui: e2e/live/master-detail.spec.ts (acceptance[0], carrier-neutrally: the showcase 'New Project + Tasks' page, one showcase_task child staged through the per-row form, not this item's invoice grid with two lines), e2e/live/form-view-subforms.spec.ts (acceptance[4] ONLY: the stock New Invoice dialog renders the relationship-derived Line Items section, found by its heading, and its line grid). The roll-up spec dropped at revision 5 is not a pin of this item (history, revision 5). packages/qa/dogfood/test/master-detail-batch-atomic.dogfood.test.ts, at the cross-object POST /api/v1/batch the form saves through (child ops pointing at the parent by {$ref: 0}), on the showcase invoice and lines as shipped: acceptance[1] (the invoice and two catalog-product lines re-read over REST with the values sent), acceptance[5]'s persisted half (each stored amount is quantity × unit_price; a client-sent amount does not stand), acceptance[2] (total equals the sum of line amounts on the atomic create, after a line is added and after one is deleted) and acceptance[3] with negative[0] (a batch whose second line has no product is 400 VALIDATION_FAILED naming product, and neither the invoice nor its valid sibling line exists afterwards). acceptance[0]'s batch count, negative[1] and acceptance[5]'s live client recompute stay network/dom legs" + "ref": "objectui: e2e/live/master-detail.spec.ts (acceptance[0], carrier-neutrally: the showcase 'New Project + Tasks' page, one showcase_task child staged through the per-row form, not this item's invoice grid with two lines), e2e/live/form-view-subforms.spec.ts (acceptance[4] ONLY: the stock New Invoice dialog renders the relationship-derived Line Items section, found by its heading, and its line grid). The roll-up spec dropped at revision 5 is not a pin of this item (history, revision 5). packages/qa/dogfood/test/master-detail-batch-atomic.dogfood.test.ts, at the cross-object POST /api/v1/batch the form saves through (child ops pointing at the parent by {$ref: 0}), on the showcase invoice and lines as shipped: acceptance[1] (the invoice and two catalog-product lines re-read over REST with the values sent), acceptance[5]'s persisted half (each stored amount is quantity × unit_price; a client-sent amount does not stand), acceptance[2] (total equals the sum of line amounts on the atomic create, after a line is added and after one is deleted) and acceptance[3] with negative[0] (a batch whose second line has no product is 400 VALIDATION_FAILED naming product, and neither the invoice nor its valid sibling line exists afterwards). acceptance[0]'s batch count, negative[1] and acceptance[5]'s live client recompute stay network/dom legs. acceptance[6] (the record page's edit state, #35599): ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx block 'RecordDetailView.recordEditState-35599' (the real record page over a mocked adapter: one batchTransaction carrying the record update and two body tables' create, update and delete; a refused batch keeps every edit and draws the reason on its line; Cancel restores) and ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts (the batch and the refusal placement). Neither drives a live server: the one-transaction and nothing-lands halves are the batch route's, pinned by the dogfood battery above" }, "source": [ "#3358 §4", @@ -1663,6 +1672,12 @@ "date": "2026-11-15", "change": "steps[1] gains a driver note: 'Add line' beside the grid's trailing blank row makes it a middle all-null row that the save submits and the batch refuses (400 'Product is required', nothing written). QA run #33861, ledger row 146. No clause changed. Ledger 6896511848 of the v18.5.0 sweep anchor #33761, carried by batch-A card #33963; read at base 895783a1.", "ref": "#33990" + }, + { + "revision": 11, + "date": "2026-11-20", + "change": "the record page's edit state (#35599) saves through the same batch door: steps[7] and [8], acceptance[6] and negative[2] added for it, and automated.ref names its two unit pins. The form clauses above are unchanged", + "ref": "#35599" } ] }, diff --git a/packages/plugins/plugin-approvals/src/approvals-plugin.ts b/packages/plugins/plugin-approvals/src/approvals-plugin.ts index e7d4d90c0ea..5940ae255ba 100644 --- a/packages/plugins/plugin-approvals/src/approvals-plugin.ts +++ b/packages/plugins/plugin-approvals/src/approvals-plugin.ts @@ -28,6 +28,7 @@ import { } from './approval-service.js'; import { bindApprovalLockHook, + bindDetailRowLockHook, bindDelegationWriteGuard, bindRecordDeleteCancelHook, unbindAllHooks, @@ -369,6 +370,9 @@ export class ApprovalsServicePlugin implements Plugin { // …and it is worded in the writer's locale, with the object's label in // that locale, through the same lazily-read `i18n` service. bindApprovalLockHook(engine, ctx.logger, fieldVisibility, i18nService); + // Ruling A on the record-page edit card: a locked master's detail rows + // refuse insert / update / delete as well. + bindDetailRowLockHook(engine, ctx.logger, i18nService); bindRecordDeleteCancelHook(engine, this.service, ctx.logger); bindDelegationWriteGuard(engine, ctx.logger); // [#10749] Generic-door snapshot redaction. Registered here so the diff --git a/packages/plugins/plugin-approvals/src/detail-row-lock.integration.test.ts b/packages/plugins/plugin-approvals/src/detail-row-lock.integration.test.ts new file mode 100644 index 00000000000..c5cca2731c6 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/detail-row-lock.integration.test.ts @@ -0,0 +1,216 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The DETAIL-ROW lock (ruling A on the record-page edit card, 「一起锁」): while + * a master record is held by a locking pending approval, its master-detail rows + * refuse insert, update and delete with `RECORD_LOCKED` — driven through the + * REAL hook, a real {@link ObjectQL} and a real sqlite driver (the rig of + * `record-lock-batch-row-status.integration.test.ts`), so every write shape + * below is the engine's own dispatch, not fixture code. + * + * Each refusal cell sits beside its control: the same write under a master no + * approval holds, the system write, the opening run, and a `lockRecord: false` + * node all still land. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { bindDetailRowLockHook } from './lifecycle-hooks.js'; +import type { EngineQueryOptions } from '@objectstack/spec/data'; +import { installDefaultOrganization } from './default-organization.testkit.js'; + +const opportunity = { + name: 'opportunity', + label: 'Opportunity', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + name: { name: 'name', type: 'text' as const }, + }, +}; + +const lineItem = { + name: 'opportunity_line', + label: 'Opportunity Line', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + product: { name: 'product', type: 'text' as const }, + quantity: { name: 'quantity', type: 'number' as const }, + opportunity: { name: 'opportunity', type: 'master_detail' as const, reference: 'opportunity' }, + }, +}; + +/** A plain lookup child: the lock does NOT reach it (ruling A names master-detail rows). */ +const note = { + name: 'opportunity_note', + label: 'Opportunity Note', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + body: { name: 'body', type: 'text' as const }, + opportunity: { name: 'opportunity', type: 'lookup' as const, reference: 'opportunity' }, + }, +}; + +const approvalRequest = { + name: 'sys_approval_request', + label: 'Approval Request', + fields: { + id: { name: 'id', type: 'text' as const, primaryKey: true }, + object_name: { name: 'object_name', type: 'text' as const }, + record_id: { name: 'record_id', type: 'text' as const }, + status: { name: 'status', type: 'text' as const }, + flow_run_id: { name: 'flow_run_id', type: 'text' as const }, + node_config_json: { name: 'node_config_json', type: 'text' as const }, + }, +}; + +const SYSTEM = { context: { isSystem: true } } as any; +const USER = { context: { userId: 'u1' } } as any; + +async function refusal(write: () => Promise): Promise { + try { + await write(); + } catch (err) { + return err; + } + return null; +} + +describe('ruling A — a locked master\'s detail rows refuse insert / update / delete', () => { + let engine: ObjectQL; + let lockedId: string; + let freeId: string; + let openNodeId: string; + let lineOfLocked: string; + let lineOfFree: string; + + afterEach(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + beforeEach(async () => { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', + connection: { filename: ':memory:' }, + useNullAsDefault: true, + }), true); + await engine.init(); + for (const o of [opportunity, lineItem, note, approvalRequest]) { + engine.registry.registerObject(o as any, 'com.objectstack.test.detail-row-lock'); + } + await engine.syncSchemas(); + await installDefaultOrganization(engine); + + lockedId = String((await engine.insert('opportunity', { name: 'Locked deal' }, SYSTEM)).id); + freeId = String((await engine.insert('opportunity', { name: 'Free deal' }, SYSTEM)).id); + openNodeId = String((await engine.insert('opportunity', { name: 'Open-node deal' }, SYSTEM)).id); + lineOfLocked = String((await engine.insert('opportunity_line', { product: 'A', quantity: 1, opportunity: lockedId }, SYSTEM)).id); + lineOfFree = String((await engine.insert('opportunity_line', { product: 'B', quantity: 1, opportunity: freeId }, SYSTEM)).id); + await engine.insert('sys_approval_request', { + object_name: 'opportunity', + record_id: lockedId, + status: 'pending', + flow_run_id: 'run_open', + node_config_json: JSON.stringify({ lockRecord: true }), + }, SYSTEM); + await engine.insert('sys_approval_request', { + object_name: 'opportunity', + record_id: openNodeId, + status: 'pending', + flow_run_id: 'run_other', + node_config_json: JSON.stringify({ lockRecord: false }), + }, SYSTEM); + + bindDetailRowLockHook(engine as any); + }); + + const expectLocked = (err: any) => { + expect(err).not.toBeNull(); + expect(err.code).toBe('RECORD_LOCKED'); + expect(err.statusCode).toBe(409); + // The master is named by its label, never by its id or API name. + expect(err.userMessage).toBe( + 'This Opportunity is locked while an approval is in progress, and cannot be edited until that approval is complete', + ); + }; + + it('insert under a locked master is refused; under a free master it lands (CONTROL)', async () => { + expectLocked(await refusal(() => engine.insert('opportunity_line', { product: 'C', quantity: 2, opportunity: lockedId }, USER))); + const created = await engine.insert('opportunity_line', { product: 'C', quantity: 2, opportunity: freeId }, USER); + expect(created?.id).toBeTruthy(); + const underLocked = await engine.find('opportunity_line', { where: { opportunity: lockedId }, context: { isSystem: true } } satisfies EngineQueryOptions); + expect(underLocked).toHaveLength(1); + }); + + it('a non-scalar FK naming a locked master ({ id }) fails closed: refused, nothing lands', async () => { + expectLocked(await refusal(() => engine.insert('opportunity_line', { product: 'D', quantity: 1, opportunity: { id: lockedId } }, USER))); + const lines = await engine.find('opportunity_line', { where: { product: 'D' }, context: { isSystem: true } } satisfies EngineQueryOptions); + expect(lines).toHaveLength(0); + }); + + it('update of a locked master\'s row is refused and nothing lands; a free master\'s row updates (CONTROL)', async () => { + expectLocked(await refusal(() => engine.update('opportunity_line', { quantity: 9 }, { where: { id: lineOfLocked }, ...USER }))); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfLocked } }))?.quantity).toBe(1); + await engine.update('opportunity_line', { quantity: 9 }, { where: { id: lineOfFree }, ...USER }); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfFree } }))?.quantity).toBe(9); + }); + + it('delete of a locked master\'s row is refused; a free master\'s row deletes (CONTROL)', async () => { + expectLocked(await refusal(() => engine.delete('opportunity_line', { where: { id: lineOfLocked }, ...USER }))); + expect(await engine.findOne('opportunity_line', { where: { id: lineOfLocked } })).toBeTruthy(); + await engine.delete('opportunity_line', { where: { id: lineOfFree }, ...USER }); + expect(await engine.findOne('opportunity_line', { where: { id: lineOfFree } })).toBeFalsy(); + }); + + it('reparent is checked at both ends: into a locked master and out of one are both refused', async () => { + expectLocked(await refusal(() => engine.update('opportunity_line', { opportunity: lockedId }, { where: { id: lineOfFree }, ...USER }))); + expectLocked(await refusal(() => engine.update('opportunity_line', { opportunity: freeId }, { where: { id: lineOfLocked }, ...USER }))); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfFree } }))?.opportunity).toBe(freeId); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfLocked } }))?.opportunity).toBe(lockedId); + }); + + it('a predicate (multi-row) write touching a locked master\'s row is refused', async () => { + expectLocked(await refusal(() => engine.update( + 'opportunity_line', + { quantity: 5 }, + { where: { quantity: 1 }, multi: true, ...USER } as any, + ))); + expectLocked(await refusal(() => engine.delete( + 'opportunity_line', + { where: { quantity: 1 }, multi: true, ...USER } as any, + ))); + expect(await engine.find('opportunity_line', { where: { quantity: 1 }, context: { isSystem: true } } satisfies EngineQueryOptions)).toHaveLength(2); + }); + + it('the batch path (one transaction): a refused row rolls the whole transaction back', async () => { + const err = await refusal(() => engine.transaction(async (trx: any) => { + await engine.update('opportunity_line', { quantity: 7 }, { where: { id: lineOfFree }, context: { ...trx, userId: 'u1' } } as any); + await engine.insert('opportunity_line', { product: 'D', quantity: 1, opportunity: lockedId }, { context: { ...trx, userId: 'u1' } } as any); + }, { userId: 'u1' } as any, { require: true } as any)); + expectLocked(err); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfFree } }))?.quantity).toBe(1); + }); + + it('CONTROL — a system write is exempt', async () => { + await engine.update('opportunity_line', { quantity: 3 }, { where: { id: lineOfLocked }, ...SYSTEM }); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfLocked } }))?.quantity).toBe(3); + }); + + it('CONTROL — the run that opened the approval is exempt; another run is not', async () => { + const run = (flowRunId: string) => ({ context: { runAs: 'user', userId: 'u1', flowRunId } }) as any; + expectLocked(await refusal(() => engine.update('opportunity_line', { quantity: 4 }, { where: { id: lineOfLocked }, ...run('run_stranger') }))); + await engine.update('opportunity_line', { quantity: 4 }, { where: { id: lineOfLocked }, ...run('run_open') }); + expect((await engine.findOne('opportunity_line', { where: { id: lineOfLocked } }))?.quantity).toBe(4); + }); + + it('CONTROL — a `lockRecord: false` node does not hold the rows', async () => { + const created = await engine.insert('opportunity_line', { product: 'E', quantity: 1, opportunity: openNodeId }, USER); + expect(created?.id).toBeTruthy(); + }); + + it('CONTROL — a lookup child of a locked record is not a detail row and is not held', async () => { + const created = await engine.insert('opportunity_note', { body: 'hi', opportunity: lockedId }, USER); + expect(created?.id).toBeTruthy(); + }); +}); diff --git a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts index 1519530e337..b09bd39144b 100644 --- a/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts +++ b/packages/plugins/plugin-approvals/src/lifecycle-hooks.ts @@ -130,7 +130,7 @@ */ import { withoutOperationPrivateKeys } from '@objectstack/core'; -import { resolveDisplayField } from '@objectstack/spec/data'; +import { resolveDisplayField, type EngineQueryOptions } from '@objectstack/spec/data'; import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system'; import { redactSnapshot, resolveReadableSnapshotFields, type FieldVisibilitySource } from './payload-redaction.js'; import { negotiatedReaderLocale, readerLabelsFor, type ReaderLabelI18n } from './reader-locale-labels.js'; @@ -505,9 +505,25 @@ export async function recordHeldByLockingApproval( objectName: string, recordId: string, ): Promise { - if (isApprovalBookkeepingObject(objectName)) return false; - const gating = await pendingRequestsForRecords(engine, objectName, [recordId]); - return gating.some((pending) => nodeConfigLocksRecord(parseJson(pending?.node_config_json, {}))); + return (await lockingRequestsForRecords(engine, objectName, [recordId])).length > 0; +} + +/** + * The pending requests that hold any of `recordIds` of `objectName` under a + * LOCKING node — the rows {@link recordHeldByLockingApproval} answers from, + * handed back whole so a write-side caller can apply the WRITE's exemptions + * (the opening run, #3456) per request. One lookup and one judgement + * ({@link nodeConfigLocksRecord}) for the record-anchored read and the + * detail-row lock below, so the two cannot disagree about "is this held". + */ +async function lockingRequestsForRecords( + engine: Pick, + objectName: string, + recordIds: ReadonlyArray, +): Promise { + if (isApprovalBookkeepingObject(objectName)) return []; + const gating = await pendingRequestsForRecords(engine, objectName, recordIds); + return gating.filter((pending) => nodeConfigLocksRecord(parseJson(pending?.node_config_json, {}))); } /** @@ -720,6 +736,211 @@ export function bindApprovalLockHook( logger?.info?.('[approvals] record-lock hook bound'); } +/** + * One master-detail edge of a detail object: the `master_detail` field on the + * DETAIL and the master object it names (ADR-0035 — the field is the single + * declaration point of the relationship). + */ +interface MasterEdge { + fk: string; + master: string; +} + +/** + * The master-detail edges of `objectName`, read off its registered schema — an + * in-memory registry read, no I/O, resolved at write time so a schema the boot + * registers after this plugin binds is still seen (AGENTS.md, startup registry + * reads). + * + * EVERY `master_detail` field counts, not only "the" parent: a junction with + * two masters is a detail row of each, and a lock on either master holds it. + * `reference` is the canonical key; the rejected `referenceTo` alias is read + * too, for the reason `@objectstack/objectql`'s `resolveMasterDetailRelation` + * gives — a raw `registerObject` skips Zod, and an unread spelling here would + * be a lock that silently does not apply. + */ +function masterEdgesOf(engine: MinimalEngine, objectName: string): MasterEdge[] { + let schema: any; + try { schema = engine.getSchema?.(objectName); } catch { return []; } + const fields = schema?.fields; + if (!fields || typeof fields !== 'object') return []; + const edges: MasterEdge[] = []; + for (const [name, def] of Object.entries(fields as Record)) { + if (!def || def.type !== 'master_detail') continue; + const master = typeof def.reference === 'string' && def.reference + ? def.reference + : (typeof def.referenceTo === 'string' && def.referenceTo ? def.referenceTo : undefined); + if (!master || isApprovalBookkeepingObject(master)) continue; + edges.push({ fk: def.name ?? name, master }); + } + return edges; +} + +/** A scalar foreign-key value, or `null` for an empty or non-scalar one. */ +function scalarFk(value: unknown): string | null { + if (typeof value === 'string') return value ? value : null; + if (typeof value === 'number' && Number.isFinite(value)) return String(value); + return null; +} + +/** + * A supplied FK value that names SOMETHING but not as a scalar id — an object + * such as `{ id }`, or an array. The guard cannot tell which master it names + * and does not rely on a later step unwrapping it, so the write is judged as + * unresolved (fail closed), never as touching no master (L1-a R2, #35755). + */ +function unscalarFk(value: unknown): boolean { + if (value === undefined || value === null || value === '') return false; + return scalarFk(value) === null; +} + +/** + * Bind the DETAIL-ROW lock (ruling A on the record-page edit card, + * 「一起锁」): while a master record is held by a LOCKING pending approval, its + * master-detail rows refuse insert, update and delete with `RECORD_LOCKED`. + * The approver decides "this record with its lines"; lines that move during the + * decision change what is being decided. + * + * ## Which masters a write touches + * + * - insert → the master each `master_detail` FK of the new row names; + * - update → the master the row stands under now (`previous`) AND, when the + * write sets the FK, the master it moves to — a reparent is checked at both + * ends, so a line can be neither pulled out of nor pushed into a locked + * record; + * - delete → the master the row stands under (`previous`). + * + * The engine binds `previous` on every by-id and predicate update/delete + * before the `before*` hooks run (ADR-0058 Addendum II, per-row dispatch). + * A dispatch that names a row but carries no pre-image reads the FK columns of + * that row as SYSTEM (the #4630 rule: a row the caller cannot read is still a + * row they must not write). A dispatch that names no row at all — a whole + * predicate write handed over in one call — fails CLOSED whenever any record + * of a master object is held by a locking approval: "we could not tell which + * rows" is never read as "no locked row is touched". + * + * ## Exemptions — the record lock's own, carried over + * + * - a SYSTEM session (engine self-writes, seeds, the approvals service); + * - the run that OPENED the request (`provenance.flowRunId`, #3456 / #3712): + * it may keep writing under the record it holds the request against, so a + * flow that adjusts the lines between opening the approval and the + * decision does not die on its own lock. + * + * There is no admin exemption, for the reason the module docstring gives. + * The status-mirror exemption has no analogue: it is about a field of the + * master itself. + * + * ## The refusal + * + * The END-USER sentence of the record lock ({@link recordLockRefusal}), naming + * the MASTER — the record that is locked, and the reason this line cannot + * change. No title: the master row is not read on the deny path (the module + * docstring's rule), so the sentence takes its label-only degradation. + */ +export function bindDetailRowLockHook( + engine: MinimalEngine, + logger?: MinimalLogger, + i18nService?: () => ReaderLabelI18n | undefined, +): void { + const guard = (event: 'insert' | 'update' | 'delete') => async (ctx: any) => { + const object = (ctx?.object ?? ctx?.objectName) as string | undefined; + if (!object || isApprovalBookkeepingObject(object)) return; + const edges = masterEdgesOf(engine, object); + if (edges.length === 0) return; + if ((ctx?.session as any)?.isSystem) return; + + const data = (ctx?.input?.data ?? {}) as Record; + // An update that changes nothing writes nothing (the record lock's own rule). + if (event === 'update' && Object.keys(data).filter((k) => k !== 'id' && k !== 'updated_at').length === 0) return; + + // The masters this write touches, per edge. + const touched: Array<{ master: string; id: string }> = []; + let unresolved = false; + if (event === 'insert') { + for (const e of edges) { + const id = scalarFk(data[e.fk]); + if (id) touched.push({ master: e.master, id }); + else if (unscalarFk(data[e.fk])) unresolved = true; + } + } else { + let previous = ctx?.previous as Record | undefined; + const rowId = asIdList(ctx?.input?.id); + if (!previous && rowId && rowId.length === 1) { + try { + const rows = await engine.find(object, { + where: { id: rowId[0] }, + fields: ['id', ...edges.map((e) => e.fk)], + limit: 1, + // SYSTEM_CTX's arrays are `as const` (readonly); the declared type wants mutable ones. + context: { ...SYSTEM_CTX, positions: [], permissions: [] }, + } satisfies EngineQueryOptions); + previous = Array.isArray(rows) && rows[0] ? rows[0] : undefined; + } catch { + previous = undefined; + } + } + if (!previous) unresolved = true; + for (const e of edges) { + const before = previous ? scalarFk(previous[e.fk]) : null; + if (before) touched.push({ master: e.master, id: before }); + if (event === 'update' && Object.prototype.hasOwnProperty.call(data, e.fk)) { + const after = scalarFk(data[e.fk]); + if (after && after !== before) touched.push({ master: e.master, id: after }); + else if (unscalarFk(data[e.fk])) unresolved = true; + } + } + } + + const writerRun = (ctx?.provenance as any)?.flowRunId; + const exempt = (pending: any) => + !!writerRun && !!pending?.flow_run_id && String(writerRun) === String(pending.flow_run_id); + + // The end-user sentence naming the MASTER object (the record lock's own). + const sentenceFor = (master: string): string => { + let schema: unknown; + try { schema = engine.getSchema?.(master); } catch { /* registry unavailable — label degrades */ } + const declaredLabel = typeof (schema as any)?.label === 'string' && (schema as any).label + ? String((schema as any).label) + : undefined; + const { locale, service, translate } = refusalLocalization(ctx, i18nService); + const masterLabel = readerLabelsFor(service, locale)?.objectLabel(master) ?? declaredLabel; + return recordLockRefusal(masterLabel, undefined, locale, translate); + }; + + // Fail closed on a write whose rows could not be named: refused when any + // record of any master is held by a locking approval. + if (unresolved) { + for (const e of edges) { + const held = (await pendingRequestsForObject(engine, e.master)) ?? []; + const locking = held.filter((p) => nodeConfigLocksRecord(parseJson(p?.node_config_json, {})) && !exempt(p)); + if (locking.length > 0) { + lockedError( + `cannot determine which '${e.master}' record a ${event} on its detail object '${object}' falls under, ` + + `and ${locking.length} record(s) of '${e.master}' carry a locking pending approval, so the write is refused`, + sentenceFor(e.master), + ); + } + } + } + + for (const { master, id } of touched) { + const locking = (await lockingRequestsForRecords(engine, master, [id])).filter((p) => !exempt(p)); + if (locking.length === 0) continue; + logger?.info?.( + `[approvals] ${event} on detail object '${object}' refused RECORD_LOCKED: its master '${master}' ` + + `record '${id}' is held by pending approval request '${String(locking[0]?.id ?? '')}'`, + ); + const sentence = sentenceFor(master); + lockedError(sentence, sentence); + } + }; + engine.registerHook('beforeInsert', guard('insert'), { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 }); + engine.registerHook('beforeUpdate', guard('update'), { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 }); + engine.registerHook('beforeDelete', guard('delete'), { packageId: APPROVALS_HOOK_PACKAGE, priority: 50 }); + logger?.info?.('[approvals] detail-row lock hook bound'); +} + /** * The approvals plugin's own bookkeeping tables. * diff --git a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx index d41b6692f47..b72d8389fb3 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -2841,3 +2841,350 @@ describe('RecordDetailView.objectRouteAbsence-34740', () => { expect(withheld.replaceAll(WITHHELD, 'NAME')).toBe(missing.replaceAll(MISSING, 'NAME')); }); }); + +// ── RecordDetailView.recordEditState-35599 ────────────────────────────────── + +/** + * objectstack#35599 — the record page's EDIT STATE, on a page that draws + * master-detail body tables: Edit turns the fields into inputs and the body + * tables into editable lines, the header shows Cancel / Save, and ONE Save + * writes the record and every table in one `batchTransaction` (one + * `POST /api/v1/batch`). A refused batch keeps every edit and places the + * reason on the line it is about; Cancel puts everything back. + * + * Also pinned: ruling B (「全部保留」, recorded on the card) — inline edit stays + * on a page with body tables and saves the record alone through the save bar; + * the two modes run one at a time (the edit state offers no inline edit, and + * Edit over unsaved inline changes asks to discard them first, CONTROL: no + * changes, no question); ruling A's client half — a record an approval locks + * draws no New on its master-detail body table (CONTROL: the same page + * unlocked does); item 5 — a child without `bulk` keeps its table read-only + * in the edit state, with a notice saying why. + * + * Fixtures: the `bodyTablePredicate-27478` harness at 1440 px. + */ +describe('RecordDetailView.recordEditState-35599', () => { + restoreAfterBlock(); + + const PARENT = 'showcase_quote'; + const RECORD_ID = 'q-1'; + const fk = { type: 'master_detail', reference: PARENT, label: 'Quote' }; + + const objectsWith = ({ lineEnable }: { lineEnable?: Record } = {}) => [ + { + name: PARENT, + label: 'Quote', + pluralLabel: 'Quotes', + fields: { id: { type: 'text', label: 'Id' }, name: { type: 'text', label: 'Name' }, summary: { type: 'text', label: 'Summary' } }, + }, + { + name: 'showcase_line', + label: 'Line', + pluralLabel: 'Lines', + ...(lineEnable ? { enable: lineEnable } : {}), + fields: { id: { type: 'text', label: 'Id' }, product: { type: 'text', label: 'Product' }, quantity: { type: 'number', label: 'Quantity' }, quote: fk }, + }, + { + name: 'showcase_task', + label: 'Task', + pluralLabel: 'Tasks', + fields: { id: { type: 'text', label: 'Id' }, subject: { type: 'text', label: 'Subject' }, quote: fk }, + }, + { + name: 'showcase_note', + label: 'Note', + pluralLabel: 'Notes', + fields: { id: { type: 'text', label: 'Id' }, body: { type: 'text', label: 'Body' }, quote: { type: 'lookup', reference: PARENT, label: 'Quote' } }, + }, + ]; + + const ROWS: Record>> = { + showcase_line: [ + { id: 'l1', product: 'Anvil', quantity: 1, quote: RECORD_ID }, + { id: 'l2', product: 'Bolt', quantity: 2, quote: RECORD_ID }, + ], + showcase_task: [{ id: 't1', subject: 'Call', quote: RECORD_ID }], + }; + + function renderPage(objects: ReturnType, opts: { emptyTables?: boolean } = {}) { + const metadata = { + objects, pages: [], loading: false, error: null, + refresh: async () => {}, invalidate: () => {}, + ensureType: async () => [], getItem: async () => null, getItemsByType: () => [], + } as never; + const dataSource = { + find: vi.fn(async (o: string) => { + const data = opts.emptyTables ? [] : (ROWS[o] ?? []).map((r) => ({ ...r })); + return { data, total: data.length }; + }), + create: vi.fn(async (_o: string, row: unknown) => row), + findOne: vi.fn(async (_o: string, recordId: string) => ({ id: recordId, name: `Quote ${recordId}`, summary: 'First' })), + update: vi.fn(async () => ({})), + delete: vi.fn(async () => ({})), + getObjectSchema: vi.fn(async (o: string) => objects.find((d) => d.name === o) ?? null), + batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })), + }; + const onEdit = vi.fn(); + const view = render( + + + + + {/* The app route: the related-record bridge offers New only under an app. */} + } + /> + + + + , + ); + return { ...view, dataSource, onEdit }; + } + + const jsonResponse = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + + /** `locked`: the approvals read answers a pending `lock_record` request (the `approvalLock-25934` shape). */ + function stubApi({ locked = false }: { locked?: boolean } = {}) { + const request = { + id: 'req-1', process_name: 'flow:quote_review', object_name: PARENT, record_id: RECORD_ID, + status: 'pending', submitter_id: 'u_submitter', current_step: 'manager_review', + pending_approvers: ['u_manager'], lock_record: true, + }; + vi.stubGlobal('fetch', vi.fn(async (url: string) => { + const u = String(url); + if (locked && u.includes('/approvals/requests?object=')) return jsonResponse(200, { data: [request] }); + if (locked && u.endsWith('/approvals/requests/req-1')) return jsonResponse(200, request); + return jsonResponse(200, { data: [] }); + })); + } + + beforeEach(() => { + cleanup(); + window.localStorage.clear(); + RelatedCountStore._reset(); + stubApi(); + const measure = HTMLElement.prototype.getBoundingClientRect; + vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) { + if (!this.hasAttribute('data-record-page-root')) return measure.call(this); + return { x: 0, y: 0, top: 0, left: 0, right: 1440, bottom: 800, width: 1440, height: 800, toJSON: () => ({}) } as DOMRect; + }); + }); + + afterEach(() => { + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + }); + + const headerButton = (label: string) => + (Array.from(document.querySelectorAll('button')).find((b) => (b.textContent ?? '').trim() === label) as HTMLButtonElement | undefined) ?? null; + const pencils = (container: HTMLElement) => container.querySelectorAll('button[aria-label="Double-click to edit"]').length; + const editor = (container: HTMLElement, id: string) => container.querySelector(`[data-body-table-editor="${id}"]`) as HTMLElement | null; + const cells = (scope: HTMLElement, label: string) => Array.from(scope.querySelectorAll(`input[aria-label="${label}"]`)) as HTMLInputElement[]; + const summaryInput = (container: HTMLElement) => + (Array.from(container.querySelectorAll('[data-record-column="details"] input')) as HTMLInputElement[]).find((i) => i.value === 'First') ?? null; + + async function enterEditState(view: ReturnType) { + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + fireEvent.click(headerButton('Edit')!); + await waitFor(() => expect(editor(view.container, 'showcase_line.quote')).not.toBeNull(), { timeout: 5000 }); + await waitFor(() => expect(cells(editor(view.container, 'showcase_line.quote')!, 'Product').length).toBeGreaterThanOrEqual(2), { timeout: 5000 }); + await waitFor(() => expect(cells(editor(view.container, 'showcase_task.quote')!, 'Subject').length).toBeGreaterThanOrEqual(1), { timeout: 5000 }); + } + + /** Edit the record and both tables: one changed line, one new line, one removed line, one changed task. */ + function editEverything(container: HTMLElement) { + fireEvent.change(summaryInput(container)!, { target: { value: 'Second' } }); + const lines = editor(container, 'showcase_line.quote')!; + fireEvent.change(cells(lines, 'Quantity')[0], { target: { value: '5' } }); + fireEvent.click(lines.querySelectorAll('button[aria-label="Remove row"]')[1] as HTMLElement); + const products = cells(lines, 'Product'); + fireEvent.change(products[products.length - 1], { target: { value: 'Crate' } }); + const tasks = editor(container, 'showcase_task.quote')!; + fireEvent.change(cells(tasks, 'Subject')[0], { target: { value: 'Visit' } }); + } + + /** The pencil of the Summary field (the inline-edit entry), on the details column. */ + const summaryPencil = (container: HTMLElement) => + (Array.from(container.querySelectorAll('[data-record-column="details"] button[aria-label="Double-click to edit"]')) as HTMLElement[]) + .find((b) => (b.closest('.group')?.textContent ?? '').includes('Summary')) ?? null; + const saveBar = () => document.querySelector('[role="region"][aria-label="Edit fields"]') as HTMLElement | null; + const detailInputValues = (container: HTMLElement) => + (Array.from(container.querySelectorAll('[data-record-column="details"] input')) as HTMLInputElement[]).map((i) => i.value); + + it('ruling B (「全部保留」): a page drawing body tables keeps inline edit, which saves the record alone through the save bar; the edit state offers none', async () => { + const view = renderPage(objectsWith()); + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + await waitFor(() => expect(summaryPencil(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.click(summaryPencil(view.container)!); + await waitFor(() => expect(summaryInput(view.container)).not.toBeNull(), { timeout: 5000 }); + // Inline edit is the field alone: the body tables stay tables, no editor. + expect(editor(view.container, 'showcase_line.quote')).toBeNull(); + fireEvent.change(summaryInput(view.container)!, { target: { value: 'Inline' } }); + const barSave = Array.from(saveBar()!.querySelectorAll('button')).find((b) => (b.textContent ?? '').trim() === 'Save')!; + await act(async () => { fireEvent.click(barSave); }); + await waitFor(() => expect(view.dataSource.update).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(view.dataSource.update.mock.calls[0].slice(0, 3)).toEqual([PARENT, RECORD_ID, { summary: 'Inline' }]); + expect(view.dataSource.batchTransaction).not.toHaveBeenCalled(); + // The edit state: Edit opens it (not the record form), and there inline edit is not offered. + await waitFor(() => expect(saveBar()).toBeNull(), { timeout: 5000 }); + fireEvent.click(headerButton('Edit')!); + await waitFor(() => expect(editor(view.container, 'showcase_line.quote')).not.toBeNull(), { timeout: 5000 }); + expect(view.onEdit).not.toHaveBeenCalled(); + expect(pencils(view.container)).toBe(0); + expect(saveBar()).toBeNull(); + expect(headerButton('Save')).not.toBeNull(); + expect(headerButton('Cancel')).not.toBeNull(); + expect(headerButton('Edit')).toBeNull(); + }); + + it('one mode at a time: Edit with unsaved inline changes asks first — Keep editing stays inline, Discard enters the edit state with the stored values', async () => { + const view = renderPage(objectsWith()); + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + await waitFor(() => expect(summaryPencil(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.click(summaryPencil(view.container)!); + await waitFor(() => expect(summaryInput(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.change(summaryInput(view.container)!, { target: { value: 'Inline' } }); + expect(headerButton('Edit')?.disabled).toBe(false); + // The question is the page's own dialog, never the browser's. + const nativeConfirm = vi.fn(() => true); + vi.stubGlobal('confirm', nativeConfirm); + fireEvent.click(headerButton('Edit')!); + const dialog = await waitFor(() => { + const el = document.querySelector('[data-record-edit-discard-inline]') as HTMLElement | null; + expect(el).not.toBeNull(); + return el!; + }); + expect(dialog.textContent).toContain('Discard changes?'); + expect(nativeConfirm).not.toHaveBeenCalled(); + // Keep editing: the dialog closes, the inline draft stays, no edit state. + fireEvent.click(Array.from(dialog.querySelectorAll('button')).find((b) => (b.textContent ?? '').trim() === 'Keep editing')!); + await waitFor(() => expect(document.querySelector('[data-record-edit-discard-inline]')).toBeNull(), { timeout: 5000 }); + expect(editor(view.container, 'showcase_line.quote')).toBeNull(); + expect(detailInputValues(view.container)).toContain('Inline'); + // Discard: the draft goes, the edit state opens over the stored record. + fireEvent.click(headerButton('Edit')!); + const again = await waitFor(() => { + const el = document.querySelector('[data-record-edit-discard-inline]') as HTMLElement | null; + expect(el).not.toBeNull(); + return el!; + }); + fireEvent.click(Array.from(again.querySelectorAll('button')).find((b) => (b.textContent ?? '').trim() === 'Discard')!); + await waitFor(() => expect(editor(view.container, 'showcase_line.quote')).not.toBeNull(), { timeout: 5000 }); + await waitFor(() => expect(summaryInput(view.container)).not.toBeNull(), { timeout: 5000 }); + expect(detailInputValues(view.container)).not.toContain('Inline'); + expect(headerButton('Save')).not.toBeNull(); + expect(nativeConfirm).not.toHaveBeenCalled(); + expect(view.dataSource.update).not.toHaveBeenCalled(); + expect(view.dataSource.batchTransaction).not.toHaveBeenCalled(); + }); + + it('CONTROL — an inline session with no changes is simply ended: Edit enters the edit state without asking', async () => { + const view = renderPage(objectsWith()); + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + await waitFor(() => expect(summaryPencil(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.click(summaryPencil(view.container)!); + await waitFor(() => expect(summaryInput(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.click(headerButton('Edit')!); + await waitFor(() => expect(editor(view.container, 'showcase_line.quote')).not.toBeNull(), { timeout: 5000 }); + expect(document.querySelector('[data-record-edit-discard-inline]')).toBeNull(); + }); + + it('one Save sends ONE batch carrying the record and both body tables', async () => { + const view = renderPage(objectsWith()); + await enterEditState(view); + editEverything(view.container); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(view.dataSource.update).not.toHaveBeenCalled(); + expect(view.dataSource.create).not.toHaveBeenCalled(); + expect(view.dataSource.delete).not.toHaveBeenCalled(); + const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array>; + expect(ops[0]).toEqual({ object: PARENT, action: 'update', id: RECORD_ID, data: { summary: 'Second' } }); + const rest = ops.slice(1).map((o) => [o.object, o.action, o.id ?? null]); + expect(rest).toEqual(expect.arrayContaining([ + ['showcase_line', 'create', null], + ['showcase_line', 'update', 'l1'], + ['showcase_line', 'delete', 'l2'], + ['showcase_task', 'update', 't1'], + ])); + expect(rest).toHaveLength(4); + expect(ops.find((o) => o.action === 'create')?.data).toMatchObject({ product: 'Crate', quote: RECORD_ID }); + expect(ops.find((o) => o.id === 'l1')?.data).toEqual({ quantity: 5 }); + expect(ops.find((o) => o.id === 't1')?.data).toEqual({ subject: 'Visit' }); + // Saved: the page leaves its edit state. + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(editor(view.container, 'showcase_line.quote')).toBeNull(); + }); + + it('a refused batch keeps every edit and places the reason on its line; Cancel then restores', async () => { + const view = renderPage(objectsWith()); + await enterEditState(view); + view.dataSource.batchTransaction.mockRejectedValueOnce( + Object.assign(new Error('Validation failed'), { + details: { error: 'Validation failed', fields: [{ field: 'product', message: 'Unknown product' }] }, + }), + ); + editEverything(view.container); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.container.querySelector('[data-body-table-row-error]')).not.toBeNull(), { timeout: 5000 }); + expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1); + const lines = editor(view.container, 'showcase_line.quote')!; + const rowError = lines.querySelector('[data-body-table-row-error]')!; + // The new line is the second line drawn (the removed one is gone). + expect(rowError.getAttribute('data-body-table-row-error')).toBe('1'); + expect(rowError.textContent).toContain('Unknown product'); + expect(view.container.querySelector('[data-record-edit-error]')?.textContent).toBe('Validation failed'); + // Every edit is still there, still in the edit state. + expect(summaryInput(view.container)).toBeNull(); + expect((Array.from(view.container.querySelectorAll('[data-record-column="details"] input')) as HTMLInputElement[]).some((i) => i.value === 'Second')).toBe(true); + expect(cells(lines, 'Quantity')[0].value).toBe('5'); + expect(cells(lines, 'Product').map((i) => i.value)).toContain('Crate'); + expect(headerButton('Save')).not.toBeNull(); + + fireEvent.click(headerButton('Cancel')!); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(editor(view.container, 'showcase_line.quote')).toBeNull(); + expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1); + // Back in: the lines and the record read as stored, not as edited. + fireEvent.click(headerButton('Edit')!); + await waitFor(() => expect(cells(editor(view.container, 'showcase_line.quote') ?? document.body, 'Product').length).toBeGreaterThanOrEqual(2), { timeout: 5000 }); + const again = editor(view.container, 'showcase_line.quote')!; + expect(cells(again, 'Quantity')[0].value).toBe('1'); + expect(cells(again, 'Product').map((i) => i.value)).toEqual(expect.arrayContaining(['Anvil', 'Bolt'])); + expect(cells(again, 'Product').map((i) => i.value)).not.toContain('Crate'); + expect(summaryInput(view.container)).not.toBeNull(); + }); + + it('item 5: a child without bulk keeps its table read-only in the edit state, with the notice', async () => { + const view = renderPage(objectsWith({ lineEnable: { apiMethods: ['get', 'list', 'create', 'update', 'delete'] } })); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + fireEvent.click(headerButton('Edit')!); + await waitFor(() => expect(view.container.querySelector('[data-record-edit-tables-read-only]')).not.toBeNull(), { timeout: 5000 }); + expect(view.container.querySelector('[data-body-table-editor]')).toBeNull(); + // The record's own fields still edit and save, through the plain update. + await waitFor(() => expect(summaryInput(view.container)).not.toBeNull(), { timeout: 5000 }); + fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } }); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.update).toHaveBeenCalledTimes(1), { timeout: 5000 }); + expect(view.dataSource.update.mock.calls[0]).toEqual([PARENT, RECORD_ID, { summary: 'Second' }]); + expect(view.dataSource.batchTransaction).not.toHaveBeenCalled(); + }); + + it('ruling A client half: a locked record\'s body table draws no New; the same page unlocked does (CONTROL)', async () => { + const control = renderPage(objectsWith(), { emptyTables: true }); + await waitFor(() => expect(control.container.querySelectorAll('[data-record-column="details"] [data-body-table-empty-add]').length).toBe(2), { timeout: 5000 }); + cleanup(); + stubApi({ locked: true }); + const view = renderPage(objectsWith(), { emptyTables: true }); + await waitFor(() => expect(view.container.querySelectorAll('[data-record-column="details"] [data-body-table-empty-row]').length).toBe(2), { timeout: 5000 }); + // The lock has been read (no Edit is drawn on a locked record) before the absence is read. + await waitFor(() => expect(view.container.querySelector('[data-record-column="details"]')?.textContent).toContain('Tasks'), { timeout: 5000 }); + await waitFor(() => expect(headerButton('Edit')).toBeNull(), { timeout: 5000 }); + expect(view.container.querySelectorAll('[data-record-column="details"] [data-body-table-empty-add]').length).toBe(0); + }); +}); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index 63e9a138718..8c5685040b5 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -38,6 +38,7 @@ import { ActionResultDialog, type ResultDialogState } from './ActionResultDialog import { FlowRunner, type ScreenFlowState, type ScreenSpec } from './FlowRunner.js'; import { FlowRefusalNotice, type FlowRefusalState } from './FlowRefusalNotice.js'; import { RelatedRecordActionsBridge } from './RelatedRecordActionsBridge.js'; +import { RecordEditStateController, bodyTablesSaveTogether, isMasterDetailChild, withDetailWritesWithheld, type RecordEditStateControl, type RecordEditStateEntry } from './recordEditState.js'; import { isRecordPagePushed, useRecordPageScrollMemory } from './recordPagePush.js'; import { phoneRecordHeader } from './recordPhoneHeader.js'; import { usePhoneViewport } from '../hooks/usePhoneViewport.js'; @@ -2354,6 +2355,23 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri openApproval: openApprovalOf(approvals), recordStatus: (pageRecord as any)?.approval_status, }); + // objectstack#35599 — the record page's EDIT STATE (`recordEditState.tsx`): + // on a page that draws master-detail body tables, Edit turns the overview + // into a form — the fields become inputs, the body tables editable lines — + // and one Save writes all of it in one batch. `recordEditEligible` is + // set where the page's body tables are known (below the early returns, + // where no hook may run, so as a state update during render) and read by + // the header's Edit. + const [recordEditState, setRecordEditState] = useState(false); + const [recordEditSaving, setRecordEditSaving] = useState(false); + const recordEditControlRef = useRef(null); + const recordEditEnterRef = useRef(null); + const [recordEditEligible, setRecordEditEligible] = useState(false); + const exitRecordEditState = useCallback(() => setRecordEditState(false), []); + const enterRecordEditState = useCallback(() => setRecordEditState(true), []); + useEffect(() => { + setRecordEditState(false); + }, [objectName, pureRecordId]); // How far the pending node's tally has got (objectstack#4478). Multi-approver // nodes — `quorum`, `unanimous`, `per_group` — do not finalize on one // decision, so an approver standing on the record needs the count to know @@ -4804,7 +4822,34 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // objectstack#35593 — a record an approval locks draws no Edit at all: the // header's approval tag says why it cannot be changed. Every other reason // for "off" keeps Edit drawn and greyed, as below. - if (affordances.edit && !approvalLocked) { + // objectstack#35599 — in the edit state the Edit button's place holds the + // state's Cancel and Save, through the same system-action props. + if (affordances.edit && !approvalLocked && recordEditState) { + items.push({ + name: 'sys_record_edit_cancel', + label: t('detail.cancel', { defaultValue: 'Cancel' }), + icon: 'x', + type: 'script', + locations: ['record_header'], + variant: 'outline', + order: 99, + disabled: recordEditSaving, + onClick: () => recordEditControlRef.current?.cancel(), + } as any); + items.push({ + name: 'sys_record_edit_save', + label: recordEditSaving + ? t('detail.saving', { defaultValue: 'Saving…' }) + : t('detail.save', { defaultValue: 'Save' }), + icon: 'check', + type: 'script', + locations: ['record_header'], + order: 100, + disabled: recordEditSaving, + onClick: () => { void recordEditControlRef.current?.save(); }, + } as any); + } + if (affordances.edit && !approvalLocked && !recordEditState) { const editOff = approvalLocked || editDisabledByPredicate || editLockedByState; // objectstack#35135 — the reason a predicate-disabled Edit gives. The // approval band and the state-lock badge explain their own locks, so @@ -4837,7 +4882,14 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // the page:header renderer greys this CTA out so the classic form // can't be stacked on top of the draft (two competing edit sessions // with no reconciliation). - disableDuringInlineEdit: true, + // + // objectstack#35599, ruling B (「全部保留」) — on a page drawing body + // tables both modes stay: inline edit saves the record alone through + // the save bar, Edit → Save the record and its lines in one batch. So + // Edit stays pressable during an inline session there, and entering + // the edit state with unsaved inline changes asks first + // (`RecordEditStateController`'s discard confirm). + disableDuringInlineEdit: !recordEditEligible, // framework#3794 — an approval-LOCKED record refuses every write (the // server answers RECORD_LOCKED), so opening the form only to be // rejected on Save after filling a screen is wasted work. Disabled @@ -4872,7 +4924,11 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri // The desktop row keeps it greyed in place for every reason, and an // Edit that is on is untouched. ...(phonePage && editOff ? { component: 'action:menu' } : {}), - onClick: () => onEdit({ id: pureRecordId }, objectName), + // objectstack#35599 — a page drawing body tables enters its edit state; + // every other page opens the record form, as before. + onClick: () => (recordEditEligible + ? (recordEditEnterRef.current ? recordEditEnterRef.current.requestEnter() : setRecordEditState(true)) + : onEdit({ id: pureRecordId }, objectName)), } as any); } // The record's favorites entry (objectui#12427), in the `⋯` overflow ahead @@ -5148,6 +5204,18 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri ? authoredBodyTableIds(renderedPage, childRelations) : bodyTableIdsOf(renderedPage); + // objectstack#35599 — the edit state's two inputs read off the body tables: + // Edit enters it on a page that draws one (and is otherwise the record form), + // and each table is drawn as an editor only when one batch can carry it + // (item 5, `bodyTablesSaveTogether`). The page itself is not rewritten: the + // edit state's controller draws the editors in the body tables' places + // (`RecordBodyTableEditorSlotContext`). + // A state update during render (not an effect: no hook may run here), so + // the header's Edit never reads a stale verdict; React re-renders before + // committing, and the update is a no-op once the value agrees. + if (recordEditEligible !== bodyTableIds.size > 0) setRecordEditEligible(bodyTableIds.size > 0); + const bodyTablesEditable = bodyTablesSaveTogether(objectDef, objects, bodyTableIds); + // objectstack#27052 / objectstack#27524, Targets 4 and 7 — the right-column // switch: ONE ⊟ icon (「右栏」), drawn in the record's top bar after its step // group (the page's own bar below; a pane's bar through @@ -5561,6 +5629,29 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri defaultValue: 'This record has a pending approval request; editing is locked', })} > + 0 && !bodyTablesEditable} + readOnlyNotice={t('detail.bodyTablesReadOnlyBulk')} + unsavedMessage={t('form.unsavedChanges')} + > withDetailWritesWithheld(bridge, (child, fk) => isMasterDetailChild(objects, objectName, child, fk)) + : undefined} > {/* objectstack#26678 / objectstack#27524 — the synthesized page's blocks laid out by its width; `?tab=` addresses a @@ -5835,7 +5932,9 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri {/* Record-level inline-edit Save/Cancel bar (objectui#2407 P2) — commits the whole draft (highlights + body) in ONE atomic OCC update; renders (sticky) only while editing. */} - + />} + diff --git a/ui/packages/app-shell/src/views/recordEditState.helpers-35599.test.ts b/ui/packages/app-shell/src/views/recordEditState.helpers-35599.test.ts new file mode 100644 index 00000000000..e229f883c3a --- /dev/null +++ b/ui/packages/app-shell/src/views/recordEditState.helpers-35599.test.ts @@ -0,0 +1,66 @@ +/** + * 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 record page edit state's pure pieces (objectstack#35599): the item-5 + * decision (can one batch carry the tables), and ruling A's client half (a + * locked record's detail children draw no write actions). + */ + +import { describe, it, expect } from 'vitest'; +import { + bodyTablesSaveTogether, + isMasterDetailChild, + withDetailWritesWithheld, +} from './recordEditState'; + +describe('bodyTablesSaveTogether — item 5: the batch is a bulk surface', () => { + const ids = new Set(['order_line.order']); + const all = { apiMethods: ['get', 'list', 'create', 'update', 'delete', 'bulk'] }; + const noBulk = { apiMethods: ['get', 'list', 'create', 'update', 'delete'] }; + + it('objects that declare no restriction save together', () => { + expect(bodyTablesSaveTogether({}, [{ name: 'order_line' }], ids)).toBe(true); + expect(bodyTablesSaveTogether({ enable: all }, [{ name: 'order_line', enable: all }], ids)).toBe(true); + }); + + it('a child without bulk, or the record without bulk, keeps the tables read-only', () => { + expect(bodyTablesSaveTogether({ enable: all }, [{ name: 'order_line', enable: noBulk }], ids)).toBe(false); + expect(bodyTablesSaveTogether({ enable: noBulk }, [{ name: 'order_line', enable: all }], ids)).toBe(false); + expect( + bodyTablesSaveTogether({}, [{ name: 'order_line', enable: { apiMethods: ['get', 'list', 'create', 'update', 'bulk'] } }], ids), + ).toBe(false); + }); + + it('no body tables → nothing to save together', () => { + expect(bodyTablesSaveTogether({}, [], new Set())).toBe(false); + }); +}); + +describe('ruling A client half — a locked record\'s detail children draw no write actions', () => { + const objects = [ + { name: 'order_line', fields: { order: { type: 'master_detail', reference: 'order' } } }, + { name: 'order_note', fields: { order: { type: 'lookup', reference: 'order' } } }, + ]; + + it('isMasterDetailChild reads the child\'s own field', () => { + expect(isMasterDetailChild(objects, 'order', 'order_line', 'order')).toBe(true); + expect(isMasterDetailChild(objects, 'order', 'order_note', 'order')).toBe(false); + expect(isMasterDetailChild(objects, 'account', 'order_line', 'order')).toBe(false); + }); + + it('strips New / Edit / Delete for a detail child only; a lookup child keeps them (CONTROL)', () => { + const handlers = { onCreate: () => {}, onEdit: () => {}, onDelete: () => {}, onView: () => {} }; + const bridge = { resolve: () => handlers } as any; + const served = withDetailWritesWithheld(bridge, (child, fk) => isMasterDetailChild(objects, 'order', child, fk)); + const detail = served.resolve({ objectName: 'order_line', relationshipField: 'order' } as any); + expect(Object.keys(detail).sort()).toEqual(['onView']); + const lookup = served.resolve({ objectName: 'order_note', relationshipField: 'order' } as any); + expect(Object.keys(lookup).sort()).toEqual(['onCreate', 'onDelete', 'onEdit', 'onView']); + }); +}); diff --git a/ui/packages/app-shell/src/views/recordEditState.tsx b/ui/packages/app-shell/src/views/recordEditState.tsx new file mode 100644 index 00000000000..2071475c6f3 --- /dev/null +++ b/ui/packages/app-shell/src/views/recordEditState.tsx @@ -0,0 +1,397 @@ +/** + * 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 record page's EDIT STATE — "Edit" turns the overview into a form: the + * record's fields become inputs (the record-level inline-edit session), the + * master-detail body tables become editable lines, and ONE Save writes the + * record's changes and every table's creates / updates / deletes in one + * `POST /api/v1/batch`, one transaction: all of it lands, or none of it does. + * + * Pieces, each consumed by `RecordDetailView`: + * + * - {@link RecordEditStateController} — mounted under the page's + * `InlineEditProvider`; enters the session, owns Save / Cancel (the header's + * two buttons call it), places a refused save's reasons on the field or line + * they are about, and registers the unsaved edits with the shell's + * leave guard. While the state is open it draws each body table as + * `@object-ui/plugin-form`'s `RecordBodyTableEditor`, through + * `@object-ui/plugin-detail`'s `RecordBodyTableEditorSlotContext`: the page + * keeps its `record:related_list` nodes, and each one whose relationship + * is a body table renders the editor in its place. The editor is a host + * element, never a registered node type a page could carry. + * - {@link bodyTablesSaveTogether} — whether the batch path can carry the + * tables at all (the card's item 5, see there). + * - {@link withDetailWritesWithheld} — ruling A's client half: a locked + * record's master-detail children draw no New / Edit / Delete. + */ + +import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { runBatchTransaction } from '@object-ui/core'; +import { + RecordEditSessionContext, + attributeRecordEditRefusal, + buildRecordEditBatch, + RecordBodyTableEditor, + type BodyTableEditHandle, + type RecordEditSession, +} from '@object-ui/plugin-form'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from '@object-ui/components'; +import { useInlineEdit, type RelatedRecordActionsValue } from '@object-ui/react'; +import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '@object-ui/plugin-detail'; +import { canServeApiOperation } from '@objectstack/spec/data'; +import { useRegisterUnsavedEdits } from '../chrome/unsavedEdits.js'; + +/** + * Can ONE batch carry this record's body tables (the card's item 5)? + * + * `POST /api/v1/batch` is a bulk surface: every object it writes must grant the + * `bulk` primitive AND the write it performs (`bulk ∧ child`, the REST batch + * route's gate, read here through the same spec derivation + * `canServeApiOperation`). The record needs `bulk ∧ update`; each body table's + * child `bulk ∧ create / update / delete`. When any is refused the page does + * not offer an edit it cannot save: the tables stay read-only in the edit state + * with a notice saying why, and the record's own fields save through the plain + * update they always used. Decided from the objects' `enable` blocks the page + * already holds — no request. + */ +export function bodyTablesSaveTogether( + objectDef: { enable?: unknown } | null | undefined, + objects: ReadonlyArray | null | undefined, + bodyTableIds: ReadonlySet, +): boolean { + if (bodyTableIds.size === 0) return false; + if (!canServeApiOperation(objectDef?.enable as any, 'bulk', { bulkChild: 'update' })) return false; + for (const id of bodyTableIds) { + const child = id.slice(0, id.indexOf('.')); + const def = (objects ?? []).find((o) => o?.name === child); + for (const op of ['create', 'update', 'delete'] as const) { + if (!canServeApiOperation(def?.enable, 'bulk', { bulkChild: op })) return false; + } + } + return true; +} + +/** + * Is `childObject.fk` a master-detail child of `parentObject` — a detail row + * ruling A's lock holds? Read off the child's own field definition. + */ +export function isMasterDetailChild( + objects: ReadonlyArray | null | undefined, + parentObject: string | undefined, + childObject: string, + fk: string | undefined, +): boolean { + if (!parentObject || !fk) return false; + const def = (objects ?? []).find((o) => o?.name === childObject); + const field = def?.fields?.[fk]; + return field?.type === 'master_detail' && (field.reference === parentObject || field.referenceTo === parentObject); +} + +/** + * Ruling A, client half (「一起锁」): what the related-record bridge serves while + * the record is held by a locking approval — its master-detail children's + * lists and body tables draw no New, Edit or Delete, because the server refuses + * each of them `RECORD_LOCKED`. Everything else the bridge serves, and every + * other child, is untouched. Handed to `RelatedRecordActionsBridge`'s existing + * `serve` prop. + */ +export function withDetailWritesWithheld( + bridge: RelatedRecordActionsValue, + isDetail: (childObject: string, fk: string | undefined) => boolean, +): RelatedRecordActionsValue { + return { + ...bridge, + resolve: (input) => { + const handlers = bridge.resolve(input); + if (!isDetail(input.objectName, input.relationshipField)) return handlers; + const { onCreate: _create, onEdit: _edit, onDelete: _delete, ...rest } = handlers; + return rest; + }, + }; +} + +/** What the header's Cancel / Save call. */ +export interface RecordEditStateControl { + save: () => Promise; + cancel: () => void; +} + +/** + * What the header's Edit calls to ENTER the edit state (ruling B, 「全部保留」: + * inline edit and the edit state are two modes, one at a time). With no inline + * session it enters; with an inline session holding no changes it ends that + * session and enters; with unsaved inline changes it asks first — discard + * them and enter, or keep editing inline and save them through the save bar. + */ +export interface RecordEditStateEntry { + requestEnter: () => void; +} + +export interface RecordEditStateControllerProps { + /** The page is in its edit state. */ + active: boolean; + /** Leave the edit state (after a save, or a cancel). */ + onExit: () => void; + /** Enter the edit state (once any inline session is out of the way). */ + onEnter: () => void; + /** Filled each render with the controller's Save / Cancel. */ + controlRef: React.MutableRefObject; + /** Filled each render with the controller's enter request. */ + enterRef: React.MutableRefObject; + /** The discard confirm's title, message and two buttons. */ + discardInlineTitle: string; + discardInlineMessage: string; + discardLabel: string; + keepEditingLabel: string; + /** A save started or settled — the header greys its two buttons meanwhile. */ + onSavingChange: (saving: boolean) => void; + dataSource: any; + objectName: string | undefined; + recordId: string | number | null | undefined; + /** Re-read the record after a save. */ + refresh: () => void | Promise; + /** The page's body tables, by relationship id (`CHILD_OBJECT.FK_FIELD`). */ + bodyTableIds: ReadonlySet; + /** The body tables are edited (one batch can carry them) — see {@link bodyTablesSaveTogether}. */ + bodyTablesEditable: boolean; + /** The page draws body tables that stay read-only (the batch cannot carry them). */ + bodyTablesReadOnly: boolean; + /** The notice shown when they do. */ + readOnlyNotice: string; + /** The question asked before unsaved edits are dropped. */ + unsavedMessage: string; + children: React.ReactNode; +} + +export const RecordEditStateController: React.FC = ({ + active, + onExit, + onEnter, + controlRef, + enterRef, + discardInlineTitle, + discardInlineMessage, + discardLabel, + keepEditingLabel, + onSavingChange, + dataSource, + objectName, + recordId, + refresh, + bodyTableIds, + bodyTablesEditable, + bodyTablesReadOnly, + readOnlyNotice, + unsavedMessage, + children, +}) => { + const inline = useInlineEdit(); + const tablesRef = useRef(new Map()); + const [dirtyTables, setDirtyTables] = useState>(() => new Set()); + const [saving, setSaving] = useState(false); + // Stable by construction (a `useState` initializer), never a memo's identity + // (ui AGENTS.md #10): the editors key their registration effect on these. + const [api] = useState(() => ({ + register: (handle: BodyTableEditHandle) => { + tablesRef.current.set(handle.id, handle); + return () => { + if (tablesRef.current.get(handle.id) === handle) tablesRef.current.delete(handle.id); + }; + }, + reportDirty: (id: string, dirty: boolean) => { + setDirtyTables((prev) => { + if (prev.has(id) === dirty) return prev; + const next = new Set(prev); + if (dirty) next.add(id); else next.delete(id); + return next; + }); + }, + })); + const session: RecordEditSession = { register: api.register, reportDirty: api.reportDirty, saving }; + + // The body tables drawn as editors while the state is open (and one batch + // can carry them). Keyed on the ids' content, not the set's identity: the + // page computes the set afresh each render, and every related list on the + // page reads this value. + const editedTablesKey = active && bodyTablesEditable ? [...bodyTableIds].sort().join('\n') : ''; + const editorSlot = useMemo( + () => (editedTablesKey + ? { + ids: new Set(editedTablesKey.split('\n')), + render: ({ objectName: child, relationshipField, title }) => ( + + ), + } + : null), + [editedTablesKey], + ); + + // Enter the record-level session once the edit state opens (the provider's + // `canEdit` admits it on the render that set `active`), and leave the edit + // state if the session ends some other way. + const editing = !!inline?.editing; + const canEdit = !!inline?.canEdit; + const enter = inline?.enter; + const enteredRef = useRef(false); + useEffect(() => { + if (!active) { + enteredRef.current = false; + return; + } + if (!enteredRef.current && canEdit && !editing) { + enteredRef.current = true; + enter?.(); + } + }, [active, canEdit, editing, enter]); + const wasEditingRef = useRef(false); + useEffect(() => { + if (active && wasEditingRef.current && !editing && !saving) onExit(); + wasEditingRef.current = editing; + }, [active, editing, saving, onExit]); + useEffect(() => { + if (!active) setDirtyTables((prev) => (prev.size === 0 ? prev : new Set())); + }, [active]); + + useEffect(() => { onSavingChange(saving); }, [saving, onSavingChange]); + + const draftKeys = inline ? Object.keys(inline.draft) : []; + const dirty = active && (draftKeys.length > 0 || dirtyTables.size > 0); + useRegisterUnsavedEdits(dirty, unsavedMessage); + + const finish = useCallback(async () => { + inline?.reset(); + setDirtyTables(new Set()); + onExit(); + await refresh(); + }, [inline, onExit, refresh]); + + const save = useCallback(async () => { + if (!inline || saving || !dataSource || !objectName || recordId == null) return; + const draft = inline.draft; + const handles = [...tablesRef.current.values()]; + inline.setError(null); + inline.setFieldErrors(null); + for (const h of handles) h.setErrors(null); + const tables = bodyTablesEditable + ? handles.flatMap((h) => { + const snap = h.snapshot(); + return snap ? [{ id: h.id, ...snap }] : []; + }) + : []; + const built = buildRecordEditBatch(objectName, String(recordId), draft, tables); + // An untouched record writes no update of its own: op 0 goes when the draft is empty. + const hasDraft = Object.keys(draft).length > 0; + const ops = hasDraft ? built.ops : built.ops.slice(1); + const owners = hasDraft ? built.owners : built.owners.slice(1); + if (ops.length === 0) { + await finish(); + return; + } + setSaving(true); + inline.setSaving(true); + try { + if (tables.length === 0) { + // The record alone — the plain update the inline session always used. + await dataSource.update(objectName, recordId, draft); + } else { + await runBatchTransaction(dataSource, ops); + } + await finish(); + } catch (err) { + const refusal = attributeRecordEditRefusal(err, ops, owners); + inline.setFieldErrors(refusal.fieldErrors); + inline.setError(refusal.message); + for (const h of handles) { + h.setErrors(refusal.rowErrors[h.id] ?? null, refusal.tableErrors[h.id] ?? null); + } + } finally { + inline.setSaving(false); + setSaving(false); + } + }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish]); + + const cancel = useCallback(() => { + inline?.cancel(); + setDirtyTables(new Set()); + onExit(); + }, [inline, onExit]); + + controlRef.current = active ? { save, cancel } : null; + + // Ruling B (「全部保留」): one mode at a time. The edit state enters the same + // inline session, so an inline session already open is ended first — after + // a confirm when it holds changes. `wasEditingRef` is cleared before the + // session ends, so ending it is not read as leaving the edit state. + const [confirmDiscard, setConfirmDiscard] = useState(false); + const enterNow = () => { + if (inline?.editing) { + wasEditingRef.current = false; + inline.cancel(); + } + onEnter(); + }; + enterRef.current = active + ? null + : { + requestEnter: () => { + if (inline?.editing && Object.keys(inline.draft).length > 0) setConfirmDiscard(true); + else enterNow(); + }, + }; + + return ( + + + {children} + + { if (!open) setConfirmDiscard(false); }}> + + + {discardInlineTitle} + {discardInlineMessage} + + + {keepEditingLabel} + { + setConfirmDiscard(false); + enterNow(); + }} + > + {discardLabel} + + + + + {active && (inline?.error || bodyTablesReadOnly) && ( +
+ {bodyTablesReadOnly && ( +

{readOnlyNotice}

+ )} + {inline?.error && ( +

{inline.error}

+ )} +
+ )} +
+ ); +}; diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 11f8f66d11b..8e4fe48a1c7 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -1579,6 +1579,9 @@ const ar = { lockedByApproval: "مقفل للموافقة", lockedTooltip: "يحتوي هذا السجل على طلب موافقة معلق؛ التعديل مقفل", lockedByState: "غير قابل للتعديل في حالته الحالية", + bodyTableRow: "الصف {{row}}", + bodyTablesReadOnlyBulk: "تبقى جداول البنود هذه للقراءة فقط أثناء التعديل: حفظها مع السجل يتطلب تمكين الكتابة المجمعة على كائناتها. لا يزال بإمكانك تعديل حقول السجل نفسه وحفظها.", + discardInlineEditsMessage: "لديك تغييرات غير محفوظة على حقول هذا السجل. تجاهلها لتعديل السجل بالكامل، أو تابع التعديل واحفظها أولاً.", writeStrippedTitle: "تم الحفظ، لكن بعض الحقول لم تُطبَّق", writeWarningsTitle: "تم الحفظ، مع تحذيرات", writeStrippedReadonly: "للقراءة فقط، لذلك لم تُطبَّق: {{fields}}", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 402b2caa211..0c25c7c4236 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -1405,6 +1405,9 @@ const de = { lockedByApproval: "Zur Genehmigung gesperrt", lockedTooltip: "Dieser Datensatz hat eine ausstehende Genehmigungsanfrage; die Bearbeitung ist gesperrt", lockedByState: "Im aktuellen Status nicht bearbeitbar", + bodyTableRow: "Zeile {{row}}", + bodyTablesReadOnlyBulk: "Diese Positionstabellen bleiben beim Bearbeiten schreibgeschützt: Um sie zusammen mit dem Datensatz zu speichern, müssen für ihre Objekte Massenschreibvorgänge aktiviert sein. Die Felder des Datensatzes selbst können weiterhin bearbeitet und gespeichert werden.", + discardInlineEditsMessage: "Sie haben ungespeicherte Änderungen an den Feldern dieses Datensatzes. Verwerfen Sie sie, um den ganzen Datensatz zu bearbeiten, oder bearbeiten Sie weiter und speichern Sie sie zuerst.", writeStrippedTitle: "Gespeichert — einige Felder wurden jedoch nicht übernommen", writeWarningsTitle: "Gespeichert — mit Warnungen", writeStrippedReadonly: "Schreibgeschützt und daher nicht übernommen: {{fields}}", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index fbfade3313b..b84a1376830 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1539,6 +1539,9 @@ const en = { lockedByApproval: 'Locked for approval', lockedTooltip: 'This record has a pending approval request; editing is locked', lockedByState: 'Not editable in its current state', + bodyTableRow: 'Row {{row}}', + bodyTablesReadOnlyBulk: 'These line tables stay read-only while you edit: saving them together with the record needs bulk writes enabled on their objects. The record\'s own fields can still be edited and saved.', + discardInlineEditsMessage: 'You have unsaved changes to this record\'s fields. Discard them to edit the whole record, or keep editing and save them first.', writeStrippedTitle: 'Saved — but some fields did not take effect', writeWarningsTitle: 'Saved — with warnings', writeStrippedReadonly: 'Read-only, so it did not take effect: {{fields}}', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index ea13c934c77..3d2e5d77a56 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -1450,6 +1450,9 @@ const es = { lockedByApproval: "Bloqueado para aprobación", lockedTooltip: "Este registro tiene una solicitud de aprobación pendiente; la edición está bloqueada", lockedByState: "No editable en su estado actual", + bodyTableRow: "Fila {{row}}", + bodyTablesReadOnlyBulk: "Estas tablas de líneas quedan en solo lectura mientras editas: guardarlas junto con el registro requiere habilitar escrituras masivas en sus objetos. Los campos del propio registro aún se pueden editar y guardar.", + discardInlineEditsMessage: "Tienes cambios sin guardar en los campos de este registro. Descártalos para editar el registro completo, o sigue editando y guárdalos primero.", writeStrippedTitle: "Guardado, pero algunos campos no se aplicaron", writeWarningsTitle: "Guardado, con advertencias", writeStrippedReadonly: "De solo lectura, por lo que no se aplicó: {{fields}}", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index bb36668428e..81dab6bea6b 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -1447,6 +1447,9 @@ const fr = { lockedByApproval: "Verrouillé pour approbation", lockedTooltip: "Cet enregistrement a une demande d'approbation en attente ; la modification est verrouillée", lockedByState: "Non modifiable dans son état actuel", + bodyTableRow: "Ligne {{row}}", + bodyTablesReadOnlyBulk: "Ces tableaux de lignes restent en lecture seule pendant la modification : les enregistrer avec la fiche exige que les écritures en masse soient activées sur leurs objets. Les champs de la fiche elle-même restent modifiables et enregistrables.", + discardInlineEditsMessage: "Vous avez des modifications non enregistrées dans les champs de cet enregistrement. Ignorez-les pour modifier l'enregistrement entier, ou continuez la modification et enregistrez-les d'abord.", writeStrippedTitle: "Enregistré — mais certains champs n'ont pas été appliqués", writeWarningsTitle: "Enregistré — avec des avertissements", writeStrippedReadonly: "En lecture seule, donc non appliqué : {{fields}}", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 63892739d0f..b464c986924 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -1473,6 +1473,9 @@ const ja = { lockedByApproval: "承認のためロック中", lockedTooltip: "このレコードには承認待ちのリクエストがあります。編集はロックされています", lockedByState: "現在の状態では編集できません", + bodyTableRow: "{{row}} 行目", + bodyTablesReadOnlyBulk: "編集中、これらの明細テーブルは読み取り専用です。レコードと一緒に保存するには、それぞれのオブジェクトで一括書き込みを有効にする必要があります。レコード自体のフィールドは引き続き編集・保存できます。", + discardInlineEditsMessage: "このレコードの項目に未保存の変更があります。破棄してレコード全体を編集するか、編集を続けて先に保存してください。", writeStrippedTitle: "保存しました(一部の項目は反映されていません)", writeWarningsTitle: "保存しました(警告があります)", writeStrippedReadonly: "次の項目は読み取り専用のため反映されませんでした: {{fields}}", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7102bb64cb5..b3ae801b7c3 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -1405,6 +1405,9 @@ const ko = { lockedByApproval: "승인을 위해 잠김", lockedTooltip: "이 레코드에 대기 중인 승인 요청이 있습니다. 편집이 잠겨 있습니다", lockedByState: "현재 상태에서는 편집할 수 없습니다", + bodyTableRow: "{{row}}행", + bodyTablesReadOnlyBulk: "편집하는 동안 이 항목 표는 읽기 전용입니다. 레코드와 함께 저장하려면 해당 개체에서 일괄 쓰기를 사용하도록 설정해야 합니다. 레코드 자체의 필드는 계속 편집하고 저장할 수 있습니다.", + discardInlineEditsMessage: "이 레코드의 필드에 저장하지 않은 변경 사항이 있습니다. 변경 사항을 버리고 레코드 전체를 편집하거나, 계속 편집하여 먼저 저장하세요.", writeStrippedTitle: "저장되었지만 일부 필드는 적용되지 않았습니다", writeWarningsTitle: "저장되었지만 경고가 있습니다", writeStrippedReadonly: "다음 필드는 읽기 전용이므로 적용되지 않았습니다: {{fields}}", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index e8f3037a073..1bb6cf50932 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -1447,6 +1447,9 @@ const pt = { lockedByApproval: "Bloqueado para aprovação", lockedTooltip: "Este registro tem uma solicitação de aprovação pendente; a edição está bloqueada", lockedByState: "Não editável no estado atual", + bodyTableRow: "Linha {{row}}", + bodyTablesReadOnlyBulk: "Estas tabelas de itens ficam somente leitura durante a edição: salvá-las junto com o registro exige gravações em massa habilitadas em seus objetos. Os campos do próprio registro ainda podem ser editados e salvos.", + discardInlineEditsMessage: "Você tem alterações não salvas nos campos deste registro. Descarte-as para editar o registro inteiro ou continue editando e salve-as primeiro.", writeStrippedTitle: "Salvo, mas alguns campos não foram aplicados", writeWarningsTitle: "Salvo, com avisos", writeStrippedReadonly: "Somente leitura, portanto não foi aplicado: {{fields}}", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index a9ec60a09af..fc2f0272b1a 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -1576,6 +1576,9 @@ const ru = { lockedByApproval: "Заблокировано для согласования", lockedTooltip: "У этой записи есть ожидающий запрос на согласование; редактирование заблокировано", lockedByState: "Недоступно для редактирования в текущем состоянии", + bodyTableRow: "Строка {{row}}", + bodyTablesReadOnlyBulk: "Эти таблицы строк при редактировании доступны только для чтения: чтобы сохранять их вместе с записью, для их объектов должна быть включена массовая запись. Поля самой записи по-прежнему можно редактировать и сохранять.", + discardInlineEditsMessage: "В полях этой записи есть несохранённые изменения. Отмените их, чтобы редактировать всю запись, или продолжите редактирование и сначала сохраните их.", writeStrippedTitle: "Сохранено, но часть полей не применена", writeWarningsTitle: "Сохранено, но есть предупреждения", writeStrippedReadonly: "Поля только для чтения, поэтому не применены: {{fields}}", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index b274c770900..2c6888239a1 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -1271,6 +1271,9 @@ const zh = { lockedByApproval: '审批中已锁定', lockedTooltip: '该记录有待审批的请求,编辑已被锁定', lockedByState: '当前状态下不可编辑', + bodyTableRow: '第 {{row}} 行', + bodyTablesReadOnlyBulk: '编辑时这些明细表保持只读:要和主记录一起保存,需要在它们的对象上开启批量写入。主记录本身的字段仍可编辑和保存。', + discardInlineEditsMessage: '此记录的字段有未保存的更改。放弃这些更改以编辑整条记录,或继续编辑并先保存。', writeStrippedTitle: '已保存,但部分字段未生效', writeWarningsTitle: '已保存,但有警告', writeStrippedReadonly: '以下字段为只读,未生效:{{fields}}', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index e1cf997a235..07f2591d9db 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -1271,6 +1271,9 @@ const zhHant = { lockedByApproval: '審批中已鎖定', lockedTooltip: '該記錄有待審批的請求,編輯已被鎖定', lockedByState: '當前狀態下不可編輯', + bodyTableRow: '第 {{row}} 行', + bodyTablesReadOnlyBulk: '編輯時這些明細表保持只讀:要和主記錄一起儲存,需要在它們的物件上開啟批次寫入。主記錄本身的欄位仍可編輯和儲存。', + discardInlineEditsMessage: '此記錄的欄位有未儲存的更改。放棄這些更改以編輯整條記錄,或繼續編輯並先儲存。', writeStrippedTitle: '已儲存,但部分欄位未生效', writeWarningsTitle: '已儲存,但有警告', writeStrippedReadonly: '以下欄位為只讀,未生效:{{fields}}', diff --git a/ui/packages/plugin-detail/src/index.tsx b/ui/packages/plugin-detail/src/index.tsx index 6398dce940d..f837c4eddf6 100644 --- a/ui/packages/plugin-detail/src/index.tsx +++ b/ui/packages/plugin-detail/src/index.tsx @@ -227,6 +227,10 @@ export type { RecordPageColumnsProps } from './RecordPageColumns'; // synthesized default page in its tabbed tier marks it, as the column tiers do. export { DefaultRecordPageContext } from './defaultRecordPage'; export { RecordBodyTablesContext } from './relatedListCompact'; +// objectstack#35599 — the record page's edit state draws its body tables as +// the host's editor through this slot. +export { RecordBodyTableEditorSlotContext } from './relatedListCompact'; +export type { RecordBodyTableEditorSlot } from './relatedListCompact'; // objectstack#27056 — for the app-shell record drawer's prefetch: it warms // the next record's related counts before the reader steps to it. export { prefetchRelatedCounts, relatedCountTargetsIn } from './useRelatedCounts'; diff --git a/ui/packages/plugin-detail/src/relatedListCompact.ts b/ui/packages/plugin-detail/src/relatedListCompact.ts index b9d5777b52a..2982f15d773 100644 --- a/ui/packages/plugin-detail/src/relatedListCompact.ts +++ b/ui/packages/plugin-detail/src/relatedListCompact.ts @@ -75,6 +75,29 @@ export const RELATED_CARD_DROP_LINE = */ export const RecordBodyTablesContext = React.createContext>(new Set()); +/** + * What a record page's EDIT STATE draws in place of its body tables + * (objectstack#35599): the relationship ids (`CHILD_OBJECT.FK_FIELD`) it edits, + * and the element it draws for each — the host's editor, supplied by the host + * because this package does not draw editable lines. A `record:related_list` + * whose id is in `ids` renders `render(...)` instead of its read-only list; + * every other list, and every list while the value is `null` (read mode, and + * every page that is not a record page in its edit state), renders as before. + * + * Set by the record page host only while its edit state is open and one batch + * can carry the tables. The page keeps its `record:related_list` nodes: the + * editor is a host element, never a node type a page could carry. + */ +export interface RecordBodyTableEditorSlot { + /** The body tables the edit state edits, by relationship id. */ + ids: ReadonlySet; + /** The editor drawn in a body table's place. */ + render: (table: { objectName: string; relationshipField: string; title?: string }) => React.ReactNode; +} + +/** The open edit state's body-table editor slot, or `null` (see {@link RecordBodyTableEditorSlot}). */ +export const RecordBodyTableEditorSlotContext = React.createContext(null); + /** Enlarge a related list in place — the host's `?related=` — for a body table. */ export const RelatedEnlargeContext = React.createContext<((id: string) => void) | null>(null); diff --git a/ui/packages/plugin-detail/src/renderers/__tests__/record-related-list.editorSlot-35599.test.tsx b/ui/packages/plugin-detail/src/renderers/__tests__/record-related-list.editorSlot-35599.test.tsx new file mode 100644 index 00000000000..7b8f3072e5b --- /dev/null +++ b/ui/packages/plugin-detail/src/renderers/__tests__/record-related-list.editorSlot-35599.test.tsx @@ -0,0 +1,103 @@ +/** + * 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 record page's edit state draws its body tables as the host's editor + * (objectstack#35599). The page keeps its `record:related_list` nodes; a host + * provides `RecordBodyTableEditorSlotContext` while the edit state is open, and + * a list whose relationship id (`CHILD_OBJECT.FK_FIELD`) is in the slot's set + * draws the slot's element in its place — it reads no rows of its own. Every + * other list draws as before. CONTROLs: no slot (read mode, every other page) + * and a slot naming other relationships leave every list a read-only list. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, render, screen, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import { RecordContextProvider, SchemaRenderer, SchemaRendererProvider } from '@object-ui/react'; +import type { DataSource } from '@object-ui/types'; +// Registers `record:related_list`, the block under test. +import '../../index'; +import { RecordBodyTableEditorSlotContext, type RecordBodyTableEditorSlot } from '../../relatedListCompact'; + +afterEach(() => cleanup()); + +const PARENT = 'crm_account'; + +const ROWS: Record>> = { + crm_quote: [{ id: 'q1', name: 'Q-001', account_id: 'a1' }], + crm_contact: [{ id: 'c1', name: 'Ada', account_id: 'a1' }], +}; + +const makeDataSource = () => ({ + find: vi.fn(async (object: string) => { + const data = ROWS[object] ?? []; + return { data, total: data.length }; + }), + getObjectSchema: vi.fn(async (name: string) => ({ name, fields: { name: { type: 'text', label: 'Name' } } })), + onMutation: () => () => {}, +}); + +const NODES = [ + { type: 'record:related_list', id: 'quotes', properties: { objectName: 'crm_quote', relationshipField: 'account_id', title: 'Quotes', columns: ['name'] } }, + { type: 'record:related_list', properties: { objectName: 'crm_contact', relationshipField: 'account_id', title: 'Contacts', columns: ['name'] } }, +]; + +const slotFor = (ids: string[]): RecordBodyTableEditorSlot => ({ + ids: new Set(ids), + render: ({ objectName, relationshipField, title }) => ( +
+ {title ?? ''} +
+ ), +}); + +function mount(slot: RecordBodyTableEditorSlot | null) { + const ds = makeDataSource(); + render( + + + + {NODES.map((node, idx) => ( + + ))} + + + , + ); + return ds; +} + +const readObjects = (ds: ReturnType) => ds.find.mock.calls.map((c) => c[0]); + +describe('record:related_list — the edit state draws a body table as the host editor (objectstack#35599)', () => { + it('a list named by the slot draws the slot element with its relationship and title, and reads no rows; the other list is unchanged', async () => { + const ds = mount(slotFor(['crm_quote.account_id'])); + await screen.findByText('Ada'); + const editors = screen.getAllByTestId('slot-editor'); + expect(editors).toHaveLength(1); + expect(editors[0]).toHaveAttribute('data-table', 'crm_quote.account_id'); + expect(editors[0]).toHaveTextContent('Quotes'); + expect(screen.queryByText('Q-001')).toBeNull(); + expect(readObjects(ds)).not.toContain('crm_quote'); + }); + + it('CONTROL — with no slot every list is the read-only list', async () => { + const ds = mount(null); + await screen.findByText('Ada'); + await screen.findByText('Q-001'); + expect(screen.queryByTestId('slot-editor')).toBeNull(); + await waitFor(() => expect(readObjects(ds)).toContain('crm_quote')); + }); + + it('CONTROL — a slot naming other relationships leaves every list as it was', async () => { + mount(slotFor(['crm_quote.other_fk', 'crm_order.account_id'])); + await screen.findByText('Ada'); + await screen.findByText('Q-001'); + expect(screen.queryByTestId('slot-editor')).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-detail/src/renderers/record-related-list.tsx b/ui/packages/plugin-detail/src/renderers/record-related-list.tsx index 707a9c9a469..b8aa9e5da87 100644 --- a/ui/packages/plugin-detail/src/renderers/record-related-list.tsx +++ b/ui/packages/plugin-detail/src/renderers/record-related-list.tsx @@ -41,7 +41,7 @@ import { } from '@object-ui/core'; import type { RecordRelatedListComponentProps } from '@object-ui/types'; import { RelatedList } from '../RelatedList'; -import { RecordBodyTablesContext, RelatedListCompactContext, RelatedListTotalReportContext } from '../relatedListCompact'; +import { RecordBodyTableEditorSlotContext, RecordBodyTablesContext, RelatedListCompactContext, RelatedListTotalReportContext } from '../relatedListCompact'; import { relatedCardId } from '../synth/relatedArrangement'; import { useRecordAriaProps } from './recordComponentAria'; import { ParentRecordBinding } from './recordBinding'; @@ -918,9 +918,32 @@ const NoParentRecord: React.FC<{ * "declared but not reached" shape in miniature. */ export const RecordRelatedListRenderer: React.FC = elementDataSourceBlock((props) => ( - + )); +/** + * objectstack#35599 — a record page in its edit state draws each body table it + * edits as the host's editor (`RecordBodyTableEditorSlotContext`), in this + * block's place and before either binding: the editor reads the page's record + * and its lines itself. Every other list, and every list outside an open edit + * state, is the bound block below. + */ +const RecordRelatedListOrEditor: React.FC = (props) => { + const slot = React.useContext(RecordBodyTableEditorSlotContext); + const objectName = props.schema?.objectName; + const relationshipField = props.schema?.relationshipField; + if ( + slot + && typeof objectName === 'string' + && typeof relationshipField === 'string' + && slot.ids.has(`${objectName}.${relationshipField}`) + ) { + const title = props.schema?.title; + return <>{slot.render({ objectName, relationshipField, title: typeof title === 'string' ? title : undefined })}; + } + return ; +}; + /** The block bound to its parent record and its child rows — see above. */ const RecordRelatedListBound: React.FC = (props) => { const { schema, className, ...rest } = props; diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts new file mode 100644 index 00000000000..f9190e805e3 --- /dev/null +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.recordEditBatch-35599.test.ts @@ -0,0 +1,120 @@ +/** + * 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 record-page save's ONE batch (objectstack#35599): the record's field + * draft plus every body table's lines, each op traceable to the line that + * wrote it — and a refused batch placed back on that line. + */ + +import { describe, it, expect } from 'vitest'; +import { attributeRecordEditRefusal, buildRecordEditBatch } from './RecordBodyTableEditor'; + +const childSchema = { + fields: { + id: { type: 'text' }, + product: { type: 'text' }, + quantity: { type: 'number' }, + order: { type: 'master_detail', reference_to: 'order' }, + }, +}; + +const lines = { + id: 'order_line.order', + childObject: 'order_line', + relationshipField: 'order', + childSchema, + original: [ + { id: 'l1', product: 'A', quantity: 1, order: 'o1' }, + { id: 'l2', product: 'B', quantity: 2, order: 'o1' }, + ], + rows: [ + { id: 'l1', product: 'A', quantity: 5, order: 'o1' }, // edited + { product: '', quantity: undefined }, // blank ghost line: no op + { product: 'C', quantity: 3 }, // new + // l2 removed + ], +}; + +const notes = { + id: 'order_note.order', + childObject: 'order_note', + relationshipField: 'order', + childSchema: { fields: { id: { type: 'text' }, body: { type: 'text' }, order: { type: 'master_detail' } } }, + original: [], + rows: [{ body: 'hello' }], +}; + +describe('buildRecordEditBatch — one batch for the record and all its body tables', () => { + it('op 0 is the record update; each table is diffed into create / update / delete, traced to its line', () => { + const { ops, owners } = buildRecordEditBatch('order', 'o1', { name: 'Renamed' }, [lines, notes]); + expect(ops.map((o) => [o.object, o.action, o.id ?? null])).toEqual([ + ['order', 'update', 'o1'], + ['order_line', 'create', null], + ['order_line', 'update', 'l1'], + ['order_line', 'delete', 'l2'], + ['order_note', 'create', null], + ]); + expect(ops[0].data).toEqual({ name: 'Renamed' }); + // The new line carries its FK to the record; the edited line only its dirty field. + expect(ops[1].data).toMatchObject({ product: 'C', quantity: 3, order: 'o1' }); + expect(ops[2].data).toEqual({ quantity: 5 }); + expect(owners).toEqual([ + { kind: 'parent' }, + { kind: 'row', table: 'order_line.order', row: 2 }, // past the blank line, by position + { kind: 'row', table: 'order_line.order', row: 0 }, + { kind: 'row', table: 'order_line.order', row: -1 }, // a removed line is no longer drawn + { kind: 'row', table: 'order_note.order', row: 0 }, + ]); + }); + + it('an untouched table emits no ops', () => { + const { ops } = buildRecordEditBatch('order', 'o1', {}, [{ ...lines, rows: lines.original }]); + expect(ops).toHaveLength(1); + }); +}); + +describe('attributeRecordEditRefusal — a refused batch is placed where it belongs', () => { + const { ops, owners } = buildRecordEditBatch('order', 'o1', { name: 'Renamed' }, [lines, notes]); + const refused = (fields: Array<{ field: string; message: string }>) => + Object.assign(new Error('Validation failed'), { details: { error: 'Validation failed', fields } }); + + it('a field only the record writes goes on the record; a field one line writes goes on that line', () => { + const r = attributeRecordEditRefusal( + refused([ + { field: 'name', message: 'Name is too long' }, + { field: 'body', message: 'Body is required' }, + ]), + ops, + owners, + ); + expect(r.fieldErrors).toEqual({ name: 'Name is too long' }); + expect(r.rowErrors).toEqual({ 'order_note.order': [{ row: 0, field: 'body', message: 'Body is required' }] }); + expect(r.tableErrors).toEqual({}); + expect(r.message).toBe('Validation failed'); + }); + + it('a field several lines of a table write goes on the table, not on a guessed line', () => { + // `product` is carried by the new line only — the edited line's update carries only `quantity`. + const r = attributeRecordEditRefusal(refused([{ field: 'product', message: 'Unknown product' }]), ops, owners); + expect(r.rowErrors).toEqual({ 'order_line.order': [{ row: 2, field: 'product', message: 'Unknown product' }] }); + const both = attributeRecordEditRefusal(refused([{ field: 'quantity', message: 'Must be positive' }]), ops, owners); + expect(both.rowErrors).toEqual({}); + expect(both.tableErrors).toEqual({ 'order_line.order': ['Must be positive'] }); + }); + + it('a reason that names no field (a lock) stays the summary line', () => { + const lock = Object.assign(new Error('locked'), { + details: { error: 'This Order is locked while an approval is in progress' }, + }); + const r = attributeRecordEditRefusal(lock, ops, owners); + expect(r.fieldErrors).toBeNull(); + expect(r.rowErrors).toEqual({}); + expect(r.message).toBe('This Order is locked while an approval is in progress'); + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx new file mode 100644 index 00000000000..1967ac92149 --- /dev/null +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -0,0 +1,351 @@ +/** + * 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. + */ + +/** + * RecordBodyTableEditor — a record page's master-detail body table in the + * page's EDIT STATE: the child rows as editable lines (add / edit / remove), + * saved together with the record's own fields in ONE batch by the page host. + * + * The record page draws its body tables as `record:related_list` nodes. In its + * edit state the host draws this editor in each one's place and owns the + * save: the editor holds its rows, and hands the host a snapshot (rows, the rows as + * loaded, the child schema) through {@link RecordEditSessionContext}. The host + * folds the record's field draft and every table's snapshot into one + * `POST /api/v1/batch` with {@link buildRecordEditBatch} — the same + * `buildMasterDetailEditBatch` construction `MasterDetailForm` and + * `LineItemsPanel` persist through, so a line is diffed into + * create / update / delete exactly as the edit form diffs it. + * + * The pieces are `MasterDetailForm`'s: the `LineItemsField` grid, the child + * columns `deriveDetail` derives, the field-permission pass + * (`applyColumnPermissions`) and the add / remove rows of the + * affordance-to-grant map (`relatedNew` / `relatedRowDelete`), so the lines + * edit here as they edit in the form. + * + * ⚖️ The server is the validation authority on the record page (the inline + * surface's ruling, `InlineEditSaveBar`): nothing here evaluates a rule. A + * refused batch is PRESENTED — {@link attributeRecordEditRefusal} places each + * reason the server named on the record's field or on the line whose write + * carried that field. + */ + +import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; +import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/types'; +import { resolveAffordance, type SchemaLike } from '@object-ui/core'; +import { LineItemsField, lookupAutofillByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; +import { cn } from '@object-ui/components'; +import { usePermissions } from '@object-ui/permissions'; +import { + extractFieldErrors, + extractWriteErrorMessage, + useRecordContext, +} from '@object-ui/react'; +import { buildMasterDetailEditBatch, idOf, isBlankRow, type ChildSchema } from './masterDetailTx'; +import { applyColumnPermissions } from './fieldWriteGate'; +import { deriveDetail } from './deriveMasterDetail'; +import { useFormChromeTranslation } from './formChrome'; + +/** One reason the server gave about one line of a body table. */ +export interface BodyTableRowError { + /** The line's position in the table as drawn, from 0. */ + row: number; + /** The child field the reason names, when it names one. */ + field?: string; + message: string; +} + +/** What a body-table editor hands the host at save time. */ +export interface BodyTableSnapshot { + childObject: string; + relationshipField: string; + rows: Record[]; + original: Record[]; + childSchema: ChildSchema; +} + +/** One body-table editor, as the host's session sees it. */ +export interface BodyTableEditHandle { + /** The relationship id, `child.fk`. */ + id: string; + /** `null` while the table's rows or schema are still loading — the host does not save then. */ + snapshot(): BodyTableSnapshot | null; + /** Show (or clear, with `null`) the server's reasons about this table's lines. */ + setErrors(rows: BodyTableRowError[] | null, table?: string[] | null): void; +} + +/** The host's edit session, read by every body-table editor under it. */ +export interface RecordEditSession { + /** Register an editor; the returned function unregisters it. */ + register(handle: BodyTableEditHandle): () => void; + /** An editor's lines moved away from (or back to) what it loaded. */ + reportDirty(id: string, dirty: boolean): void; + /** A save is in flight: every editor takes no input. */ + saving: boolean; +} + +export const RecordEditSessionContext = React.createContext(null); + +/** Who wrote each operation of a record edit batch, by operation index. */ +export type RecordEditOpOwner = { kind: 'parent' } | { kind: 'row'; table: string; row: number }; + +/** + * The ONE batch of a record-page save: the record's field draft (op 0, an + * update of only the edited keys) and every body table's lines diffed into + * create / update / delete — `buildMasterDetailEditBatch`, table by table, so + * each op can be traced back to the line it came from ({@link RecordEditOpOwner}). + */ +export function buildRecordEditBatch( + parentObject: string, + parentId: string, + parentDraft: Record, + tables: ReadonlyArray<{ id: string } & BodyTableSnapshot>, +): { ops: BatchTransactionOperation[]; owners: RecordEditOpOwner[] } { + const ops: BatchTransactionOperation[] = [buildMasterDetailEditBatch(parentObject, parentId, parentDraft, [])[0]]; + const owners: RecordEditOpOwner[] = [{ kind: 'parent' }]; + for (const t of tables) { + const tableOps = buildMasterDetailEditBatch(parentObject, parentId, {}, [t]).slice(1); + // Rows are traced back by id (update / delete) or by position among the + // id-less rows (create): the builder emits creates first, in row order, + // skipping blank rows; then updates; then deletes. + const createRows = t.rows + .map((r, i) => ({ r, i })) + .filter(({ r }) => !idOf(r) && !isBlankRow({ ...r, [t.relationshipField]: parentId }, t.relationshipField)); + let createCursor = 0; + for (const op of tableOps) { + let row = -1; + if (op.action === 'create') { + row = createRows[createCursor++]?.i ?? -1; + } else if (op.id != null) { + row = t.rows.findIndex((r) => idOf(r) === String(op.id)); + } + ops.push(op); + owners.push({ kind: 'row', table: t.id, row }); + } + } + return { ops, owners }; +} + +/** How a refused record-edit batch reads, placed on the field or line it is about. */ +export interface RecordEditRefusal { + /** Reasons about the record's own fields, by field name. */ + fieldErrors: Record | null; + /** Reasons about body-table lines, by table id. */ + rowErrors: Record; + /** Reasons about a table that no single line carries, by table id. */ + tableErrors: Record; + /** The summary line for the whole save. */ + message: string; +} + +/** + * Place a refused batch's reasons (objectui#6868: presented, never + * re-derived). The batch answers ONE error for the transaction and does not + * say which operation raised it, so each reason the server attributes to a + * field is placed by the operations that WROTE that field: on the record when + * only the record's update carries it, on a line when exactly one line's write + * carries it, and on its table when several lines of one table do. A reason + * that names no field (a lock, a permission refusal) stays the summary. + */ +export function attributeRecordEditRefusal( + err: unknown, + ops: ReadonlyArray, + owners: ReadonlyArray, +): RecordEditRefusal { + const message = extractWriteErrorMessage(err) ?? (err instanceof Error ? err.message : String(err)); + const out: RecordEditRefusal = { fieldErrors: null, rowErrors: {}, tableErrors: {}, message }; + const fields = extractFieldErrors(err); + if (!fields) return out; + const parentFields: Record = {}; + for (const { field, message: reason } of fields) { + const carriers = ops + .map((op, i) => ({ op, owner: owners[i] })) + .filter(({ op }) => op.action !== 'delete' && op.data && Object.prototype.hasOwnProperty.call(op.data, field)); + const rows = carriers.filter((c) => c.owner?.kind === 'row') as Array<{ op: BatchTransactionOperation; owner: { kind: 'row'; table: string; row: number } }>; + const parent = carriers.some((c) => c.owner?.kind === 'parent'); + if (rows.length === 0) { + // Only the record writes it — or nothing does, and the record is still + // the best place: its fields are the page's inputs. + parentFields[field] = reason; + continue; + } + if (parent) parentFields[field] = reason; + const tables = new Set(rows.map((r) => r.owner.table)); + if (rows.length === 1 && rows[0].owner.row >= 0) { + const { table, row } = rows[0].owner; + (out.rowErrors[table] ??= []).push({ row, field, message: reason }); + } else { + for (const table of tables) (out.tableErrors[table] ??= []).push(reason); + } + } + out.fieldErrors = Object.keys(parentFields).length > 0 ? parentFields : null; + return out; +} + +export interface RecordBodyTableEditorProps { + /** The child object of the body table. */ + objectName: string; + /** The child's master-detail FK back to the record. */ + relationshipField: string; + /** The table's heading, as the read-mode table drew it. */ + title?: string; +} + +/** Lines read for one table — the window `LineItemsPanel` and `MasterDetailForm` read. */ +const BODY_TABLE_EDIT_LIMIT = 500; + +/** + * The editor itself. Reads the record (parent) and the data source from + * `RecordContextProvider` (as the page's related lists do), and the session from + * {@link RecordEditSessionContext}; with no session it renders nothing — it is + * a part of the record page's edit state, never a standalone block. + */ +export const RecordBodyTableEditor: React.FC = ({ objectName, relationshipField, title }) => { + const session = useContext(RecordEditSessionContext); + const record = useRecordContext(); + // The record page's adapter, as its related lists read it. + const dataSource = record?.dataSource as any; + const parentObject = record?.objectName; + const parentId = record?.recordId; + const perms = usePermissions(); + const { t } = useFormChromeTranslation(); + const booleanLabel = useBooleanValueLabel(); + const booleanTrue = booleanLabel(true); + const booleanFalse = booleanLabel(false); + const id = `${objectName}.${relationshipField}`; + + const [childSchema, setChildSchema] = useState<{ fields?: Record } | null>(null); + const [rows, setRows] = useState[] | null>(null); + const [original, setOriginal] = useState[]>([]); + const [rowErrors, setRowErrors] = useState(null); + const [tableErrors, setTableErrors] = useState(null); + const [loadFailed, setLoadFailed] = useState(false); + + useEffect(() => { + let cancelled = false; + if (!dataSource || typeof dataSource.getObjectSchema !== 'function') return; + Promise.resolve(dataSource.getObjectSchema(objectName)) + .then((s: any) => { if (!cancelled) setChildSchema(s ?? { fields: {} }); }) + .catch(() => { if (!cancelled) setLoadFailed(true); }); + return () => { cancelled = true; }; + }, [dataSource, objectName]); + + const derived = useMemo(() => { + if (!childSchema || !parentObject) return null; + try { + return deriveDetail(objectName, childSchema as any, parentObject, { booleanLabel, relationshipField }); + } catch { + return null; + } + // Keyed on the two WORDS, not on `booleanLabel` (a new function each render). + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [childSchema, parentObject, objectName, relationshipField, booleanTrue, booleanFalse]); + + // The lines as stored, read once per edit session (the editor mounts with it). + useEffect(() => { + let cancelled = false; + if (!dataSource || parentId == null || !derived) return; + Promise.resolve(dataSource.find(objectName, { + $filter: { [relationshipField]: parentId }, + ...(derived.sortField + ? { $orderby: [{ field: derived.sortField, order: 'asc' as const }, { field: 'id', order: 'asc' as const }] } + : {}), + $top: BODY_TABLE_EDIT_LIMIT, + })) + .then((res: any) => { + if (cancelled) return; + const loaded = (res?.data ?? []) as Record[]; + setOriginal(loaded.map((r) => ({ ...r }))); + setRows(loaded.map((r) => ({ ...r }))); + }) + .catch(() => { if (!cancelled) setLoadFailed(true); }); + return () => { cancelled = true; }; + }, [dataSource, parentId, derived, objectName, relationshipField]); + + const snapshotRef = useRef(null); + snapshotRef.current = rows && derived + ? { childObject: objectName, relationshipField, rows, original, childSchema } + : null; + + const register = session?.register; + useEffect(() => { + if (!register) return; + return register({ + id, + snapshot: () => snapshotRef.current, + setErrors: (r, tbl) => { + setRowErrors(r && r.length > 0 ? r : null); + setTableErrors(tbl && tbl.length > 0 ? tbl : null); + }, + }); + }, [register, id]); + + const reportDirty = session?.reportDirty; + const onChange = useCallback((next: Record[]) => { + setRows(next); + reportDirty?.(id, true); + }, [reportDirty, id]); + + if (!session) return null; + + const lineSource = { objectSchema: childSchema as SchemaLike | null, objectName, perms }; + const heading = title || (childSchema as any)?.pluralLabel || (childSchema as any)?.label || objectName; + const labelOf = (field?: string) => + (field && (derived?.columns.find((c) => c.name === field)?.label || (childSchema?.fields as any)?.[field]?.label)) || field; + + return ( +
+

{heading}

+ {loadFailed ? ( +

+ {t('form.lineItems.loadFailed')} +

+ ) : rows === null || !derived ? ( +

{t('common.loading')}

+ ) : ( + | undefined} + lookupAutofill={lookupAutofillByField(childSchema?.fields as Record | undefined)} + field={({ + columns: applyColumnPermissions(derived.columns as GridColumn[], { perms, objectName, mode: 'edit' }), + totalField: derived.amountField, + sortField: derived.sortField, + allowAdd: resolveAffordance('relatedNew', lineSource).allowed, + allowDelete: resolveAffordance('relatedRowDelete', lineSource).allowed, + } satisfies Partial) as GridFieldMetadata} + /> + )} + {(rowErrors || tableErrors) && ( +
    + {(rowErrors ?? []).map((e, i) => ( +
  • + + {t('detail.bodyTableRow', { row: e.row + 1 })} + {e.field ? ` · ${labelOf(e.field)}` : ''} + + {': '} + {e.message} +
  • + ))} + {(tableErrors ?? []).map((message, i) => ( +
  • {message}
  • + ))} +
+ )} +
+ ); +}; diff --git a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx index 6affc9565ae..500efd81612 100644 --- a/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx +++ b/ui/packages/plugin-form/src/affordanceGrantMap-12082.test.tsx @@ -829,6 +829,15 @@ const WRITE_SITES: Record = { "(absent from the spec's PLATFORM_OBJECTS_BY_PACKAGE and CLOUD_PROVIDED_OBJECT_NAMES, read 2026-10-11), so it fails " + 'for every caller whatever their grant; no in-app link reaches its route either', ), + // objectstack#35599 — the record page's edit state: Edit (recordEdit, read + // by the page) enters it; Save writes the record alone as the plain update, + // or the record and its body tables as one batch, whose line add / remove + // read relatedNew / relatedRowDelete in the body-table editor and whose + // line cells are the field write gate's edit columns. + 'packages/app-shell/src/views/recordEditState.tsx :: RecordEditStateController > save :: update': + mapped(['recordEdit'], RECORD_PAGE), + 'packages/app-shell/src/views/recordEditState.tsx :: RecordEditStateController > save :: batch': + mapped(['recordEdit', 'relatedNew', 'relatedRowDelete', 'editFormFields'], RECORD_PAGE, 'packages/plugin-form/src/RecordBodyTableEditor.tsx', FIELD_WRITE_GATE), // ── plugin-detail ── 'packages/plugin-detail/src/InlineEditSaveBar.tsx :: updateVia :: update': { ...mapped(['recordEdit'], RECORD_PAGE, RECORD_DETAILS, DETAIL_SECTION, HEADER_HIGHLIGHT), diff --git a/ui/packages/plugin-form/src/formChrome.ts b/ui/packages/plugin-form/src/formChrome.ts index 4e3faed6618..227e414a407 100644 --- a/ui/packages/plugin-form/src/formChrome.ts +++ b/ui/packages/plugin-form/src/formChrome.ts @@ -82,6 +82,11 @@ const FORM_CHROME_DEFAULTS = { // The heading of the fields no declared field group claims // (`deriveFieldGroupSections`' trailing bucket). 'common.ungroupedSection': 'Other', + // The record page's edit-state body table (`RecordBodyTableEditor`): its + // loading line, a failed read, and the label of a refused line. + 'common.loading': 'Loading…', + 'form.lineItems.loadFailed': 'Failed to load line items', + 'detail.bodyTableRow': 'Row {{row}}', }; /** diff --git a/ui/packages/plugin-form/src/index.tsx b/ui/packages/plugin-form/src/index.tsx index 324159c8fe6..0c24af6f20c 100644 --- a/ui/packages/plugin-form/src/index.tsx +++ b/ui/packages/plugin-form/src/index.tsx @@ -66,6 +66,23 @@ export type { } from './MasterDetailForm'; export { LineItemsPanel } from './LineItemsPanel'; export type { LineItemsPanelSchema } from './LineItemsPanel'; +// The record page's edit state: a body table as editable lines, saved with the +// record in one batch by the page host (`RecordBodyTableEditor.tsx`). +export { + RecordBodyTableEditor, + RecordEditSessionContext, + buildRecordEditBatch, + attributeRecordEditRefusal, +} from './RecordBodyTableEditor'; +export type { + RecordBodyTableEditorProps, + RecordEditSession, + RecordEditOpOwner, + RecordEditRefusal, + BodyTableEditHandle, + BodyTableSnapshot, + BodyTableRowError, +} from './RecordBodyTableEditor'; export { deriveDetail, deriveColumns, deriveFormFields, findRelationshipField, resolveInlineMode } from './deriveMasterDetail'; export type { DerivedDetail, InlineMode, ChildObjectSchemaLike } from './deriveMasterDetail';