diff --git a/.changeset/36865-lookup-param-allowcreate-filters.md b/.changeset/36865-lookup-param-allowcreate-filters.md new file mode 100644 index 00000000000..16a076fa3af --- /dev/null +++ b/.changeset/36865-lookup-param-allowcreate-filters.md @@ -0,0 +1,16 @@ +--- +'@object-ui/core': patch +'@object-ui/fields': patch +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +'@object-ui/app-shell': patch +--- + +fix(fields): an action's lookup param honours the borrowed field's `allowCreate: false`, and a record created in a filtered picker that fails the filters is not selected + +Clause-②: yes (widening) +Metadata-protocol: none + +- **A field-backed lookup param reads the field's `allowCreate`.** A param written `{ field, objectOverride }` already took the field's `lookupFilters`, `lookupColumns`, `lookupPageSize` and `descriptionField`, but not `allowCreate`. As a result, a field declaring `allowCreate: false` still showed "+ New" in an action's picker. `resolveActionParams` now copies it, app-shell's `paramToField` forwards it to the record-header dialog's picker, and the selection toolbar's dialog carries it through `resolvePromotedBulkParams`. Both the desktop popover and the phone drawer honour it. `@object-ui/core`'s `ActionParamDef` gains the optional `allowCreate` member it travels on. An author who writes `allowCreate` on a raw param is warned by name in development, like the other inherited picker keys: the spec's `ActionParamSchema` does not declare it. +- **A quick-created record is selected only if the picker could have offered it.** The create form accepts whatever the user enters, so the new record can fail the field's `lookupFilters`, for example a `draft` where the field asks for `approved`. The picker used to select it anyway, and the save or action that read the field then refused it. The picker now re-reads the new id through its own filter, the field's `lookupFilters` and `dependsOn` scope combined with the id. If the server does not return the record, it is not selected, and the picker reopens with the line `lookup.createdOutsideFilters` ("The record was created, but it does not match this field's filters, so it cannot be chosen here."), in every shipped locale. If the check itself fails, the record is not selected either, and the line `lookup.createdUnchecked` says the record was created but could not be checked, so the user searches for it instead of creating a duplicate. A picker with no filter selects the new record as before, without the extra read. +- **A create notice no longer hides the candidate list.** A create notice (the two lines above, or a failed inline create) now sits above the list instead of replacing it, so the user can pick an existing record straight away. Closing the picker clears it. Before, a failed inline create hid the list and its create entry until the widget was remounted. diff --git a/ui/packages/app-shell/src/utils/paramToField.allowCreate-36865.test.tsx b/ui/packages/app-shell/src/utils/paramToField.allowCreate-36865.test.tsx new file mode 100644 index 00000000000..005f5e072dc --- /dev/null +++ b/ui/packages/app-shell/src/utils/paramToField.allowCreate-36865.test.tsx @@ -0,0 +1,116 @@ +/** + * 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. + */ + +/** + * A field-backed lookup param reads `allowCreate` from the field it borrows + * (objectstack#36865, half 1, the record-header path). + * + * The param `{ field, objectOverride }` already inherited the field's + * `lookupFilters`, `lookupColumns`, `lookupPageSize` and `descriptionField`, + * but not `allowCreate`, so a field declaring `allowCreate: false` still drew + * "+ New" in an action's picker. These rows run the real chain the record + * header's dialog runs — `resolveActionParam` → `paramToField` → `LookupField` + * — on both faces of the picker (the desktop popover and the phone drawer). + * + * - `allowCreate: false` on the field: no create entry, popover and drawer; + * - CONTROL, a field that allows create: the create entry shows on both. + */ +import { render, screen, fireEvent, waitFor, act, cleanup, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { LookupField, resolveActionParam } from '@object-ui/fields'; +import { paramToField } from './paramToField'; + +const realInnerWidth = Object.getOwnPropertyDescriptor(window, 'innerWidth'); +const realMatchMedia = window.matchMedia; + +function setViewportWidth(width: number) { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: width }); + window.matchMedia = ((query: string) => ({ + matches: window.innerWidth < 768, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })) as any; +} + +afterEach(() => { + cleanup(); + if (realInnerWidth) Object.defineProperty(window, 'innerWidth', realInnerWidth); + window.matchMedia = realMatchMedia; +}); + +/** The borrowed field, as the expense app declares it. */ +const requestField = (allowCreate: boolean | undefined) => ({ + type: 'lookup', + label: 'Travel Request', + reference: 'crm_expense_request', + displayField: 'name', + lookupFilters: [{ field: 'status', operator: 'eq', value: 'approved' }], + ...(allowCreate === undefined ? {} : { allowCreate }), +}); + +function widgetFieldFor(allowCreate: boolean | undefined) { + const resolved = resolveActionParam( + { field: 'crm_expense_request', objectOverride: 'crm_expense_report' } as any, + { + objectName: 'crm_expense', + objects: [{ name: 'crm_expense_report', fields: { crm_expense_request: requestField(allowCreate) } }], + fieldLabel: (_o: string, _f: string, fallback: string) => fallback, + } as any, + ); + return paramToField(resolved); +} + +/** Open the picker on the given face and report whether it offers create. */ +async function offersCreate(allowCreate: boolean | undefined, face: 'popover' | 'drawer'): Promise { + setViewportWidth(face === 'drawer' ? 390 : 1280); + const field = widgetFieldFor(allowCreate); + const ds = { + find: vi.fn(async () => ({ data: [{ id: 'r1', name: 'Shanghai trip', status: 'approved' }], total: 1 })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + }; + render(); + await act(async () => { + fireEvent.click(screen.getByTestId(`lookup-trigger-${field.name}`)); + }); + const panel = await screen.findByTestId(face === 'drawer' ? 'lookup-drawer' : 'lookup-popover'); + await waitFor(() => expect(within(panel).getAllByRole('option')).toHaveLength(1)); + return within(panel).queryByTestId('lookup-create-new') !== null; +} + +describe('a field-backed action param honours the borrowed field\'s allowCreate (objectstack#36865)', () => { + it('the resolved widget field carries the field\'s allowCreate', () => { + expect(widgetFieldFor(false).allowCreate).toBe(false); + expect(widgetFieldFor(true).allowCreate).toBe(true); + }); + + it('allowCreate: false — no create entry in the desktop popover', async () => { + expect(await offersCreate(false, 'popover')).toBe(false); + }); + + it('allowCreate: false — no create entry in the phone drawer', async () => { + expect(await offersCreate(false, 'drawer')).toBe(false); + }); + + it('CONTROL — allowCreate: true shows the create entry in the popover', async () => { + expect(await offersCreate(true, 'popover')).toBe(true); + }); + + it('CONTROL — allowCreate: true shows the create entry in the drawer', async () => { + expect(await offersCreate(true, 'drawer')).toBe(true); + }); +}); diff --git a/ui/packages/app-shell/src/utils/paramToField.ts b/ui/packages/app-shell/src/utils/paramToField.ts index 213dfa49a68..6ffc7b73e26 100644 --- a/ui/packages/app-shell/src/utils/paramToField.ts +++ b/ui/packages/app-shell/src/utils/paramToField.ts @@ -203,6 +203,9 @@ export function paramToField(param: ActionParamDef): Record { lookupColumns: param.lookupColumns, lookupFilters: param.lookupFilters, lookupPageSize: param.lookupPageSize, + // The borrowed field's `allowCreate`, the spelling `LookupField` reads; + // undefined leaves the picker's own default in place. + allowCreate: param.allowCreate, // ⭐ objectui#7357 retired `depends_on`, objectui's snake_case twin of // the spec's field-level cascade key. This emit was the ONE in-repo // framework producer of that spelling on a widget field-metadata bag — diff --git a/ui/packages/core/src/actions/ActionRunner.ts b/ui/packages/core/src/actions/ActionRunner.ts index f47c1e3b971..4fc5fe72a22 100644 --- a/ui/packages/core/src/actions/ActionRunner.ts +++ b/ui/packages/core/src/actions/ActionRunner.ts @@ -976,6 +976,12 @@ export interface ActionParamDef { lookupFilters?: unknown[]; /** Page size for the typeahead popover. */ lookupPageSize?: number; + /** + * The field's `allowCreate` (`@objectstack/spec` `FieldSchema.allowCreate`): + * `false` keeps quick-create ("+ New") out of the param's picker. Absent, the + * picker applies its own default. + */ + allowCreate?: boolean; /** Form-field dependencies that gate / parameterise the picker query. */ dependsOn?: unknown[]; diff --git a/ui/packages/fields/src/resolveActionParams.ts b/ui/packages/fields/src/resolveActionParams.ts index 63928912e7f..e9aa0af56fa 100644 --- a/ui/packages/fields/src/resolveActionParams.ts +++ b/ui/packages/fields/src/resolveActionParams.ts @@ -333,6 +333,7 @@ export const RESOLVED_ONLY_PARAM_KEYS: Readonly> = (() => lookupColumns: fromField, lookupFilters: fromField, lookupPageSize: fromField, + allowCreate: fromField, dependsOn: fromField, }; })(); @@ -462,6 +463,13 @@ interface RuntimeField { lookupFilters?: unknown[]; lookup_filters?: unknown[]; lookupPageSize?: number; + /** + * `@objectstack/spec`'s `FieldSchema.allowCreate`: whether the picker offers + * quick-create. Copied onto a field-backed lookup param with the picker keys + * above, so `allowCreate: false` on the field keeps "+ New" out of the + * param's picker too. + */ + allowCreate?: boolean; dependsOn?: unknown[]; } @@ -882,6 +890,11 @@ export function resolveActionParam( lookupColumns: field.lookupColumns, lookupFilters: field.lookupFilters ?? field.lookup_filters, lookupPageSize: field.lookupPageSize, + // The field's quick-create switch travels with its other picker + // settings: without it a field that says `allowCreate: false` still + // drew "+ New" in an action's picker, and the record made there could + // be one the action must refuse. + allowCreate: field.allowCreate, dependsOn: field.dependsOn, } : {}; diff --git a/ui/packages/fields/src/widgets/LookupField.quickCreateFilters-36865.test.tsx b/ui/packages/fields/src/widgets/LookupField.quickCreateFilters-36865.test.tsx new file mode 100644 index 00000000000..4eef4dbe39f --- /dev/null +++ b/ui/packages/fields/src/widgets/LookupField.quickCreateFilters-36865.test.tsx @@ -0,0 +1,247 @@ +/** + * 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. + */ + +/** + * A record made through the picker's quick-create is selected only when the + * picker could have offered it (objectstack#36865, half 2). + * + * ## The defect + * + * The create form takes whatever the user enters, so the record it returns can + * fail the field's `lookupFilters` — measured in an expense app: the field asks + * for an `approved` request, the form saves a `draft`. The picker selected it + * anyway; the action that read the field then refused the run. + * + * ## What holds it now + * + * The new id is re-read through the picker's own filter (the field's + * `lookupFilters` merged with the id), the same query the recents rail sends, + * so the server decides. Absent from the answer: the record is not selected, + * and the picker reopens with a line saying why, in the slot a failed create + * already uses. + * + * ## The rows + * + * - modal create, the record fails the filters: not selected, the line shows; + * - CONTROL, modal create, the record passes: selected, no line; + * - the one-field inline create (no modal host) is held the same way; + * - the re-read carries the field's filter AND the new id; + * - CONTROL, a field with no filter selects without a re-read. + */ +import { render, screen, fireEvent, waitFor, act, cleanup, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { ActionProvider } from '@object-ui/react'; +import { LookupField } from './LookupField'; + +// A selected record joins the picker's recently-used list in localStorage, and +// the rail re-reads those ids on the next open: cleared, so each row starts +// with no recents and the only id-carrying query is the one under test. +afterEach(() => { + cleanup(); + localStorage.clear(); +}); + +const TARGET = 'crm_expense_request'; +const OUTSIDE = "The record was created, but it does not match this field's filters, so it cannot be chosen here."; +const UNCHECKED = "The record was created, but it could not be checked against this field's filters, so it was not chosen. Search for it here rather than creating it again."; + +const filteredField = { + name: 'crm_expense_request', + label: 'Travel Request', + reference: TARGET, + reference_field: 'name', + lookupFilters: [{ field: 'status', operator: 'eq', value: 'approved' }], +} as any; + +/** + * The server, as the picker sees it: a query answers the rows of `table` its + * `$filter` admits. The picker sends either an object filter (field equality, + * bare or `$eq`) or a filter AST (`['and', …]`, `[field, '=', value]`, a list + * of conditions); equality under any nesting is all these rows need. + */ +function admits(row: Record, filter: unknown): boolean { + if (!filter || typeof filter !== 'object') return true; + if (Array.isArray(filter)) { + const [head, ...rest] = filter as unknown[]; + if (head === 'and') return rest.every((part) => admits(row, part)); + if (head === 'or') return rest.some((part) => admits(row, part)); + if (typeof head === 'string' && filter.length === 3) { + const [, op, value] = filter as [string, string, unknown]; + if (op === '=' || op === '==' || op === 'eq') return row[head] === value; + if (op === 'in') return Array.isArray(value) && value.includes(row[head]); + throw new Error(`test server: unhandled operator ${op}`); + } + return (filter as unknown[]).every((part) => admits(row, part)); + } + return Object.entries(filter as Record).every(([key, cond]) => { + if (key === '$and' && Array.isArray(cond)) return cond.every((part) => admits(row, part)); + const want = cond && typeof cond === 'object' && '$eq' in (cond as object) ? (cond as any).$eq : cond; + return row[key] === want; + }); +} + +/** Open the picker, type a name nothing matches, and quick-create `created`. */ +async function quickCreate(opts: { + field?: any; + created: Record; + modal: boolean; + /** Rows already in the table before the create. */ + existing?: Array>; + /** The re-read of the new id fails (a transport error). */ + reReadFails?: boolean; +}) { + const table: Array> = [...(opts.existing ?? [])]; + const ds = { + find: vi.fn(async (_object: string, params: any) => { + if (opts.reReadFails && JSON.stringify(params?.$filter ?? {}).includes(String(opts.created.id))) { + throw new Error('network down'); + } + const data = table.filter((r) => admits(r, params?.$filter)); + return { data, total: data.length }; + }), + findOne: vi.fn(), + create: vi.fn(async () => { + table.push(opts.created); + return opts.created; + }), + update: vi.fn(), + delete: vi.fn(), + }; + // The console's create-modal host: the user saved `created` in the form. + const onModal = vi.fn(async () => { + table.push(opts.created); + return { success: true, data: opts.created }; + }); + const onChange = vi.fn(); + const widget = ( + + ); + render(opts.modal ? {widget} : widget); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: /Select/i })); + }); + const input = await screen.findByRole('combobox'); + await act(async () => { + fireEvent.change(input, { target: { value: 'Trip' } }); + }); + await act(async () => { + fireEvent.click(await screen.findByText('Create new "Trip"')); + }); + return { ds, onChange, onModal }; +} + +describe('LookupField selects a quick-created record only when the field\'s filters admit it (objectstack#36865)', () => { + it('modal create, the record fails the filters: not selected, and the picker says why', async () => { + const { onChange, onModal } = await quickCreate({ + modal: true, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(onModal).toHaveBeenCalled()); + expect(await screen.findByText(OUTSIDE)).toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('CONTROL — modal create, the record passes the filters: selected, and no line', async () => { + const { onChange } = await quickCreate({ + modal: true, + created: { id: 'req_ok', name: 'Trip', status: 'approved' }, + }); + await waitFor(() => expect(onChange).toHaveBeenCalledWith('req_ok')); + expect(screen.queryByText(OUTSIDE)).toBeNull(); + }); + + it('the one-field inline create (no modal host) is held the same way', async () => { + const { ds, onChange } = await quickCreate({ + modal: false, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(ds.create).toHaveBeenCalled()); + expect(await screen.findByText(OUTSIDE)).toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); + }); + + it('the re-read asks for the new id under the field\'s own filter', async () => { + const { ds, onModal } = await quickCreate({ + modal: true, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(onModal).toHaveBeenCalled()); + await screen.findByText(OUTSIDE); + const reRead = ds.find.mock.calls.find(([, p]: any[]) => JSON.stringify(p?.$filter ?? {}).includes('req_draft')); + expect(reRead).toBeDefined(); + const filterText = JSON.stringify(reRead![1].$filter); + expect(filterText).toContain('approved'); + expect(filterText).toContain('req_draft'); + }); + + it('CONTROL — a field with no filter selects the created record without a re-read', async () => { + const { lookupFilters: _f, ...plain } = filteredField; + const { ds, onChange } = await quickCreate({ + modal: true, + field: plain, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(onChange).toHaveBeenCalledWith('req_draft')); + expect(ds.find.mock.calls.some(([, p]: any[]) => JSON.stringify(p?.$filter ?? {}).includes('req_draft'))).toBe(false); + }); +}); + +describe('after a quick-created record is turned away, the picker still lists and picks (objectstack#36865 review S1, N1)', () => { + const existing = [{ id: 'req_old', name: 'Shanghai trip', status: 'approved' }]; + + it('the notice sits above the list: the existing candidates stay listed, and one can be picked at once', async () => { + const { onChange, onModal } = await quickCreate({ + modal: true, + existing, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(onModal).toHaveBeenCalled()); + const notice = await screen.findByText(OUTSIDE); + const panel = screen.getByTestId('lookup-popover'); + expect(panel).toContainElement(notice); + const option = await waitFor(() => within(panel).getByRole('option', { name: /Shanghai trip/ })); + await act(async () => { + fireEvent.click(option); + }); + expect(onChange).toHaveBeenCalledWith('req_old'); + expect(onChange).not.toHaveBeenCalledWith('req_draft'); + }); + + it('closing the picker clears the notice; reopened, it lists the candidates with no notice', async () => { + const { onModal } = await quickCreate({ + modal: true, + existing, + created: { id: 'req_draft', name: 'Trip', status: 'draft' }, + }); + await waitFor(() => expect(onModal).toHaveBeenCalled()); + await screen.findByText(OUTSIDE); + await act(async () => { + fireEvent.keyDown(document.activeElement ?? document.body, { key: 'Escape' }); + }); + await waitFor(() => expect(screen.queryByTestId('lookup-popover')).toBeNull()); + await act(async () => { + fireEvent.click(screen.getByRole('button', { name: /Select/i })); + }); + const panel = await screen.findByTestId('lookup-popover'); + await waitFor(() => expect(within(panel).getByRole('option', { name: /Shanghai trip/ })).toBeInTheDocument()); + expect(screen.queryByText(OUTSIDE)).toBeNull(); + }); + + it('the re-read fails: not selected, and the line says the record exists and could not be checked', async () => { + const { onChange, onModal } = await quickCreate({ + modal: true, + reReadFails: true, + created: { id: 'req_new', name: 'Trip', status: 'approved' }, + }); + await waitFor(() => expect(onModal).toHaveBeenCalled()); + expect(await screen.findByText(UNCHECKED)).toBeInTheDocument(); + expect(onChange).not.toHaveBeenCalled(); + }); +}); diff --git a/ui/packages/fields/src/widgets/LookupField.tsx b/ui/packages/fields/src/widgets/LookupField.tsx index 32d98647559..c6ad76feee4 100644 --- a/ui/packages/fields/src/widgets/LookupField.tsx +++ b/ui/packages/fields/src/widgets/LookupField.tsx @@ -897,7 +897,17 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro const searchQuery = popoverQuery.search; const loading = popoverQuery.loading; const totalCount = popoverQuery.total; - const error = popoverQuery.error ?? createError; + // The fetch error alone gates the list. A create error — a failed inline + // create, or a quick-created record this picker will not take + // (objectstack#36865) — is a notice drawn above the list instead: the + // candidates stay listed and selectable, so the user can pick an existing + // record right after reading why the new one was not chosen. + const error = popoverQuery.error; + // The notice belongs to the panel it was raised in: closing the picker + // clears it, so a later open starts clean. + useEffect(() => { + if (!isOpen) setCreateError(null); + }, [isOpen]); // Built from the row with its relations collapsed to ids — see // `candidateExpand` for why the option never sees the expanded form. const fetchedOptions = useMemo( @@ -1625,6 +1635,41 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro perms, }).allowed; const canCreate = !!onCreateNew || (allowCreate && createGranted && (hasActionProvider || hasDataSource)); + // objectstack#36865 — a record made through quick-create is selected only + // when this picker could have offered it. The create form takes whatever the + // user enters, so the new record can fail the field's `lookupFilters` (a + // `draft` where the field asks for `approved`); selected anyway, it sat in + // the field until the server refused the save or the action. So the new id + // is re-read through the picker's own filter — `popoverFilter` merged with + // the id through `mergeFilterNodes`, the recents rail's query — and the + // SERVER decides, exactly as it does for every listed candidate. Absent + // from the answer: not selected, and the picker reopens saying why. A + // picker with no filter, or no data source to ask, selects as before. + // A failed re-read is reported as unchecked, never read as a pass. + const admitCreated = useCallback( + async (created: Record): Promise => { + if (!popoverFilter || !hasDataSource || !dataSource || !referenceTo) return true; + const rid = recordValue(created, idField); + if (rid === undefined || rid === null) return true; + let admitted = false; + try { + const res = await dataSource.find(referenceTo, { + $filter: mergeFilterNodes(popoverFilter, { [idField]: rid }), + $top: 1, + } as QueryParams); + const rows = (res as any)?.data ?? res ?? []; + admitted = Array.isArray(rows) && rows.length > 0; + if (!admitted) setCreateError(t('lookup.createdOutsideFilters')); + } catch { + // Fail closed, and say the record EXISTS: a bare transport error read + // as "the create failed" invites a second, duplicate create. + setCreateError(t('lookup.createdUnchecked')); + } + if (!admitted) setIsOpen(true); + return admitted; + }, + [popoverFilter, hasDataSource, dataSource, referenceTo, idField, t], + ); const handleCreateNew = useCallback( async (q: string) => { const label = (q || '').trim(); @@ -1665,6 +1710,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro }, } as any); if (result?.success && result.data) { + if (!(await admitCreated(result.data))) return; const opt = recordToOption(result.data, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, perms, referenceTo); handleSelect(opt, result.data); return; @@ -1681,6 +1727,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro setCreating(true); try { const created = await (dataSource as any).create(referenceTo, { ...(dependentFilter ?? {}), [displayField]: label }); + if (!(await admitCreated(created))) return; const opt = recordToOption(created, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, perms, referenceTo); handleSelect(opt, created); } catch (err) { @@ -1689,7 +1736,7 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro setCreating(false); } }, - [onCreateNew, allowCreate, createGranted, referenceTo, hasActionProvider, execute, dataSource, displayField, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, handleSelect, perms, dependentFilter], + [onCreateNew, allowCreate, createGranted, referenceTo, hasActionProvider, execute, dataSource, displayField, declaredDisplayField, idField, effectiveDescriptionField, refObjectSchema, handleSelect, perms, dependentFilter, admitCreated], ); /** @@ -2094,6 +2141,14 @@ export function LookupField({ value, onChange, field, readonly, error: fieldErro )} + {/* Create notice — above the list, never in place of it. */} + {createError && ( +
+ +

{createError}

+
+ )} + {/* Error state */} {error && (
diff --git a/ui/packages/fields/src/widgets/useFieldTranslation.ts b/ui/packages/fields/src/widgets/useFieldTranslation.ts index e00abc8940b..f41a1093a0e 100644 --- a/ui/packages/fields/src/widgets/useFieldTranslation.ts +++ b/ui/packages/fields/src/widgets/useFieldTranslation.ts @@ -72,6 +72,12 @@ const FIELD_DEFAULTS: Record = { 'lookup.nextPage': 'Next page', 'lookup.jumpToPage': 'Jump to page', 'lookup.retry': 'Retry', + // objectstack#36865 — why a quick-created record was not selected: it fails + // the field's `lookupFilters`. Same value as the `en` pack. + 'lookup.createdOutsideFilters': "The record was created, but it does not match this field's filters, so it cannot be chosen here.", + // objectstack#36865 — the re-read that checks a quick-created record failed: + // the record exists, so the line says so. Same value as the `en` pack. + 'lookup.createdUnchecked': "The record was created, but it could not be checked against this field's filters, so it was not chosen. Search for it here rather than creating it again.", // objectui#3231 — the empty / dependency-gated state of the fixed-option // widgets (select, multiselect, radio, checkboxes). Only used when the host // supplies no `emptyHint`; the gate sentence shares its key with the form diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index 6481e93f10f..7c0bf2be5f7 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -40,6 +40,8 @@ const ar = { allResults: 'كل النتائج', createNew: 'إنشاء جديد', createNamed: 'إنشاء «{{name}}»', + createdOutsideFilters: 'تم إنشاء السجل، لكنه لا يطابق عوامل تصفية هذا الحقل، لذا لا يمكن اختياره هنا.', + createdUnchecked: 'تم إنشاء السجل، لكن تعذّر التحقق من مطابقته لعوامل تصفية هذا الحقل، لذا لم يتم اختياره. ابحث عنه هنا بدلًا من إنشائه مرة أخرى.', showingResults: 'عرض {{shown}} من {{total}} نتيجة', showAllResults: 'عرض كل النتائج ({{count}})', selectedBadge: 'محدد', diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 3618aa66269..a2b49a85180 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -40,6 +40,8 @@ const de = { allResults: 'Alle Ergebnisse', createNew: 'Neu erstellen', createNamed: '„{{name}}“ erstellen', + createdOutsideFilters: 'Der Datensatz wurde erstellt, entspricht aber nicht den Filtern dieses Felds und kann hier daher nicht ausgewählt werden.', + createdUnchecked: 'Der Datensatz wurde erstellt, konnte aber nicht gegen die Filter dieses Felds geprüft werden und wurde daher nicht ausgewählt. Suchen Sie ihn hier, statt ihn erneut anzulegen.', showingResults: '{{shown}} von {{total}} Ergebnissen', showAllResults: 'Alle Ergebnisse anzeigen ({{count}})', selectedBadge: 'Ausgewählt', diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index c93b6f83dec..5528dcb115b 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -49,6 +49,9 @@ const en = { noRecords: 'No records found', createNew: 'Create new', createNamed: 'Create new "{{name}}"', + // objectstack#36865 — a quick-created record the field's lookupFilters exclude is not selected; this says why. + createdOutsideFilters: "The record was created, but it does not match this field's filters, so it cannot be chosen here.", + createdUnchecked: "The record was created, but it could not be checked against this field's filters, so it was not chosen. Search for it here rather than creating it again.", showingResults: 'Showing {{shown}} of {{total}} results', showAllResults: 'Show all results ({{count}})', selectedBadge: 'Selected', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index f68c888e982..83479fee284 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -40,6 +40,8 @@ const es = { allResults: 'Todos los resultados', createNew: 'Crear nuevo', createNamed: 'Crear «{{name}}»', + createdOutsideFilters: 'El registro se creó, pero no cumple los filtros de este campo, así que no se puede elegir aquí.', + createdUnchecked: 'El registro se creó, pero no se pudo comprobar si cumple los filtros de este campo, así que no se ha elegido. Búsquelo aquí en lugar de crearlo de nuevo.', showingResults: 'Mostrando {{shown}} de {{total}} resultados', showAllResults: 'Ver todos los resultados ({{count}})', selectedBadge: 'Seleccionado', diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index c42e540aaa9..22f15954467 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -40,6 +40,8 @@ const fr = { allResults: 'Tous les résultats', createNew: 'Créer', createNamed: 'Créer « {{name}} »', + createdOutsideFilters: 'L’enregistrement a été créé, mais il ne correspond pas aux filtres de ce champ ; il ne peut donc pas être choisi ici.', + createdUnchecked: 'L’enregistrement a été créé, mais sa conformité aux filtres de ce champ n’a pas pu être vérifiée ; il n’a donc pas été choisi. Recherchez-le ici plutôt que de le créer à nouveau.', showingResults: 'Affichage de {{shown}} sur {{total}} résultats', showAllResults: 'Afficher tous les résultats ({{count}})', selectedBadge: 'Sélectionné', diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index a1fdd70062b..a4f1eee6638 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -40,6 +40,8 @@ const ja = { allResults: 'すべての結果', createNew: '新規作成', createNamed: '「{{name}}」を新規作成', + createdOutsideFilters: 'レコードは作成されましたが、この項目の絞り込み条件に一致しないため、ここでは選択できません。', + createdUnchecked: 'レコードは作成されましたが、この項目の絞り込み条件に合うか確認できなかったため、選択していません。もう一度作成せず、ここで検索してください。', showingResults: '{{total}} 件中 {{shown}} 件を表示', showAllResults: 'すべての結果を表示 ({{count}})', selectedBadge: '選択済み', diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index 25678dcb68a..2956e154147 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -40,6 +40,8 @@ const ko = { allResults: '모든 결과', createNew: '새로 만들기', createNamed: '“{{name}}” 새로 만들기', + createdOutsideFilters: '레코드가 생성되었지만 이 필드의 필터 조건에 맞지 않아 여기에서 선택할 수 없습니다.', + createdUnchecked: '레코드가 생성되었지만 이 필드의 필터 조건에 맞는지 확인하지 못해 선택하지 않았습니다. 다시 만들지 말고 여기에서 검색하세요.', showingResults: '{{total}}개 중 {{shown}}개 표시', showAllResults: '모든 결과 보기 ({{count}})', selectedBadge: '선택됨', diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index f200d78d394..06e8bd11b4c 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -40,6 +40,8 @@ const pt = { allResults: 'Todos os resultados', createNew: 'Criar novo', createNamed: 'Criar “{{name}}”', + createdOutsideFilters: 'O registro foi criado, mas não atende aos filtros deste campo, por isso não pode ser escolhido aqui.', + createdUnchecked: 'O registro foi criado, mas não foi possível verificar se ele atende aos filtros deste campo, por isso não foi escolhido. Procure-o aqui em vez de criá-lo novamente.', showingResults: 'Mostrando {{shown}} de {{total}} resultados', showAllResults: 'Ver todos os resultados ({{count}})', selectedBadge: 'Selecionado', diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 0e654cd1e4b..bb98d6bc730 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -40,6 +40,8 @@ const ru = { allResults: 'Все результаты', createNew: 'Создать', createNamed: 'Создать «{{name}}»', + createdOutsideFilters: 'Запись создана, но не соответствует фильтрам этого поля, поэтому её нельзя выбрать здесь.', + createdUnchecked: 'Запись создана, но проверить её на соответствие фильтрам этого поля не удалось, поэтому она не выбрана. Найдите её здесь поиском, а не создавайте заново.', showingResults: 'Показано {{shown}} из {{total}} результатов', showAllResults: 'Показать все результаты ({{count}})', selectedBadge: 'Выбрано', diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e7d97485756..2a779b84d1e 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -52,6 +52,8 @@ const zh = { noRecords: '未找到记录', createNew: '新建', createNamed: '新建“{{name}}”', + createdOutsideFilters: '记录已创建,但不符合此字段的筛选条件,因此不能在这里选择。', + createdUnchecked: '记录已创建,但未能核对它是否符合此字段的筛选条件,因此没有选中。请在这里搜索它,不要重复创建。', showingResults: '显示 {{total}} 条结果中的 {{shown}} 条', showAllResults: '查看全部结果({{count}})', selectedBadge: '已选', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 39fba0d8405..a1047baee67 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -52,6 +52,8 @@ const zhHant = { noRecords: '未找到記錄', createNew: '新建', createNamed: '新建“{{name}}”', + createdOutsideFilters: '記錄已建立,但不符合此欄位的篩選條件,因此不能在這裡選擇。', + createdUnchecked: '記錄已建立,但未能核對它是否符合此欄位的篩選條件,因此沒有選中。請在這裡搜尋它,不要重複建立。', showingResults: '顯示 {{total}} 條結果中的 {{shown}} 條', showAllResults: '檢視全部結果({{count}})', selectedBadge: '已選', diff --git a/ui/packages/plugin-grid/src/__tests__/bulkFieldBackedParam-12105.test.tsx b/ui/packages/plugin-grid/src/__tests__/bulkFieldBackedParam-12105.test.tsx index 82828712b0e..2923043007d 100644 --- a/ui/packages/plugin-grid/src/__tests__/bulkFieldBackedParam-12105.test.tsx +++ b/ui/packages/plugin-grid/src/__tests__/bulkFieldBackedParam-12105.test.tsx @@ -45,7 +45,7 @@ */ import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; -import { render, screen, waitFor, fireEvent, cleanup } from '@testing-library/react'; +import { render, screen, waitFor, fireEvent, cleanup, act, within } from '@testing-library/react'; import '@testing-library/jest-dom'; import React from 'react'; @@ -58,7 +58,7 @@ vi.mock('@object-ui/permissions', async (importOriginal) => { }); import type { BulkActionDef } from '@object-ui/types'; -import { registerAllFields, resolveActionParam, type ResolveActionParamsContext } from '@object-ui/fields'; +import { LookupField, registerAllFields, resolveActionParam, type ResolveActionParamsContext } from '@object-ui/fields'; import { ActionProvider, MetadataCtx, type MetadataContextValue } from '@object-ui/react'; import { ObjectGrid } from '../ObjectGrid'; import { resolveBulkActions, resolvePromotedBulkParams, unresolvedFieldOf } from '../resolveBulkActions'; @@ -450,3 +450,81 @@ describe('ObjectGrid bulk dialog — a field-backed param on the selection bar ( } }); }); + +/** + * objectstack#36865 — the selection toolbar's picker honours the borrowed + * field's `allowCreate`, as the record header's does. `toBulkParam` carried + * the field's other picker settings and dropped this one, so a field + * declaring `allowCreate: false` still drew "+ New" in the bulk dialog. The + * rows run the real fold (`resolvePromotedBulkParams` → `bulkParamToField` → + * `LookupField`) on both faces of the picker. + */ +describe('the bulk picker honours the borrowed field\'s allowCreate (objectstack#36865)', () => { + const realInnerWidth = Object.getOwnPropertyDescriptor(window, 'innerWidth'); + const realMatchMedia = window.matchMedia; + const setViewportWidth = (width: number) => { + Object.defineProperty(window, 'innerWidth', { writable: true, configurable: true, value: width }); + window.matchMedia = ((query: string) => ({ + matches: window.innerWidth < 768, + media: query, + onchange: null, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + dispatchEvent: () => false, + })) as any; + }; + afterEach(() => { + cleanup(); + if (realInnerWidth) Object.defineProperty(window, 'innerWidth', realInnerWidth); + window.matchMedia = realMatchMedia; + }); + + const bulkWidgetField = (allowCreate: boolean) => { + const member = { + name: 'crm_campaign_member', + fields: { crm_campaign: { ...FILTERED_CAMPAIGN_MEMBER.fields.crm_campaign, allowCreate } }, + }; + const [param] = resolvePromotedBulkParams(promote(ADD_TO_CAMPAIGN), ctx([member])).params ?? []; + return bulkParamToField(param, false); + }; + + const offersCreate = async (allowCreate: boolean, face: 'popover' | 'drawer'): Promise => { + setViewportWidth(face === 'drawer' ? 390 : 1280); + const field = bulkWidgetField(allowCreate); + const ds = { + find: vi.fn(async () => ({ data: [{ id: 'c1', name: 'Spring launch', status: 'planning' }], total: 1 })), + findOne: vi.fn(), + create: vi.fn(), + update: vi.fn(), + delete: vi.fn(), + }; + render(); + await act(async () => { + fireEvent.click(screen.getByTestId(`lookup-trigger-${field.name}`)); + }); + const panel = await screen.findByTestId(face === 'drawer' ? 'lookup-drawer' : 'lookup-popover'); + await waitFor(() => expect(within(panel).getAllByRole('option')).toHaveLength(1)); + return within(panel).queryByTestId('lookup-create-new') !== null; + }; + + it('the bulk widget field carries the field\'s allowCreate', () => { + expect(bulkWidgetField(false).allowCreate).toBe(false); + expect(bulkWidgetField(true).allowCreate).toBe(true); + }); + + it('allowCreate: false — no create entry in the desktop popover', async () => { + expect(await offersCreate(false, 'popover')).toBe(false); + }); + + it('allowCreate: false — no create entry in the phone drawer', async () => { + expect(await offersCreate(false, 'drawer')).toBe(false); + }); + + it('CONTROL — allowCreate: true shows the create entry on both faces', async () => { + expect(await offersCreate(true, 'popover')).toBe(true); + cleanup(); + expect(await offersCreate(true, 'drawer')).toBe(true); + }); +}); diff --git a/ui/packages/plugin-grid/src/resolveBulkActions.ts b/ui/packages/plugin-grid/src/resolveBulkActions.ts index 14941657c24..563496e5576 100644 --- a/ui/packages/plugin-grid/src/resolveBulkActions.ts +++ b/ui/packages/plugin-grid/src/resolveBulkActions.ts @@ -153,7 +153,7 @@ export function unresolvedFieldOf(param: BulkActionParam): string | undefined { * promoted param always delivered them (the hand-mapper spread the raw param). * * The picker settings a reference-bearing field declares — `lookupFilters`, - * `lookupColumns`, `lookupPageSize` and `descriptionField` — are carried under + * `lookupColumns`, `lookupPageSize`, `descriptionField` and `allowCreate` — are carried under * their own names, the spellings `LookupField` reads and the ones app-shell's * `paramToField` hands the single-record dialog's picker * (objectstack-ai/objectstack#26951). No rename is needed: `BulkActionParam`'s @@ -188,6 +188,7 @@ function toBulkParam(resolved: ActionParamDef): BulkActionParam | null { ...(resolved.lookupColumns !== undefined && { lookupColumns: resolved.lookupColumns }), ...(resolved.lookupFilters !== undefined && { lookupFilters: resolved.lookupFilters }), ...(resolved.lookupPageSize !== undefined && { lookupPageSize: resolved.lookupPageSize }), + ...(resolved.allowCreate !== undefined && { allowCreate: resolved.allowCreate }), ...(resolved.accept !== undefined && { accept: resolved.accept }), ...(resolved.maxSize !== undefined && { maxSize: resolved.maxSize }), ...(resolved.unresolvedField !== undefined && { [UNRESOLVED_FIELD_KEY]: resolved.unresolvedField }), diff --git a/ui/packages/types/src/__tests__/page-nav-misc-spec-parity.test.ts b/ui/packages/types/src/__tests__/page-nav-misc-spec-parity.test.ts index 8e431fb3021..40bcb57d383 100644 --- a/ui/packages/types/src/__tests__/page-nav-misc-spec-parity.test.ts +++ b/ui/packages/types/src/__tests__/page-nav-misc-spec-parity.test.ts @@ -435,7 +435,7 @@ type LocalOnlyParamKey = Exclude; describe('ActionParam declares ONLY authorable keys (objectui#3174)', () => { it('does not declare the resolved-side picker group', () => { - // These nine live on `@object-ui/core`'s RESOLVED `ActionParamDef`, which + // These ten live on `@object-ui/core`'s RESOLVED `ActionParamDef`, which // `resolveActionParams()` EMITS. Declaring them on the authoring type made // `{ type: 'lookup', referenceTo: 'account' }` compile, lose its picker // target in the resolver, and render as a record-id text box — while the @@ -466,11 +466,14 @@ describe('ActionParam declares ONLY authorable keys (objectui#3174)', () => { const withLookupPageSize: ActionParam = { name: 'p', lookupPageSize: 20 }; // @ts-expect-error inherited from the referenced field, not authored const withDependsOn: ActionParam = { name: 'p', dependsOn: [] }; + // @ts-expect-error inherited from the referenced field, not authored (objectstack#36865) + const withAllowCreate: ActionParam = { name: 'p', allowCreate: false }; expect([ withDisplayField, withIdField, withDescriptionField, withTitleFormat, withLookupColumns, withLookupFilters, withLookupPageSize, withDependsOn, - ]).toHaveLength(8); + withAllowCreate, + ]).toHaveLength(9); }); it('keeps `reference` as the one authorable picker spelling', () => {