diff --git a/.changeset/35940-master-detail-form-new-lines.md b/.changeset/35940-master-detail-form-new-lines.md new file mode 100644 index 00000000000..fbb21100687 --- /dev/null +++ b/.changeset/35940-master-detail-form-new-lines.md @@ -0,0 +1,19 @@ +--- +'@object-ui/plugin-form': patch +'@object-ui/fields': patch +'@object-ui/app-shell': patch +'@object-ui/i18n': patch +--- + +fix(form): a new detail line on a master-detail create / edit form starts on the child's defaults, does not read red before a save is tried, and a line added and left untouched is skipped with a notice on the form and the record page + +Clause-②: no +Metadata-protocol: none + +On a parent object's create or edit form, a line added to a detail table started blank, so a required column with a default (a status that defaults to "Pending") read red at once although saving would store the default. The record page's edit state already started its new lines on their defaults; the form now does the same. + +**New lines on the form.** A new line starts on the child object's static defaults, the values a create form of the child seeds, whether it is added with Add or with Enter on the last line. A default the server resolves at insert (`NOW()`, a CEL expression) is left to the server. A new line's empty required cell reads red once a save of the form was tried, not the moment the line appears; a stored line is flagged as before. A line added with Add and then applied from the row editor is the user's input and is saved. + +**A line added and left untouched** (maintainer ruling, card comment 7056413638: 「跳过并提示未保存」). A line Add started on its defaults that nobody edited holds only those defaults. It is still not written, and the save now says so: once the save lands, the form and the record page's edit state show "1 blank line was not saved" (or "N blank lines were not saved"), also when the host supplies its own save confirmation. Such a line never reads red, before or after a refused save, since there is nothing in it to fix; once the user edits any of its cells it is input, saved and flagged like any other new line. On an edit form that stays open after saving, the skipped line leaves with the save, as it does on the record page. A line the user typed into and then cleared is blank and is skipped as before, without the notice. The pack key is `form.lineItems.untouchedNotSaved`, in every built-in locale. + +**Seeding context.** The defaults on both the form and the record page's edit state are now read with the session facts a create form uses: a child field defaulted to the acting user starts on that user, and the organization's currency and time zone seed the fields they seed on a create form. With no known user that field starts empty and the server fills it, as before. diff --git a/ui/e2e/live/record-page-polish-35745.spec.ts b/ui/e2e/live/record-page-polish-35745.spec.ts index 5efa6c9fdde..4a33f2da279 100644 --- a/ui/e2e/live/record-page-polish-35745.spec.ts +++ b/ui/e2e/live/record-page-polish-35745.spec.ts @@ -12,7 +12,8 @@ import { test, expect, type Page } from '@playwright/test'; * 3. in the edit state Save is the one filled button, after Cancel; * 4. a line added to the Expense Lines table starts on the child object's * defaults (Category "Other", Status "Submitted") with no cell flagged - * red, and a line added and left as it came is not stored by the save. + * red, and a line added and left as it came is not stored by the save, + * which says so. * * ⚠️ Layout is the reason this is a Playwright spec: jsdom lays nothing out, * so the 12 px is read here off real boxes. The vitest pins @@ -101,22 +102,27 @@ test('record page polish (#35745, #35816) — showcase Expense Report', async ({ // ── 4. A new line starts on its defaults, unflagged; left as it came, it is not stored. ── const editor = page.locator('[data-body-table-editor]').first(); await editor.scrollIntoViewIfNeeded(); - const lines = editor.locator('tbody tr'); + // A line row, not the empty state's row (an empty grid draws one). + const lines = editor.locator('tbody tr').filter({ hasNot: page.getByTestId('line-items-empty') }); const before = await lines.count(); await editor.getByTestId('line-items-add').click(); await expect(lines).toHaveCount(before + 1); - // The grid keeps a trailing entry line, so the added line is the one before it. - const added = lines.nth(before - 1); + const added = lines.nth(before); await expect(added).toContainText('Other'); await expect(added).toContainText('Submitted'); await expect(editor.locator('[data-testid^="line-items-invalid"]')).toHaveCount(0); await save.click(); await expect(toolbar.getByRole('button', { name: 'Edit', exact: true })).toBeVisible({ timeout: 15_000 }); - const stored = await request.get(`${API}/api/v1/data/${LINE}?$top=500`); + // objectstack#35940 (ruling 7056413638): the save says the line was left out. + await expect(page.getByText('1 blank line was not saved')).toBeVisible(); + // Asked of the server for this report's lines only: a filter the route + // ignored would answer other reports' lines, and fail the count. + const ofThisReport = encodeURIComponent(JSON.stringify([['expense_report', 'equals', id]])); + const stored = await request.get(`${API}/api/v1/data/${LINE}?$filter=${ofThisReport}`); expect(stored.ok(), await stored.text()).toBeTruthy(); const body = await stored.json(); - const rows: any[] = (body.records ?? body.data ?? []).filter((r: any) => r.expense_report === id); + const rows: any[] = body.records ?? body.data ?? []; expect(rows, 'an added line left on its defaults is not stored').toHaveLength(0); } finally { await request.delete(`${API}/api/v1/data/${OBJECT}/${encodeURIComponent(id)}`); diff --git a/ui/package.json b/ui/package.json index d322e082bc9..2d1369cf83f 100644 --- a/ui/package.json +++ b/ui/package.json @@ -110,7 +110,7 @@ "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", "test:e2e:live": "playwright test --config=playwright.live.config.ts", - "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts", + "test:e2e:live:ci": "playwright test --config=playwright.live.config.ts screen-flow.spec.ts action-modal.spec.ts master-detail.spec.ts saved-view-filter.spec.ts studio-object-designer.spec.ts studio-editor.spec.ts record-form-direct-url.spec.ts list-row-action-cel.spec.ts studio-customize-journey.spec.ts record-page-polish-35745.spec.ts", "test:e2e:live:nightly": "playwright test --config=playwright.live.config.ts cascading-options.spec.ts declared-sharing-rules-reach-13091.spec.ts field-conditional-rules.spec.ts form-view-subforms.spec.ts grid-conditional-rules.spec.ts grid-file-upload.spec.ts grid-parent-rules.spec.ts inline-edit-polish-2572.spec.ts read-only-member-record.spec.ts record-history-display.spec.ts required-when-submit.spec.ts summary-rollup.spec.ts user-filters.spec.ts phone-nav-drawer-back-29131.spec.ts", "test:e2e:import-console": "playwright test --config=playwright.import-console.config.ts" }, 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 af35e27ffac..1ced4d09113 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.harness.test.tsx @@ -48,6 +48,7 @@ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest'; import { render, waitFor, cleanup, screen, act, fireEvent } from '@testing-library/react'; import { MemoryRouter, Route, Routes, BrowserRouter } from 'react-router-dom'; +import { toast } from 'sonner'; import { RelatedCountStore } from '@object-ui/components'; import { ComponentRegistry } from '@object-ui/core'; import { I18nProvider, LocalizationProvider, createI18n } from '@object-ui/i18n'; @@ -2941,7 +2942,8 @@ describe('RecordDetailView.recordEditState-35599', () => { showcase_task: [{ id: 't1', subject: 'Call', quote: RECORD_ID }], }; - function renderPage(objects: ReturnType, opts: { emptyTables?: boolean } = {}) { + /** `i18n`: under the real English provider, so a notice reads as the pack writes it. */ + function renderPage(objects: ReturnType, opts: { emptyTables?: boolean; i18n?: boolean } = {}) { const metadata = { objects, pages: [], loading: false, error: null, refresh: async () => {}, invalidate: () => {}, @@ -2960,7 +2962,7 @@ describe('RecordDetailView.recordEditState-35599', () => { batchTransaction: vi.fn(async (ops: unknown[]) => ({ results: ops.map(() => ({})) })), }; const onEdit = vi.fn(); - const view = render( + const page = ( @@ -2973,7 +2975,12 @@ describe('RecordDetailView.recordEditState-35599', () => { - , + + ); + const view = render( + opts.i18n + ? {page} + : page, ); return { ...view, dataSource, onEdit }; } @@ -3196,6 +3203,36 @@ describe('RecordDetailView.recordEditState-35599', () => { expect(summaryInput(view.container)).not.toBeNull(); }); + it('objectstack#35940 (ruling 7056413638): a line Add started and nobody edited is not written, and the save says so', async () => { + const view = renderPage(objectsWith(), { i18n: true }); + await enterEditState(view); + vi.mocked(toast.info).mockClear(); + fireEvent.change(summaryInput(view.container)!, { target: { value: 'Second' } }); + const lines = editor(view.container, 'showcase_line.quote')!; + const before = cells(lines, 'Product').length; + fireEvent.click(lines.querySelector('[data-testid="line-items-add"]') as HTMLElement); + await waitFor(() => expect(cells(lines, 'Product').length).toBe(before + 1), { timeout: 5000 }); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + // The record's update alone: the untouched line is not created. + const ops = view.dataSource.batchTransaction.mock.calls[0][0] as Array>; + expect(ops.map((o) => [o.object, o.action])).toEqual([[PARENT, 'update']]); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(toast.info).toHaveBeenCalledTimes(1); + expect(toast.info).toHaveBeenCalledWith('1 blank line was not saved'); + }); + + it('CONTROL — a save that skips no untouched line says nothing more', async () => { + const view = renderPage(objectsWith()); + await enterEditState(view); + vi.mocked(toast.info).mockClear(); + editEverything(view.container); + await act(async () => { fireEvent.click(headerButton('Save')!); }); + await waitFor(() => expect(view.dataSource.batchTransaction).toHaveBeenCalledTimes(1), { timeout: 5000 }); + await waitFor(() => expect(headerButton('Edit')).not.toBeNull(), { timeout: 5000 }); + expect(toast.info).not.toHaveBeenCalled(); + }); + 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 }); diff --git a/ui/packages/app-shell/src/views/RecordDetailView.tsx b/ui/packages/app-shell/src/views/RecordDetailView.tsx index fc1296b2d5f..97bb18fe291 100644 --- a/ui/packages/app-shell/src/views/RecordDetailView.tsx +++ b/ui/packages/app-shell/src/views/RecordDetailView.tsx @@ -5671,6 +5671,7 @@ export function RecordDetailView({ dataSource, objects, onEdit, objectNameOverri bodyTablesReadOnly={bodyTableIds.size > 0 && !bodyTablesEditable} readOnlyNotice={t('detail.bodyTablesReadOnlyBulk')} unsavedMessage={t('form.unsavedChanges')} + untouchedNotSaved={(count) => t('form.lineItems.untouchedNotSaved', { count })} > string; children: React.ReactNode; } @@ -198,6 +205,7 @@ export const RecordEditStateController: React.FC bodyTablesReadOnly, readOnlyNotice, unsavedMessage, + untouchedNotSaved, children, }) => { const inline = useInlineEdit(); @@ -294,12 +302,19 @@ export const RecordEditStateController: React.FC }) : []; const built = buildRecordEditBatch(objectName, String(recordId), draft, tables); + // objectstack#35940 — the lines the batch skips untouched: never written, + // and said so once the save has landed (or had nothing else to write). + const skipped = tables.reduce((n, table) => n + table.rows.filter(isUntouchedNewRow).length, 0); + const sayWhatWasSkipped = () => { + if (skipped > 0) toast.info(untouchedNotSaved(skipped)); + }; // 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(); + sayWhatWasSkipped(); return; } setSaving(true); @@ -312,6 +327,7 @@ export const RecordEditStateController: React.FC await runBatchTransaction(dataSource, ops); } await finish(); + sayWhatWasSkipped(); } catch (err) { const refusal = attributeRecordEditRefusal(err, ops, owners); inline.setFieldErrors(refusal.fieldErrors); @@ -323,7 +339,7 @@ export const RecordEditStateController: React.FC inline.setSaving(false); setSaving(false); } - }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish]); + }, [inline, saving, dataSource, objectName, recordId, bodyTablesEditable, finish, untouchedNotSaved]); const cancel = useCallback(() => { inline?.cancel(); diff --git a/ui/packages/fields/src/widgets/GridField.test.tsx b/ui/packages/fields/src/widgets/GridField.test.tsx index a73d6c11628..8d01d64c1f5 100644 --- a/ui/packages/fields/src/widgets/GridField.test.tsx +++ b/ui/packages/fields/src/widgets/GridField.test.tsx @@ -847,6 +847,46 @@ describe('GridField — a new line starts on its defaults and waits to read red }); }); +describe('GridField — a line Add started on its defaults and nobody edited never reads red (objectstack#35940)', () => { + const taskColumns = { + columns: [ + { name: 'name', label: 'Name', type: 'text' as const, required: true }, + { name: 'status', label: 'Status', type: 'text' as const, required: true }, + ], + } as any; + + it('stays unflagged after the host says a save was refused, while an edited new line is flagged', () => { + const rows = [ + { name: null, status: 'pending', [UNTOUCHED_NEW_ROW]: true }, + { name: null, status: 'done' }, + ]; + render( {}} field={taskColumns} newRowValues={{ status: 'pending' }} newRowRequiredShown />); + expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull(); + expect(screen.getByTestId('line-items-invalid-1-name')).toBeTruthy(); + }); + + it('a line Enter appends on the last line starts on the defaults and is marked untouched, as Add\'s is', () => { + const onChange = vi.fn(); + render(); + fireEvent.keyDown(screen.getByDisplayValue('done'), { key: 'Enter' }); + const appended = onChange.mock.lastCall![0][1]; + expect(appended).toMatchObject({ status: 'pending' }); + expect(isUntouchedNewRow(appended)).toBe(true); + }); + + it('its first edit makes it input, and from then on it is flagged like any new line', () => { + const onChange = vi.fn(); + const field = { columns: [...taskColumns.columns, { name: 'note', label: 'Note', type: 'text' as const }] } as any; + const rows = [{ name: null, status: 'pending', note: null, [UNTOUCHED_NEW_ROW]: true }]; + const { rerender } = render( + , + ); + fireEvent.change(screen.getAllByDisplayValue('pending')[0], { target: { value: 'done' } }); + rerender(); + expect(screen.getByTestId('line-items-invalid-0-name')).toBeTruthy(); + }); +}); + /** * objectstack#35507 — no blank entry row beside "Add line". The grid used to * append an always-present empty "ghost" line under the data rows; it carried diff --git a/ui/packages/fields/src/widgets/GridField.tsx b/ui/packages/fields/src/widgets/GridField.tsx index 1a5224d841f..44fda94024d 100644 --- a/ui/packages/fields/src/widgets/GridField.tsx +++ b/ui/packages/fields/src/widgets/GridField.tsx @@ -702,7 +702,9 @@ type GridFieldProps = FieldWidgetComponentProps & { * no id) is flagged only while it is `true` (objectstack#35816): a line * the user just added does not read red before the host has tried to save * it, and does once a save was refused. A stored line is flagged as - * before. Absent: every line is flagged at once, as before. */ + * before. Absent: every line is flagged at once, as before. A line still + * marked {@link UNTOUCHED_NEW_ROW} is never flagged (objectstack#35940): + * the host skips it at save. */ newRowRequiredShown?: boolean; /** The help text of each column's child field, by column name * ({@link ColumnHelp}, objectstack#35804): drawn as an info button beside @@ -1698,8 +1700,12 @@ function GridFieldBody({ const required = cellRules(c, row).required; // objectstack#35816 — a new line waits for the host's // word before it reads red; a stored line does not. + // objectstack#35940 — a line Add started on its defaults + // and nobody edited never reads red: the save skips it + // and says so, so there is nothing in it to fix. const newRowWaits = - newRowRequiredShown === false && !isGhost && !rowHasId(row); + (newRowRequiredShown === false && !isGhost && !rowHasId(row)) || + isUntouchedNewRow(row); const invalid = (!isGhost || hostFailedEmpty) && !newRowWaits && diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 70af4a16288..67769631b20 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -233,6 +233,13 @@ const ar = { notLoaded: "لم يتم تحميل بنود هذا السجل.", loadFailed: "تعذّر تحميل البنود", saveFailed: "تعذّر حفظ البنود", + untouchedNotSaved: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_zero: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_one: "لم يُحفظ {{count}} سطر فارغ", + untouchedNotSaved_two: "لم يُحفظ سطران فارغان ({{count}})", + untouchedNotSaved_few: "لم تُحفظ {{count}} أسطر فارغة", + untouchedNotSaved_many: "لم يُحفظ {{count}} سطرًا فارغًا", + untouchedNotSaved_other: "لم يُحفظ {{count}} سطر فارغ", noChildObject: "لم يُكوَّن كائن فرعي لهذه اللوحة: عيّن {{property}} إلى الكائن الذي تسرد صفوفه.", }, keepEditing: "متابعة التحرير", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 7e99247e5ca..f090a90eb7a 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -219,6 +219,9 @@ const de = { notLoaded: "Die Positionen dieses Datensatzes wurden nicht geladen.", loadFailed: "Positionen konnten nicht geladen werden", saveFailed: "Positionen konnten nicht gespeichert werden", + untouchedNotSaved: "{{count}} leere Position wurde nicht gespeichert", + untouchedNotSaved_one: "{{count}} leere Position wurde nicht gespeichert", + untouchedNotSaved_other: "{{count}} leere Positionen wurden nicht gespeichert", noChildObject: "Für dieses Panel ist kein untergeordnetes Objekt konfiguriert: Setzen Sie {{property}} auf das Objekt, dessen Zeilen es auflistet.", }, keepEditing: "Weiter bearbeiten", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 13266e90f2a..89dd2914793 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -351,6 +351,12 @@ const en = { notLoaded: 'This record’s line items have not been loaded.', loadFailed: 'Failed to load line items', saveFailed: 'Failed to save line items', + // The notice after a save that skipped lines Add started on their + // defaults and nobody edited (objectstack#35940): the master-detail + // form and the record page's edit state. `{{count}}` is how many. + untouchedNotSaved: '{{count}} blank line was not saved', + untouchedNotSaved_one: '{{count}} blank line was not saved', + untouchedNotSaved_other: '{{count}} blank lines were not saved', noChildObject: 'This panel has no child object configured: set {{property}} to the object whose rows it lists.', }, keepEditing: 'Keep editing', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f06b1b1529d..7dda54c0492 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -226,6 +226,10 @@ const es = { notLoaded: "Las líneas de detalle de este registro no se han cargado.", loadFailed: "No se pudieron cargar las líneas de detalle", saveFailed: "No se pudieron guardar las líneas de detalle", + untouchedNotSaved: "{{count}} línea vacía no se guardó", + untouchedNotSaved_one: "{{count}} línea vacía no se guardó", + untouchedNotSaved_many: "{{count}} de líneas vacías no se guardaron", + untouchedNotSaved_other: "{{count}} líneas vacías no se guardaron", noChildObject: "Este panel no tiene configurado ningún objeto secundario: establezca {{property}} en el objeto cuyas filas enumera.", }, keepEditing: "Seguir editando", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 749a7bfda0e..c4902c71399 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -221,6 +221,10 @@ const fr = { notLoaded: "Les lignes de cet enregistrement n'ont pas été chargées.", loadFailed: "Échec du chargement des lignes", saveFailed: "Échec de l'enregistrement des lignes", + untouchedNotSaved: "{{count}} ligne vide n’a pas été enregistrée", + untouchedNotSaved_one: "{{count}} ligne vide n’a pas été enregistrée", + untouchedNotSaved_many: "{{count}} de lignes vides n’ont pas été enregistrées", + untouchedNotSaved_other: "{{count}} lignes vides n’ont pas été enregistrées", noChildObject: "Aucun objet enfant n'est configuré pour ce panneau : définissez {{property}} sur l'objet dont il liste les lignes.", }, keepEditing: "Continuer l'édition", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 9ff01af1738..d7e8dad1023 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -219,6 +219,9 @@ const ja = { notLoaded: "このレコードの明細行は読み込まれていません。", loadFailed: "明細行の読み込みに失敗しました", saveFailed: "明細行の保存に失敗しました", + untouchedNotSaved: "空白の明細行 {{count}} 行は保存されませんでした", + untouchedNotSaved_one: "空白の明細行 {{count}} 行は保存されませんでした", + untouchedNotSaved_other: "空白の明細行 {{count}} 行は保存されませんでした", noChildObject: "このパネルには子オブジェクトが設定されていません。{{property}} に、行を一覧表示するオブジェクトを設定してください。", }, keepEditing: "編集を続ける", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 7136511d607..e6591ce415d 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -219,6 +219,9 @@ const ko = { notLoaded: "이 레코드의 라인 항목을 불러오지 않았습니다.", loadFailed: "라인 항목을 불러오지 못했습니다", saveFailed: "라인 항목을 저장하지 못했습니다", + untouchedNotSaved: "빈 명세 행 {{count}}개는 저장되지 않았습니다", + untouchedNotSaved_one: "빈 명세 행 {{count}}개는 저장되지 않았습니다", + untouchedNotSaved_other: "빈 명세 행 {{count}}개는 저장되지 않았습니다", noChildObject: "이 패널에 하위 개체가 구성되지 않았습니다. {{property}}을(를) 행을 나열할 개체로 설정하세요.", }, keepEditing: "계속 편집", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 0d1c9c34747..08f53f0f727 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -221,6 +221,10 @@ const pt = { notLoaded: "Os itens de linha deste registro não foram carregados.", loadFailed: "Falha ao carregar os itens de linha", saveFailed: "Falha ao salvar os itens de linha", + untouchedNotSaved: "{{count}} linha em branco não foi salva", + untouchedNotSaved_one: "{{count}} linha em branco não foi salva", + untouchedNotSaved_many: "{{count}} de linhas em branco não foram salvas", + untouchedNotSaved_other: "{{count}} linhas em branco não foram salvas", noChildObject: "Este painel não tem nenhum objeto filho configurado: defina {{property}} como o objeto cujas linhas ele lista.", }, keepEditing: "Continuar editando", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index ef52983f948..64bade87a86 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -226,6 +226,11 @@ const ru = { notLoaded: "Позиции этой записи не загружены.", loadFailed: "Не удалось загрузить позиции", saveFailed: "Не удалось сохранить позиции", + untouchedNotSaved: "{{count}} пустая строка не сохранена", + untouchedNotSaved_one: "{{count}} пустая строка не сохранена", + untouchedNotSaved_few: "{{count}} пустые строки не сохранены", + untouchedNotSaved_many: "{{count}} пустых строк не сохранено", + untouchedNotSaved_other: "{{count}} пустой строки не сохранено", noChildObject: "Для этой панели не настроен дочерний объект: укажите в {{property}} объект, строки которого она выводит.", }, keepEditing: "Продолжить редактирование", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index 7288c069e0d..20108ae57d6 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -231,6 +231,9 @@ const zh = { notLoaded: '此记录的明细行尚未加载。', loadFailed: '明细行加载失败', saveFailed: '明细行保存失败', + untouchedNotSaved: '{{count}} 行空白明细未保存', + untouchedNotSaved_one: '{{count}} 行空白明细未保存', + untouchedNotSaved_other: '{{count}} 行空白明细未保存', noChildObject: '此面板未配置子对象:请将 {{property}} 设为其所列行所属的对象。', }, keepEditing: '继续编辑', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 33893d18585..feb7b0521af 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -231,6 +231,9 @@ const zhHant = { notLoaded: '此記錄的明細行尚未載入。', loadFailed: '明細行載入失敗', saveFailed: '明細行儲存失敗', + untouchedNotSaved: '{{count}} 行空白明細未儲存', + untouchedNotSaved_one: '{{count}} 行空白明細未儲存', + untouchedNotSaved_other: '{{count}} 行空白明細未儲存', noChildObject: '此面板未配置子物件:請將 {{property}} 設為其所列行所屬的物件。', }, keepEditing: '繼續編輯', diff --git a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx index dbcc112782a..473e762e828 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.test.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.test.tsx @@ -1,7 +1,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; -import { render, screen, waitFor, fireEvent } from '@testing-library/react'; +import { act, render, screen, waitFor, fireEvent, within } from '@testing-library/react'; import React from 'react'; import { registerAllFields } from '@object-ui/fields'; +import { MePermissionsProvider } from '@object-ui/permissions'; import { MasterDetailForm } from './MasterDetailForm'; // Capture toast calls so we can assert the form is never a silent no-op. @@ -17,14 +18,14 @@ import { MasterDetailForm } from './MasterDetailForm'; // single surviving raiser, and only the deep-module mock can see it — the // same reason `MasterDetailForm.outcomeToastSupersede.test.tsx` (#7345) // already mocks this exact path. -const { toastSuccess, toastError } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn() })); +const { toastSuccess, toastError, toastInfo } = vi.hoisted(() => ({ toastSuccess: vi.fn(), toastError: vi.fn(), toastInfo: vi.fn() })); vi.mock('@object-ui/components/ui/sonner', async (orig) => { const actual = await (orig as any)(); // Inherit the real toast surface and override only what this file asserts: // a hand-listed double freezes sonner's methods at whatever was typed that // day, and the next one the form calls (`dismiss`, objectui#7345) resolves // to undefined — the `check:vi-mock-inherit` defect, one level down. - return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError } }; + return { ...actual, toast: { ...actual.toast, success: toastSuccess, error: toastError, info: toastInfo } }; }); registerAllFields(); @@ -352,6 +353,177 @@ describe('MasterDetailForm — showSubmit gate (Studio screen preview)', () => { }); }); +describe('MasterDetailForm — a new line starts on the child\'s defaults and waits to read red (objectstack#35940)', () => { + const USER_ID = 'user-42'; + // `name` is required with no default; `note` is required with one; + // `applicant` defaults to the acting user, which only a known session can seed. + const lineSchema = { + name: 'po_line', + fields: { + name: { type: 'text', label: 'Name', required: true }, + note: { type: 'text', label: 'Note', required: true, defaultValue: 'Pending' }, + applicant: { type: 'user', label: 'Applicant', defaultValue: 'current_user' }, + po: { type: 'master_detail', label: 'PO', reference: 'po' }, + }, + }; + const ME_PERMISSIONS = { + authenticated: true, + userId: USER_ID, + tenantId: 't1', + roles: ['user'], + permissionSets: [], + objects: { '*': { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true } }, + fields: {}, + }; + const columns = [ + { name: 'name', label: 'Name', type: 'text', required: true }, + { name: 'note', label: 'Note', type: 'text', required: true }, + ]; + const lineDataSource = (overrides: any = {}) => + makeDataSource({ + getObjectSchema: vi.fn(async (name: string) => (name === 'po_line' ? lineSchema : parentSchema)), + ...overrides, + }); + const schemaWith = (detail: Record = {}, extra: Record = {}) => + ({ + objectName: 'po', + mode: 'create', + fields: ['ref'], + details: [{ childObject: 'po_line', relationshipField: 'po', columns, ...detail }], + ...extra, + }) as any; + const cell = (container: HTMLElement, row: number, col: number) => + container.querySelector(`[data-cell="${row}-${col}"]`) as HTMLInputElement | null; + const lineCount = (container: HTMLElement) => container.querySelectorAll('[data-testid="line-items"] tbody tr').length; + /** Add a line once the child schema (and so its defaults) has answered, and see it start on them. */ + const addSeededLine = async (container: HTMLElement, linesBefore = 0) => { + await screen.findByTestId('line-items-add'); + await act(async () => { await new Promise((resolve) => setTimeout(resolve, 0)); }); + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(lineCount(container)).toBe(linesBefore + 1)); + await waitFor(() => expect(cell(container, linesBefore, 1)?.value).toBe('Pending')); + }; + const createOps = (batch: ReturnType) => + (batch.mock.calls[0][0] as Array<{ object: string; action: string; data?: Record }>).filter( + (op) => op.object === 'po_line' && op.action === 'create', + ); + + it('an added line shows the defaults and no red cell; once a save is tried its empty required cell reads red', async () => { + const batchTransaction = vi.fn().mockRejectedValue(new Error('Name is required')); + const { container } = render(); + await addSeededLine(container); + expect(cell(container, 0, 1)!.value).toBe('Pending'); + // An edit to another cell: the line is the user's input, its Name still empty. + fireEvent.change(cell(container, 0, 1)!, { target: { value: 'Later' } }); + expect(container.querySelector('[data-testid^="line-items-invalid-"]')).toBeNull(); + + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-0-name')).toBeInTheDocument()); + // The cell with a default is filled, so it is never flagged. + expect(screen.queryByTestId('line-items-invalid-0-note')).toBeNull(); + }); + + it('CONTROL: a stored line\'s empty required cell is flagged at once, as before', async () => { + const ds = lineDataSource({ + find: vi.fn().mockResolvedValue({ data: [{ id: 'l1', po: 'p1', name: null, note: 'x' }] }), + findOne: vi.fn().mockResolvedValue({ id: 'p1', ref: 'PO-1' }), + }); + render(); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-0-name')).toBeInTheDocument()); + }); + + it('the line is written with its defaults, the acting user included (the context a create form seeds with)', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }, { id: 'l1' }] }); + const { container } = render( + + + , + ); + await addSeededLine(container); + fireEvent.change(cell(container, 0, 0)!, { target: { value: 'Bolts' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([ + expect.objectContaining({ data: expect.objectContaining({ name: 'Bolts', note: 'Pending', applicant: USER_ID }) }), + ]); + }); + + it('a line Add started and the row editor then applied is input, and is written', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }, { id: 'l1' }] }); + const { container } = render( + , + ); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('line-items-expand-0')); + const editor = await waitFor(() => screen.getByTestId('md-row-form')); + const name = await waitFor(() => { + const el = editor.querySelector('input[name="name"]') as HTMLInputElement | null; + if (!el) throw new Error('row editor not ready'); + return el; + }); + // Typed in the editor, not in the grid: only Apply carries it to the line, + // and a line still marked untouched would be skipped whatever it holds. + fireEvent.change(name, { target: { value: 'Washers' } }); + fireEvent.click(within(editor).getByRole('button', { name: 'Apply' })); + await waitFor(() => expect(screen.queryByTestId('md-row-form')).toBeNull()); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(batchTransaction).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([ + expect.objectContaining({ data: expect.objectContaining({ name: 'Washers', note: 'Pending' }) }), + ]); + }); + describe('ruling 7056413638: a line Add started and nobody edited is skipped, said so, and never red', () => { + beforeEach(() => toastInfo.mockClear()); + + it('create: the line is not written, the save says so, and a host onSuccess still hears the rest', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'po1' }] }); + const onSuccess = vi.fn(); + const { container } = render( + , + ); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(onSuccess).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([]); + expect(toastInfo).toHaveBeenCalledTimes(1); + expect(toastInfo.mock.calls[0][0]).toBe('1 blank line was not saved'); + }); + + it('a refused save flags the edited new line and leaves the untouched one unflagged', async () => { + const batchTransaction = vi.fn().mockRejectedValue(new Error('Name is required')); + const { container } = render(); + await addSeededLine(container); + fireEvent.click(screen.getByTestId('line-items-add')); + await waitFor(() => expect(lineCount(container)).toBe(2)); + fireEvent.change(cell(container, 1, 1)!, { target: { value: 'Later' } }); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(screen.getByTestId('line-items-invalid-1-name')).toBeInTheDocument()); + expect(screen.queryByTestId('line-items-invalid-0-name')).toBeNull(); + expect(toastInfo).not.toHaveBeenCalled(); + }); + + it('edit: the skipped line leaves with the save, as on the record page', async () => { + const batchTransaction = vi.fn().mockResolvedValue({ results: [{ id: 'p1' }] }); + const ds = lineDataSource({ + batchTransaction, + find: vi.fn().mockResolvedValue({ data: [{ id: 'l1', po: 'p1', name: 'Nuts', note: 'x' }] }), + findOne: vi.fn().mockResolvedValue({ id: 'p1', ref: 'PO-1' }), + }); + const { container } = render(); + await waitFor(() => expect(cell(container, 0, 0)?.value).toBe('Nuts')); + await addSeededLine(container, 1); + fireEvent.click(screen.getByTestId('md-form-submit')); + await waitFor(() => expect(toastInfo).toHaveBeenCalledTimes(1)); + expect(createOps(batchTransaction)).toEqual([]); + await waitFor(() => expect(lineCount(container)).toBe(1)); + expect(cell(container, 0, 0)!.value).toBe('Nuts'); + }); + }); +}); + /** * objectstack#35804 — the line grid's column headers show each child field's * help, read from the child object's definition as `getObjectSchema` serves diff --git a/ui/packages/plugin-form/src/MasterDetailForm.tsx b/ui/packages/plugin-form/src/MasterDetailForm.tsx index 657734d901c..e48202c8b4f 100644 --- a/ui/packages/plugin-form/src/MasterDetailForm.tsx +++ b/ui/packages/plugin-form/src/MasterDetailForm.tsx @@ -33,7 +33,7 @@ import React, { startTransition, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react'; import type { BatchTransactionOperation, DataSource, GridFieldMetadata, I18nLabel } from '@object-ui/types'; import { resolveAffordance, runBatchTransaction } from '@object-ui/core'; -import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; +import { isUntouchedNewRow, LineItemsField, lookupAutofillByField, columnHelpByField, UNTOUCHED_NEW_ROW, useBooleanValueLabel, type BooleanValueLabel, type ColumnHelp, type GridColumn, type LookupAutofillByField } from '@object-ui/fields'; import { Button, Card, CardContent, CardHeader, CardTitle, cn, toast } from '@object-ui/components'; import { formatDisplayNumber, @@ -64,6 +64,7 @@ import { isSameStoredValue } from './sanitize'; import { resolveInitialRecord } from './initialRecord'; import { sectionEntryName } from './sectionFields'; import { deriveDetail } from './deriveMasterDetail'; +import { schemaDefaultValues } from './schemaDefaults'; import { parentCurrencyFieldsOf, followedColumnCurrencies } from './parentCurrencyColumns'; // objectui#11428 — the per-row form's offer test is the spec's rule. import { isInlineRowFormOffered } from '@objectstack/spec/data'; @@ -826,6 +827,16 @@ function withCodeHoles(sentence: string, holes: Record): Record { + const { [UNTOUCHED_NEW_ROW]: _untouched, ...rest } = row as Record & { [UNTOUCHED_NEW_ROW]?: true }; + return rest; +} + interface MasterDetailLinesProps { entries: DetailEntry[]; /** Row state addressed by ENTRY ID, never by array position (objectui#6371). */ @@ -867,6 +878,19 @@ interface MasterDetailLinesProps { * Remove asks the child's delete grant: a create form's lines are drafts. */ formMode: 'create' | 'edit'; + /** + * The values a new line starts with, by CHILD object name (objectstack#35940): + * the child's static defaults, seeded as a create form seeds them. A child + * whose schema has not answered has no entry, and its new lines start blank. + */ + newRowValuesByChild: Readonly>>; + /** + * A save of this form was tried since the lines were last saved: from then + * on a new line's empty required cell reads red (objectstack#35940). Before + * it, a line the user just added is not flagged for a cell they have not + * reached yet. + */ + newRowRequiredShown: boolean; } /** @@ -896,6 +920,8 @@ const MasterDetailLines: React.FC = ({ onAddViaForm, parentObjectName, formMode, + newRowValuesByChild, + newRowRequiredShown, }) => { // The subtotal / tax / grand-total stack formats in the display locale; it // used to pass `toLocaleString` an explicit `undefined`, i.e. the MACHINE's @@ -1134,6 +1160,11 @@ const MasterDetailLines: React.FC = ({ // The columns whose amount follows this header's currency // (ADR-0144 D2 as amended), in the header's live code. columnCurrencies={followedColumnCurrencies(entry.parentCurrencyFields, parentRecord, tenantCurrency)} + // objectstack#35940 — a new line starts on the child's defaults, + // and its empty required cell reads red once a save was tried, + // as on the record page's edit state. + newRowValues={newRowValuesByChild[d.childObject]} + newRowRequiredShown={newRowRequiredShown} // 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 @@ -1485,6 +1516,10 @@ export const MasterDetailForm: React.FC = ({ // never resets — the header (see #1581). Reads happen at submit // time, long after the fetch resolves. const childSchemasRef = useRef }>>({}); + // objectstack#35940 — the same answer for the lines' new-line defaults, which + // are read at render. It lands once, in the render the lines' own load lands + // in, and the header 's props do not depend on it. + const [childSchemas, setChildSchemas] = useState }>>({}); useEffect(() => { const ds: any = dataSource; if (!ds || typeof ds.getObjectSchema !== 'function') return; @@ -1501,11 +1536,34 @@ export const MasterDetailForm: React.FC = ({ const next: Record }> = {}; for (const [obj, sch] of entries) if (sch) next[obj] = sch; childSchemasRef.current = next; + setChildSchemas(next); })(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [dataSource, schema.objectName, schema.details]); + // objectstack#35940 — every new line is a child record to create, so it + // starts on the values a create form of the child seeds: its static + // defaults, with the same session facts `ObjectForm` threads (the acting + // user, the organization's currency and time zone). A default the server + // resolves per insert (`NOW()`, CEL) is left to the server. + const perms = usePermissions(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); + const newRowValuesByChild = useMemo(() => { + const out: Record> = {}; + for (const [childObject, childSchema] of Object.entries(childSchemas)) { + out[childObject] = schemaDefaultValues(childSchema, { currentUserId: perms.userId, homeCurrency, homeTimeZone }); + } + return out; + }, [childSchemas, perms.userId, homeCurrency, homeTimeZone]); + // objectstack#35940 — set when a save is tried, cleared when one lands: a + // new line's empty required cell reads red from the try on. + const [saveTried, setSaveTried] = useState(false); + // objectstack#35940 (ruling 7056413638) — how many lines the batch in flight + // skips because Add started them on their defaults and nobody edited them. + // A save that lands says so; such a line is never written. + const untouchedSkippedRef = useRef(0); + // Bumped after a successful CREATE to remount the parent (which // owns react-hook-form state) so its fields clear for the next entry. const [formKey, setFormKey] = useState(0); @@ -1833,7 +1891,9 @@ export const MasterDetailForm: React.FC = ({ const cur = prev[entryId] ?? { rows: [], original: [] }; return { ...prev, - [entryId]: { ...cur, rows: cur.rows.map((r, j) => (j === rowIdx ? { ...r, ...values } : r)) }, + // An applied editor is input, so the line loses the untouched mark + // an Add on its defaults gave it (objectstack#35940). + [entryId]: { ...cur, rows: cur.rows.map((r, j) => (j === rowIdx ? { ...withoutUntouchedMark(r), ...values } : r)) }, }; }); }, @@ -1879,6 +1939,7 @@ export const MasterDetailForm: React.FC = ({ async (parent: any) => { releaseSave(); setHeaderDirty(false); + setSaveTried(false); if (!schema.onSuccess) { toast.success( isEdit @@ -1887,6 +1948,13 @@ export const MasterDetailForm: React.FC = ({ { id: outcomeToastId }, ); } + // Said whoever owns the confirmation: a host's own toast cannot know + // that lines were left out. + const skipped = untouchedSkippedRef.current; + untouchedSkippedRef.current = 0; + if (skipped > 0) { + toast.info(t('form.lineItems.untouchedNotSaved', { count: skipped }), { id: `form-untouched:${formInstanceId}` }); + } // An edit keeps its rows: `submitViaBatch` has already advanced their // baseline to what this save wrote (objectui#10564). if (!isEdit) { @@ -1899,7 +1967,7 @@ export const MasterDetailForm: React.FC = ({ await schema.onSuccess?.(parent); }, // eslint-disable-next-line react-hooks/exhaustive-deps - [isEdit, schema.onSuccess, titleText, entries.length, releaseSave, outcomeToastId, t], + [isEdit, schema.onSuccess, titleText, entries.length, releaseSave, outcomeToastId, formInstanceId, t], ); /** @@ -1948,6 +2016,9 @@ export const MasterDetailForm: React.FC = ({ async (parentValues: Record) => { if (!dataSource) throw new Error('MasterDetailForm: dataSource is required'); const parentData: Record = { ...parentValues }; + untouchedSkippedRef.current = entries + .filter((e) => e.config.relationshipField) + .reduce((n, e) => n + (rowStateRef.current[e.id]?.rows ?? []).filter(isUntouchedNewRow).length, 0); // Client-side rollups merged into the parent payload (hooks can't do // nested writes — see ADR-0001). entries.forEach((e) => { @@ -2020,12 +2091,15 @@ export const MasterDetailForm: React.FC = ({ // flight (objectui#10631), so every such row is still that object. // Were one replaced anyway, it keeps no id: the next save then // deletes the created record and creates the row as it now stands. - const rows = s.createdIds.size === 0 + // A line the save skipped untouched (objectstack#35940) leaves + // with the save, as it does on the record page: it was never + // written, and the notice above says so. + const rows = (s.createdIds.size === 0 ? cur.rows : cur.rows.map((r) => { const id = s.createdIds.get(r); return id === undefined ? r : { ...r, id }; - }); + })).filter((r) => !isUntouchedNewRow(r)); next = { ...next, [s.entryId]: { rows, original: s.original } }; } return next; @@ -2055,6 +2129,7 @@ export const MasterDetailForm: React.FC = ({ throw new Error('This save was not sent: another save of this form was still in progress.'); } batchInFlightRef.current = true; + setSaveTried(true); holdSaveForBatch(); try { return await sendBatch(parentValues); @@ -2166,6 +2241,7 @@ export const MasterDetailForm: React.FC = ({ if (!form) return; savingRef.current = true; setSaving(true); + setSaveTried(true); // The previous attempt's outcome belongs to the previous attempt: retire it // the moment a new one starts, so no host can confirm a success while this // form's last refusal is still on screen (objectui#7345). @@ -2221,6 +2297,8 @@ export const MasterDetailForm: React.FC = ({ onAddViaForm={addRowViaForm} parentObjectName={schema.objectName} formMode={isEdit ? 'edit' : 'create'} + newRowValuesByChild={newRowValuesByChild} + newRowRequiredShown={saveTried} /> {/* Per-row "expand to full form": an inline editor panel for the selected diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx new file mode 100644 index 00000000000..8d17da82dd7 --- /dev/null +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.seedContext-35940.test.tsx @@ -0,0 +1,94 @@ +/** + * 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 body-table editor seeds a new line with the values a + * create form of the child seeds (objectstack#35940): its static defaults, and + * the session facts `ObjectForm` threads, so a field defaulted to the acting + * user starts on that user. CONTROL: with no known user that field starts + * empty and is left to the server, as on a create form. + */ + +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { RecordContextProvider } from '@object-ui/react'; +import { MePermissionsProvider } from '@object-ui/permissions'; +import { registerAllFields } from '@object-ui/fields'; +import { + RecordBodyTableEditor, + RecordEditSessionContext, + type BodyTableEditHandle, + type RecordEditSession, +} from './RecordBodyTableEditor'; + +registerAllFields(); +afterEach(() => cleanup()); + +const USER_ID = 'user-42'; + +const TASK_SCHEMA = { + name: 'meeting_task', + fields: { + name: { type: 'text', label: 'Name', required: true }, + status: { type: 'text', label: 'Status', required: true, defaultValue: 'pending' }, + assignee: { type: 'user', label: 'Assignee', defaultValue: 'current_user' }, + meeting: { type: 'master_detail', label: 'Meeting', reference: 'meeting' }, + }, +}; + +const ME_PERMISSIONS = { + authenticated: true, + userId: USER_ID, + tenantId: 't1', + roles: ['user'], + permissionSets: [], + objects: { '*': { allowCreate: true, allowRead: true, allowEdit: true, allowDelete: true } }, + fields: {}, +}; + +function mount(withUser: boolean) { + const ds = { + getObjectSchema: vi.fn(async () => TASK_SCHEMA), + find: vi.fn(async () => ({ data: [] })), + onMutation: () => () => {}, + }; + let handle: BodyTableEditHandle | null = null; + const session: RecordEditSession = { + register: (h) => { + handle = h; + return () => { handle = null; }; + }, + reportDirty: () => {}, + saving: false, + }; + const editor = ( + + + + + + ); + render(withUser ? {editor} : editor); + return { rows: () => (handle as BodyTableEditHandle | null)?.snapshot()?.rows ?? null }; +} + +describe('RecordBodyTableEditor — a new line seeds what a create form seeds (objectstack#35940)', () => { + it('a field defaulted to the acting user starts on that user, beside the static defaults', async () => { + const { rows } = mount(true); + fireEvent.click(await screen.findByTestId('line-items-add')); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(rows()![0]).toMatchObject({ status: 'pending', assignee: USER_ID }); + }); + + it('CONTROL: with no known user the field starts empty, left to the server', async () => { + const { rows } = mount(false); + fireEvent.click(await screen.findByTestId('line-items-add')); + await waitFor(() => expect(rows()).toHaveLength(1)); + expect(rows()![0]).toMatchObject({ status: 'pending' }); + expect(rows()![0].assignee ?? null).toBeNull(); + }); +}); diff --git a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx index cfd6caa7381..347ff290009 100644 --- a/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx +++ b/ui/packages/plugin-form/src/RecordBodyTableEditor.tsx @@ -39,6 +39,7 @@ import type { BatchTransactionOperation, GridFieldMetadata } from '@object-ui/ty import { resolveAffordance, type SchemaLike } from '@object-ui/core'; import { LineItemsField, lookupAutofillByField, columnHelpByField, useBooleanValueLabel, type GridColumn } from '@object-ui/fields'; import { cn } from '@object-ui/components'; +import { useLocalization } from '@object-ui/i18n'; import { usePermissions } from '@object-ui/permissions'; import { extractFieldErrors, @@ -213,6 +214,7 @@ export const RecordBodyTableEditor: React.FC = ({ ob const parentObject = record?.objectName; const parentId = record?.recordId; const perms = usePermissions(); + const { currency: homeCurrency, timezone: homeTimeZone } = useLocalization(); const { t } = useFormChromeTranslation(); const booleanLabel = useBooleanValueLabel(); const booleanTrue = booleanLabel(true); @@ -271,10 +273,16 @@ export const RecordBodyTableEditor: React.FC = ({ ob // defaults, the values a create form seeds (`schemaDefaultValues`), so a // required column with a default is filled instead of flagged empty. A // default the server resolves per insert (`NOW()`, a CEL expression) is not - // seeded; the server fills it as it fills an omitted field. + // seeded; the server fills it as it fills an omitted field. The session + // facts are the ones `ObjectForm` threads (objectstack#35940): the acting + // user, the organization's currency and time zone. Until the child schema + // answers there are no defaults, and a new line starts blank. const newRowValues = useMemo( - () => schemaDefaultValues(childSchema as Parameters[0]), - [childSchema], + () => + childSchema + ? schemaDefaultValues(childSchema, { currentUserId: perms.userId, homeCurrency, homeTimeZone }) + : undefined, + [childSchema, perms.userId, homeCurrency, homeTimeZone], ); const snapshotRef = useRef(null); diff --git a/ui/packages/plugin-form/src/formChrome.ts b/ui/packages/plugin-form/src/formChrome.ts index 227e414a407..9cfcbc84f2c 100644 --- a/ui/packages/plugin-form/src/formChrome.ts +++ b/ui/packages/plugin-form/src/formChrome.ts @@ -86,6 +86,11 @@ const FORM_CHROME_DEFAULTS = { // loading line, a failed read, and the label of a refused line. 'common.loading': 'Loading…', 'form.lineItems.loadFailed': 'Failed to load line items', + // The notice after a save that skipped lines nobody edited since Add started + // them on their defaults (objectstack#35940). + 'form.lineItems.untouchedNotSaved': '{{count}} blank line was not saved', + 'form.lineItems.untouchedNotSaved_one': '{{count}} blank line was not saved', + 'form.lineItems.untouchedNotSaved_other': '{{count}} blank lines were not saved', 'detail.bodyTableRow': 'Row {{row}}', };