Skip to content

Commit ffbc44b

Browse files
committed
fix(plugin-grid): list each field of a multi-field row conflict; format a summary column's footer total as its cell
A grid row save that changed several fields and met a 409 now fills the conflict dialog's per-field list (column header, your edit, current value) instead of handing it the draft map, which printed as raw JSON. The footer total of a roll-up (summary) column now takes the arm the list cell draws the same field with: money when the summary declares its currency, else a number at its declared scale. @object-ui/fields exports summaryDeclaresCurrency, the cell's own test, for the footer to reuse. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FEkQ5mDVzZmSX2UmJXU7sH
1 parent 5604aeb commit ffbc44b

5 files changed

Lines changed: 388 additions & 4 deletions

File tree

‎ui/packages/fields/src/index.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -575,7 +575,9 @@ function isPlainObjectValue(value: unknown): value is Record<string, unknown> {
575575
import { resolveFieldCurrency, summaryDeclaresCurrency } from './currency.js';
576576
export { withFollowedParentObject, FOLLOWED_PARENT_OBJECT_KEY } from './currency.js';
577577
import { HomeAmountHint } from './widgets/CurrencyField.js';
578-
export { resolveFieldCurrency };
578+
// `summaryDeclaresCurrency` is the cell's own test for drawing a roll-up as
579+
// money; the grid footer formats the same field's total by it.
580+
export { resolveFieldCurrency, summaryDeclaresCurrency };
579581

580582
/**
581583
* `formatCurrency` lives beside `formatNumberFieldValue` in

‎ui/packages/plugin-grid/src/ObjectGrid.tsx‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2289,7 +2289,8 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
22892289
/**
22902290
* The dialog's payload for one row's 409, in the shape `InlineEditSaveBar`
22912291
* builds for a record's draft: one edited field shows its own before and
2292-
* after, several show the record-level summary.
2292+
* after; several list each field (`fields`) with its column header and both
2293+
* values, so the dialog never prints the draft map as raw JSON.
22932294
*/
22942295
const buildRowConflict = (
22952296
changes: Record<string, any>,
@@ -2315,6 +2316,12 @@ export const ObjectGrid: React.FC<ObjectGridComponentProps> = ({
23152316
currentValue: current ? Object.fromEntries(keys.map((k) => [k, current[k]])) : undefined,
23162317
currentVersion: err.currentVersion,
23172318
currentRecord: current,
2319+
fields: keys.map((k) => ({
2320+
field: k,
2321+
label: columnHeaderOf(k),
2322+
pendingValue: changes[k],
2323+
currentValue: current ? current[k] : undefined,
2324+
})),
23182325
};
23192326
};
23202327

Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#33542 — the footer total of a roll-up (`summary`) column is
11+
* formatted as the list cell draws the same field.
12+
*
13+
* HotCRM's All Invoices footer read "Paid 230,000" for a `Field.summary` with
14+
* `scale: 2`, beside "Open 215,000.00" for a currency field: the footer's
15+
* formatter keyed on the column type, and a `summary` fell to the plain
16+
* default, which never reads `scale`. The served object metadata carries the
17+
* summary's `scale` (measured on the showcase's `showcase_expense_report`).
18+
*
19+
* The cell draws a summary through `FormulaCellRenderer`: as money when the
20+
* summary declares its currency (`currencyConfig`, `summaryDeclaresCurrency`),
21+
* else as a number at its `resolveFieldScale` width. The footer now takes the
22+
* same two arms, the ones a plain `currency` / `number` column takes.
23+
*
24+
* Pinned through the real `ObjectGrid` footer, its field catalogue read from
25+
* the data source's object schema, under a real `I18nProvider` in en and zh-CN:
26+
*
27+
* - a summary with `scale: 2` totals to two decimals;
28+
* - a summary declaring a `fixed` currency totals exactly as a plain currency
29+
* column with the same config does;
30+
* - CONTROL: a summary with no `scale` and no currency keeps today's face.
31+
*/
32+
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
33+
import { render, screen, cleanup, waitFor } from '@testing-library/react';
34+
import '@testing-library/jest-dom';
35+
import React from 'react';
36+
37+
import { ObjectGrid } from '../ObjectGrid';
38+
import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts';
39+
import { installExplainDouble } from './explainDouble';
40+
import { registerAllFields } from '@object-ui/fields';
41+
import { ActionProvider, I18nProvider } from '@object-ui/react';
42+
43+
beforeAll(() => {
44+
registerAllFields();
45+
if (!Element.prototype.scrollIntoView) {
46+
Element.prototype.scrollIntoView = vi.fn() as unknown as Element['scrollIntoView'];
47+
}
48+
});
49+
beforeEach(() => {
50+
__clearRecordCrudVerdictCache();
51+
installExplainDouble();
52+
});
53+
afterEach(() => {
54+
cleanup();
55+
vi.unstubAllGlobals();
56+
});
57+
58+
const OBJECT = 'invoice_33542';
59+
60+
const CNY = { currencyMode: 'fixed', defaultCurrency: 'CNY' } as const;
61+
62+
/** The served field catalogue: three roll-ups and a plain currency field. */
63+
const FIELDS = {
64+
id: { type: 'text', label: 'Id' },
65+
invoice_number: { type: 'text', label: 'Invoice Number' },
66+
paid_amount: {
67+
type: 'summary', label: 'Paid', scale: 2,
68+
summaryOperations: { object: 'payment', field: 'amount', function: 'sum' },
69+
},
70+
paid_cny: {
71+
type: 'summary', label: 'Paid (CNY)', scale: 2, currencyConfig: CNY,
72+
summaryOperations: { object: 'payment', field: 'amount', function: 'sum' },
73+
},
74+
billed_cny: { type: 'currency', label: 'Billed (CNY)', currencyConfig: CNY },
75+
payment_count: {
76+
type: 'summary', label: 'Payments',
77+
summaryOperations: { object: 'payment', function: 'count' },
78+
},
79+
};
80+
81+
/** Totals: 230,000 for every amount column, 7 payments. */
82+
const ROWS = [
83+
{ id: 'i1', invoice_number: 'INV-1', paid_amount: 100000, paid_cny: 100000, billed_cny: 100000, payment_count: 3 },
84+
{ id: 'i2', invoice_number: 'INV-2', paid_amount: 130000, paid_cny: 130000, billed_cny: 130000, payment_count: 4 },
85+
];
86+
87+
function renderGrid(language: 'en' | 'zh-CN') {
88+
const dataSource = {
89+
find: vi.fn(async () => ({ data: ROWS.map((r) => ({ ...r })), total: ROWS.length, hasMore: false, pageSize: 50 })),
90+
getObjectSchema: vi.fn(async (name: string) => ({ name, fields: FIELDS })),
91+
} as any;
92+
const schema: any = {
93+
type: 'object-grid',
94+
objectName: OBJECT,
95+
columns: [
96+
{ field: 'invoice_number', label: 'Invoice Number' },
97+
{ field: 'paid_amount', label: 'Paid', summary: 'sum' },
98+
{ field: 'paid_cny', label: 'Paid (CNY)', summary: 'sum' },
99+
{ field: 'billed_cny', label: 'Billed (CNY)', summary: 'sum' },
100+
{ field: 'payment_count', label: 'Payments', summary: 'sum' },
101+
],
102+
pagination: { pageSize: 50 },
103+
};
104+
return render(
105+
<I18nProvider config={{ defaultLanguage: language, detectBrowserLanguage: false }} persistLanguage={false}>
106+
<ActionProvider>
107+
<ObjectGrid schema={schema} dataSource={dataSource} />
108+
</ActionProvider>
109+
</I18nProvider>,
110+
);
111+
}
112+
113+
/** The footer text of a column once the grid has its field catalogue. */
114+
async function footerOf(field: string): Promise<string> {
115+
const cell = await screen.findByTestId(`summary-${field}`);
116+
return cell.textContent ?? '';
117+
}
118+
119+
describe('a summary column footer total is formatted as its cell (objectstack#33542)', () => {
120+
it('en: a summary with scale 2 totals to two decimals', async () => {
121+
renderGrid('en');
122+
await waitFor(async () => expect(await footerOf('paid_amount')).toContain('Sum: 230,000.00'));
123+
});
124+
125+
it('zh-CN: a summary with scale 2 totals to two decimals, under the zh prefix', async () => {
126+
renderGrid('zh-CN');
127+
await waitFor(async () => expect(await footerOf('paid_amount')).toContain('合计:230,000.00'));
128+
});
129+
130+
it.each(['en', 'zh-CN'] as const)('%s: a summary declaring a fixed currency totals as a plain currency column does', async (language) => {
131+
renderGrid(language);
132+
await waitFor(async () => expect(await footerOf('billed_cny')).toMatch(/230,000\.00/));
133+
const currencyTotal = (await footerOf('billed_cny')).replace(/^.*?:/, '');
134+
// The plain currency column draws money (a currency sign beside the amount).
135+
expect(currencyTotal).not.toBe('230,000.00');
136+
expect((await footerOf('paid_cny')).replace(/^.*?:/, '')).toBe(currencyTotal);
137+
});
138+
139+
it('CONTROL: a summary with no scale and no currency keeps the plain total', async () => {
140+
renderGrid('en');
141+
await waitFor(async () => expect(await footerOf('paid_amount')).toContain('230,000.00'));
142+
expect(await footerOf('payment_count')).toContain('Sum: 7');
143+
expect(await footerOf('payment_count')).not.toContain('7.0');
144+
});
145+
});
Lines changed: 216 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,216 @@
1+
/**
2+
* ObjectUI
3+
* Copyright (c) 2024-present ObjectStack Inc.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
/**
10+
* objectstack#33557 — a grid row save that changed several fields and meets a
11+
* newer version (409 `CONCURRENT_UPDATE`) lists each field on the conflict
12+
* dialog, under its column header, with both values. It printed the whole
13+
* draft and the current subset as two raw JSON objects.
14+
*
15+
* The real `ObjectGrid` renders the real `data-table` and the real
16+
* `ConcurrentUpdateDialog`; every write goes through the real
17+
* `@object-ui/data-objectstack` adapter and `@objectstack/client`. Only `fetch`
18+
* is stubbed, by a small server that answers a stale `If-Match` with the 409
19+
* envelope `@objectstack/types` maps a `ConcurrentUpdateError` to. The cells
20+
* are edited the way a user types them.
21+
*
22+
* CONTROL: a row save that changed one field keeps the one-field face (the
23+
* field's own before and after, no list).
24+
*/
25+
import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest';
26+
import { render, screen, waitFor, fireEvent, cleanup, within } from '@testing-library/react';
27+
import '@testing-library/jest-dom';
28+
import React from 'react';
29+
30+
import { ObjectStackAdapter } from '@object-ui/data-objectstack';
31+
import { registerAllFields } from '@object-ui/fields';
32+
import { ActionProvider, SchemaRendererProvider } from '@object-ui/react';
33+
import { ObjectGrid } from '../ObjectGrid';
34+
import { __clearRecordCrudVerdictCache } from '../hooks/useRecordCrudVerdicts';
35+
import { installExplainDouble } from './explainDouble';
36+
37+
registerAllFields();
38+
39+
beforeAll(() => {
40+
if (!Element.prototype.scrollIntoView) {
41+
Element.prototype.scrollIntoView = vi.fn() as any;
42+
}
43+
});
44+
45+
beforeEach(() => {
46+
__clearRecordCrudVerdictCache();
47+
installExplainDouble();
48+
});
49+
afterEach(() => {
50+
cleanup();
51+
vi.unstubAllGlobals();
52+
});
53+
54+
const OBJECT = 'task_33557';
55+
56+
const json = (status: number, body: unknown) =>
57+
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
58+
59+
/** A store with an `updated_at` per record, refusing a stale `If-Match` with the 409 envelope. */
60+
function makeServer(seed: Array<Record<string, unknown> & { id: string }>) {
61+
let clock = 0;
62+
const stamp = () => `2026-11-15 00:00:${String(++clock).padStart(2, '0')}.000`;
63+
const store: Record<string, Record<string, unknown>> = {};
64+
for (const row of seed) store[row.id] = { ...row, updated_at: stamp() };
65+
const statuses: number[] = [];
66+
67+
const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
68+
const url = String(input);
69+
const method = (init?.method ?? 'GET').toUpperCase();
70+
if (url.endsWith('/api/v1/discovery')) {
71+
return json(200, { success: true, data: { capabilities: {}, routes: {} } });
72+
}
73+
const match = url.match(/\/api\/v1\/data\/([^/?]+)\/([^/?]+)$/);
74+
if (!match || method !== 'PATCH') throw new Error(`unexpected request ${method} ${url}`);
75+
const [, object, rawId] = match;
76+
const id = decodeURIComponent(rawId);
77+
const ifMatch = ((init?.headers ?? {}) as Record<string, string>)['If-Match'];
78+
const body = JSON.parse(String(init?.body ?? '{}')) as Record<string, unknown>;
79+
const current = store[id];
80+
if (ifMatch !== undefined && ifMatch !== current.updated_at) {
81+
statuses.push(409);
82+
return json(409, {
83+
error: 'Record was modified by another user',
84+
code: 'CONCURRENT_UPDATE',
85+
currentVersion: current.updated_at,
86+
currentRecord: { ...current },
87+
object,
88+
});
89+
}
90+
store[id] = { ...current, ...body, updated_at: stamp() };
91+
statuses.push(200);
92+
return json(200, { success: true, data: { object, id, record: { ...store[id] } } });
93+
});
94+
95+
const adapter = new ObjectStackAdapter({ baseUrl: 'http://test.local', fetch, autoReconnect: false });
96+
const project = (row: Record<string, unknown>, select: unknown) =>
97+
Array.isArray(select)
98+
? Object.fromEntries(select.filter((k) => k in row).map((k) => [k, row[k]]))
99+
: { ...row };
100+
101+
const dataSource = {
102+
find: vi.fn(async (_object: string, params?: { $select?: unknown }) => {
103+
const rows = Object.values(store).map((r) => project(r, params?.$select));
104+
return { data: rows, total: rows.length, hasMore: false, pageSize: 50 };
105+
}),
106+
findOne: vi.fn(async (_object: string, id: string) => ({ ...store[id] })),
107+
update: vi.fn((object: string, id: string, data: any, opts?: { ifMatch?: string }) =>
108+
adapter.update(object, id, data, opts),
109+
),
110+
getObjectSchema: vi.fn(async (name: string) => ({
111+
name,
112+
fields: {
113+
id: { type: 'text' },
114+
title: { type: 'text', label: 'Title' },
115+
estimate_hours: { type: 'number', label: 'Estimate' },
116+
owner_note: { type: 'text', label: 'Owner note' },
117+
},
118+
})),
119+
} as any;
120+
121+
return {
122+
store,
123+
statuses,
124+
dataSource,
125+
writeAsOtherUser(id: string, changes: Record<string, unknown>) {
126+
store[id] = { ...store[id], ...changes, updated_at: stamp() };
127+
},
128+
};
129+
}
130+
131+
function renderGrid(server: ReturnType<typeof makeServer>) {
132+
const schema: any = {
133+
type: 'object-grid',
134+
objectName: OBJECT,
135+
editable: true,
136+
singleClickEdit: true,
137+
columns: [
138+
{ field: 'title', label: 'Title', editable: false },
139+
{ field: 'estimate_hours', label: 'Estimate', type: 'number' },
140+
{ field: 'owner_note', label: 'Owner note' },
141+
],
142+
pagination: { pageSize: 50 },
143+
};
144+
return render(
145+
<ActionProvider>
146+
<SchemaRendererProvider dataSource={server.dataSource}>
147+
<ObjectGrid schema={schema} dataSource={server.dataSource} onEdit={() => {}} onDelete={() => {}} />
148+
</SchemaRendererProvider>
149+
</ActionProvider>,
150+
);
151+
}
152+
153+
const rowOf = (title: string) => screen.getByText(title).closest('tr') as HTMLElement;
154+
155+
/** Stage a new value on the cell of the row titled `title` that reads `from`, the way a user types it. */
156+
async function editCell(title: string, from: string, to: string) {
157+
const td = await waitFor(() => {
158+
const cell = Array.from(rowOf(title).querySelectorAll('td')).find(
159+
(c) => c.textContent?.trim() === from,
160+
);
161+
if (!cell) throw new Error(`no ${from} cell on ${title}`);
162+
return cell as HTMLElement;
163+
});
164+
fireEvent.click(td);
165+
const input = await waitFor(() => {
166+
const el = td.querySelector('input') as HTMLInputElement | null;
167+
if (!el) throw new Error('editor not open');
168+
return el;
169+
});
170+
fireEvent.change(input, { target: { value: to } });
171+
fireEvent.keyDown(input, { key: 'Enter' });
172+
await waitFor(() => expect(within(rowOf(title)).getByText(to)).toBeInTheDocument());
173+
}
174+
175+
async function staleRowSave(edits: Array<[from: string, to: string]>) {
176+
const server = makeServer([{ id: 't1', title: 'Ingest pipeline', estimate_hours: 60, owner_note: 'ready' }]);
177+
renderGrid(server);
178+
await waitFor(() => expect(screen.getByText('Ingest pipeline')).toBeInTheDocument());
179+
server.writeAsOtherUser('t1', { estimate_hours: 77, owner_note: 'blocked' });
180+
for (const [from, to] of edits) await editCell('Ingest pipeline', from, to);
181+
fireEvent.click(within(rowOf('Ingest pipeline')).getByTitle('Save row'));
182+
const dialog = await screen.findByRole('alertdialog');
183+
expect(server.statuses).toEqual([409]);
184+
return dialog;
185+
}
186+
187+
describe('a multi-field grid row conflict lists each field (objectstack#33557)', () => {
188+
it('two changed fields + a 409: two rows, each under its column header with both values, no raw JSON', async () => {
189+
const dialog = await staleRowSave([['60', '61'], ['ready', 'shipped']]);
190+
191+
const rows = within(dialog).getAllByTestId('concurrent-update-field');
192+
expect(rows.map((r) => r.getAttribute('data-field'))).toEqual(['estimate_hours', 'owner_note']);
193+
194+
const [estimate, note] = rows;
195+
expect(within(estimate).getByText('Estimate')).toBeInTheDocument();
196+
expect(within(estimate).getByText('61')).toBeInTheDocument();
197+
expect(within(estimate).getByText('77')).toBeInTheDocument();
198+
expect(within(note).getByText('Owner note')).toBeInTheDocument();
199+
expect(within(note).getByText('shipped')).toBeInTheDocument();
200+
expect(within(note).getByText('blocked')).toBeInTheDocument();
201+
202+
// Neither value is drawn as a serialized object.
203+
expect(dialog.textContent).not.toMatch(/[{}]/);
204+
expect(dialog.textContent).not.toContain('"estimate_hours"');
205+
});
206+
207+
it('CONTROL: one changed field keeps the one-field face (no list), naming the column and both values', async () => {
208+
const dialog = await staleRowSave([['60', '61']]);
209+
210+
expect(within(dialog).queryByTestId('concurrent-update-field-list')).toBeNull();
211+
expect(within(dialog).getByText('Estimate')).toBeInTheDocument();
212+
expect(within(dialog).getByText('61')).toBeInTheDocument();
213+
expect(within(dialog).getByText('77')).toBeInTheDocument();
214+
expect(dialog.textContent).not.toMatch(/[{}]/);
215+
});
216+
});

0 commit comments

Comments
 (0)