-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMasterDetailForm.tsx
More file actions
737 lines (700 loc) · 32.6 KB
/
Copy pathMasterDetailForm.tsx
File metadata and controls
737 lines (700 loc) · 32.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
/**
* 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.
*/
/**
* MasterDetailForm — enter a parent record together with its child "line
* items" in a single screen, and persist them as one client-orchestrated
* transaction (see ADR-0001).
*
* The parent fields are rendered by the existing <ObjectForm>; the child
* collection(s) by <LineItemsField>. On submit we build ONE ordered
* cross-object operation list — parent create/update as op 0, each child a
* create/update/delete linked to it (via `{ $ref: 0 }` on create, or the
* known parent id on edit) — and hand it to `dataSource.batchTransaction`
* through {@link runBatchTransaction}. Client-side rollups are folded into the
* parent payload so they commit in the same batch.
*
* The form is deliberately ignorant of atomicity: a server with the
* transactional `/api/v1/batch` endpoint commits all-or-nothing, while an
* adapter without one emulates the batch internally (sequential writes with
* best-effort compensation, see `emulateBatchTransaction` in `@object-ui/core`).
* Either way there is no master-detail-specific cleanup code here (ObjectStack
* objectui #2679 / framework ADR-0034 item 4).
*
* No `@objectstack/spec` change: the relationship is a `master_detail` (or
* `lookup`) FK on the child object.
*/
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import type { DataSource } from '@object-ui/types';
import { runBatchTransaction } from '@object-ui/core';
import { LineItemsField, type GridColumn } from '@object-ui/fields';
import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components';
import { ObjectForm } from './ObjectForm';
import { buildMasterDetailBatch, buildMasterDetailEditBatch, sumRows } from './masterDetailTx';
import { deriveDetail, hydrateColumns, type InlineMode } from './deriveMasterDetail';
export interface MasterDetailDetailConfig {
/** Child object name, e.g. 'expense_line'. */
childObject: string;
/** FK field on the child pointing back to the parent, e.g. 'expense_claim'.
* Optional — auto-detected from the child's master_detail/lookup field that
* references the parent object when omitted. */
relationshipField?: string;
/** Editable columns for the child grid. Optional — derived from the child
* object's fields (via DataSource.getObjectSchema) when omitted. */
columns?: GridColumn[];
/** Field names for the per-row expand form. Optional — derived from the child
* object's fields (broader than `columns`: includes rich types) when omitted. */
formFields?: string[];
/** Inline-edit form factor: 'grid' = editable cells; 'form' = read-only list +
* per-row full form. Optional — resolved from the relationship's `inlineEdit`
* (incl. the smart default) when omitted. */
inlineMode?: InlineMode;
/** Numeric child column to sum, e.g. 'amount'. */
amountField?: string;
/** Child field holding the line sort position — stamped on drag-reorder so
* order persists. Auto-derived from a `position`/`sort_order`/… field. */
sortField?: string;
/** Parent field to receive the rolled-up sum, e.g. 'total_amount'. */
totalField?: string;
/** Section title. */
title?: string;
minRows?: number;
maxRows?: number;
addLabel?: string;
}
export interface MasterDetailFormSchema {
type?: 'object-master-detail-form';
/** Parent object name, e.g. 'expense_claim'. */
objectName: string;
mode?: 'create' | 'edit';
/**
* `string | number` to match `ObjectFormSchema` and the drawer/modal/split/
* tabbed/wizard envelopes that hand a record straight through to this form —
* a numeric primary key is a real backend shape. Narrowed to a string only at
* the batch-transaction boundary, whose `BatchTransactionOperation.id` is a
* string by protocol.
*/
recordId?: string | number;
/** Prefilled parent header values (create mode) — seeds the parent form's
* initial values, e.g. a conversion wizard carrying the lead/account over. */
initialValues?: Record<string, any>;
initialData?: Record<string, any>;
/** Parent form sections/fields — passed straight through to ObjectForm. */
sections?: any[];
fields?: any[];
formType?: 'simple' | 'tabbed';
title?: string;
submitText?: string;
/** Label for the Cancel button in the action bar. i18n is the host's job
* (this plugin is locale-agnostic); defaults to English 'Cancel'. */
cancelText?: string;
/** Hide the bottom Save/Cancel action bar — e.g. a non-persisting design
* preview. Defaults to shown (the form owns the only Save in this layout). */
showSubmit?: boolean;
/** One or more child collections. */
details: MasterDetailDetailConfig[];
/** Parent header field holding a tax rate (percent). When the parent form has
* this field, a live Subtotal / Tax / Total stack renders under the lines.
* Defaults to `tax_rate`; the stack only appears if the field is present. */
taxRateField?: string;
onSuccess?: (parent: any) => void | Promise<void>;
onError?: (err: Error) => void;
onCancel?: () => void;
className?: string;
}
/** Rows keyed by their persisted id (when known), for edit-mode diffing. */
interface RowState {
rows: Record<string, any>[];
/** Snapshot of the persisted rows (edit mode) for diffing on submit. */
original: Record<string, any>[];
}
/**
* Read the live header record from the rendered parent-form host by scraping its
* named controls. The header is owned by react-hook-form (inside <ObjectForm>),
* which exposes no values callback here; rather than couple into its internals
* we read the DOM the same way the tax-rate stack does. Radix <Select> renders a
* visually-hidden native `<select name=...>` for form participation, so selects
* (e.g. an invoice `status`) are captured too, and a user's pick dispatches a
* bubbling `change` the host listener catches.
*/
function scrapeHeaderRecord(host: HTMLElement | null): Record<string, unknown> {
if (!host) return {};
const out: Record<string, unknown> = {};
const els = host.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>('[name]');
els.forEach((el) => {
const name = el.getAttribute('name');
if (!name) return;
if (el.tagName === 'INPUT') {
const input = el as HTMLInputElement;
if (input.type === 'checkbox') { out[name] = input.checked; return; }
if (input.type === 'radio') { if (input.checked) out[name] = input.value; return; }
if (input.type === 'number' || input.type === 'range') {
if (input.value === '') { out[name] = null; return; }
const n = Number(input.value);
out[name] = Number.isFinite(n) ? n : input.value;
return;
}
out[name] = input.value;
return;
}
// <select> (incl. Radix's hidden native select) and <textarea>.
out[name] = (el as HTMLSelectElement | HTMLTextAreaElement).value;
});
return out;
}
interface MasterDetailLinesProps {
details: MasterDetailDetailConfig[];
state: RowState[];
setRows: (detailIdx: number, rows: Record<string, any>[]) => void;
/** Host wrapping the header <ObjectForm> — scraped for the live parent record. */
formHostRef: React.RefObject<HTMLDivElement | null>;
taxRateField: string;
/** Bumped when the header form remounts (after create) so the lines re-scrape. */
formKey: number;
onRowExpand: (detailIdx: number, rowIdx: number) => void;
onAddViaForm: (detailIdx: number) => void;
}
/**
* The line-item grids + document totals, isolated from the header form.
*
* It owns `parentRecord` — the live header values, scraped from the form host —
* and binds it to every grid as `contextRecord`, so a column's `readonlyWhen` /
* `requiredWhen` CEL rule can react to the header (the "paid invoice → lock
* lines" case, `parent.status == 'paid'`; see #1581 / ADR-0036).
*
* Holding `parentRecord` HERE rather than in <MasterDetailForm> is the whole
* point: a header keystroke re-renders only these lines, never the header
* <ObjectForm> whose react-hook-form state would otherwise reset mid-edit. The
* scrape is deduped by value so an identical re-read causes no state churn.
*/
const MasterDetailLines: React.FC<MasterDetailLinesProps> = ({
details,
state,
setRows,
formHostRef,
taxRateField,
formKey,
onRowExpand,
onAddViaForm,
}) => {
const [parentRecord, setParentRecord] = useState<Record<string, unknown>>({});
const parentKeyRef = useRef<string>('');
useEffect(() => {
const host = formHostRef.current;
if (!host) return;
const read = () => {
const next = scrapeHeaderRecord(host);
let key: string;
try { key = JSON.stringify(next); } catch { key = String(Math.random()); }
if (key === parentKeyRef.current) return; // value-identical → no re-render
parentKeyRef.current = key;
setParentRecord(next);
};
read();
const onEvt = () => read();
host.addEventListener('input', onEvt);
host.addEventListener('change', onEvt);
// The header populates asynchronously (schema fetch → edit-mode load → RHF
// reset), none of which fire input events, so re-read on a few ticks to
// capture the initial record (e.g. an already-paid invoice loads locked).
const timers = [120, 360, 800].map((ms) => setTimeout(read, ms));
return () => {
host.removeEventListener('input', onEvt);
host.removeEventListener('change', onEvt);
timers.forEach(clearTimeout);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [formHostRef, formKey, details.length]);
// Document totals: Subtotal (Σ line amounts) → Tax (header rate %) → Total.
// Shown only when the header carries the tax-rate field AND a detail has an
// amount column; otherwise each grid keeps its own footer total.
const taxRaw = parentRecord[taxRateField];
const taxRate = taxRaw === undefined ? null : (Number.isFinite(Number(taxRaw)) ? Number(taxRaw) : 0);
const subtotal = details.reduce((acc, d, i) => acc + sumRows(state[i]?.rows ?? [], d.amountField || 'amount'), 0);
const showTaxStack = taxRate !== null && details.some((d) => !!d.amountField);
const taxPct = taxRate ?? 0;
const taxAmount = subtotal * (taxPct / 100);
const grandTotal = subtotal + taxAmount;
const money = (n: number) => `¥${n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
return (
<>
{/* Line items below the header. Rendered as a light section (label + the
grid's own bordered table) rather than a heavy Card — a Card here would
double-frame the grid and its p-6 padding wastes the width the line
table needs. */}
{details.map((d, i) => (
<section key={`${d.childObject}-${i}`} className="space-y-2">
<h3 className="text-sm font-medium text-foreground">{d.title || 'Line Items'}</h3>
{!d.columns?.length ? (
<p className="py-4 text-sm text-muted-foreground">Loading columns…</p>
) : (
<LineItemsField
value={state[i]?.rows ?? []}
onChange={(rows) => setRows(i, rows)}
// The live header record — a line cell's readonlyWhen/requiredWhen
// CEL rule evaluates against it as `parent` (e.g. lock when
// parent.status == 'paid').
contextRecord={parentRecord}
// Per-row "expand to full form" is offered when it adds something:
// always in form mode (it IS the editor), and in grid mode only
// when the full form has fields the grid omits. A thin grid whose
// columns already cover every field (e.g. invoice lines) shows no
// redundant expand button.
{...((d.inlineMode === 'form' || (d.formFields?.length ?? 0) > (d.columns?.length ?? 0))
? { onRowExpand: (rowIdx: number) => onRowExpand(i, rowIdx) }
: {})}
displayMode={d.inlineMode === 'form' ? 'list' : 'grid'}
{...(d.inlineMode === 'form' ? { onAdd: () => onAddViaForm(i) } : {})}
field={
{
columns: d.columns,
// Show the per-grid running total whenever an amount column is
// set — unless the document totals stack below subsumes it.
total_field: showTaxStack ? undefined : (d.amountField || (d.totalField ? 'amount' : undefined)),
sort_field: d.sortField,
min_rows: d.minRows,
max_rows: d.maxRows,
add_label: d.inlineMode === 'form' ? (d.addLabel || 'Add') : d.addLabel,
} as any
}
/>
)}
</section>
))}
{/* Document totals stack (Subtotal / Tax / Total) — the right-aligned block
every invoicing tool shows. Live as lines and the header tax rate change. */}
{showTaxStack && (
<div className="flex justify-end">
<dl className="w-64 space-y-1.5 text-sm" data-testid="md-totals">
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">Subtotal</dt>
<dd className="tabular-nums" data-testid="md-subtotal">{money(subtotal)}</dd>
</div>
<div className="flex items-center justify-between">
<dt className="text-muted-foreground">Tax ({taxPct}%)</dt>
<dd className="tabular-nums" data-testid="md-tax">{money(taxAmount)}</dd>
</div>
<div className="flex items-center justify-between border-t border-border pt-1.5 text-base font-semibold">
<dt>Total</dt>
<dd className="tabular-nums" data-testid="md-grand-total">{money(grandTotal)}</dd>
</div>
</dl>
</div>
)}
</>
);
};
export interface MasterDetailFormProps {
schema: MasterDetailFormSchema;
dataSource?: DataSource;
className?: string;
}
export const MasterDetailForm: React.FC<MasterDetailFormProps> = ({
schema,
dataSource,
className,
}) => {
const rawDetails = schema.details || [];
const isEdit = schema.mode === 'edit' && !!schema.recordId;
// A detail can be configured with just `{ childObject }` — the relationship
// FK and grid columns are then derived from the child object's metadata
// (DataSource.getObjectSchema). We also resolve when columns are hand-authored
// as bare `{ field, label }` (no `type`): those need their widget type
// hydrated from the child schema, else every cell falls back to a text input.
const needsDerive = rawDetails.some(
(d) => !d.relationshipField || !d.columns?.length || d.columns.some((c) => !c.type),
);
const [resolvedDetails, setResolvedDetails] = useState<MasterDetailDetailConfig[] | null>(
needsDerive ? null : rawDetails,
);
const details = resolvedDetails ?? rawDetails; // length always matches rawDetails
useEffect(() => {
if (!needsDerive) { setResolvedDetails(rawDetails); return; }
if (!dataSource || typeof (dataSource as any).getObjectSchema !== 'function') return;
let cancelled = false;
(async () => {
const out = await Promise.all(
rawDetails.map(async (d) => {
const columnsTyped = d.columns?.length ? d.columns.every((c) => !!c.type) : false;
// Fully configured (FK + every column typed) — nothing to resolve.
if (d.relationshipField && columnsTyped) return d;
try {
const childSchema = await dataSource.getObjectSchema(d.childObject);
// Author gave the FK + an explicit column set but left some columns
// untyped — hydrate just their widget types from the schema, keeping
// their exact column set / order / labels (don't re-derive columns).
if (d.relationshipField && d.columns?.length) {
return { ...d, columns: hydrateColumns(d.columns, childSchema) };
}
const derived = deriveDetail(d.childObject, childSchema, schema.objectName, {
relationshipField: d.relationshipField,
columns: d.columns,
amountField: d.amountField,
});
return {
...d,
relationshipField: derived.relationshipField,
columns: derived.columns,
formFields: d.formFields ?? derived.formFields,
inlineMode: d.inlineMode ?? derived.mode,
amountField: d.amountField ?? derived.amountField,
sortField: d.sortField ?? derived.sortField,
};
} catch {
return d; // leave as-is; the grid card will show a config hint
}
}),
);
if (!cancelled) setResolvedDetails(out);
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dataSource, schema.objectName, schema.details]);
// One row-state per detail collection (length is known up-front from rawDetails).
const [state, setState] = useState<RowState[]>(() =>
rawDetails.map(() => ({ rows: [], original: [] })),
);
const stateRef = useRef(state);
stateRef.current = state;
// Cache of child object schemas (keyed by childObject), fetched once so the
// client-orchestrated and atomic-batch child writes can strip computed /
// read-only columns from each row — parity with the parent form's
// `sanitizeFormData`. Child rows are seeded from a full record read, so an
// edit would otherwise round-trip formula/summary columns the server rejects.
// A ref (not state) so a late-arriving schema never re-renders — and thus
// never resets — the header <ObjectForm> (see #1581). Reads happen at submit
// time, long after the fetch resolves.
const childSchemasRef = useRef<Record<string, { fields?: Record<string, any> }>>({});
useEffect(() => {
const ds: any = dataSource;
if (!ds || typeof ds.getObjectSchema !== 'function') return;
let cancelled = false;
const objects = Array.from(new Set(rawDetails.map((d) => d.childObject).filter(Boolean)));
(async () => {
const entries = await Promise.all(
objects.map(async (obj) => {
try { return [obj, await ds.getObjectSchema(obj)] as const; }
catch { return [obj, null] as const; }
}),
);
if (cancelled) return;
const next: Record<string, { fields?: Record<string, any> }> = {};
for (const [obj, sch] of entries) if (sch) next[obj] = sch;
childSchemasRef.current = next;
})();
return () => { cancelled = true; };
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [dataSource, schema.objectName, schema.details]);
// Bumped after a successful CREATE to remount the parent <ObjectForm> (which
// owns react-hook-form state) so its fields clear for the next entry.
const [formKey, setFormKey] = useState(0);
const [saving, setSaving] = useState(false);
const savingRef = useRef(false);
const saveGuardTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
const releaseSave = useCallback(() => {
savingRef.current = false;
setSaving(false);
if (saveGuardTimer.current) {
clearTimeout(saveGuardTimer.current);
saveGuardTimer.current = null;
}
}, []);
// Edit mode: load existing children for each detail collection.
useEffect(() => {
let cancelled = false;
if (!isEdit || !dataSource) return;
(async () => {
const loaded = await Promise.all(
details.map(async (d) => {
if (!d.relationshipField) return { rows: [], original: [] }; // not resolved yet
try {
const res = await dataSource.find(d.childObject, {
$filter: { [d.relationshipField]: schema.recordId },
$top: 500,
});
const rows = (res?.data ?? []) as Record<string, any>[];
return { rows: rows.map((r) => ({ ...r })), original: rows.map((r) => ({ ...r })) };
} catch {
return { rows: [], original: [] };
}
}),
);
if (!cancelled) setState(loaded);
})();
return () => {
cancelled = true;
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isEdit, dataSource, schema.recordId, resolvedDetails]);
const setRows = useCallback((detailIdx: number, rows: Record<string, any>[]) => {
setState((prev) => prev.map((s, i) => (i === detailIdx ? { ...s, rows } : s)));
}, []);
// Header tax-rate field name — the live value is read by <MasterDetailLines>
// (which scrapes the header record) and drives the Subtotal / Tax / Total stack.
const taxRateField = schema.taxRateField || 'tax_rate';
// Per-row "expand to full form": opens the child's complete form (all business
// fields, incl. rich types the grid omits) in a drawer, pre-filled with the
// row. Saving writes back into the in-memory row — the atomic batch still
// persists everything on the parent Save (no separate backend write here).
// `isNew` marks a row created by "Add" in list/form mode — cancelling the
// editor without applying discards that empty row.
const [expanded, setExpanded] = useState<{ detailIdx: number; rowIdx: number; isNew?: boolean } | null>(null);
const expandedRow =
expanded ? state[expanded.detailIdx]?.rows?.[expanded.rowIdx] : undefined;
const expandedDetail = expanded ? details[expanded.detailIdx] : undefined;
const applyRowEdit = useCallback(
(detailIdx: number, rowIdx: number, values: Record<string, any>) => {
setState((prev) =>
prev.map((s, i) =>
i === detailIdx
? { ...s, rows: s.rows.map((r, j) => (j === rowIdx ? { ...r, ...values } : r)) }
: s,
),
);
},
[],
);
/** List/form mode "Add": append a blank row and open it in the full form. */
const addRowViaForm = useCallback((detailIdx: number) => {
setState((prev) => {
const next = prev.map((s, i) => (i === detailIdx ? { ...s, rows: [...s.rows, {}] } : s));
const rowIdx = next[detailIdx].rows.length - 1;
setExpanded({ detailIdx, rowIdx, isNew: true });
return next;
});
}, []);
/** Editor cancelled: drop the row if it was a freshly-added (empty) one. */
const cancelRowEdit = useCallback(() => {
setExpanded((cur) => {
if (cur?.isNew) {
setState((prev) =>
prev.map((s, i) => (i === cur.detailIdx ? { ...s, rows: s.rows.filter((_, j) => j !== cur.rowIdx) } : s)),
);
}
return null;
});
}, []);
/**
* Built-in feedback so a save is NEVER silent (a silent success looks broken
* and invites duplicate submits). On CREATE also clears the form for the next
* entry by resetting the line items + remounting the parent form.
*
* The success toast is only our fallback: when the host supplies `onSuccess`
* it owns confirmation (e.g. the console toasts a localized message via its
* crud-success handler), so we stay quiet to avoid double-confirming — the
* same contract flat `ObjectForm` follows. Without a host `onSuccess` we keep
* the built-in toast so the save is never silent.
*/
const handleSaved = useCallback(
async (parent: any) => {
releaseSave();
if (!schema.onSuccess) {
toast.success(isEdit ? (schema.title ? `${schema.title} saved` : 'Saved') : 'Created');
}
if (!isEdit) {
setState(details.map(() => ({ rows: [], original: [] })));
setFormKey((k) => k + 1);
}
await schema.onSuccess?.(parent);
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[isEdit, schema.onSuccess, schema.title, details.length, releaseSave],
);
/** Surface failures (validation / network / atomic rollback) to the user. */
const handleError = useCallback(
(err: Error) => {
releaseSave();
toast.error(err?.message || 'Save failed');
schema.onError?.(err);
},
[schema, releaseSave],
);
// Persistence ALWAYS goes through dataSource.batchTransaction: the parent and
// all child collections are expressed as one ordered operation list and
// handed to runBatchTransaction, which uses the adapter's atomic endpoint
// when present and emulates it (sequential + best-effort compensation)
// otherwise. This covers BOTH create (parent + child creates via `$ref`) and
// edit (parent update + child create/update/delete diffs). There is no
// separate client-orchestrated / cleanup path anymore (#2679).
const submitViaBatch = useCallback(
async (parentValues: Record<string, any>) => {
if (!dataSource) throw new Error('MasterDetailForm: dataSource is required');
const parentData: Record<string, any> = { ...parentValues };
// Client-side rollups merged into the parent payload (hooks can't do
// nested writes — see ADR-0001).
details.forEach((d, i) => {
if (d.totalField) parentData[d.totalField] = sumRows(stateRef.current[i]?.rows ?? [], d.amountField || 'amount');
});
const ops = isEdit
? buildMasterDetailEditBatch(
schema.objectName,
String(schema.recordId),
parentData,
details.filter((d) => d.relationshipField).map((d, i) => ({
childObject: d.childObject,
relationshipField: d.relationshipField!,
rows: stateRef.current[i]?.rows ?? [],
original: stateRef.current[i]?.original ?? [],
childSchema: childSchemasRef.current[d.childObject],
})),
)
: buildMasterDetailBatch(
schema.objectName,
parentData,
details.filter((d) => d.relationshipField).map((d, i) => ({
childObject: d.childObject,
relationshipField: d.relationshipField!,
rows: stateRef.current[i]?.rows ?? [],
childSchema: childSchemasRef.current[d.childObject],
})),
);
const res = await runBatchTransaction(dataSource, ops);
// create → parent is op 0; edit → echo the parent values back.
return res?.results?.[0] ?? { ...parentData, id: schema.recordId };
},
[dataSource, details, schema.objectName, schema.recordId, isEdit],
);
// The parent form renders WITHOUT its own submit button — the master-detail
// form owns a single action bar at the bottom (header → lines → Save), the
// layout every mainstream enterprise platform uses for header+line entry.
const parentSchema = useMemo(
() => ({
type: 'object-form',
objectName: schema.objectName,
mode: schema.mode ?? 'create',
recordId: schema.recordId,
// Carry prefilled header values into the parent form (create-mode
// wizards, e.g. lead conversion prefilling name/account).
initialValues: schema.initialValues,
initialData: schema.initialData,
formType: schema.formType,
sections: schema.sections,
fields: schema.fields,
title: schema.title,
showSubmit: false,
showCancel: false,
// ObjectForm validates + hands the parent values to submitViaBatch (which
// persists parent + children as one batch via dataSource.batchTransaction),
// then handleSaved (toast + reset + page onSuccess).
submitHandler: submitViaBatch,
onSuccess: handleSaved,
onError: handleError,
}),
[schema, submitViaBatch, handleSaved, handleError],
);
const formHostRef = useRef<HTMLDivElement>(null);
const submitText = schema.submitText ?? (isEdit ? 'Save' : 'Create');
const handleSave = useCallback(() => {
// Drive the (button-less) parent form's submit so its validation + RHF
// onSubmit fire; success chains into child persistence via onSuccess.
if (savingRef.current) return; // guard against duplicate submits
const form = formHostRef.current?.querySelector('form') as HTMLFormElement | null;
if (!form) return;
savingRef.current = true;
setSaving(true);
// IMPORTANT: defer the submit out of this click's React dispatch AND
// re-query the <form> inside the timer. Calling requestSubmit()
// synchronously inside the onClick (or on a form reference captured before
// the setSaving() re-render) intermittently fails to invoke react-hook-form's
// onSubmit — the nested submit event is dropped — which made "Create" feel
// unresponsive (only the occasional lucky click submitted). A fresh query in
// a macrotask reliably triggers RHF validation + submit.
setTimeout(() => {
const liveForm = formHostRef.current?.querySelector('form') as HTMLFormElement | null;
liveForm?.requestSubmit();
}, 0);
// Safety net: react-hook-form blocks invalid submits without firing
// onSuccess/onError, which would otherwise leave the button stuck. Release
// the guard after a beat so the user can correct fields and retry.
saveGuardTimer.current = setTimeout(() => releaseSave(), 1500);
}, [releaseSave]);
useEffect(() => () => { if (saveGuardTimer.current) clearTimeout(saveGuardTimer.current); }, []);
return (
<div className={cn('space-y-6', className, schema.className)}>
{/* 1) Header fields on top */}
<div ref={formHostRef}>
<ObjectForm key={formKey} schema={parentSchema as any} dataSource={dataSource} />
</div>
{/* 2) Line items + document totals, in a sibling component that owns the
live header record (scraped from the form host) so header edits never
re-render — and thus never reset — the header <ObjectForm> (see #1581). */}
<MasterDetailLines
details={details}
state={state}
setRows={setRows}
formHostRef={formHostRef}
taxRateField={taxRateField}
formKey={formKey}
onRowExpand={(detailIdx, rowIdx) => setExpanded({ detailIdx, rowIdx })}
onAddViaForm={addRowViaForm}
/>
{/* Per-row "expand to full form": an inline editor panel for the selected
row. Rendered INLINE (not a portaled drawer) so it behaves identically
whether this form is itself inside a modal (New-from-list) or a full
page — nested portaled overlays inherit the host modal's
pointer-events / aria-hidden lock and become unclickable. Edits the
row in the child's COMPLETE form (rich types the grid omits) and writes
the values back into the in-memory row; the atomic batch persists
everything on the parent Save. */}
{expanded && expandedDetail && (
<Card className="border-primary/40 shadow-none ring-1 ring-primary/10" data-testid="md-row-form">
<CardHeader className="pb-2 flex flex-row items-center justify-between gap-2 space-y-0">
<CardTitle className="text-sm font-medium">
{(expandedDetail.title || 'Line item')} — row {expanded.rowIdx + 1}
</CardTitle>
<Button
type="button"
variant="ghost"
size="sm"
className="h-7 text-xs text-muted-foreground"
onClick={cancelRowEdit}
>
Close
</Button>
</CardHeader>
<CardContent>
<ObjectForm
key={`row-${expanded.detailIdx}-${expanded.rowIdx}`}
schema={{
type: 'object-form',
objectName: expandedDetail.childObject,
mode: 'edit',
// No recordId → ObjectForm uses initialData (no backend fetch).
initialData: expandedRow ?? {},
...(expandedDetail.formFields?.length ? { fields: expandedDetail.formFields } : {}),
submitText: 'Apply',
// Non-persisting: return the values; the atomic batch on the
// parent Save does the real write.
submitHandler: async (values: any) => values,
onSuccess: (values: any) => {
applyRowEdit(expanded.detailIdx, expanded.rowIdx, values);
setExpanded(null);
},
onCancel: cancelRowEdit,
} as any}
dataSource={dataSource}
/>
</CardContent>
</Card>
)}
{/* Single action bar at the bottom — suppressed when the host opts out
(e.g. the Studio screen-preview, which must never persist). */}
{schema.showSubmit !== false && (
<div className="flex items-center justify-end gap-2 border-t border-border pt-4">
{schema.onCancel && (
<Button type="button" variant="outline" onClick={schema.onCancel} disabled={saving} data-testid="md-form-cancel">
{schema.cancelText ?? 'Cancel'}
</Button>
)}
<Button type="button" onClick={handleSave} disabled={saving || (needsDerive && !resolvedDetails)} data-testid="md-form-submit">
{saving ? 'Saving…' : submitText}
</Button>
</div>
)}
</div>
);
};