|
| 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