|
| 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 | +} |
0 commit comments