diff --git a/.changeset/39630-design-mode-widget-new-dataset.md b/.changeset/39630-design-mode-widget-new-dataset.md new file mode 100644 index 00000000000..63400993980 --- /dev/null +++ b/.changeset/39630-design-mode-widget-new-dataset.md @@ -0,0 +1,18 @@ +--- +"@object-ui/app-shell": patch +"@object-ui/i18n": patch +--- + +feat(app-shell): in the app's design mode, a dashboard card's New dataset publishes the dataset at once into the dashboard's package and picks it for the card + +Clause-②: no +Metadata-protocol: none + +Who sees it: a workspace admin designing a dashboard in the app's design mode (the dashboard's Edit, or a dashboard opened from App Studio). + +- **A selected card's dataset picker offers New dataset** in the design mode, as it does in App Studio. While no dataset reads one of the app's objects, the card panel says so in one sentence. +- **New dataset writes nothing until you name the dataset and press Create.** The dataset is then saved and published in the same act into the dashboard's own package (a writable app package, including a dashboard that an app's customization package owns), and picked for the card, so the dashboard you then save reads a published dataset. +- **A refused publish leaves no dataset or draft behind** and shows the server's reason in the dialog; the card stays unbound. +- **No entry where the dashboard's own package cannot hold the dataset**: an installed (read-only) app's dashboard, which the design mode saves as a customization of that app, offers no New dataset, because its cards read as the installed app's package and could not read a dataset held only in the customization package. Neither does a dashboard that names no package, or one the design mode refuses. +- App Studio's own New dataset is unchanged (it still saves a draft, published with the package). +- Known residue: a dataset created this way stays published if you then Cancel the dashboard edit. diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts index b78709a35aa..eb348691853 100644 --- a/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts +++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.test.ts @@ -12,6 +12,7 @@ import { describe, it, expect, vi } from 'vitest'; import '@objectstack/lint'; import '@objectstack/formula'; import { + datasetPublishFor, filtersSectionLabel, openDashboardForEdit, withAddedWidget, @@ -188,3 +189,29 @@ describe('the page\'s own buffer edits', () => { expect(filtersSectionLabel('en-US')).toBe('Filters'); }); }); + +describe('where a card\'s New dataset publishes in the design mode (objectstack#39630)', () => { + it('a writable owning package: the dataset is published there', async () => { + const publish = datasetPublishFor({ kind: 'package', packageId: 'crm' }); + expect(publish?.packageId).toBe('crm'); + await expect(publish!.pickPackage()).resolves.toBe('crm'); + }); + + it('a dashboard an app\'s customization pair owns is a writable package like any other', async () => { + const publish = datasetPublishFor({ kind: 'package', packageId: 'crm.custom' }); + expect(publish?.packageId).toBe('crm.custom'); + await expect(publish!.pickPackage()).resolves.toBe('crm.custom'); + }); + + it('an installed (read-only) app\'s dashboard, saved as an override in its pair: no entry, listed pair or not', () => { + // Its cards read as the installed package, whose closure does not reach the pair (ADR-0150 D3). + expect(datasetPublishFor({ kind: 'customization', base: 'crm', basedOn: '3.0.0', pair: null })).toBeNull(); + expect(datasetPublishFor({ kind: 'customization', base: 'crm', basedOn: '3.0.0', pair: 'crm.custom' })).toBeNull(); + }); + + it('no package to name, or nothing open: no entry', () => { + expect(datasetPublishFor({ kind: 'unbound' })).toBeNull(); + expect(datasetPublishFor(null)).toBeNull(); + expect(datasetPublishFor(undefined)).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx index 7a2c8ecac6d..f475493c721 100644 --- a/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx +++ b/ui/packages/app-shell/src/views/DashboardInPageEditor.tsx @@ -40,6 +40,13 @@ * a menu entry may name apart from the app's (objectstack#39459): a gate * that answers no refuses it at selection too, with the reason. * + * objectstack#39630 — a card's dataset picker offers New dataset here too + * (ruling record 7408596103, A): the dataset is saved and published at once + * into the dashboard's own package ({@link datasetPublishFor}), then picked + * for the card, so the dashboard the bar's Save publishes reads a published + * dataset. A dashboard with no package of its own to write, or an installed + * app's (saved as an override in its customization pair), offers none. + * * Out of scope here: undo, a business user's own copy, a new dashboard, chart * drawing and drill-down. */ @@ -78,6 +85,7 @@ import { getDashboardForm } from './metadata-admin/dashboard-schema.js'; import { useMetadataLocale, type SupportedLocale } from './metadata-admin/i18n.js'; import type { MetadataSelection } from './metadata-admin/preview-registry.js'; import { ServedWidgetTextContext, servedWidgetTextOf } from './studio-design/servedDashboardText.js'; +import { DatasetPublishAuthoringContext, type DatasetPublishAuthoring } from './studio-design/datasetCreate.js'; import { studioPackagePath } from './studio-design/studioAddress.js'; /** Where the editor would save, as read at open (nothing is written to open). */ @@ -226,6 +234,26 @@ export function withResizedWidget( return { ...doc, widgets: next }; } +/** + * objectstack#39630 — where a card's New dataset writes in the design mode: + * the dashboard's own package, when the bar's Save writes the dashboard there + * (a writable package; a dashboard an app's customization pair owns is one), + * so the dataset and the dashboard that reads it land together and the card + * reads it as its own package's (ADR-0150 D3). + * + * `null`, so no entry is offered, where there is no such package: a dashboard + * bound to none, nothing open, and an installed (read-only) app's dashboard, + * whose Save writes an override into the app's customization pair. That + * override is still served, and its cards read, as the installed app's + * package, whose dependency closure does not reach the pair: a dataset made + * there would be refused to the card (409) in the editor and after the Save. + */ +export function datasetPublishFor(target: WritableDashboardEditTarget | null | undefined): DatasetPublishAuthoring | null { + if (!target || target.kind !== 'package') return null; + const packageId = target.packageId; + return { packageId, pickPackage: async () => packageId }; +} + /** The label of the panel section that edits the page filters (`globalFilters`). */ export function filtersSectionLabel(locale: SupportedLocale): string | null { const form = getDashboardForm(locale); @@ -287,6 +315,9 @@ export function DashboardEditActions({ onAddCard }: { onAddCard: (type: string) * served dashboard, `published` the stored document the edit opened, paired * widget by widget ({@link servedWidgetTextOf}). Without the pair the title box * shows the stored source and an edit there replaces it. + * + * objectstack#39630: `datasetPublish` ({@link DashboardInPageEdit.datasetPublish}) + * is handed to the card panel's New dataset; absent, the panel offers none. */ export function DashboardEditPanel({ name, @@ -299,9 +330,12 @@ export function DashboardEditPanel({ served, published, shipped = null, + datasetPublish = null, }: { name: string; draft: Record; + /** Where a card's New dataset publishes, `null` for no entry. */ + datasetPublish?: DatasetPublishAuthoring | null; /** The dashboard as the page serves it, in the session's language. */ served?: Record | null; /** The stored document the edit state opened, before any change. */ @@ -342,6 +376,7 @@ export function DashboardEditPanel({ data-testid="dashboard-edit-panel" > + {selection?.kind === 'widget' ? ( )} + ); @@ -488,6 +524,12 @@ export interface DashboardInPageEdit { shipped: Record | null; /** A change to this dashboard is staged. */ dirty: boolean; + /** + * objectstack#39630 — where a card's New dataset publishes + * ({@link datasetPublishFor} of the save target), `null` unless editing or + * when there is no package to name. + */ + datasetPublish: DatasetPublishAuthoring | null; selection: MetadataSelection | null; revealFilters: boolean; /** Enter the mode with this dashboard selected; `false` when the mode refuses (it says why). */ @@ -635,6 +677,9 @@ export function useDashboardInPageEdit({ [stageDraft], ); + const editTarget = editing ? current!.target : null; + const datasetPublish = React.useMemo(() => datasetPublishFor(editTarget), [editTarget]); + const enterOpening = mode?.enterOpening; const open = React.useCallback( () => (enterOpening && name ? enterOpening({ select: { type: 'dashboard', name } }) : false), @@ -650,6 +695,7 @@ export function useDashboardInPageEdit({ published: editing ? current!.published : null, shipped: editing ? current!.shipped : null, dirty: change.value !== undefined, + datasetPublish, selection: editing ? selection : null, revealFilters, open, diff --git a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx index 12e2c76513b..8f7411acc3f 100644 --- a/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.inPageEdit-36372.test.tsx @@ -30,19 +30,25 @@ * - where Studio's Customize is walled for the caller, or a draft is * already pending, the dashboard is refused when it is selected: drawn * read-only with the reason, and nothing is written; - * - the bar's Cancel drops every change and writes nothing. + * - the bar's Cancel drops every change and writes nothing; + * - objectstack#39630: a card's New dataset publishes into the dashboard's + * own writable package and picks the dataset for the card; an installed + * app's dashboard offers none. * * Studio's two dashboard panels and the add-card picker are stubbed to the - * props this view hands them: their own behaviour is pinned beside them. + * props this view hands them: their own behaviour is pinned beside them. The + * objectstack#39630 cases draw the real card panel (`inspector.real`). */ import * as React from 'react'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; -import { render, screen, act, cleanup, fireEvent, waitFor } from '@testing-library/react'; +import { render, screen, act, cleanup, fireEvent, waitFor, within } from '@testing-library/react'; import { MetadataCtx } from '@object-ui/react'; // Paid during collection, not inside a case's clock: Studio's card panel -// reaches `@objectstack/lint` through a dynamic import (check:test-source-alias). +// reaches `@objectstack/lint` through a dynamic import (check:test-source-alias), +// and its New dataset dialog `@objectstack/formula` (objectstack#39630). import '@objectstack/lint'; +import '@objectstack/formula'; const meta = vi.hoisted(() => ({ value: null as unknown })); /** `reading`: the gate's package list not answered yet (objectstack#39459). */ @@ -65,6 +71,8 @@ const route = vi.hoisted(() => ({ navigate: null as null | ((...a: unknown[]) => void), })); const toasts = vi.hoisted(() => ({ success: [] as unknown[], error: [] as unknown[] })); +/** objectstack#39630 — draw Studio's real card panel instead of its stub. */ +const inspector = vi.hoisted(() => ({ real: false })); vi.mock('../providers/MetadataProvider', () => ({ useMetadata: () => meta.value })); vi.mock('react-router-dom', () => ({ @@ -118,20 +126,22 @@ vi.mock('sonner', () => ({ info: vi.fn(), }, })); -vi.mock('./metadata-admin/inspectors/DashboardWidgetInspector', async () => { +vi.mock('./metadata-admin/inspectors/DashboardWidgetInspector', async (importOriginal) => { // objectstack#36373: the stub reads the served title the real panel reads. const { useServedWidgetText } = await import('./studio-design/servedDashboardText'); + const { DashboardWidgetInspector: Real } = await importOriginal>(); + const Stub = (p: any) => { + const pair = useServedWidgetText()?.widgets.get(p.selection.id); + return ( +
+ {p.selection.id} + {pair ? `${pair.served} ← ${pair.authored}` : 'none'} + {JSON.stringify(p.shipped ?? null)} +
+ ); + }; return { - DashboardWidgetInspector: (p: any) => { - const pair = useServedWidgetText()?.widgets.get(p.selection.id); - return ( -
- {p.selection.id} - {pair ? `${pair.served} ← ${pair.authored}` : 'none'} - {JSON.stringify(p.shipped ?? null)} -
- ); - }, + DashboardWidgetInspector: (p: any) => (inspector.real ? : ), }; }); vi.mock('./metadata-admin/inspectors/DashboardDefaultInspector', () => ({ @@ -159,6 +169,7 @@ import { } from '../layout/designMode'; import { DesignModeBar } from '../layout/DesignModeBar'; import { useDesignModeArrival } from '../layout/useDesignModeArrival'; +import { t } from './metadata-admin/i18n'; /** The served dashboard: translated for the session, with its read's decorations. */ const served = { @@ -269,6 +280,7 @@ beforeEach(() => { route.state = null; route.search = ''; route.navigate = null; + inspector.real = false; }); afterEach(() => { @@ -1097,3 +1109,212 @@ describe('a dashboard published by someone else since it was opened is refused a expect(screen.getByTestId('stub-draft-label')).toHaveTextContent('Renamed (36372)'); }); }); + +/** + * objectstack#39630 — in the design mode, a card's dataset picker offers New + * dataset (ruling record 7408596103, A): the dataset is saved and published + * at once into the dashboard's own writable package, then picked for the + * card. An installed app's dashboard (saved as an override in its pair) + * offers none. Studio's REAL card panel, entry and dialog are drawn + * here, over a metadata client that keeps what it is told. + */ +describe('DashboardView in the design mode: a card\'s New dataset (objectstack#39630)', () => { + const REPAIR_ORDER = { + name: 'repair_order', + label: 'Repair order', + _packageId: 'crm', + fields: { + name: { type: 'text', label: 'Name' }, + urgency: { type: 'select', label: 'Urgency', options: [{ value: 'high', label: 'High' }] }, + }, + }; + const OTHER_DATASET = { name: 'task_metrics', label: 'Task Metrics', object: 'sys_task', _packageId: 'platform', measures: [{ name: 'count', aggregate: 'count' }], dimensions: [] }; + + /** What the server holds, written only through the client's doors. */ + let world: { datasets: Array>; drafts: Map>; publishRefusal: Error | null }; + /** Every write, in order: `[door, type, name, packageId]`. */ + let writes: Array<[string, string, string, string | undefined]>; + /** Dataset catalog reads made in the draft world (the dialog's object reads are always draft-overlaid). */ + let draftDatasetReads: number; + + function worldClient(over: Partial> = {}) { + const base = makeClient({ + save: vi.fn(async (type: string, name: string, body: Record, options: { packageId?: string }) => { + writes.push(['save', type, name, options?.packageId]); + if (type === 'dataset') world.drafts.set(name, body); + return { version: `${name}-draft` }; + }), + publish: vi.fn(async (type: string, name: string, options: { packageId?: string }) => { + writes.push(['publish', type, name, options?.packageId]); + if (type !== 'dataset') return {}; + if (world.publishRefusal) throw world.publishRefusal; + world.datasets = [...world.datasets, { ...world.drafts.get(name), _packageId: options?.packageId }]; + world.drafts.delete(name); + return {}; + }), + ...over, + }); + const c: any = { + ...base, + reset: vi.fn(async (type: string, name: string, options: { packageId?: string }) => { + writes.push(['reset', type, name, options?.packageId]); + if (type === 'dataset') world.drafts.delete(name); + return {}; + }), + list: vi.fn(async (type: string) => (type === 'object' ? [REPAIR_ORDER] : world.datasets)), + listDrafts: vi.fn(async () => [...world.drafts.values()]), + get: vi.fn(async (type: string, name: string) => + type === 'object' ? (name === REPAIR_ORDER.name ? REPAIR_ORDER : null) : (world.datasets.find((d) => d.name === name) ?? null), + ), + }; + c.withPreviewDrafts = vi.fn(() => ({ + ...c, + list: vi.fn(async (type: string) => { + if (type === 'dataset') draftDatasetReads += 1; + return c.list(type); + }), + })); + return c; + } + + const dataSource = { queryDataset: vi.fn(async () => ({ rows: [], fields: [] })) }; + + beforeEach(() => { + inspector.real = true; + world = { datasets: [OTHER_DATASET], drafts: new Map(), publishRefusal: null }; + writes = []; + draftDatasetReads = 0; + client.value = worldClient(); + }); + + /** Enter the mode and select the dashboard's one card. */ + async function selectCard() { + mount(served, dataSource); + await openEdit(); + fireEvent.click(screen.getByTestId('dashboard-preview-widget-widget_total')); + } + + /** Open New dataset under the card's picker, name the dataset, group by Urgency, press Create. */ + async function createRepairOrders() { + fireEvent.click(await screen.findByTestId('widget-new-dataset-open')); + const dialog = await screen.findByRole('dialog', { name: t('engine.studio.interfaces.newDataset.publishTitle', 'en-US') }); + expect(dialog).toHaveTextContent(t('engine.studio.interfaces.newDataset.publishWidgetDescription', 'en-US')); + fireEvent.change(within(dialog).getByLabelText(t('engine.studio.interfaces.newDataset.nameLabel', 'en-US')), { + target: { value: 'Repair orders' }, + }); + // Opened on the app's one object: its fields are offered at once. + fireEvent.click(await within(dialog).findByRole('checkbox', { name: /^Urgency\b/ })); + await act(async () => { + fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createLive', 'en-US') })); + }); + return dialog; + } + + it('on a writable package the card offers New dataset; Create publishes it there and picks it; the bar\'s Save publishes the card reading it', async () => { + await selectCard(); + // No dataset reads the app's objects yet: the card panel says so, in the app's words. + expect(await screen.findByTestId('widget-new-dataset-hint')).toHaveTextContent( + t('engine.studio.interfaces.newDataset.noAppDatasets', 'en-US'), + ); + expect(writes).toEqual([]); + await createRepairOrders(); + + // Saved and published at once, in the dashboard's package, before anything of the dashboard. + await waitFor(() => expect(writes).toEqual([ + ['save', 'dataset', 'repair_orders', 'crm'], + ['publish', 'dataset', 'repair_orders', 'crm'], + ])); + expect(world.datasets.map((d) => d.name)).toEqual(['task_metrics', 'repair_orders']); + expect(world.drafts.size).toBe(0); + // The published world: the card's dataset catalog is never read from the drafts here. + await waitFor(() => expect(client.value.list.mock.calls.filter((c: unknown[]) => c[0] === 'dataset').length).toBeGreaterThan(1)); + expect(draftDatasetReads).toBe(0); + // Picked for the card: the dialog is gone, the edit is staged. + await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull()); + await waitFor(() => expect(barSave()).not.toBeDisabled()); + + await act(async () => { + fireEvent.click(barSave()); + }); + const dashboardSave = client.value.save.mock.calls.find((c: unknown[]) => c[0] === 'dashboard'); + expect(dashboardSave?.[2].widgets[0]).toMatchObject({ id: 'widget_total', dataset: 'repair_orders' }); + expect(writes.slice(2)).toEqual([ + ['save', 'dashboard', 'ops_board', 'crm'], + ['publish', 'dashboard', 'ops_board', 'crm'], + ]); + // The dataset the saved card reads is a published one. + expect(world.datasets.some((d) => d.name === 'repair_orders' && d._packageId === 'crm')).toBe(true); + }); + + it('an installed (read-only) app\'s dashboard, saved as an override in its pair, offers no New dataset', async () => { + // Its cards read as the installed package, whose closure does not reach the pair: a dataset made + // there would be refused to the card (ADR-0150 D3), in the editor and after the Save. + packages.listed = new Map([['crm', { id: 'crm', writable: false, manifest: { id: 'crm', version: '1.4.0' } }]]); + gate.entry = { path: '/studio/crm', posture: 'view' }; + client.value = worldClient({ + layered: vi.fn(async (_t: string, _n: string, o: { packageId?: string }) => + o.packageId === 'crm' ? { code: stored, overlay: null, effective: stored } : { code: null, overlay: null, effective: null }, + ), + }); + await selectCard(); + // The real card panel is drawn and its catalog read, with no entry under the picker. + await waitFor(() => expect(client.value.list).toHaveBeenCalledWith('dataset')); + expect(screen.getByText(t('engine.inspector.widget.datasetSection', 'en-US'))).toBeInTheDocument(); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(screen.queryByTestId('widget-new-dataset-open')).toBeNull(); + expect(screen.queryByTestId('widget-new-dataset-hint')).toBeNull(); + expect(packages.ensured).toEqual([]); + expect(writes).toEqual([]); + }); + + it('a refused publish leaves no dataset, shows the server\'s reason, and picks nothing', async () => { + world.publishRefusal = Object.assign(new Error('Dataset member "urgency" names no field of repair_order.'), { status: 422 }); + await selectCard(); + const dialog = await createRepairOrders(); + + expect(await within(dialog).findByText(/names no field of repair_order/)).toBeInTheDocument(); + // The draft it wrote is taken back, pinned to its own version, in the same package. + expect(writes).toEqual([ + ['save', 'dataset', 'repair_orders', 'crm'], + ['publish', 'dataset', 'repair_orders', 'crm'], + ['reset', 'dataset', 'repair_orders', 'crm'], + ]); + expect(client.value.reset).toHaveBeenCalledWith('dataset', 'repair_orders', { + state: 'draft', + ifMatch: 'repair_orders-draft', + packageId: 'crm', + }); + expect(world.drafts.size).toBe(0); + expect(world.datasets.map((d) => d.name)).toEqual(['task_metrics']); + // Nothing picked: the dashboard has no change to save. + expect(barSave()).toBeDisabled(); + }); + + it('a dashboard bound to no package offers no New dataset', async () => { + mount({ ...served, _packageId: undefined }, dataSource); + await openEdit(); + fireEvent.click(screen.getByTestId('dashboard-preview-widget-widget_total')); + // The real card panel is drawn, with its dataset picker and no entry under it. + await waitFor(() => expect(client.value.list).toHaveBeenCalledWith('dataset')); + expect(screen.getByText(t('engine.inspector.widget.datasetSection', 'en-US'))).toBeInTheDocument(); + expect(screen.queryByTestId('widget-new-dataset-open')).toBeNull(); + }); + + it('a read-only base with no customization target is refused, and no New dataset is offered', async () => { + packages.listed = new Map([['crm', { id: 'crm', writable: false, manifest: { id: 'crm', version: '1.4.0' } }]]); + gate.entry = { path: '/studio/crm', posture: 'view' }; + gate.walled = true; + mount(served, dataSource); + const edit = await screen.findByTestId('dashboard-edit'); + await act(async () => { + fireEvent.click(edit); + }); + expect(await screen.findByTestId('dashboard-design-refused')).toBeInTheDocument(); + expect(screen.queryByTestId('dashboard-edit-panel')).toBeNull(); + expect(screen.queryByTestId('widget-new-dataset-open')).toBeNull(); + expect(packages.ensured).toEqual([]); + expect(writes).toEqual([]); + }); +}); diff --git a/ui/packages/app-shell/src/views/DashboardView.tsx b/ui/packages/app-shell/src/views/DashboardView.tsx index a33fc1cc3eb..1c3cda33109 100644 --- a/ui/packages/app-shell/src/views/DashboardView.tsx +++ b/ui/packages/app-shell/src/views/DashboardView.tsx @@ -568,6 +568,7 @@ export function DashboardView({ dataSource }: { dataSource?: any }) { served={dashboard as Record | undefined} published={edit.published} shipped={edit.shipped} + datasetPublish={edit.datasetPublish} /> )} diff --git a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx index 574a32e50ef..bbdbed86fcd 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/inspectors/DashboardWidgetInspector.tsx @@ -56,7 +56,11 @@ import { useDatasetCatalog, useDatasetSemantics, type DatasetDimensionInfo } fro import { datasetLabelOptions, packageDatasetsFirst } from './dataset-picker-options.js'; import { shownLabel, writtenLabel, servedLabelNote, useLabelLanguage } from './servedLabel.js'; import { useServedWidgetText } from '../../studio-design/servedDashboardText.js'; -import { DatasetCreateEntry, useStudioDatasetAuthoring } from '../../studio-design/datasetCreate.js'; +import { + DatasetCreateEntry, + useDatasetPublishAuthoring, + useStudioDatasetAuthoring, +} from '../../studio-design/datasetCreate.js'; import type { ObjectFieldInfo } from '../previews/useObjectFields.js'; import { widgetMissingInputs } from '../../studio-design/metadataError.js'; import { WIDGET_TYPE_IDS, WIDGET_TYPE_META } from '../previews/widget-types.js'; @@ -160,7 +164,11 @@ export function DashboardWidgetInspector({ // objectstack#27518 — in the Studio (its authoring context is present) the // catalog is the draft-overlaid one, this package's datasets first, and the // New dataset entry sits under the picker. + // objectstack#39630 — in the app's design mode the entry publishes at once + // into the dashboard's save target; the catalog stays the published one. const datasetAuthoring = useStudioDatasetAuthoring(); + const datasetPublish = useDatasetPublishAuthoring(); + const leadPackageId = datasetAuthoring?.packageId ?? datasetPublish?.packageId; const catalog = useDatasetCatalog(undefined, { previewDrafts: datasetAuthoring !== null }); const semantics = useDatasetSemantics(datasetName || undefined, catalog); @@ -173,13 +181,13 @@ export function DashboardWidgetInspector({ // on hover (`nameOnHover` on each combo below). const datasetComboOptions: InspectorComboOption[] = React.useMemo(() => { const opts: InspectorComboOption[] = datasetLabelOptions( - packageDatasetsFirst(catalog.datasets, datasetAuthoring?.packageId), + packageDatasetsFirst(catalog.datasets, leadPackageId), ); if (datasetName && !opts.some((o) => o.value === datasetName)) { opts.push({ value: datasetName, label: datasetName }); } return opts; - }, [catalog.datasets, datasetName, datasetAuthoring?.packageId]); + }, [catalog.datasets, datasetName, leadPackageId]); const measureOptions: ObjectFieldInfo[] = React.useMemo( () => datasetMeasureOptions(semantics.measures, locale), [semantics.measures, locale], @@ -455,9 +463,9 @@ export function DashboardWidgetInspector({

{t('engine.inspector.widget.datasetHint', locale)}

- {datasetAuthoring && !readOnly && ( + {!readOnly && (datasetAuthoring || datasetPublish) && ( patchWidget({ dataset: name } as Partial)} locale={locale} diff --git a/ui/packages/app-shell/src/views/studio-design/datasetCreate.test.tsx b/ui/packages/app-shell/src/views/studio-design/datasetCreate.test.tsx index fdd0a3299fb..b7d31b86ab8 100644 --- a/ui/packages/app-shell/src/views/studio-design/datasetCreate.test.tsx +++ b/ui/packages/app-shell/src/views/studio-design/datasetCreate.test.tsx @@ -9,13 +9,15 @@ * - the picker entry, and the empty-state line's condition: no dataset reads * one of this package's objects, whatever else the catalog holds; * - the post-create selection: the draft is saved in this package through - * the draft door, the catalog is read again, and the picker binds it. + * the draft door, the catalog is read again, and the picker binds it; + * - objectstack#39630, the app's design mode: the entry saves and publishes + * at once in the package its context picks. */ import '@testing-library/jest-dom/vitest'; import * as React from 'react'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; +import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { MemoryRouter } from 'react-router-dom'; import { DatasetSchema } from '@objectstack/spec/ui'; @@ -44,8 +46,11 @@ const mockClient = { save: vi.fn(async (_type: string, _name: string, body: Record) => { // The draft-overlaid list serves the draft from now on, as the server does. datasets = [...datasets, { ...body, _packageId: PKG, _draft: true }]; - return {}; + return { version: 'v1' }; }), + // objectstack#39630 — the design mode's write publishes the draft at once, and takes it back when refused. + publish: vi.fn(async (): Promise => ({})), + reset: vi.fn(async (): Promise => ({})), withPreviewDrafts: vi.fn(() => mockClient), }; @@ -54,7 +59,12 @@ vi.mock('../metadata-admin/useMetadata', async (importOriginal) => { return { ...mod, useMetadataClient: () => mockClient }; }); -import { buildDatasetSkeleton, datasetCandidateFields, StudioDatasetAuthoringContext } from './datasetCreate'; +import { + buildDatasetSkeleton, + datasetCandidateFields, + DatasetPublishAuthoringContext, + StudioDatasetAuthoringContext, +} from './datasetCreate'; import { DashboardWidgetInspector } from '../metadata-admin/inspectors/DashboardWidgetInspector'; import type { ObjectFieldInfo } from '../metadata-admin/previews/useObjectFields'; import { t } from '../metadata-admin/i18n'; @@ -187,3 +197,123 @@ describe('the widget inspector\'s New dataset entry (objectstack#27518)', () => expect(mockClient.withPreviewDrafts).not.toHaveBeenCalled(); }); }); + +describe('the widget inspector\'s New dataset in the app\'s design mode (objectstack#39630)', () => { + function renderWidget( + onPatch: (patch: Record) => void, + pickPackage: () => Promise, + packageId: string = PKG, + ) { + return render( + + + + + , + ); + } + + /** Open New dataset, name it, group by Status, and press Create. */ + async function createLive() { + fireEvent.click(await screen.findByTestId('widget-new-dataset-open')); + const dialog = await screen.findByRole('dialog', { name: t('engine.studio.interfaces.newDataset.publishTitle', 'en-US') }); + expect(dialog).toHaveTextContent(t('engine.studio.interfaces.newDataset.publishWidgetDescription', 'en-US')); + fireEvent.change(within(dialog).getByLabelText(t('engine.studio.interfaces.newDataset.nameLabel', 'en-US')), { + target: { value: 'Work orders' }, + }); + fireEvent.click(await within(dialog).findByRole('checkbox', { name: /^Status\b/ })); + fireEvent.click(within(dialog).getByRole('button', { name: t('engine.studio.createLive', 'en-US') })); + return dialog; + } + + it('Create saves and publishes in the picked package and binds the widget', async () => { + const onPatch = vi.fn(); + const pickPackage = vi.fn(async () => 'field_service.custom'); + renderWidget(onPatch, pickPackage); + // The app's words: no package is named in the app. + expect(await screen.findByTestId('widget-new-dataset-hint')).toHaveTextContent( + t('engine.studio.interfaces.newDataset.noAppDatasets', 'en-US'), + ); + await createLive(); + await waitFor(() => + expect(onPatch).toHaveBeenCalledWith({ widgets: [{ id: 'w1', type: 'bar', title: 'Hours', dataset: 'work_orders' }] }), + ); + expect(pickPackage).toHaveBeenCalledTimes(1); + expect(mockClient.save).toHaveBeenCalledWith( + 'dataset', + 'work_orders', + expect.objectContaining({ object: 'fs_work_order' }), + expect.objectContaining({ mode: 'draft', packageId: 'field_service.custom', ifNoneMatch: '*' }), + ); + expect(mockClient.publish).toHaveBeenCalledWith('dataset', 'work_orders', { + packageId: 'field_service.custom', + draftVersion: 'v1', + }); + }); + + it('a refused publish takes the draft back, shows the server\'s reason, and binds nothing', async () => { + mockClient.publish.mockRejectedValueOnce(Object.assign(new Error('Dataset "work_orders" is refused by the server (39630).'), { status: 422 })); + const onPatch = vi.fn(); + renderWidget(onPatch, vi.fn(async () => PKG)); + const dialog = await createLive(); + expect(await within(dialog).findByText(/refused by the server \(39630\)/)).toBeInTheDocument(); + expect(mockClient.reset).toHaveBeenCalledWith('dataset', 'work_orders', { state: 'draft', ifMatch: 'v1', packageId: PKG }); + expect(onPatch).not.toHaveBeenCalled(); + }); + + it('a dashboard owned by an app\'s customization pair reads the app\'s objects from its base: the hint goes once a dataset reads one', async () => { + const BASE = 'com.example.fs'; + objects = [ + { name: WORK_ORDER.name, label: WORK_ORDER.label, _packageId: BASE }, + { name: 'sys_user', label: 'User', isSystem: true }, + ]; + renderWidget(vi.fn(), vi.fn(async () => `${BASE}.custom`), `${BASE}.custom`); + // No dataset reads the base's object yet: the hint shows, and the dialog opens on that object. + expect(await screen.findByTestId('widget-new-dataset-hint')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('widget-new-dataset-open')); + const dialog = await screen.findByRole('dialog', { name: t('engine.studio.interfaces.newDataset.publishTitle', 'en-US') }); + expect(await within(dialog).findByRole('checkbox', { name: /^Status\b/ })).toBeInTheDocument(); + cleanup(); + + // A dataset in the pair reading the base's object: no hint. + datasets = [PLATFORM_DATASET, { name: 'work_orders', object: WORK_ORDER.name, _packageId: `${BASE}.custom`, measures: [{ name: 'count', aggregate: 'count' }], dimensions: [] }]; + renderWidget(vi.fn(), vi.fn(async () => `${BASE}.custom`), `${BASE}.custom`); + // Both reads answered, and their answers rendered, before the hint is judged. + await waitFor(() => expect(mockClient.list).toHaveBeenCalledWith('object')); + await waitFor(() => expect(mockClient.list).toHaveBeenCalledWith('dataset')); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 0)); + }); + expect(screen.queryByTestId('widget-new-dataset-hint')).toBeNull(); + }); + + it('a read-only panel offers no entry', async () => { + render( + + PKG) }}> + + + , + ); + await waitFor(() => expect(mockClient.list).toHaveBeenCalledWith('dataset')); + expect(screen.queryByTestId('widget-new-dataset-open')).toBeNull(); + }); +}); diff --git a/ui/packages/app-shell/src/views/studio-design/datasetCreate.tsx b/ui/packages/app-shell/src/views/studio-design/datasetCreate.tsx index 252afc17893..5bf5a631e95 100644 --- a/ui/packages/app-shell/src/views/studio-design/datasetCreate.tsx +++ b/ui/packages/app-shell/src/views/studio-design/datasetCreate.tsx @@ -20,16 +20,21 @@ * the author's name, label and object, one dimension per picked group-by * field and one `sum` measure per picked number field. * - * Studio only: Studio's All-metadata area (`StudioMetadataArea`) provides - * {@link StudioDatasetAuthoringContext} on a writable package, and a picker - * outside it (Setup's editors, a read-only package) has no entry. + * Where the entry is: Studio's All-metadata area (`StudioMetadataArea`) + * provides {@link StudioDatasetAuthoringContext} on a writable package (a + * draft, published with the package), and the app's design mode + * (`DashboardInPageEditor`, objectstack#39630) provides + * {@link DatasetPublishAuthoringContext} where the dashboard's own package is + * writable (saved and published at once, as the dashboard's own Save is). A + * picker under neither (Setup's editors, a read-only package, an installed + * app's dashboard in the design mode) has no entry. * * Internal to app-shell: not exported from the package root. */ import * as React from 'react'; import { Plus } from 'lucide-react'; -import { getMetadataCreateSeed } from '@objectstack/spec/kernel'; +import { customizationBasePackageId, getMetadataCreateSeed } from '@objectstack/spec/kernel'; import type { Dataset } from '@objectstack/spec/ui'; import { Button } from '@object-ui/components'; import { t, tFormat, type SupportedLocale } from '../metadata-admin/i18n.js'; @@ -158,6 +163,33 @@ export interface DatasetPublishTarget { pickPackage: () => Promise; } +/** + * objectstack#39630 — the app's design mode's New dataset, beside a dashboard + * widget's dataset picker: saved and published at once in the dashboard's own + * writable package ({@link DatasetPublishTarget}), so the dashboard the author + * then saves reads a published dataset. + */ +export interface DatasetPublishAuthoring extends DatasetPublishTarget { + /** + * The dashboard's package: its datasets lead the picker, and its objects + * are the app's objects the dialog opens on and the hint reads (with its + * base's, when it is an app's customization pair). + */ + packageId: string; +} + +/** + * Provided by the design mode's dashboard panel where the dashboard has a + * package to save in. Unlike {@link StudioDatasetAuthoringContext} it changes + * no picker's world: a dataset made here is published, so the catalog stays + * the published one. + */ +export const DatasetPublishAuthoringContext = React.createContext(null); + +export function useDatasetPublishAuthoring(): DatasetPublishAuthoring | null { + return React.useContext(DatasetPublishAuthoringContext); +} + /** The three metadata doors {@link saveAndPublishDataset} writes through. */ export interface DatasetPublishClient { save(type: string, name: string, body: unknown, options: Record): Promise; @@ -256,8 +288,9 @@ function toggled(set: ReadonlySet, name: string, on: boolean): Set void; + /** What will read the published dataset, as its description says: a report, or a dashboard widget's chart. */ + readBy?: 'report' | 'widget'; /** The object the dialog opens on, when the picker knows it. */ initialObject?: string; /** The objects the server serves: a name outside them is refused here. */ @@ -419,13 +455,18 @@ export function NewDatasetDialog({ extra: fieldsForm, }; // One dialog per write, each saying what its Create does (objectui#11787): - // the report builder's is published at once and says Create; the Studio's is - // a draft and says Save as draft. + // the report builder's and the design mode's are published at once and say + // Create; the Studio's is a draft and says Save as draft. return publishTo ? ( ) : ( @@ -439,21 +480,29 @@ export function NewDatasetDialog({ } /** - * The entry a dataset picker shows in the Studio: a line saying no dataset - * reads this package's objects yet, while that is so (whatever else the - * catalog holds), and the New dataset button with its dialog. The dialog opens - * on the package's object when it has exactly one. A create reloads the - * picker's catalog, then hands the new name to `onCreated` for the picker to - * bind. + * How a picker's entry writes: the Studio's draft (`authoring`), or saved and + * published at once in the design mode's target (`publishTo`, objectstack#39630). + */ +export type DatasetCreateEntryWrite = + | { authoring: StudioDatasetAuthoring; publishTo?: undefined } + | { authoring?: undefined; publishTo: DatasetPublishAuthoring }; + +/** + * The entry a dataset picker shows in the Studio, or in the app's design + * mode: a line saying no dataset reads this package's (the app's) objects + * yet, while that is so (whatever else the catalog holds), and the New + * dataset button with its dialog. The dialog opens on the package's object + * when it has exactly one. A create reloads the picker's catalog, then hands + * the new name to `onCreated` for the picker to bind. */ export function DatasetCreateEntry({ authoring, + publishTo, catalog, onCreated, locale, testId, -}: { - authoring: StudioDatasetAuthoring; +}: DatasetCreateEntryWrite & { catalog: UseDatasetCatalogResult; onCreated: (name: string) => void; locale: SupportedLocale; @@ -461,19 +510,31 @@ export function DatasetCreateEntry({ }): React.ReactElement { const objects = useObjectCatalog(); const [open, setOpen] = React.useState(false); + const packageId = authoring ? authoring.packageId : publishTo.packageId; const served = objects.status === 'loaded' ? objects.data : null; const knownObjects = React.useMemo(() => new Set((served ?? []).map((o) => o.name)), [served]); + // In the design mode a dashboard may be owned by an app's customization + // pair (`.custom`): the app's objects are its base's, and the pair's + // own. The Studio reads the package it is in, as before. + const basePackageId = publishTo ? customizationBasePackageId(packageId) : null; const packageObjects = React.useMemo( - () => (served ?? []).filter((o) => o.packageId === authoring.packageId && !o.isSystem).map((o) => o.name), - [served, authoring.packageId], + () => + (served ?? []) + .filter((o) => (o.packageId === packageId || (basePackageId !== null && o.packageId === basePackageId)) && !o.isSystem) + .map((o) => o.name), + [served, packageId, basePackageId], ); const unread = served !== null && !catalog.loading && !readsAnyObject(catalog.datasets, new Set(packageObjects)); + // The Studio says "this package"; the app's design mode, where a package is not named, says "this app". + const hint = authoring + ? 'engine.studio.interfaces.newDataset.noPackageDatasets' + : 'engine.studio.interfaces.newDataset.noAppDatasets'; return (
{unread && (

- {t('engine.studio.interfaces.newDataset.noPackageDatasets', locale)} + {t(hint, locale)}

)}