diff --git a/.changeset/33557-grid-conflict-fields-summary-footer-scale.md b/.changeset/33557-grid-conflict-fields-summary-footer-scale.md new file mode 100644 index 00000000000..09c870ed4be --- /dev/null +++ b/.changeset/33557-grid-conflict-fields-summary-footer-scale.md @@ -0,0 +1,13 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/fields': patch +--- + +fix(plugin-grid): a multi-field row conflict lists each field, and a summary column's footer total is formatted as its cells + +Clause-②: yes (widening) — `@object-ui/fields` gains the export `summaryDeclaresCurrency`; nothing is removed or narrowed, and the `@object-ui/plugin-grid` changes are internal. +Metadata-protocol: none + +**Row save conflicts in the grid.** A row save that changed several fields and met a newer version (409 `CONCURRENT_UPDATE`) opened the conflict dialog with your edit and the current value printed as two raw JSON objects. The dialog now lists each changed field on its own row, under its column header, with your edit and the current value. A one-field conflict looks as before. + +**The list footer total of a roll-up (`summary`) field.** The total ignored the field's `scale`, so a summary with `scale: 2` read "Paid 230,000" beside a currency column's "215,000.00". The footer now formats a summary's total the way the list cell draws the same field: as money when the summary declares its currency (`currencyConfig`), else as a number at its declared `scale`. A summary that declares neither keeps its plain total. Money follows the summary's own `currencyConfig`, not the type of the field it sums, as the spec states and as the cell already draws it. diff --git a/ui/packages/fields/src/index.tsx b/ui/packages/fields/src/index.tsx index 855f918219d..7e7cc7490f0 100644 --- a/ui/packages/fields/src/index.tsx +++ b/ui/packages/fields/src/index.tsx @@ -575,7 +575,9 @@ function isPlainObjectValue(value: unknown): value is Record { import { resolveFieldCurrency, summaryDeclaresCurrency } from './currency.js'; export { withFollowedParentObject, FOLLOWED_PARENT_OBJECT_KEY } from './currency.js'; import { HomeAmountHint } from './widgets/CurrencyField.js'; -export { resolveFieldCurrency }; +// `summaryDeclaresCurrency` is the cell's own test for drawing a roll-up as +// money; the grid footer formats the same field's total by it. +export { resolveFieldCurrency, summaryDeclaresCurrency }; /** * `formatCurrency` lives beside `formatNumberFieldValue` in diff --git a/ui/packages/plugin-grid/src/ObjectGrid.tsx b/ui/packages/plugin-grid/src/ObjectGrid.tsx index bbcc42ed08c..7c4d76f5dbd 100644 --- a/ui/packages/plugin-grid/src/ObjectGrid.tsx +++ b/ui/packages/plugin-grid/src/ObjectGrid.tsx @@ -2289,7 +2289,8 @@ export const ObjectGrid: React.FC = ({ /** * The dialog's payload for one row's 409, in the shape `InlineEditSaveBar` * builds for a record's draft: one edited field shows its own before and - * after, several show the record-level summary. + * after; several list each field (`fields`) with its column header and both + * values, so the dialog never prints the draft map as raw JSON. */ const buildRowConflict = ( changes: Record, @@ -2315,6 +2316,12 @@ export const ObjectGrid: React.FC = ({ currentValue: current ? Object.fromEntries(keys.map((k) => [k, current[k]])) : undefined, currentVersion: err.currentVersion, currentRecord: current, + fields: keys.map((k) => ({ + field: k, + label: columnHeaderOf(k), + pendingValue: changes[k], + currentValue: current ? current[k] : undefined, + })), }; }; diff --git a/ui/packages/plugin-grid/src/__tests__/footerSummaryFieldScale-33542.test.tsx b/ui/packages/plugin-grid/src/__tests__/footerSummaryFieldScale-33542.test.tsx new file mode 100644 index 00000000000..eea4cb4c098 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/footerSummaryFieldScale-33542.test.tsx @@ -0,0 +1,146 @@ +/** + * 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. + */ + +/** + * objectstack#33542 — the footer total of a roll-up (`summary`) column is + * formatted as the list cell draws the same field. + * + * HotCRM's All Invoices footer read "Paid 230,000" for a `Field.summary` with + * `scale: 2`, beside "Open 215,000.00" for a currency field: the footer's + * formatter keyed on the column type, and a `summary` fell to the plain + * default, which never reads `scale`. The served object metadata carries the + * summary's `scale` (measured on the showcase's `showcase_expense_report`). + * + * The cell draws a summary through `FormulaCellRenderer`: as money when the + * summary declares its currency (`currencyConfig`, `summaryDeclaresCurrency`), + * else as a number at its `resolveFieldScale` width. The footer now takes the + * same two arms, the ones a plain `currency` / `number` column takes. + * + * Pinned through the real `ObjectGrid` footer, its field catalogue read from + * the data source's object schema, under a real `I18nProvider` in en and zh-CN: + * + * - a summary with `scale: 2` totals to two decimals; + * - a summary declaring a `fixed` currency totals exactly as a plain currency + * column with the same config does; + * - CONTROL: a summary with no `scale` and no currency keeps today's face. + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, cleanup, waitFor } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectGrid } from '../ObjectGrid'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { installExplainDouble } from './explainDouble'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, I18nProvider } from '@object-ui/react'; + +beforeAll(() => { + registerAllFields(); + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView']; + } +}); +beforeEach(() => { + __clearRecordCrudVerdictCache(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const OBJECT = 'invoice_33542'; + +const CNY = { currencyMode: 'fixed', defaultCurrency: 'CNY' } as const; + +/** The served field catalogue: three roll-ups and a plain currency field. */ +const FIELDS = { + id: { type: 'text', label: 'Id' }, + invoice_number: { type: 'text', label: 'Invoice Number' }, + paid_amount: { + type: 'summary', label: 'Paid', scale: 2, + summaryOperations: { object: 'payment', field: 'amount', function: 'sum' }, + }, + paid_cny: { + type: 'summary', label: 'Paid (CNY)', scale: 2, currencyConfig: CNY, + summaryOperations: { object: 'payment', field: 'amount', function: 'sum' }, + }, + billed_cny: { type: 'currency', label: 'Billed (CNY)', currencyConfig: CNY }, + payment_count: { + type: 'summary', label: 'Payments', + summaryOperations: { object: 'payment', function: 'count' }, + }, +}; + +/** Totals: 230,000 for every amount column, 7 payments. */ +const ROWS = [ + { id: 'i1', invoice_number: 'INV-1', paid_amount: 100000, paid_cny: 100000, billed_cny: 100000, payment_count: 3 }, + { id: 'i2', invoice_number: 'INV-2', paid_amount: 130000, paid_cny: 130000, billed_cny: 130000, payment_count: 4 }, +]; + +function renderGrid(language: 'en' | 'zh-CN') { + const dataSource = { + find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length, hasMore: false, pageSize: 50 })), + getObjectSchema: vi.fn(async (name: string) => ({ name, fields: FIELDS })), + } as any; + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + columns: [ + { field: 'invoice_number', label: 'Invoice Number' }, + { field: 'paid_amount', label: 'Paid', summary: 'sum' }, + { field: 'paid_cny', label: 'Paid (CNY)', summary: 'sum' }, + { field: 'billed_cny', label: 'Billed (CNY)', summary: 'sum' }, + { field: 'payment_count', label: 'Payments', summary: 'sum' }, + ], + pagination: { pageSize: 50 }, + }; + return render( + + + + + , + ); +} + +/** The footer text of a column once the grid has its field catalogue. */ +async function footerOf(field: string): Promise { + const cell = await screen.findByTestId(`summary-${field}`); + return cell.textContent ?? ''; +} + +describe('a summary column footer total is formatted as its cell (objectstack#33542)', () => { + it('en: a summary with scale 2 totals to two decimals', async () => { + renderGrid('en'); + await waitFor(async () => expect(await footerOf('paid_amount')).toContain('Sum: 230,000.00')); + }); + + it('zh-CN: a summary with scale 2 totals to two decimals, under the zh prefix', async () => { + renderGrid('zh-CN'); + await waitFor(async () => expect(await footerOf('paid_amount')).toContain('合计:230,000.00')); + }); + + it.each(['en', 'zh-CN'] as const)('%s: a summary declaring a fixed currency totals as a plain currency column does', async (language) => { + renderGrid(language); + await waitFor(async () => expect(await footerOf('billed_cny')).toMatch(/230,000\.00/)); + const currencyTotal = (await footerOf('billed_cny')).replace(/^.*?:/, ''); + // The plain currency column draws money (a currency sign beside the amount). + expect(currencyTotal).not.toBe('230,000.00'); + expect((await footerOf('paid_cny')).replace(/^.*?:/, '')).toBe(currencyTotal); + }); + + it('CONTROL: a summary with no scale and no currency keeps the plain total', async () => { + renderGrid('en'); + // The catalogue has landed once the plain currency column draws money. + await waitFor(async () => expect(await footerOf('billed_cny')).toMatch(/230,000\.00/)); + expect(await footerOf('payment_count')).toContain('Sum: 7'); + expect(await footerOf('payment_count')).not.toContain('7.0'); + }); +}); diff --git a/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx b/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx new file mode 100644 index 00000000000..ffe41cc79f0 --- /dev/null +++ b/ui/packages/plugin-grid/src/__tests__/inlineEditConflictFields-33557.test.tsx @@ -0,0 +1,216 @@ +/** + * 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. + */ + +/** + * objectstack#33557 — a grid row save that changed several fields and meets a + * newer version (409 `CONCURRENT_UPDATE`) lists each field on the conflict + * dialog, under its column header, with both values. It printed the whole + * draft and the current subset as two raw JSON objects. + * + * The real `ObjectGrid` renders the real `data-table` and the real + * `ConcurrentUpdateDialog`; every write goes through the real + * `@object-ui/data-objectstack` adapter and `@objectstack/client`. Only `fetch` + * is stubbed, by a small server that answers a stale `If-Match` with the 409 + * envelope `@objectstack/types` maps a `ConcurrentUpdateError` to. The cells + * are edited the way a user types them. + * + * CONTROL: a row save that changed one field keeps the one-field face (the + * field's own before and after, no list). + */ +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ObjectStackAdapter } from '@object-ui/data-objectstack'; +import { registerAllFields } from '@object-ui/fields'; +import { ActionProvider, SchemaRendererProvider } from '@object-ui/react'; +import { ObjectGrid } from '../ObjectGrid'; +import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts'; +import { installExplainDouble } from './explainDouble'; + +registerAllFields(); + +beforeAll(() => { + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn() as any; + } +}); + +beforeEach(() => { + __clearRecordCrudVerdictCache(); + installExplainDouble(); +}); +afterEach(() => { + cleanup(); + vi.unstubAllGlobals(); +}); + +const OBJECT = 'task_33557'; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } }); + +/** A store with an `updated_at` per record, refusing a stale `If-Match` with the 409 envelope. */ +function makeServer(seed: Array & { id: string }>) { + let clock = 0; + const stamp = () => `2026-11-15 00:00:${String(++clock).padStart(2, '0')}.000`; + const store: Record> = {}; + for (const row of seed) store[row.id] = { ...row, updated_at: stamp() }; + const statuses: number[] = []; + + const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const url = String(input); + const method = (init?.method ?? 'GET').toUpperCase(); + if (url.endsWith('/api/v1/discovery')) { + return json(200, { success: true, data: { capabilities: {}, routes: {} } }); + } + const match = url.match(/\/api\/v1\/data\/([^/?]+)\/([^/?]+)$/); + if (!match || method !== 'PATCH') throw new Error(`unexpected request ${method} ${url}`); + const [, object, rawId] = match; + const id = decodeURIComponent(rawId); + const ifMatch = ((init?.headers ?? {}) as Record)['If-Match']; + const body = JSON.parse(String(init?.body ?? '{}')) as Record; + const current = store[id]; + if (ifMatch !== undefined && ifMatch !== current.updated_at) { + statuses.push(409); + return json(409, { + error: 'Record was modified by another user', + code: 'CONCURRENT_UPDATE', + currentVersion: current.updated_at, + currentRecord: { ...current }, + object, + }); + } + store[id] = { ...current, ...body, updated_at: stamp() }; + statuses.push(200); + return json(200, { success: true, data: { object, id, record: { ...store[id] } } }); + }); + + const adapter = new ObjectStackAdapter({ baseUrl: 'http://test.local', fetch, autoReconnect: false }); + const project = (row: Record, select: unknown) => + Array.isArray(select) + ? Object.fromEntries(select.filter((k) => k in row).map((k) => [k, row[k]])) + : { ...row }; + + const dataSource = { + find: vi.fn(async (_object: string, params?: { $select?: unknown }) => { + const rows = Object.values(store).map((r) => project(r, params?.$select)); + return { data: rows, total: rows.length, hasMore: false, pageSize: 50 }; + }), + findOne: vi.fn(async (_object: string, id: string) => ({ ...store[id] })), + update: vi.fn((object: string, id: string, data: any, opts?: { ifMatch?: string }) => + adapter.update(object, id, data, opts), + ), + getObjectSchema: vi.fn(async (name: string) => ({ + name, + fields: { + id: { type: 'text' }, + title: { type: 'text', label: 'Title' }, + estimate_hours: { type: 'number', label: 'Estimate' }, + owner_note: { type: 'text', label: 'Owner note' }, + }, + })), + } as any; + + return { + store, + statuses, + dataSource, + writeAsOtherUser(id: string, changes: Record) { + store[id] = { ...store[id], ...changes, updated_at: stamp() }; + }, + }; +} + +function renderGrid(server: ReturnType) { + const schema: any = { + type: 'object-grid', + objectName: OBJECT, + editable: true, + singleClickEdit: true, + columns: [ + { field: 'title', label: 'Title', editable: false }, + { field: 'estimate_hours', label: 'Estimate', type: 'number' }, + { field: 'owner_note', label: 'Owner note' }, + ], + pagination: { pageSize: 50 }, + }; + return render( + + + {}} onDelete={() => {}} /> + + , + ); +} + +const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement; + +/** Stage a new value on the cell of the row titled `title` that reads `from`, the way a user types it. */ +async function editCell(title: string, from: string, to: string) { + const td = await waitFor(() => { + const cell = Array.from(rowOf(title).querySelectorAll('td')).find( + (c) => c.textContent?.trim() === from, + ); + if (!cell) throw new Error(`no ${from} cell on ${title}`); + return cell as HTMLElement; + }); + fireEvent.click(td); + const input = await waitFor(() => { + const el = td.querySelector('input') as HTMLInputElement | null; + if (!el) throw new Error('editor not open'); + return el; + }); + fireEvent.change(input, { target: { value: to } }); + fireEvent.keyDown(input, { key: 'Enter' }); + await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument()); +} + +async function staleRowSave(edits: Array<[from: string, to: string]>) { + const server = makeServer([{ id: 't1', title: 'Ingest pipeline', estimate_hours: 60, owner_note: 'ready' }]); + renderGrid(server); + await waitFor(() => expect(screen.getByText('Ingest pipeline')).toBeInTheDocument()); + server.writeAsOtherUser('t1', { estimate_hours: 77, owner_note: 'blocked' }); + for (const [from, to] of edits) await editCell('Ingest pipeline', from, to); + fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row')); + const dialog = await screen.findByRole('alertdialog'); + expect(server.statuses).toEqual([409]); + return dialog; +} + +describe('a multi-field grid row conflict lists each field (objectstack#33557)', () => { + it('two changed fields + a 409: two rows, each under its column header with both values, no raw JSON', async () => { + const dialog = await staleRowSave([['60', '61'], ['ready', 'shipped']]); + + const rows = within(dialog).getAllByTestId('concurrent-update-field'); + expect(rows.map((r) => r.getAttribute('data-field'))).toEqual(['estimate_hours', 'owner_note']); + + const [estimate, note] = rows; + expect(within(estimate).getByText('Estimate')).toBeInTheDocument(); + expect(within(estimate).getByText('61')).toBeInTheDocument(); + expect(within(estimate).getByText('77')).toBeInTheDocument(); + expect(within(note).getByText('Owner note')).toBeInTheDocument(); + expect(within(note).getByText('shipped')).toBeInTheDocument(); + expect(within(note).getByText('blocked')).toBeInTheDocument(); + + // Neither value is drawn as a serialized object. + expect(dialog.textContent).not.toMatch(/[{}]/); + expect(dialog.textContent).not.toContain('"estimate_hours"'); + }); + + it('CONTROL: one changed field keeps the one-field face (no list), naming the column and both values', async () => { + const dialog = await staleRowSave([['60', '61']]); + + expect(within(dialog).queryByTestId('concurrent-update-field-list')).toBeNull(); + expect(within(dialog).getByText('Estimate')).toBeInTheDocument(); + expect(within(dialog).getByText('61')).toBeInTheDocument(); + expect(within(dialog).getByText('77')).toBeInTheDocument(); + expect(dialog.textContent).not.toMatch(/[{}]/); + }); +}); diff --git a/ui/packages/plugin-grid/src/useColumnSummary.ts b/ui/packages/plugin-grid/src/useColumnSummary.ts index 875f71cb331..7803efa5aef 100644 --- a/ui/packages/plugin-grid/src/useColumnSummary.ts +++ b/ui/packages/plugin-grid/src/useColumnSummary.ts @@ -13,7 +13,7 @@ import { deriveColumnSummary } from '@objectstack/spec/ui'; import type { CurrencyConfig } from '@objectstack/spec/data'; import { resolveFieldScale } from '@objectstack/spec/data'; import { useLocalization, useDisplayLocale, resolveFieldCurrency, recordCurrencyField, createSafeTranslation } from '@object-ui/i18n'; -import { formatCurrency, formatPercent, percentCellScale } from '@object-ui/fields'; +import { formatCurrency, formatPercent, percentCellScale, summaryDeclaresCurrency } from '@object-ui/fields'; import { temporalCellFaceOf, temporalCellText, temporalExtreme, temporalInstant } from './temporalCellFace'; /** @@ -362,6 +362,20 @@ function joinSummaryLabel(type: string, formatted: string, t: SummaryTranslate, return t(pageOnly ? 'grid.summary.pagePattern' : 'grid.summary.pattern', { label, value: formatted }); } +/** + * The arm a roll-up (`summary`) column's total is formatted by: the value type + * the list cell draws the same field as (`FormulaCellRenderer`), so the footer + * and the cells above it agree by reference. Money when the summary declares + * its currency (`summaryDeclaresCurrency`, the cell's own test; the spec gives a + * summary no currency otherwise, whatever its source field is), else a number + * at the width `resolveFieldScale` answers. A summary with neither keeps the + * plain default arm. + */ +function summaryValueType(column: { currencyConfig?: unknown; scale?: number | null }): string { + if (summaryDeclaresCurrency(column)) return 'currency'; + return resolveFieldScale(column) === undefined ? 'summary' : 'number'; +} + function formatSummaryLabel( type: string, value: number | null, @@ -405,7 +419,7 @@ function formatSummaryLabel( return join(value.toLocaleString(displayLocale)); } - const colType = column?.type; + const colType = column?.type === 'summary' ? summaryValueType(column) : column?.type; let formatted: string; if (colType === 'currency') { // objectui#10221 — a currency's decimal places are the currency's, not a