Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/37270-refusal-row-record.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@object-ui/plugin-detail': patch
'@object-ui/plugin-grid': patch
---

fix(plugin-detail, plugin-grid): a field the server's refusal adds to the fill-in dialog reads the record the change would leave

Clause-②: no
Metadata-protocol: none

The fill-in dialog adds a row for a field a refusal names. That row now carries the record the change would leave (the stored record with the change merged in), as the dialog's other rows do, in all three hosts: the stage menu, the record page's inline Save and the list cell. An option `visibleWhen` on that row reads the change, so the stage menu's confirmation, which opens with no other row, no longer shows such a row with no options to pick.
5 changes: 4 additions & 1 deletion ui/packages/plugin-detail/src/InlineEditSaveBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -761,6 +761,9 @@ export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
return Array.isArray(value) ? value.map(one).join(', ') : one(value);
};
const exclude = Object.keys(ask.draft);
// The record the draft would leave: the merge the collector judges its
// rows on. A row a refusal names carries it too (objectstack#37270).
const drafted = { ...data, ...ask.draft };
return (
<RequiredFieldsDialog
open
Expand All @@ -777,7 +780,7 @@ export const InlineEditSaveBar: React.FC<InlineEditSaveBarProps> = ({
const def = objectFields?.[name] as Record<string, unknown> | undefined;
if (!def || typeof def !== 'object' || exclude.includes(name)) return null;
if (!hasFieldEditWidget(def.type as string | undefined) || !fillable(name, def)) return null;
return label({ name, def: { name, ...def } });
return label({ name, def: { name, ...def }, record: drafted });
}}
labelOf={(name) => (objectFields?.[name] ? labelForField(name) : undefined)}
// Cancel writes nothing and leaves the edit session as it was: the
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/**
* 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#37270 — the record page's inline Save dialog: the row a refusal
* names carries the record the draft would leave (the record with the draft
* merged in, the merge the collector judges its rows on), so an option
* `visibleWhen` on that row reads the draft, as the collected rows' do.
*/
import { describe, it, expect, vi, afterEach } from 'vitest';
import { render, screen, fireEvent, cleanup } from '@testing-library/react';
import '@testing-library/jest-dom';
import React from 'react';
import { InlineEditProvider, RecordContextProvider, useInlineEdit } from '@object-ui/react';

type RefusalField = (name: string) => { name: string; record?: Record<string, unknown> } | null;
const seen = vi.hoisted(() => ({ refusalField: null as null | ((name: string) => unknown) }));

vi.mock('@object-ui/fields', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/fields')>();
const Dialog = (props: React.ComponentProps<typeof actual.RequiredFieldsDialog>) => {
seen.refusalField = props.refusalField ?? null;
return React.createElement(actual.RequiredFieldsDialog, props);
};
return { ...actual, RequiredFieldsDialog: Dialog };
});

import { registerAllFields } from '@object-ui/fields';
import { InlineEditSaveBar } from '../InlineEditSaveBar';

registerAllFields();
afterEach(() => { cleanup(); seen.refusalField = null; });

const OBJECT_SCHEMA = {
name: 'deal',
fields: {
name: { type: 'text', label: 'Name' },
stage: { type: 'select', label: 'Stage', options: [{ value: 'new', label: 'New' }, { value: 'won', label: 'Won' }] },
win_reason: { type: 'text', label: 'Win Reason', requiredWhen: 'record.stage == "won"' },
// No `requiredWhen`: only a refusal names it.
channel: {
type: 'radio',
label: 'Channel',
options: [{ value: 'won_option', label: 'Won option', visibleWhen: 'record.stage == "won"' }],
},
},
};
const DATA = { id: 'd1', name: 'Acme deal', stage: 'new', win_reason: null, channel: null, updated_at: 'v1' };

function Harness() {
const inline = useInlineEdit()!;
return (
<>
<button onClick={() => inline.enter('stage')}>edit-enter</button>
<button onClick={() => inline.setField('stage', 'won')}>edit-stage-won</button>
</>
);
}

describe('#37270 the inline Save dialog hands a refusal-named row the drafted record', () => {
it('the refusal row carries the record with the draft merged in', async () => {
const update = vi.fn().mockResolvedValue({});
render(
<RecordContextProvider objectName="deal" recordId="d1" data={DATA} objectSchema={OBJECT_SCHEMA} dataSource={{ update } as never}>
<InlineEditProvider canEdit>
<Harness />
<InlineEditSaveBar dataSource={{ update }} objectName="deal" recordId="d1" data={DATA} refresh={vi.fn()} />
</InlineEditProvider>
</RecordContextProvider>,
);
fireEvent.click(screen.getByText('edit-enter'));
fireEvent.click(screen.getByText('edit-stage-won'));
fireEvent.click(screen.getByRole('button', { name: 'Save' }));
await screen.findByTestId('required-fields-dialog');
expect(update).not.toHaveBeenCalled();
const row = (seen.refusalField as RefusalField | null)?.('channel');
expect(row?.name).toBe('channel');
expect(row?.record).toEqual({ ...DATA, stage: 'won' });
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
/**
* 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#37270 — the stage menu's dialog: a row a refusal names reads the
* record the move would leave, also when no collected row is shown. A move to
* a stage that needs nothing opens the dialog with no fields; the server then
* refuses it naming a radio whose options read `record.stage`. The row it adds
* offers the options visible on the moved record, not the empty state.
*
* `@object-ui/*` resolves to source through the root vitest alias table.
*/

import * as React from 'react';
import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest';
import { render, cleanup, fireEvent, screen, waitFor, within } from '@testing-library/react';
import '@testing-library/jest-dom';
import { InlineEditProvider, RecordContextProvider } from '@object-ui/react';

const { permsStub } = vi.hoisted(() => ({
permsStub: {
isLoaded: true,
checkField: () => true,
check: () => ({ allowed: true }),
getFieldPermissions: () => [],
getRowFilter: () => undefined,
getObjectApiOperations: () => undefined,
roles: [],
userId: null,
systemPermissions: undefined,
hasCapabilities: () => true,
can: () => true,
cannot: () => false,
},
}));

vi.mock('@object-ui/permissions', async (importOriginal) => {
const actual = await importOriginal<typeof import('@object-ui/permissions')>();
return { ...actual, usePermissions: () => permsStub as any };
});

import { RecordStageMenu } from '../RecordStageMenu';

const OPPORTUNITY = {
name: 'crm_opportunity',
fields: {
name: { type: 'text', label: 'Name' },
stage: {
type: 'select',
label: 'Stage',
options: [
{ value: 'prospecting', label: 'Prospecting' },
{ value: 'negotiation', label: 'Negotiation' },
{ value: 'closed_lost', label: 'Closed Lost' },
],
},
// No `requiredWhen`: the client cannot foresee it, only the server names it.
channel: {
type: 'radio',
label: 'Channel',
options: [
{ value: 'negotiation_option', label: 'Negotiation option', visibleWhen: 'record.stage == "negotiation"' },
{ value: 'lost_option', label: 'Lost option', visibleWhen: 'record.stage == "closed_lost"' },
],
},
},
};

beforeEach(() => {
vi.stubGlobal('fetch', vi.fn(async () => ({ ok: false, status: 501, json: async () => ({}) })));
});

afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});

describe('#37270 a refusal-named row in the stage dialog reads the moved record', () => {
it('with no collected row shown, the added row offers the options visible on the record the move leaves', async () => {
const refusal = Object.assign(new Error('VALIDATION_FAILED'), {
code: 'VALIDATION_FAILED',
fields: [{ field: 'channel', code: 'required', message: 'Channel is required to negotiate' }],
});
const dataSource = { update: vi.fn(async () => { throw refusal; }) };
render(
<RecordContextProvider
objectName="crm_opportunity"
recordId="o1"
data={{ id: 'o1', name: 'Wayne deal', stage: 'prospecting', channel: null, updated_at: 'v1' }}
objectSchema={OPPORTUNITY}
dataSource={dataSource as any}
reread={vi.fn(async () => {})}
>
<InlineEditProvider canEdit>
<RecordStageMenu field="stage" label="Prospecting" tag={<span>Prospecting</span>} />
</InlineEditProvider>
</RecordContextProvider>,
);
fireEvent.pointerDown(screen.getByRole('button', { name: /^Stage: / }), { button: 0, ctrlKey: false, pointerType: 'mouse' });
const menu = screen.getByRole('menu');
fireEvent.click(within(menu).getAllByRole('menuitem').find((el) => el.textContent?.startsWith('Negotiation'))!);
let dialog = await screen.findByRole('dialog');
expect(dialog.querySelector('[data-required-fields-field]')).toBeNull();
fireEvent.click(within(dialog).getByRole('button', { name: 'Move' }));
await waitFor(() => expect(dataSource.update).toHaveBeenCalledTimes(1));
dialog = await screen.findByRole('dialog');
const row = await waitFor(() => {
const el = dialog.querySelector('[data-required-fields-field="channel"]') as HTMLElement | null;
expect(el).not.toBeNull();
return el as HTMLElement;
});
expect(row.querySelector('[data-testid="radio-empty-channel"]')).toBeNull();
expect(within(row).getByText('Negotiation option')).toBeInTheDocument();
// Judged on the moved record, not opened up.
expect(within(row).queryByText('Lost option')).toBeNull();
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ export function useStageChange(
);
const sendable = (values: Record<string, unknown>) =>
noLongerAsked.size === 0 ? values : Object.fromEntries(Object.entries(values).filter(([k]) => !noLongerAsked.has(k)));
// The record the move would leave: the merge the collector judges its
// rows on. A row a refusal names carries it too, so its options read the
// move even when no collected row is shown (objectstack#37270).
const moved = { ...record, [statusField]: stage.value };
return (
<RequiredFieldsDialog
// A new pick is a new collection: the dialog's typed values reset.
Expand All @@ -417,7 +421,7 @@ export function useStageChange(
const def = objectFields?.[name] as Record<string, unknown> | undefined;
if (!def || typeof def !== 'object' || name === statusField) return null;
if (!hasFieldEditWidget(def.type as string | undefined) || !fillable(name, def)) return null;
return label({ name, def: { name, ...def } });
return label({ name, def: { name, ...def }, record: moved });
}}
// The stage field and an object-level (`_record`) reason read alone,
// as `stageRefusalLines` reads them; another field by its label.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* 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#37270 — the list cell's fill-in dialog: the row a refusal names
* carries the record the change would leave (the row with the cell's value
* merged in, the merge the collector judges its rows on), so an option
* `visibleWhen` on that row reads the change, as the collected rows' do.
*/

import { describe, it, expect, vi } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import type React from 'react';
import { useCellRequiredPrompt } from '../objectGridRequiredPrompt';

const FIELDS = {
name: { type: 'text', label: 'Name' },
stage: { type: 'select', label: 'Stage', options: [{ value: 'new', label: 'New' }, { value: 'won', label: 'Won' }] },
win_reason: { type: 'text', label: 'Win Reason', requiredWhen: 'record.stage == "won"' },
// No `requiredWhen`: only a refusal names it.
channel: {
type: 'radio',
label: 'Channel',
options: [{ value: 'won_option', label: 'Won option', visibleWhen: 'record.stage == "won"' }],
},
};
const ROW = { id: 'd1', name: 'Acme deal', stage: 'new', win_reason: null, channel: null };

describe('#37270 the list cell dialog hands a refusal-named row the changed record', () => {
it('the refusal row carries the row with the cell value merged in', () => {
const { result } = renderHook(() => useCellRequiredPrompt({
objectName: undefined,
objectSchema: { name: 'deal', fields: FIELDS },
objectFields: FIELDS,
perms: undefined as never,
labelOf: (f) => f,
translateOptions: (_o, _f, options) => options,
optionLabel: (_f, _c, fallback) => fallback,
emptyText: '—',
save: vi.fn(async () => {}),
}));
act(() => { void result.current.ask(ROW, 'stage', 'won', () => null); });
const dialog = result.current.renderDialog() as React.ReactElement<{
refusalField: (name: string) => { name: string; record?: Record<string, unknown> } | null;
}>;
expect(dialog).not.toBeNull();
const row = dialog.props.refusalField('channel');
expect(row?.name).toBe('channel');
expect(row?.record).toEqual({ ...ROW, stage: 'won' });
});
});
4 changes: 3 additions & 1 deletion ui/packages/plugin-grid/src/objectGridRequiredPrompt.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,9 @@ export function useCellRequiredPrompt(inputs: CellRequiredPromptInputs): {
// A field a refusal names joins the dialog when it could have been asked
// for: it has an edit widget and this reader may write it.
if (!hasFieldEditWidget(def.type) || !fillable(name, def)) return null;
return label({ name, def: { name, ...def } });
// The record the change would leave, the merge the collector judges its
// rows on, so the row's options read the change (objectstack#37270).
return label({ name, def: { name, ...def }, record: { ...record, [columnKey]: value } });
};
return (
<RequiredFieldsDialog
Expand Down
Loading