Skip to content

Commit 3cf6a44

Browse files
os-warrenclaude
andauthored
feat(console): the report builder — one page to build or edit a report (#36644)
<!-- claude-projects-attribution: {"github_login":"os-warren"} --> _Requested by **Warren** · [project thread](https://claude.ai/code/project/chan_01U5RdnAAmkSQmZbqh6FtqZ8?thread=cmsg_01U5RdnAAmkSQmZbqh6FtqZ89Betg8QPoUPD5NhDenSfS2)_ Fixes #36374 Clause-②: yes (widening) — new public exports from `@object-ui/plugin-report` (`ReportBuilder` and its model types, no value exports besides the component), a new optional `foldTableUnderChart` prop on `DatasetReportRenderer`, and new `@object-ui/i18n` keys (`report.builder.*`, `report.computedValues`) in all 11 locales; no spec, schema or server change Metadata-protocol: none ## 维护者速读 - 用户能看到什么变化:系统管理员在报表页点「编辑」,进入整页的报表搭建页:左边是实时的图,右边五项(报表类型、数据来源、指标、分组、图表);选完数据来源立刻出一个数字,缺什么就在图的位置写一句并自动打开那一项;新建报表也用这个页面。 - 为什么做:仪表盘和报表使用体验专题的搭建页这一张,照 Attio 的做法,让管理员不进 Studio 就能搭报表。 - 出错会怎样:保存被拒时搭建页不关、改动还在,并说明原因;保存成功后所有人马上看到新样子;可以直接撤回本次合并。 - 要你做什么:无。 ## What changes **The builder** (`ui/packages/plugin-report/src/builder/`, exported from `@object-ui/plugin-report`) - `ReportBuilder.tsx`: header (close ×, the name and the one-line description editable in place, Discard, Save), the report drawn live on the left, five settings on the right: report type (one entry, 「现状分析」, the dropdown kept for later types), data source (existing datasets by label), measure, grouping (+ 「再分一层」), chart (bar, line, donut, number, table, with Show values and a target line). There is no Generate button. - `reportBuilderModel.ts`: what each pick writes into the report document, all in the spec's own vocabulary: `dataset`, `values[0]` (a measure the bound dataset declares), `rows` (one or two dimensions), `chart` (`type`, `xAxis` = first grouping, `yAxis` = measure, `seriesBy` = second grouping on bar/line only, as the spec refuses it on a donut), `chart.showDataLabels`, a y-axis `chart.annotations` line for the target, and `dateRange` when the report groups by a date. Picking a dataset starts on its count measure, no grouping, `metric` chart (a number). Grouping a number turns it into bars; ungrouping bars turns them back. - Missing pieces: no data source → 「选一个数据来源」; a dataset with no measures; no measure → 「选一个指标」; a bar/line/donut with no grouping → 「选一个分组字段」. The sentence is drawn where the chart would be, and that section's picker opens by itself, once per missing piece. Save is off while a piece is missing. - `reconcile` keeps the measure and the axis an authored chart draws (`chart.yAxis` / `chart.xAxis`) across unrelated picks, whether or not `values` names that measure; only picking a measure or a grouping changes them. A report with a chart and no `values` opens with `values` seeded from its `yAxis`. The builder is network-free: the host hands in the dataset catalog and the bound dataset's members and owns Save / Discard / Close, so #36364 can host it too. - `DatasetReportRenderer` gains an optional `foldTableUnderChart`: under a drawn chart (series or single number) the table folds behind a 「计算值」 toggle, kept mounted so Download still writes it. Off by default: the report page is unchanged. **The doors** (`ui/packages/app-shell`) - `ReportBuilderHost.tsx`: the console host. Reads the catalog and members through `useDatasetCatalog` / `useDatasetSemantics` (the Studio inspector's hooks), and drives the name and description boxes through `servedLabel.ts` (`shownLabel` / `writtenLabel` / `servedLabelNote`), so the boxes read the session language and a save keeps the source text (#35008, #36373, #36481). - `ReportView.tsx`: 「编辑」 opens the builder for a dataset-bound report (`opensInBuilder`); the builder replaces the page and the draft bar sits above its preview. A `joined` report, a pre-dataset report (`objectName` / `dataSource` / inline `data`), and a dataset report with a cross-tab (`columns`), a saved `runtimeFilter` or several `values` keep the existing inspector panel, which edits every shape the spec allows. A one-time navigation-state landing (`reportBuilderArrival.ts`) opens the builder on arrival, for a door that has just created a report (#36364). - `ReportNewPage.tsx` at `reports/new` (route, chunk and metadata-read rows added): the same builder on an empty report, admin only. Save derives the identifier from the name (Chinese romanised, as the Studio inspector does), suffixed until no known report holds it, then asks the server for each candidate by name (`freeReportName`; `get` reads every served layer, and the save's draft pin covers a pending draft) and moves past any it holds, so a create never overwrites a report the list did not show; then it lands on the report page. - **Save = stage + publish in one press**, for the builder and the panel alike, through the existing `saveAndPublishRuntimeMetadata` (the list view's shared-view save). This follows the maintainer's ruling on epic #36510 (2026-11-22, verbatim: 「人改一项、点保存、立刻生效。草稿加整包发布只留给 AI 的批量改动」), relayed by the seat for this card. Relation to ADR-0034: the per-item draft/publish model is kept underneath (the body is written as the item's draft with the first-write pin, then published); only the separate manual Publish step is removed from the human edit path. Over any pending draft (including one the saving admin left earlier) nothing is written (`pending-draft`), the builder stays open and says so, and the draft bar above the preview publishes or discards that draft. - `writeRefusalCensus-11583.test.ts`: the `ReportView.tsx › saveSchema › persistRuntimeMetadata` row is removed, because the call is now `saveAndPublishRuntimeMetadata`, which is outside the census population (its view callers are not counted either). The refusal toast it pinned is still pinned, by the new builder cases in `ReportView.saveRefusal-11583.test.tsx`. **Copy**: `report.builder.*` and `report.computedValues` in all 11 locales; zh-Hant regenerated with `gen:zh-hant`. ## Why Card #36374 (epic #36255, board 49 figure 3): one page for new and existing reports, a picture at once, and the missing piece said where the chart would be. ## Verification Run on head after merging the latest `main`: - `ui`: `vitest run` on `plugin-report/src/__tests__/reportBuilder-36374.test.tsx` (model: every pick yields a report `ReportSchema` accepts; page: missing-piece sentence and auto-open, number on dataset pick, number→bars on grouping, second layer, chart switches; fold: table under a chart behind 「计算值」), `app-shell/src/views/ReportView*` (builder Save publishes, `pending-draft` keeps the builder open with the reason, refusal toast, `opensInBuilder` routing, joined / pre-dataset reports keep the panel), `reportBuilderArrival-36374.test.ts` (one-time landing, identifier from name), `writeRefusalCensus-11583.test.ts`: 11 files, 68 tests pass (one added after the browser run below caught the measure picker opening by itself on a just-picked data source; after the L2 review: the authored-chart fidelity case, the panel routing cases and `freeReportName`). The two authored-chart cases (one value that is not the charted measure; a chart with no values) fail on the previous model (2 failed | 19 passed) and pass on this one. - `@object-ui/i18n` full suite (all-locales parity, zh-Hant generated) passes. - `pnpm --filter @object-ui/app-shell type-check` (both programs): 0 errors. `plugin-report` type-check: 0 errors. - ESLint on the changed files: no new findings (the one error in `DatasetReportRenderer.tsx` is on `main` already). - `scripts/pm/overlap-check.mjs --branch=HEAD`: clean. ## Acceptance notes - **Measures come from the dataset.** The measure picker lists the measures the bound dataset declares and starts on its count measure. Picking a field plus an aggregation would edit the dataset, not the report, so it is not offered here. - **The time switch reuses the report's period chip.** Grouping by a date writes `dateRange` (builder default 「今年」); the chip on the drawn report carries the dashboard presets plus 「全部」, which is the card's preset list. - **Not built in this PR:** 「+ 筛选」, 「显示数量为 0 的分组」 (no spec key for it) and 「和上一期对比」 (#35395); the three are filed together as #36645. The card's 3-month preset is not in the period chip's existing preset list either. - **Write-refusal census:** neither report write site (`ReportView.saveSchema`, `ReportNewPage`) is in the census population now, as `saveAndPublishRuntimeMetadata` is outside `SEAM_WRITES`; both surface a refusal toast and the builder's is pinned by `ReportView.saveRefusal-11583.test.tsx`. Taking that door into the census is a follow-up. - **Joined and pre-dataset reports keep the inspector panel**, which edits every shape the spec allows; the builder covers dataset-bound reports. - **「查看明细」 stays with #36256**: the builder passes the page's drill handler through, so clicking a bar opens the same list dialog. - **#36364's door is not built here.** What it needs is in place: the `reports/new` address, the one-time arrival landing that opens the builder on a just-created report, and `ReportBuilder` / `ReportBuilderHost` taking any `onSave`. - **ADR-0034:** see *Save* above; the per-item draft + publish model stays, the human edit path presses both in one Save. - **Browser run** (showcase app, admin, zh-Hans, head `6fea0ab67`): 「编辑」 on *Hours by Status (Chart)* opens the builder with its bars and settings filled in; `reports/new` says 「选一个数据来源」 where the chart would be with that picker open; picking *Invoice Metrics* draws 12 at once; grouping by *Issued* draws monthly bars with the 「今年」 period chip; ungrouping and choosing a donut says 「选一个分组字段」 with the grouping picker open and Save off. The five screenshots went with the card report in the project thread. ## Human Minimum - [x] 1. Schemas start as Zod; `packages/spec` holds no runtime logic. (No spec change.) - [x] 2. Every name I added uses the casing for its kind. - [x] 3. No formatter ran; `pnpm lint` passes. (CI owns the repo-wide lint run.) - [x] 4. One issue, one branch off an up-to-date `main`, one pull request. - [x] 5. A change that publishes carries a changeset, and both declaration lines are filled in here and in the changeset. - [x] 6. `packages/spec` touched: n/a. - [x] 7. No hand edits to `content/docs/references/`, `packages/*/CHANGELOG.md` or `content/docs/releases/`. - [x] 8. Title, body and comments are in English. - [x] The *Before Submitting* list in CONTRIBUTING.md is done. https://claude.ai/code/session_01JQwxbXq2Dxb31zZNmSqCtz --- _Generated by [Claude Code](https://claude.ai/code)_ --------- Co-authored-by: Claude <noreply@anthropic.com>
1 parent dad9b55 commit 3cf6a44

29 files changed

Lines changed: 2559 additions & 61 deletions

‎.changeset/36374-report-builder.md‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@object-ui/plugin-report': patch
3+
'@object-ui/app-shell': patch
4+
'@object-ui/i18n': patch
5+
---
6+
7+
feat(console): the report builder — one page to build a new report or edit an existing one, with the report drawn live on the left and five settings on the right
8+
9+
Clause-②: yes (widening) — new public exports from `@object-ui/plugin-report` (`ReportBuilder` and its model types), a new optional `foldTableUnderChart` prop on `DatasetReportRenderer`, and new `@object-ui/i18n` keys (`report.builder.*`, `report.computedValues`) in all 11 locales; no spec or schema change
10+
Metadata-protocol: none
11+
12+
- **The builder** (`ReportBuilder`, `@object-ui/plugin-report`): the report previewed on the left; report type, data source, measure, grouping and chart on the right. Every pick rewrites the report and the preview draws it again; there is no Generate button. Picking a data source draws a single number at once (the dataset's count measure, no grouping). While a required piece is missing, the preview says what it is where the chart would be (「Choose a data source」, 「Choose a field to group by」) and that setting's picker opens by itself. A second grouping layer splits a bar or line chart; the chart's own switches are Show values and a target line. Grouping by a date adds the report's period chip. The report's table folds under the chart as 「Computed values」.
13+
- **The doors** (`@object-ui/app-shell`): the report page's 「Edit」 opens the builder for a dataset-bound report (a joined report, a pre-dataset report, and a dataset report with a cross-tab, a saved filter or several values keep the inspector panel), and the app's `reports/new` address opens it on a new report, created under a name no served report holds. Admin only.
14+
- **Save is seen by everyone at once:** the report is written and published in the same press, for the builder and the inspector panel alike. Over any pending draft nothing is written and the builder says so; the draft bar above the preview publishes or discards it.

‎ui/packages/app-shell/src/console/AppContent.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ const DashboardView = routeChunk.lazy(() => import('../views/DashboardView.js').
139139
const PageView = routeChunk.lazy(() => import('../views/PageView.js').then(m => m.PageView));
140140
const ReportView = routeChunk.lazy(() => import('../views/ReportView.js').then(m => m.ReportView));
141141
const AppReportIndexView = routeChunk.lazy(() => import('../views/AppReportIndexView.js').then(m => m.AppReportIndexView));
142+
const ReportNewPage = routeChunk.lazy(() => import('../views/ReportNewPage.js').then(m => m.ReportNewPage));
142143
const SearchResultsPage = routeChunk.lazy(() => import('../views/SearchResultsPage.js').then(m => m.SearchResultsPage));
143144
const RecordFormPage = routeChunk.lazy(() => import('../views/RecordFormPage.js').then(m => m.RecordFormPage));
144145
const ComponentNavView = routeChunk.lazy(() => import('../views/ComponentNavView.js').then(m => m.ComponentNavView));
@@ -184,6 +185,7 @@ const APP_ROUTE_CHUNKS: ReadonlyArray<{ path: string; chunk: { preload: () => Pr
184185
{ path: 'dashboard/:dashboardName', chunk: DashboardView },
185186
{ path: 'report/:reportName', chunk: ReportView },
186187
{ path: 'reports', chunk: AppReportIndexView },
188+
{ path: 'reports/new', chunk: ReportNewPage },
187189
{ path: 'page/:pageName', chunk: PageView },
188190
{ path: 'component/:ns/:name/*', chunk: ComponentNavView },
189191
{ path: 'design/dashboard/:dashboardName', chunk: DashboardDesignPage },
@@ -1684,6 +1686,8 @@ export function AppContent({ extraRoutes, extraRoutesNoApp }: AppContentProps =
16841686
<Route path="report/:reportName" element={<ReportView dataSource={dataSource} />} />
16851687
{/* objectui#13020: the app's report index, linked from the sidebar. */}
16861688
<Route path="reports" element={<AppReportIndexView />} />
1689+
{/* objectstack#36374 — the report builder for a new report. */}
1690+
<Route path="reports/new" element={<ReportNewPage dataSource={dataSource} />} />
16871691
<Route path="page/:pageName" element={<PageView />} />
16881692
{/* objectstack ADR-0146 D11 — the retired Setup › Packaged
16891693
automation page (`automation:packaged`): a bookmark opens

‎ui/packages/app-shell/src/console/appRouteMetadataReads.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,10 @@ export const APP_ROUTE_METADATA_READS: ReadonlyArray<{ path: string; reads: read
6666
// AppReportIndexView (objectui#13020): the report list, and the dataset
6767
// list its read verdict needs, which it waits for itself; never the objects.
6868
{ path: 'reports', reads: ['report'] },
69+
// ReportNewPage (objectstack#36374): the report builder for a new report —
70+
// the report list it names the new report against; the datasets it offers
71+
// are read by the builder itself.
72+
{ path: 'reports/new', reads: ['report'] },
6973
// A page reads the objects its page binds, through its object scope
7074
// (`appObjectScope.ts`, objectui#12980), not the whole registry; `object`
7175
// stays for the routes where the scope does not apply (a record overlay).
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* ReportBuilderHost — the console's host for the report builder
5+
* (`@object-ui/plugin-report`'s `ReportBuilder`, objectstack#36374).
6+
*
7+
* One host for both doors into the builder: the report page's 「Edit」
8+
* (`ReportView`) and the new-report page (`ReportNewPage`). It holds the edit
9+
* buffer, reads the dataset catalog and the bound dataset's members through
10+
* the metadata client (the same hooks the Studio report inspector reads), and
11+
* owns the name and description boxes, whose text depends on the served
12+
* translation of the report (`servedLabel.ts`, objectstack#35008 / #36373 /
13+
* #36481). Writing the report is the caller's: `onSave` resolves `true` when
14+
* the report was saved, and the builder closes only then.
15+
*
16+
* @module
17+
*/
18+
19+
import * as React from 'react';
20+
import { ReportBuilder, type ReportDraft, type DatasetDrillArgs } from '@object-ui/plugin-report';
21+
import type { DataSource } from '@object-ui/types';
22+
import { useDatasetCatalog, useDatasetSemantics } from './metadata-admin/previews/useDatasetCatalog.js';
23+
import { shownLabel, writtenLabel, servedLabelNote, useLabelLanguage } from './metadata-admin/inspectors/servedLabel.js';
24+
import { tFormat, useMetadataLocale } from './metadata-admin/i18n.js';
25+
import type { ServedReportText } from './studio-design/servedReportText.js';
26+
27+
export interface ReportBuilderHostProps {
28+
/** The report as the builder opens on it: the authored buffer, or a new report's seed. */
29+
initial: ReportDraft;
30+
/** The served text of the report's name and description; `null` for a new report. */
31+
servedText?: ServedReportText | null;
32+
/** Write the report. `true` when it was saved; the host then closes the builder. */
33+
onSave: (report: ReportDraft) => Promise<boolean>;
34+
/** Leave the builder without saving. */
35+
onClose: () => void;
36+
/** A notice above the preview (the pending-draft bar). */
37+
banner?: React.ReactNode;
38+
dataSource?: DataSource;
39+
onDrill?: (args: DatasetDrillArgs) => void;
40+
}
41+
42+
function Note({ note, locale, testId }: { note: ReturnType<typeof servedLabelNote>; locale: string; testId: string }) {
43+
if (!note) return null;
44+
return (
45+
<p role="note" data-testid={testId} data-note-kind={note.kind} className="px-1 text-[11px] leading-snug text-muted-foreground">
46+
{tFormat(
47+
note.kind === 'kept' ? 'engine.inspector.servedLabel.kept' : 'engine.inspector.servedLabel.ifKept',
48+
locale,
49+
{ served: note.served },
50+
)}
51+
</p>
52+
);
53+
}
54+
55+
export function ReportBuilderHost({ initial, servedText, onSave, onClose, banner, dataSource, onDrill }: ReportBuilderHostProps) {
56+
const [draft, setDraft] = React.useState<ReportDraft>(initial);
57+
const [saving, setSaving] = React.useState(false);
58+
const locale = useMetadataLocale();
59+
const language = useLabelLanguage(locale);
60+
61+
const catalog = useDatasetCatalog();
62+
const dataset = typeof draft.dataset === 'string' ? draft.dataset : '';
63+
const semantics = useDatasetSemantics(dataset || undefined, catalog);
64+
const members = React.useMemo(
65+
() => (dataset && !semantics.loading ? { measures: semantics.measures, dimensions: semantics.dimensions } : undefined),
66+
[dataset, semantics.loading, semantics.measures, semantics.dimensions],
67+
);
68+
69+
const dirty = React.useMemo(() => JSON.stringify(draft) !== JSON.stringify(initial), [draft, initial]);
70+
71+
const handleSave = React.useCallback(async () => {
72+
setSaving(true);
73+
try {
74+
await onSave(draft);
75+
} finally {
76+
setSaving(false);
77+
}
78+
}, [draft, onSave]);
79+
80+
return (
81+
<ReportBuilder
82+
report={draft}
83+
onChange={setDraft}
84+
name={{
85+
value: shownLabel(draft.label, servedText?.label, language),
86+
onChange: (v) => setDraft((d) => ({ ...d, label: writtenLabel(d.label, servedText?.label, language, v, '') })),
87+
note: <Note note={servedLabelNote(draft.label, servedText?.label, language)} locale={locale} testId="report-builder-name-note" />,
88+
}}
89+
description={{
90+
value: shownLabel(draft.description, servedText?.description, language),
91+
onChange: (v) =>
92+
setDraft((d) => {
93+
const next = { ...d, description: writtenLabel(d.description, servedText?.description, language, v, undefined) };
94+
if (next.description === undefined) delete next.description;
95+
return next;
96+
}),
97+
note: <Note note={servedLabelNote(draft.description, servedText?.description, language)} locale={locale} testId="report-builder-description-note" />,
98+
}}
99+
datasets={catalog.datasets}
100+
datasetsLoading={catalog.loading}
101+
members={members}
102+
membersLoading={!!dataset && semantics.loading}
103+
catalogError={catalog.error ?? semantics.error ?? undefined}
104+
onSave={handleSave}
105+
onDiscard={() => setDraft(initial)}
106+
onClose={onClose}
107+
dirty={dirty}
108+
saving={saving}
109+
banner={banner}
110+
dataSource={dataSource}
111+
onDrill={onDrill}
112+
/>
113+
);
114+
}
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* ReportNewPage — the report builder for a NEW report (objectstack#36374),
5+
* at the app's `reports/new` address.
6+
*
7+
* The same builder the report page's 「Edit」 opens (`ReportBuilderHost`),
8+
* started on an empty report: the preview says 「Choose a data source」 and
9+
* that picker opens by itself. Save writes the report and publishes it in the
10+
* same press (the maintainer's ruling on epic #36510 — see `ReportView`), then
11+
* lands on the report's page. Admin only, as the Edit is: a report is shared
12+
* by every member of the workspace.
13+
*
14+
* The report's identifier is derived from the name the author typed (Chinese
15+
* romanised, as the Studio inspector derives it) and made unique against the
16+
* reports the console already knows, so a new report never writes over one.
17+
*
18+
* @module
19+
*/
20+
21+
import * as React from 'react';
22+
import { useNavigate, useParams } from 'react-router-dom';
23+
import { toast } from 'sonner';
24+
import { Loader2 } from 'lucide-react';
25+
import { Empty, EmptyDescription, EmptyTitle } from '@object-ui/components';
26+
import { useObjectTranslation, pickLocalized } from '@object-ui/i18n';
27+
import { useWorkspaceAdminStatus } from '@object-ui/auth';
28+
import { formatMetadataError } from '@object-ui/data-objectstack';
29+
import type { DataSource } from '@object-ui/types';
30+
import type { ReportDraft } from '@object-ui/plugin-report';
31+
import { ReportBuilderHost } from './ReportBuilderHost.js';
32+
import { saveAndPublishRuntimeMetadata } from './runtime-metadata-persistence.js';
33+
import { useMetadataClient } from './metadata-admin/useMetadata.js';
34+
import { useMetadata } from '../providers/MetadataProvider.js';
35+
import { loadHanRomanizer, romanizeHan } from './metadata-admin/romanizeHan.js';
36+
import { toFieldNameOrEmpty } from './metadata-admin/previews/object-fields-io.js';
37+
38+
/** The report a new builder starts on: nothing bound, the one report type. */
39+
export const NEW_REPORT_SEED: ReportDraft = { name: '', label: '', type: 'summary' };
40+
41+
/**
42+
* The identifier a new report is saved under: its name as an identifier,
43+
* `report` when the name gives none, suffixed until no known report holds it.
44+
*/
45+
export function newReportName(label: string, taken: ReadonlySet<string>): string {
46+
const base = toFieldNameOrEmpty(romanizeHan(label)) || 'report';
47+
if (!taken.has(base)) return base;
48+
for (let i = 2; ; i += 1) {
49+
const candidate = `${base}_${i}`;
50+
if (!taken.has(candidate)) return candidate;
51+
}
52+
}
53+
54+
/** How many names {@link freeReportName} asks about before it gives up. */
55+
const NAME_TRIES = 50;
56+
57+
/**
58+
* The identifier a new report is created under, asked of the server by name.
59+
* A create never lands on a report that exists: the console's list can miss
60+
* one (read before another admin's create, or held by a package the list does
61+
* not show), and the draft pin of the save stops only a pending draft, so each
62+
* candidate is asked of every served layer (`exists`) first and a name it
63+
* holds moves on to the next suffix. `null` once {@link NAME_TRIES} are taken.
64+
*/
65+
export async function freeReportName(
66+
label: string,
67+
known: ReadonlySet<string>,
68+
exists: (name: string) => Promise<boolean>,
69+
): Promise<string | null> {
70+
const taken = new Set(known);
71+
for (let tries = 0; tries < NAME_TRIES; tries += 1) {
72+
const name = newReportName(label, taken);
73+
if (!(await exists(name))) return name;
74+
taken.add(name);
75+
}
76+
return null;
77+
}
78+
79+
export function ReportNewPage({ dataSource }: { dataSource?: DataSource }) {
80+
const { t, language } = useObjectTranslation();
81+
const { appName } = useParams<{ appName: string }>();
82+
const navigate = useNavigate();
83+
const metadataClient = useMetadataClient();
84+
const { reports, loading, refresh } = useMetadata();
85+
const { isAdmin, isResolved } = useWorkspaceAdminStatus();
86+
87+
const backToReports = React.useCallback(() => {
88+
if (appName) navigate(`/apps/${appName}/reports`);
89+
else navigate(-1);
90+
}, [navigate, appName]);
91+
92+
const handleSave = React.useCallback(
93+
async (draft: ReportDraft): Promise<boolean> => {
94+
if (!metadataClient) return false;
95+
await loadHanRomanizer().catch(() => {});
96+
const taken = new Set(((reports as Array<{ name?: unknown }>) ?? []).map((r) => String(r?.name ?? '')));
97+
// A report needs a name to be listed by: one left blank is saved under
98+
// the placeholder the box showed.
99+
const typed = pickLocalized(draft.label, language).trim();
100+
const label = typed ? draft.label : t('report.builder.namePlaceholder');
101+
let name: string | null;
102+
try {
103+
name = await freeReportName(
104+
typed || String(draft.dataset ?? ''),
105+
taken,
106+
async (candidate) => !!(await metadataClient.get('report', candidate)),
107+
);
108+
if (!name) {
109+
toast.error(t('form.saveError'), { description: t('report.builder.nameTaken') });
110+
return false;
111+
}
112+
const body = { ...draft, label, name };
113+
const outcome = await saveAndPublishRuntimeMetadata('report', name, body, {
114+
metadataClient,
115+
dataSource: dataSource as any,
116+
});
117+
if (outcome === 'pending-draft') {
118+
toast.error(t('form.saveError'), { description: t('report.builder.pendingDraft') });
119+
return false;
120+
}
121+
} catch (err) {
122+
toast.error(t('form.saveError'), {
123+
description: formatMetadataError(err),
124+
classNames: { description: 'whitespace-pre-line' },
125+
});
126+
return false;
127+
}
128+
await refresh().catch(() => {});
129+
navigate(appName ? `/apps/${appName}/report/${encodeURIComponent(name)}` : `../report/${encodeURIComponent(name)}`, {
130+
replace: true,
131+
});
132+
return true;
133+
},
134+
[metadataClient, reports, language, dataSource, refresh, navigate, appName, t],
135+
);
136+
137+
if (loading || !isResolved) {
138+
return (
139+
<div className="flex h-full items-center justify-center p-8">
140+
<Loader2 className="h-8 w-8 animate-spin text-muted-foreground" />
141+
</div>
142+
);
143+
}
144+
145+
if (!isAdmin) {
146+
return (
147+
<div className="flex h-full items-center justify-center p-8" data-testid="report-new-admin-only">
148+
<Empty>
149+
<EmptyTitle>{t('report.builder.adminOnlyTitle')}</EmptyTitle>
150+
<EmptyDescription>{t('report.builder.adminOnly')}</EmptyDescription>
151+
</Empty>
152+
</div>
153+
);
154+
}
155+
156+
return (
157+
<ReportBuilderHost
158+
initial={NEW_REPORT_SEED}
159+
onSave={handleSave}
160+
onClose={backToReports}
161+
dataSource={dataSource}
162+
/>
163+
);
164+
}

‎ui/packages/app-shell/src/views/ReportView.authoredEditBuffer-35008.test.tsx‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,9 @@ describe('the report quick edit edits the authored report (objectstack#35008, Re
189189
mountReport();
190190
const [type, name, body, opts] = await openEditAndSave();
191191

192-
expect([type, name, opts]).toEqual(['report', 'task_overview', { mode: 'draft' }]);
192+
// objectstack#36374 — Save stages the body and publishes it in the same press.
193+
expect([type, name, opts]).toEqual(['report', 'task_overview', { mode: 'draft', ifNoneMatch: '*' }]);
194+
expect(client.value.publish).toHaveBeenCalledWith('report', 'task_overview');
193195
// Read at the package the served report came from.
194196
expect(client.value.layered).toHaveBeenCalledWith('report', 'task_overview', { packageId: PKG });
195197
expect(body.label).toBe(SOURCE.label);

0 commit comments

Comments
 (0)