diff --git a/.changeset/37359-import-wizard-shared-mapping.md b/.changeset/37359-import-wizard-shared-mapping.md new file mode 100644 index 00000000000..4a23805c139 --- /dev/null +++ b/.changeset/37359-import-wizard-shared-mapping.md @@ -0,0 +1,14 @@ +--- +'@object-ui/plugin-grid': patch +'@object-ui/i18n': patch +'@object-ui/app-shell': patch +--- + +feat(plugin-grid, app-shell): an administrator can save the import wizard's column mapping as a shared mapping, and Manage opens the object's mapping list + +Clause-②: yes (widening) +Metadata-protocol: none + +`ImportWizard` takes two new optional props. `onSaveSharedMapping(draft)` is the host's door for saving a shared `mapping` item: when it is passed, the preview step offers "Save as shared mapping", which asks for a name and sends the columns mapped by hand (each column's header → its field), the write mode and, for update or upsert, the match fields as `upsertKey`, with `sourceFormat: 'csv'`. The other import options stay with the import that set them. A mapped column whose header is blank or shared with another column cannot be saved, because the import door finds a column by its header; the save says which headers to rename. The saved mapping joins the Saved mapping list at once. `onManageMappings()` puts "Manage" beside the Saved mapping list. Without the props nothing changes. `SavedMapping` and `SharedMappingDraft` are exported as types. New `grid.import.*` strings in every language pack. + +In the app, the list page passes both doors only to the reader who may share a view (an administrator holding `manage_metadata`), and never to the identity import. The save probes the name first and refuses one a mapping already holds; then it saves the mapping into a package of the app and publishes it at once. When no package of the app can be had the person picks or creates one, and a cancelled pick writes nothing; a system app is refused. Manage opens Studio's mapping list across every package, narrowed to the object by a new `targetObject` list param, shown as a chip whose × shows every object again. diff --git a/ui/packages/app-shell/src/views/ObjectView.tsx b/ui/packages/app-shell/src/views/ObjectView.tsx index 9243eba86d5..ac9e9bc4207 100644 --- a/ui/packages/app-shell/src/views/ObjectView.tsx +++ b/ui/packages/app-shell/src/views/ObjectView.tsx @@ -110,6 +110,7 @@ import { viewSaveRefusalText } from './viewSaveRefusal.js'; import { listDraftPreference, listDraftScope, useListDraft } from './listDraftStore.js'; import { useObjectViewViewCrud, useRuntimeCreateApp } from './objectViewViewCrud.js'; import { mayManageViews, useViewSharing } from './objectViewViewSharing.js'; +import { sharedMappingDoors } from './objectViewSharedMapping.js'; import { useCanAuthorMetadata } from '../hooks/useCanAuthorMetadata.js'; import { PERSONAL_VIEW_OBJECT, @@ -1616,6 +1617,22 @@ function ObjectViewInner({ dataSource, objects, onEdit, externalRefreshKey }: Co ), } : {})} + {...sharedMappingDoors({ + // objectstack#37359 — a shared mapping is metadata every + // importer of the object picks: only the reader who may + // share a view saves one, into a package of the app or + // the one they pick when asked (a cancelled ask writes + // nothing), and Manage opens the object's mapping list. + canManageViews, + identityImport: identityImportEnabled, + metadataClient, + dataSource, + objectName: objectDef.name, + app: sharingApp, + t, + navigate, + closeWizard: () => setShowImport(false), + })} onComplete={(result) => { refreshData(); const ok = result.importedRows; diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.targetObject-37359.test.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.targetObject-37359.test.tsx new file mode 100644 index 00000000000..f60ea2b0c17 --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.targetObject-37359.test.tsx @@ -0,0 +1,112 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37359 — the import wizard's Manage opens the mapping list + * narrowed to one object (`?targetObject=`). The real page runs, in the + * environment scope (every package's rows); only the metadata client is stubbed. Pinned, each with its control: + * + * - the mapping list with `targetObject` shows that object's mappings only, + * under a chip naming the object; + * - the chip's × shows every object again and drops the param; + * - a type whose rows name no object is not narrowed and draws no chip. + */ +import '@testing-library/jest-dom/vitest'; +import * as React from 'react'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { render, cleanup, screen, fireEvent, waitFor } from '@testing-library/react'; +import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'; +import '@object-ui/plugin-detail'; +import '@objectstack/lint'; + +const MAPPINGS: Record[] = [ + { name: 'lead_suppliers', label: 'Lead suppliers', targetObject: 'crm_lead', fieldMapping: [] }, + { name: 'lead_fair', label: 'Lead fair', targetObject: 'crm_lead', fieldMapping: [] }, + { name: 'account_feed', label: 'Account feed', targetObject: 'crm_account', fieldMapping: [] }, +]; +const SKILLS: Record[] = [ + { name: 'triage', label: 'Triage desk' }, + { name: 'billing', label: 'Billing' }, +]; + +const CLIENT = { list: async (type: string) => (type === 'mapping' ? MAPPINGS : type === 'skill' ? SKILLS : []) }; +const ENTRIES = [ + { type: 'mapping', label: 'Field Mapping', allowEnvironmentOverlay: false, allowRuntimeCreate: true }, + { type: 'skill', label: 'Skill', allowEnvironmentOverlay: false, allowRuntimeCreate: true }, +]; + +vi.mock('./useMetadata', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataClient: () => CLIENT, + useMetadataTypes: () => ({ loading: false, error: null, entries: ENTRIES }), +})); +vi.mock('./i18n', async (importOriginal) => ({ + ...(await importOriginal>()), + useMetadataLocale: () => 'en-US', +})); +vi.mock('../../hooks/useCanAuthorMetadata', () => ({ useCanAuthorMetadata: () => true })); +vi.mock('../../hooks/useTenancyPosture', async (importOriginal) => ({ + ...(await importOriginal>()), + useTenancyPosture: () => 'single', +})); + +import { MetadataResourceListPage } from './ResourceListPage'; +import { registerBuiltinAnchors } from './anchors'; +import '../../services/builtinComponents'; + +registerBuiltinAnchors(); + +afterEach(() => { + cleanup(); +}); + +function LocationProbe() { + const location = useLocation(); + return {location.pathname + location.search}; +} + +function mount(at: string) { + return render( + + + } /> + + + , + ); +} + +async function rowNames(): Promise { + await screen.findByRole('table'); + return screen + .getAllByTestId(/^metadata-row-(?!api-name$|source$|lock$)/) + .map((el) => el.getAttribute('data-testid')!.replace('metadata-row-', '')) + .sort(); +} + +describe('the mapping list narrowed to one object (objectstack#37359)', () => { + it('shows that object’s mappings under a chip naming it', async () => { + mount('/apps/setup/metadata/mapping?scope=environment&targetObject=crm_lead'); + await waitFor(async () => expect(await rowNames()).toEqual(['lead_fair', 'lead_suppliers'])); + expect(screen.getByTestId('metadata-list-target-object')).toHaveTextContent('crm_lead'); + }); + + it('the chip’s × shows every object again and drops the param', async () => { + mount('/apps/setup/metadata/mapping?scope=environment&targetObject=crm_lead'); + fireEvent.click(await screen.findByTestId('metadata-list-target-object')); + await waitFor(async () => expect(await rowNames()).toEqual(['account_feed', 'lead_fair', 'lead_suppliers'])); + expect(screen.getByTestId('location').textContent).toBe('/apps/setup/metadata/mapping?scope=environment'); + expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument(); + }); + + it('control: without the param every mapping is listed and no chip is drawn', async () => { + mount('/apps/setup/metadata/mapping?scope=environment'); + await waitFor(async () => expect(await rowNames()).toEqual(['account_feed', 'lead_fair', 'lead_suppliers'])); + expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument(); + }); + + it('a type whose rows name no object is not narrowed and draws no chip', async () => { + mount('/apps/setup/metadata/skill?scope=environment&targetObject=crm_lead'); + await waitFor(async () => expect(await rowNames()).toEqual(['billing', 'triage'])); + expect(screen.queryByTestId('metadata-list-target-object')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx index e6af4c1e3cb..8496b81b667 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx +++ b/ui/packages/app-shell/src/views/metadata-admin/ResourceListPage.tsx @@ -13,7 +13,7 @@ import * as React from 'react'; import { Link, Navigate, useLocation, useNavigate, useNavigationType, useParams, useSearchParams } from 'react-router-dom'; -import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy } from 'lucide-react'; +import { Plus, Search, RefreshCw, AlertTriangle, Lock, Copy, X } from 'lucide-react'; import { Button, NeutralIconTile, @@ -795,6 +795,11 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string matches: (row, q) => matchesQuery(row.item, q, searchableFields), source: sourceOf, ...(showCustomizedFilter && !studioList ? { customized: (row: ItemRow) => markOf(row) !== null } : {}), + // objectstack#37359 — a type whose rows name the object they serve is + // narrowed to one object by `?targetObject=` (the import wizard's Manage). + ...(TARGET_OBJECT_TYPES.has(type) + ? { targetObject: (row: ItemRow) => (typeof row.item.targetObject === 'string' ? row.item.targetObject : undefined) } + : {}), // Only a KNOWN state filters: while the ledger is unread or unreadable, no // item is either active or inactive to this filter. ...(activation @@ -807,6 +812,22 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string : {}), }; const filtered = applyListState(scopedItems, listState, rowReader, locale); + // objectstack#37359 — the object the list is narrowed to, shown as a chip + // whose × shows every object again. + const narrowedObject = rowReader.targetObject ? listState.targetObject : undefined; + const targetObjectChip = narrowedObject ? ( + + ) : null; // objectstack#36903 — a host that says what its empty list means (the // package-less scope, whose list is its source filter's narrowing of the // environment's rows) reads an unsearched, empty list as empty, not as a @@ -1485,6 +1506,7 @@ function DefaultMetadataList({ type, appName }: { type: string; appName?: string data-testid="metadata-list-search" /> + {targetObjectChip} {activation && ( updateListState({ source: v as MetadataListState['source'] })}> {/* Under Setup the source select is a filter chip (objectui#12606). */} = new Set(['mapping']); + /** Rows per page of the list. */ const LIST_PAGE_SIZE = 50; diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.targetObject-37359.test.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.targetObject-37359.test.ts new file mode 100644 index 00000000000..caeffad65ce --- /dev/null +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.targetObject-37359.test.ts @@ -0,0 +1,51 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37359 — the list state's object narrowing (`?targetObject=`): + * its codec, and that it narrows only a reader that names a row's object. + */ +import { describe, it, expect } from 'vitest'; +import { + DEFAULT_LIST_STATE, + LIST_TARGET_OBJECT_PARAM, + applyListState, + decodeListState, + writeListState, + type ListRowReader, +} from './metadataListState'; + +interface Row { name: string; targetObject?: string } +const ROWS: Row[] = [ + { name: 'lead_a', targetObject: 'crm_lead' }, + { name: 'account_a', targetObject: 'crm_account' }, + { name: 'lead_b', targetObject: 'crm_lead' }, +]; +const base: ListRowReader = { + name: (r) => r.name, + label: () => undefined, + matches: (r, q) => r.name.includes(q), + source: () => 'runtime', +}; +const withObject: ListRowReader = { ...base, targetObject: (r) => r.targetObject }; + +describe('the list state’s object narrowing (objectstack#37359)', () => { + it('round-trips through the address, and a blank value reads as none', () => { + const state = decodeListState(new URLSearchParams(`${LIST_TARGET_OBJECT_PARAM}=crm_lead&package=crm`)); + expect(state.targetObject).toBe('crm_lead'); + const written = writeListState(new URLSearchParams('package=crm'), state); + expect(written.get(LIST_TARGET_OBJECT_PARAM)).toBe('crm_lead'); + expect(written.get('package')).toBe('crm'); + expect(decodeListState(new URLSearchParams(`${LIST_TARGET_OBJECT_PARAM}=%20`))).toEqual(DEFAULT_LIST_STATE); + expect(writeListState(written, { ...state, targetObject: undefined }).has(LIST_TARGET_OBJECT_PARAM)).toBe(false); + }); + + it('narrows a reader that names the row’s object', () => { + const state = { ...DEFAULT_LIST_STATE, targetObject: 'crm_lead' }; + expect(applyListState(ROWS, state, withObject, 'en').map((r) => r.name)).toEqual(['lead_a', 'lead_b']); + }); + + it('control: a reader that names no object is not narrowed', () => { + const state = { ...DEFAULT_LIST_STATE, targetObject: 'crm_lead' }; + expect(applyListState(ROWS, state, base, 'en').map((r) => r.name)).toEqual(['account_a', 'lead_a', 'lead_b']); + }); +}); diff --git a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts index 566943d9ad9..5c0386b4f3d 100644 --- a/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts +++ b/ui/packages/app-shell/src/views/metadata-admin/metadataListState.ts @@ -39,6 +39,13 @@ export const LIST_CUSTOMIZED_PARAM = 'customized'; export const LIST_STATUS_PARAM = 'status'; /** The sort: a key, `-` before it for descending; absent = {@link DEFAULT_LIST_SORT}. */ export const LIST_SORT_PARAM = 'sort'; +/** + * objectstack#37359 — the object a list of an object-bound type is narrowed to: + * the rows whose `targetObject` is that object (the import wizard's Manage + * opens the mapping list this way). Absent = every object. Only a type whose + * rows name a `targetObject` is narrowed ({@link ListRowReader.targetObject}). + */ +export const LIST_TARGET_OBJECT_PARAM = 'targetObject'; /** Every param the list state writes. */ export const LIST_STATE_PARAMS: readonly string[] = [ @@ -47,6 +54,7 @@ export const LIST_STATE_PARAMS: readonly string[] = [ LIST_CUSTOMIZED_PARAM, LIST_STATUS_PARAM, LIST_SORT_PARAM, + LIST_TARGET_OBJECT_PARAM, ]; export type ListSourceFilter = 'all' | 'artifact' | 'runtime'; @@ -78,6 +86,8 @@ export interface MetadataListState { customizedOnly: boolean; status: ListStatusFilter; sort: ListSort; + /** objectstack#37359 — the object the rows are narrowed to ({@link LIST_TARGET_OBJECT_PARAM}); absent = every object. */ + targetObject?: string; } export const DEFAULT_LIST_STATE: MetadataListState = { @@ -114,12 +124,14 @@ export function decodeListSort(raw: string | null | undefined): ListSort { export function decodeListState(params: URLSearchParams): MetadataListState { const source = params.get(LIST_SOURCE_PARAM); const status = params.get(LIST_STATUS_PARAM); + const targetObject = params.get(LIST_TARGET_OBJECT_PARAM)?.trim(); return { query: params.get(LIST_QUERY_PARAM) ?? '', source: source === 'artifact' || source === 'runtime' ? source : 'all', customizedOnly: params.get(LIST_CUSTOMIZED_PARAM) === '1', status: status === 'active' || status === 'inactive' ? status : 'all', sort: decodeListSort(params.get(LIST_SORT_PARAM)), + ...(targetObject ? { targetObject } : {}), }; } @@ -136,6 +148,7 @@ export function writeListState(params: URLSearchParams, state: MetadataListState put(LIST_CUSTOMIZED_PARAM, state.customizedOnly ? '1' : ''); put(LIST_STATUS_PARAM, state.status === 'all' ? '' : state.status); put(LIST_SORT_PARAM, encodeListSort(state.sort)); + put(LIST_TARGET_OBJECT_PARAM, state.targetObject ?? ''); return next; } @@ -181,6 +194,12 @@ export interface ListRowReader { * every row has none and the `changed` sort is by name. */ changedAt?: (row: R) => string | undefined; + /** + * objectstack#37359 — the object the row is bound to (a mapping's + * `targetObject`). Absent, the type's rows name no object and + * {@link MetadataListState.targetObject} narrows nothing. + */ + targetObject?: (row: R) => string | undefined; } const COLLATORS = new Map(); @@ -220,6 +239,7 @@ export function applyListState( const kept = rows.filter((row) => { if (state.query && !read.matches(row, state.query)) return false; if (state.source !== 'all' && read.source(row) !== state.source) return false; + if (state.targetObject && read.targetObject && read.targetObject(row) !== state.targetObject) return false; if (state.customizedOnly && read.customized && !read.customized(row)) return false; if (state.status !== 'all' && read.active) { const active = read.active(row); diff --git a/ui/packages/app-shell/src/views/objectViewSharedMapping-37359.test.ts b/ui/packages/app-shell/src/views/objectViewSharedMapping-37359.test.ts new file mode 100644 index 00000000000..cde8de63b1f --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewSharedMapping-37359.test.ts @@ -0,0 +1,225 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37359 — the list page's door for the import wizard's "Save as + * shared mapping" (`saveSharedImportMapping`), and Manage's address. + * + * A REAL `MetadataClient` writes, so each pin reads the requests the server + * would receive; the two package doors answer through the page's `fetch`, as + * `saveAndPublishIntoApp-36409` stubs them. The rulings these hold (claim + * 7240340513 on objectstack#37359): + * - the mapping is saved into a package of the app and published at once; + * - no package of the app can be had: the person is asked, and a cancelled + * ask writes nothing (the door resolves `null`); a system app is refused + * before anything is written. Never a save naming no package; + * - a name a mapping already holds is refused before anything is written; + * an unpublished draft holding it is refused and nothing is published. + */ + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { MetadataClient } from '@object-ui/data-objectstack'; +import type { SharedMappingDraft } from '@object-ui/plugin-grid'; +import { saveSharedImportMapping, sharedMappingDoors, sharedMappingListPath } from './objectViewSharedMapping'; +import { LIST_TARGET_OBJECT_PARAM, decodeListState } from './metadata-admin/metadataListState'; + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +const DRAFT: SharedMappingDraft = { + name: 'supplier_list', + label: 'Supplier list', + targetObject: 'crm_lead', + sourceFormat: 'csv', + fieldMapping: [ + { source: 'Company', target: 'company' }, + { source: 'Email', target: 'email' }, + ], + mode: 'upsert', + upsertKey: ['email'], +}; + +function stubPackages(rows: Array<{ id: string; writable: boolean; scope?: string }>) { + vi.stubGlobal( + 'fetch', + vi.fn(async (input: RequestInfo | URL) => { + const url = String(input); + if (url === '/api/v1/packages') { + return json(200, { + success: true, + data: { + packages: rows.map(({ id, writable, scope }) => ({ + manifest: { id, name: id, version: '1.0.0', type: 'app', scope: scope ?? 'project' }, + writable, + })), + total: rows.length, + hasMore: false, + }, + }); + } + return json(404, { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: url, httpStatus: 404 } }); + }), + ); +} + +interface Seen { method: string; url: URL; body: unknown; headers: Record } +let seen: Seen[] = []; +const writesOf = () => seen.filter((r) => r.method !== 'GET'); + +/** + * A real client over a fake `/meta` door. `taken`: the probe finds a mapping + * of that name. `draftPending`: the draft save is refused by the first-write pin. + */ +function client(opts: { taken?: boolean; draftPending?: boolean } = {}): MetadataClient { + return new MetadataClient({ + baseUrl: 'http://localhost:3000', + fetch: (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input)); + const method = (init?.method ?? 'GET').toUpperCase(); + const headers = Object.fromEntries(new Headers(init?.headers ?? {}).entries()); + seen.push({ method, url, body: init?.body ? JSON.parse(String(init.body)) : undefined, headers }); + if (method === 'GET') { + if (opts.taken) { + return json(200, { type: 'mapping', name: 'supplier_list', item: { ...DRAFT, targetObject: 'crm_account' } }); + } + return json(404, { success: false, error: { code: 'RESOURCE_NOT_FOUND', message: 'none', httpStatus: 404 } }); + } + if (method === 'PUT' && opts.draftPending) { + return json(409, { + success: false, + error: { code: 'METADATA_CONFLICT', message: 'a draft exists', httpStatus: 409 }, + }); + } + return json(200, { success: true, state: 'draft', version: 'v1' }); + }) as unknown as typeof fetch, + }); +} + +const t = (key: string, options?: Record) => (options ? `${key} ${JSON.stringify(options)}` : key); + +function ctx(metadataClient: MetadataClient, app: { packageId: string | null; askPackage?: (r: { preselect?: string | null }) => Promise }) { + return { + metadataClient, + objectName: 'crm_lead', + app: { packageId: app.packageId, askPackage: app.askPackage ?? (async () => null) }, + t, + }; +} + +beforeEach(() => { + seen = []; +}); +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe('saveSharedImportMapping (objectstack#37359)', () => { + it('saves the draft into the app package and publishes it: header → field, mode, upsertKey', async () => { + stubPackages([{ id: 'com.example.crm', writable: true }]); + const ask = vi.fn(async () => null); + const saved = await saveSharedImportMapping(DRAFT, ctx(client(), { packageId: 'com.example.crm', askPackage: ask })); + expect(saved).toEqual(DRAFT); + expect(ask).not.toHaveBeenCalled(); + const [put, publish, ...rest] = writesOf(); + expect(rest).toEqual([]); + expect(put.method).toBe('PUT'); + expect(put.url.pathname).toBe('/api/v1/meta/mapping/supplier_list'); + expect(put.url.searchParams.get('package')).toBe('com.example.crm'); + expect(put.url.searchParams.get('mode')).toBe('draft'); + expect(put.headers['if-none-match']).toBe('*'); + expect(put.body).toMatchObject({ + name: 'supplier_list', + targetObject: 'crm_lead', + sourceFormat: 'csv', + fieldMapping: DRAFT.fieldMapping, + mode: 'upsert', + upsertKey: ['email'], + }); + expect(publish.url.pathname).toBe('/api/v1/meta/mapping/supplier_list/publish'); + }); + + it('a name a mapping already holds is refused, and nothing is written', async () => { + stubPackages([{ id: 'com.example.crm', writable: true }]); + await expect( + saveSharedImportMapping(DRAFT, ctx(client({ taken: true }), { packageId: 'com.example.crm' })), + ).rejects.toThrow('console.objectView.sharedMappingNameTaken {"name":"supplier_list"}'); + expect(writesOf()).toEqual([]); + }); + + it('an unpublished draft holding the name is refused, and nothing is published', async () => { + stubPackages([{ id: 'com.example.crm', writable: true }]); + await expect( + saveSharedImportMapping(DRAFT, ctx(client({ draftPending: true }), { packageId: 'com.example.crm' })), + ).rejects.toThrow('console.objectView.sharedMappingDraftPending'); + expect(writesOf().map((w) => w.method)).toEqual(['PUT']); + }); + + it('no package of the app: the person is asked, and the save names the package they pick', async () => { + stubPackages([]); + const ask = vi.fn(async () => 'com.example.picked'); + await saveSharedImportMapping(DRAFT, ctx(client(), { packageId: null, askPackage: ask })); + expect(ask).toHaveBeenCalledTimes(1); + expect(writesOf()[0].url.searchParams.get('package')).toBe('com.example.picked'); + }); + + it('a cancelled ask writes nothing and resolves null', async () => { + stubPackages([]); + const ask = vi.fn(async () => null); + expect(await saveSharedImportMapping(DRAFT, ctx(client(), { packageId: null, askPackage: ask }))).toBeNull(); + expect(ask).toHaveBeenCalledTimes(1); + expect(writesOf()).toEqual([]); + }); + + it('a system app is refused with its reason before anything is written, and never asks', async () => { + stubPackages([{ id: 'com.objectstack.setup', writable: false, scope: 'system' }]); + const ask = vi.fn(async () => 'com.example.picked'); + await expect( + saveSharedImportMapping(DRAFT, ctx(client(), { packageId: 'com.objectstack.setup', askPackage: ask })), + ).rejects.toThrow('console.objectView.sharedMappingSystemApp'); + expect(ask).not.toHaveBeenCalled(); + expect(writesOf()).toEqual([]); + }); +}); + +describe('Manage: the mapping list narrowed to the object (objectstack#37359)', () => { + it('opens every package’s mapping list with the object named', () => { + const path = sharedMappingListPath('crm_lead'); + expect(path).toBe(`/studio/~all/metadata/mapping?${LIST_TARGET_OBJECT_PARAM}=crm_lead`); + expect(decodeListState(new URL(path, 'http://x').searchParams).targetObject).toBe('crm_lead'); + }); +}); + +describe('who gets the doors (objectstack#37359)', () => { + const base = { + canManageViews: true, + identityImport: false, + metadataClient: {} as unknown, + objectName: 'crm_lead', + app: { packageId: 'com.example.crm', askPackage: async () => null }, + t, + navigate: () => {}, + closeWizard: () => {}, + }; + + it('the reader who may share a view gets both', () => { + const doors = sharedMappingDoors(base); + expect(typeof doors.onSaveSharedMapping).toBe('function'); + expect(typeof doors.onManageMappings).toBe('function'); + }); + + it('anyone else gets neither, so the wizard draws neither control', () => { + expect(sharedMappingDoors({ ...base, canManageViews: false })).toEqual({}); + }); + + it('the identity import gets neither, nor a page without a metadata client', () => { + expect(sharedMappingDoors({ ...base, identityImport: true })).toEqual({}); + expect(sharedMappingDoors({ ...base, metadataClient: null })).toEqual({}); + }); + + it('Manage closes the wizard and opens the object\'s mapping list', () => { + const navigate = vi.fn(); + const closeWizard = vi.fn(); + sharedMappingDoors({ ...base, navigate, closeWizard }).onManageMappings!(); + expect(closeWizard).toHaveBeenCalledTimes(1); + expect(navigate).toHaveBeenCalledWith('/studio/~all/metadata/mapping?targetObject=crm_lead'); + }); +}); diff --git a/ui/packages/app-shell/src/views/objectViewSharedMapping.ts b/ui/packages/app-shell/src/views/objectViewSharedMapping.ts new file mode 100644 index 00000000000..cf5355cd7e2 --- /dev/null +++ b/ui/packages/app-shell/src/views/objectViewSharedMapping.ts @@ -0,0 +1,131 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * objectstack#37359 — the list page's doors for the import wizard's shared + * mappings: "Save as shared mapping" on the preview step, and "Manage" beside + * Saved mapping. + * + * Who: the same reader who may share a view (`mayManageViews`): a shared + * `mapping` is metadata every importer of the object can pick, written through + * the `/meta` door that refuses any caller without `manage_metadata`. Anyone + * else is offered neither door, and the wizard draws neither control. + * + * The save ({@link saveSharedImportMapping}) creates the mapping the way a + * shared view is created: saved into a package of the app and published in one + * act (`saveAndPublishRuntimeMetadata`). When no package of the app can be had + * the person is asked to pick or create one (objectstack#38149); a cancelled + * ask writes nothing and the wizard's form stays open. No mapping is ever saved + * naming no package. + * + * Manage ({@link sharedMappingListPath}) opens Studio's mapping list across + * every package, narrowed to the object: the mappings the wizard's Saved + * mapping list offers. + */ + +import { formatMetadataError } from '@object-ui/data-objectstack'; +import type { SavedMapping, SharedMappingDraft } from '@object-ui/plugin-grid'; +import { + isRuntimeCreateNotSaved, + saveAndPublishRuntimeMetadata, + type RuntimeCreateApp, + type RuntimePersistCtx, +} from './runtime-metadata-persistence.js'; +import { LIST_TARGET_OBJECT_PARAM } from './metadata-admin/metadataListState.js'; +import { STUDIO_ALL_PACKAGES_SEGMENT, studioMetadataTypePath } from './studio-design/studioAddress.js'; + +/** The translator the list page holds (`useObjectTranslation().t`). */ +type Translate = (key: string, options?: Record) => string; + +export interface SharedImportMappingCtx { + metadataClient: RuntimePersistCtx['metadataClient']; + dataSource?: RuntimePersistCtx['dataSource']; + objectName: string; + /** The app the list runs in: the mapping is saved into one of its packages, or one the person picks. */ + app: RuntimeCreateApp; + t: Translate; +} + +/** + * Save `draft` as a shared mapping, published at once. Resolves the mapping as + * the wizard lists it, or `null` when the person cancelled the package ask + * (nothing was written). Rejects, with the sentence the wizard shows, when: + * - a mapping of that name exists already, in any package (a published row + * takes no first-write pin, so the save would replace it; and a name two + * packages hold is refused at import, `409`): nothing is written; + * - an unpublished draft holds the name (`'pending-draft'`): nothing is written; + * - the app is a system app, or the package door refuses this caller; + * - the server refuses the save or the publish (its own reason). + */ +export async function saveSharedImportMapping( + draft: SharedMappingDraft, + ctx: SharedImportMappingCtx, +): Promise { + const { metadataClient, dataSource, objectName, app, t } = ctx; + if (await metadataClient.get('mapping', draft.name)) { + throw new Error(t('console.objectView.sharedMappingNameTaken', { name: draft.name })); + } + let outcome: Awaited>; + try { + outcome = await saveAndPublishRuntimeMetadata('mapping', draft.name, draft, { + metadataClient, + dataSource, + objectName, + app, + }); + } catch (err) { + if (isRuntimeCreateNotSaved(err)) { + if (err.reason === 'cancelled') return null; + if (err.reason === 'system-app') throw Object.assign(new Error(t('console.objectView.sharedMappingSystemApp')), { cause: err }); + throw Object.assign(new Error(err.message), { cause: err }); + } + throw Object.assign(new Error(formatMetadataError(err)), { cause: err }); + } + if (outcome === 'pending-draft') { + throw new Error(t('console.objectView.sharedMappingDraftPending', { name: draft.name })); + } + return { ...draft }; +} + +/** The two wizard props {@link sharedMappingDoors} hands out. */ +export interface SharedMappingDoors { + onSaveSharedMapping?: (draft: SharedMappingDraft) => Promise; + onManageMappings?: () => void; +} + +/** + * The import wizard's shared-mapping doors for the list page, or none: only + * the reader who may share a view (`mayManageViews`, `canManageViews` here) + * gets them, never on the identity import (`sys_user` rows go through the + * identity door, which takes no named mapping), and never without a metadata + * client. Manage closes the wizard and opens {@link sharedMappingListPath}. + */ +export function sharedMappingDoors(input: { + canManageViews: boolean; + identityImport: boolean; + metadataClient: SharedImportMappingCtx['metadataClient'] | null | undefined; + dataSource?: SharedImportMappingCtx['dataSource']; + objectName: string; + app: RuntimeCreateApp; + t: Translate; + navigate: (path: string) => void; + closeWizard: () => void; +}): SharedMappingDoors { + const { canManageViews, identityImport, metadataClient, dataSource, objectName, app, t, navigate, closeWizard } = input; + if (!canManageViews || identityImport || !metadataClient) return {}; + return { + onSaveSharedMapping: (draft) => saveSharedImportMapping(draft, { metadataClient, dataSource, objectName, app, t }), + onManageMappings: () => { + closeWizard(); + navigate(sharedMappingListPath(objectName)); + }, + }; +} + +/** + * Studio's mapping list across every package, narrowed to `objectName`: + * `/studio/~all/metadata/mapping?targetObject=`. + */ +export function sharedMappingListPath(objectName: string): string { + const query = new URLSearchParams({ [LIST_TARGET_OBJECT_PARAM]: objectName }); + return `${studioMetadataTypePath(STUDIO_ALL_PACKAGES_SEGMENT, 'mapping')}?${query.toString()}`; +} diff --git a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts index f3c9b896f71..9d40e9949ee 100644 --- a/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts +++ b/ui/packages/app-shell/src/views/runtime-metadata-persistence.ts @@ -53,8 +53,10 @@ import { overrideDraftBody } from './studio-design/customizeOverride.js'; /** The runtime-editable artifact types ADR-0034 unifies. `page` (a record * `PageSchema`) joins the original three (#1541): a record page is edited in - * the browser and staged/published through the same `/meta` draft model. */ -export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page'; + * the browser and staged/published through the same `/meta` draft model. + * objectstack#37359 — `mapping`, a shared import mapping saved from the import + * wizard, is created the same way: into a package of the app, published at once. */ +export type RuntimeArtifactType = 'view' | 'report' | 'dashboard' | 'page' | 'mapping'; /** * The metadata `name` (the `:name` in `/meta/page/:name`) for an object's diff --git a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts index c29c631fd40..df3e3d00fbe 100644 --- a/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts +++ b/ui/packages/i18n/src/__tests__/de-quote-pairing-3876.test.ts @@ -502,7 +502,13 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // and `chatbot.build.draftPosture` — six spans fewer. // 128 once objectstack-ai/objectstack#37861 removed `console.ai.focus.switchPrompt` // with the offer it drew („{{target}}“) — one interpolated span fewer. - expect(okSpans, 'correctly paired spans').toBe(128); + // 131 once objectstack-ai/objectstack#37359 added the Import Wizard's shared + // mapping save: `grid.import.sharedSaveHint` and `.sharedSaved` name the + // „Gespeicherte Zuordnung“ list, and `.sharedSaved` its new „{{name}}“ — three spans. + // 133 once the list page's half of the same card added + // `console.objectView.sharedMappingNameTaken` and `.sharedMappingDraftPending`, + // one „{{name}}“ each — two spans. + expect(okSpans, 'correctly paired spans').toBe(133); }); it('keeps the count identity that replaces the card’s count(„) === count(“)', () => { @@ -650,7 +656,11 @@ describe('objectui#3876 — de pack closes „ with “ and not with a straight // 129 / 129 / 0 after objectstack-ai/objectstack#37682 retired six build-chat // keys, one matched pair each. // 128 / 128 / 0 after objectstack-ai/objectstack#37861 removed `console.ai.focus.switchPrompt`. - expect({ open, close, rdq }).toEqual({ open: 128, close: 128, rdq: 0 }); + // 131 / 131 / 0 after objectstack-ai/objectstack#37359 added three matched + // pairs to `grid.import.sharedSaveHint` and `grid.import.sharedSaved`. + // 133 / 133 / 0 after the same card added `console.objectView.sharedMappingNameTaken` + // and `.sharedMappingDraftPending`, one matched pair each. + expect({ open, close, rdq }).toEqual({ open: 133, close: 133, rdq: 0 }); // The durable shape: every „ closed by a “, every surplus “ an English // opener answered by a ”. Survived translating the two English values. expect(close).toBe(open + rdq); diff --git a/ui/packages/i18n/src/locales/ar.ts b/ui/packages/i18n/src/locales/ar.ts index b28875287de..a926aac411e 100644 --- a/ui/packages/i18n/src/locales/ar.ts +++ b/ui/packages/i18n/src/locales/ar.ts @@ -929,6 +929,19 @@ const ar = { savedMapping: 'التعيين المحفوظ:', chooseSavedMapping: 'اختر تعييناً محفوظاً…', manualMapping: '— تعيين الأعمدة يدويًا —', + manageMappings: 'إدارة', + sharedSave: 'حفظ كتعيين مشترك', + sharedSaveHint: 'بعد الحفظ، يمكن لكل من يستورد {{object}} اختياره من «التعيين المحفوظ». يحفظ تعيين الأعمدة ووضع الكتابة وحقول المطابقة؛ أما الخيارات الأخرى فتنطبق على هذا الاستيراد فقط.', + sharedLabel: 'اسم التعيين', + sharedName: 'اسم API', + sharedNameInvalid: 'استخدم أحرفًا لاتينية صغيرة وأرقامًا وشرطات سفلية فقط، مع البدء بحرف، وبطول حرفين على الأقل.', + sharedNeedsMapping: 'عيّن عمودًا واحدًا على الأقل لحفظ تعيين مشترك.', + sharedNeedsMatchFields: 'اختر حقول المطابقة لحفظ تعيين مشترك.', + sharedAmbiguousHeaders: 'يعثر التعيين المشترك على كل عمود من خلال عنوانه، لذا يحتاج كل عمود معيَّن إلى عنوان خاص به. أعد تسمية هذه العناوين في الملف أولًا: {{headers}}', + sharedBlankHeader: '(بلا عنوان)', + sharedSaving: 'جارٍ الحفظ…', + sharedSaved: 'تم حفظ «{{name}}»، وهو الآن مدرج في «التعيين المحفوظ».', + sharedSaveFailed: 'لم يُحفظ التعيين: {{reason}}', transform: 'التحويل', savedMappingHint: 'يطبّق التعيين "{{name}}" إعادة التسمية + التحويلات + تحويل الأنواع على الخادم. تعيين الأعمدة للقراءة فقط.', savedMappingPreviewNote: 'تعرض المعاينة الأعمدة المصدر لديك؛ وعند الاستيراد يطبّق التعيين "{{name}}" إعادة التسمية والتحويلات وتحويل الأنواع على الخادم.', @@ -3166,6 +3179,9 @@ const ar = { importedToast_many: "تم استيراد {{count}} صفًا.", importedToast_other: "تم استيراد {{count}} صف.", importedWithSkipped: "تم استيراد {{ok}} صف(صفوف)؛ تم تخطي {{skipped}}.", + sharedMappingNameTaken: "يوجد تعيين باسم «{{name}}» بالفعل. اختر اسم API آخر.", + sharedMappingDraftPending: "تستخدم مسودة غير منشورة الاسم «{{name}}» بالفعل، لذا لم يُحفظ شيء. اختر اسم API آخر.", + sharedMappingSystemApp: "لا يمكن حفظ تعيين مشترك في تطبيق نظام: فهو يأتي مع المنصة وليس له حزمة لتغييراتك. احفظه أثناء الاستيراد في أحد تطبيقات أعمالك بدلًا من ذلك.", createViewDesc: "اختر نوع العرض وأعطه اسماً. يمكن تغيير جميع الإعدادات لاحقاً.", cancel: "إلغاء", create: "إنشاء", diff --git a/ui/packages/i18n/src/locales/de.ts b/ui/packages/i18n/src/locales/de.ts index 2055601432f..cc944397d2c 100644 --- a/ui/packages/i18n/src/locales/de.ts +++ b/ui/packages/i18n/src/locales/de.ts @@ -847,6 +847,19 @@ const de = { savedMapping: 'Gespeicherte Zuordnung:', chooseSavedMapping: 'Gespeicherte Zuordnung auswählen…', manualMapping: '— Spalten manuell zuordnen —', + manageMappings: 'Verwalten', + sharedSave: 'Als gemeinsame Zuordnung speichern', + sharedSaveHint: 'Danach kann jede Person, die {{object}} importiert, sie unter „Gespeicherte Zuordnung“ auswählen. Gespeichert werden die Spaltenzuordnung, der Schreibmodus und die Abgleichsfelder; die übrigen Optionen gelten nur für diesen Import.', + sharedLabel: 'Name der Zuordnung', + sharedName: 'API-Name', + sharedNameInvalid: 'Nur Kleinbuchstaben, Ziffern und Unterstriche, beginnend mit einem Buchstaben, mindestens 2 Zeichen.', + sharedNeedsMapping: 'Ordnen Sie mindestens eine Spalte zu, um eine gemeinsame Zuordnung zu speichern.', + sharedNeedsMatchFields: 'Wählen Sie die Abgleichsfelder, um eine gemeinsame Zuordnung zu speichern.', + sharedAmbiguousHeaders: 'Eine gemeinsame Zuordnung findet jede Spalte über ihre Überschrift, daher braucht jede zugeordnete Spalte eine eigene Überschrift. Benennen Sie diese zuerst in der Datei um: {{headers}}', + sharedBlankHeader: '(keine Überschrift)', + sharedSaving: 'Wird gespeichert…', + sharedSaved: '„{{name}}“ gespeichert. Sie steht jetzt unter „Gespeicherte Zuordnung“.', + sharedSaveFailed: 'Die Zuordnung wurde nicht gespeichert: {{reason}}', transform: 'Transformation', savedMappingHint: 'Die Zuordnung „{{name}}“ wendet auf dem Server Umbenennung + Transformationen + Typkonvertierung an. Die Spaltenzuordnung ist schreibgeschützt.', savedMappingPreviewNote: 'Die Vorschau zeigt Ihre Quellspalten; beim Import wendet die Zuordnung „{{name}}“ auf dem Server Umbenennung, Transformationen und Typkonvertierung an.', @@ -2867,6 +2880,9 @@ const de = { importedToast_one: "{{count}} Zeile importiert.", importedToast_other: "{{count}} Zeilen importiert.", importedWithSkipped: "{{ok}} Zeile(n) importiert; {{skipped}} übersprungen.", + sharedMappingNameTaken: "Eine Zuordnung namens „{{name}}“ gibt es bereits. Wählen Sie einen anderen API-Namen.", + sharedMappingDraftPending: "Ein unveröffentlichter Entwurf verwendet den Namen „{{name}}“ bereits, daher wurde nichts gespeichert. Wählen Sie einen anderen API-Namen.", + sharedMappingSystemApp: "Eine gemeinsame Zuordnung kann nicht in einer System-App gespeichert werden: Sie wird mit der Plattform ausgeliefert und hat kein Paket für Ihre Änderungen. Speichern Sie sie stattdessen beim Import in einer Ihrer Geschäfts-Apps.", createViewDesc: "Wählen Sie einen Ansichtstyp und geben Sie ihm einen Namen. Alle Einstellungen können danach geändert werden.", cancel: "Abbrechen", create: "Erstellen", diff --git a/ui/packages/i18n/src/locales/en.ts b/ui/packages/i18n/src/locales/en.ts index 351c3b632dc..0a5bf35bd16 100644 --- a/ui/packages/i18n/src/locales/en.ts +++ b/ui/packages/i18n/src/locales/en.ts @@ -1014,6 +1014,19 @@ const en = { savedMapping: 'Saved mapping:', chooseSavedMapping: 'Choose a saved mapping…', manualMapping: '— Map columns manually —', + manageMappings: 'Manage', + sharedSave: 'Save as shared mapping', + sharedSaveHint: 'Everyone who imports {{object}} can then pick it under Saved mapping. It keeps the column mapping, the write mode and the match fields; the other options apply to this import only.', + sharedLabel: 'Mapping name', + sharedName: 'API name', + sharedNameInvalid: 'Use lowercase letters, digits and underscores, starting with a letter, at least 2 characters.', + sharedNeedsMapping: 'Map at least one column to save a shared mapping.', + sharedNeedsMatchFields: 'Choose the match fields to save a shared mapping.', + sharedAmbiguousHeaders: 'A shared mapping finds each column by its header, so every mapped column needs a header of its own. Rename these in the file first: {{headers}}', + sharedBlankHeader: '(no header)', + sharedSaving: 'Saving…', + sharedSaved: 'Saved “{{name}}”. It is now listed under Saved mapping.', + sharedSaveFailed: 'The mapping was not saved: {{reason}}', transform: 'Transform', savedMappingHint: 'Mapping “{{name}}” applies rename + transforms + type coercion on the server. Column mapping is read-only.', savedMappingPreviewNote: 'The preview shows your source columns; on import, mapping “{{name}}” applies rename, transforms and type coercion on the server.', @@ -3481,6 +3494,9 @@ const en = { importedToast_one: 'Imported {{count}} row.', importedToast_other: 'Imported {{count}} rows.', importedWithSkipped: 'Imported {{ok}} row(s); skipped {{skipped}}.', + sharedMappingNameTaken: 'A mapping named “{{name}}” already exists. Choose another API name.', + sharedMappingDraftPending: 'An unpublished draft already uses the name “{{name}}”, so nothing was saved. Choose another API name.', + sharedMappingSystemApp: 'A shared mapping can’t be saved in a system app: it ships with the platform and has no package for your changes. Save it while importing in one of your business apps instead.', configureView: 'Configure View', toolbarEnabledCount: '{{count}} of {{total}} enabled', searchFields: 'Search fields…', diff --git a/ui/packages/i18n/src/locales/es.ts b/ui/packages/i18n/src/locales/es.ts index 975a5b8198f..d533b4fe421 100644 --- a/ui/packages/i18n/src/locales/es.ts +++ b/ui/packages/i18n/src/locales/es.ts @@ -871,6 +871,19 @@ const es = { savedMapping: 'Asignación guardada:', chooseSavedMapping: 'Elegir una asignación guardada…', manualMapping: '— Asignar columnas manualmente —', + manageMappings: 'Administrar', + sharedSave: 'Guardar como asignación compartida', + sharedSaveHint: 'Después, cualquiera que importe {{object}} podrá elegirla en «Asignación guardada». Guarda la asignación de columnas, el modo de escritura y los campos de coincidencia; las demás opciones solo se aplican a esta importación.', + sharedLabel: 'Nombre de la asignación', + sharedName: 'Nombre de API', + sharedNameInvalid: 'Use solo minúsculas, dígitos y guiones bajos, empezando por una letra, con al menos 2 caracteres.', + sharedNeedsMapping: 'Asigne al menos una columna para guardar una asignación compartida.', + sharedNeedsMatchFields: 'Elija los campos de coincidencia para guardar una asignación compartida.', + sharedAmbiguousHeaders: 'Una asignación compartida encuentra cada columna por su encabezado, así que cada columna asignada necesita un encabezado propio. Cambie primero estos en el archivo: {{headers}}', + sharedBlankHeader: '(sin encabezado)', + sharedSaving: 'Guardando…', + sharedSaved: 'Se guardó «{{name}}». Ahora aparece en «Asignación guardada».', + sharedSaveFailed: 'La asignación no se guardó: {{reason}}', transform: 'Transformación', savedMappingHint: 'La asignación "{{name}}" aplica el cambio de nombre + las transformaciones + la conversión de tipos en el servidor. La asignación de columnas es de solo lectura.', savedMappingPreviewNote: 'La vista previa muestra sus columnas de origen; al importar, la asignación "{{name}}" aplica el cambio de nombre, las transformaciones y la conversión de tipos en el servidor.', @@ -2943,6 +2956,9 @@ const es = { importedToast_many: "{{count}} de filas importadas.", importedToast_other: "{{count}} filas importadas.", importedWithSkipped: "{{ok}} fila(s) importada(s); {{skipped}} omitida(s).", + sharedMappingNameTaken: "Ya existe una asignación llamada «{{name}}». Elija otro nombre de API.", + sharedMappingDraftPending: "Un borrador sin publicar ya usa el nombre «{{name}}», así que no se guardó nada. Elija otro nombre de API.", + sharedMappingSystemApp: "No se puede guardar una asignación compartida en una aplicación del sistema: viene con la plataforma y no tiene un paquete para sus cambios. Guárdela al importar en una de sus aplicaciones de negocio.", createViewDesc: "Elija un tipo de vista y asígnele un nombre. Todas las configuraciones se pueden cambiar después.", cancel: "Cancelar", create: "Crear", diff --git a/ui/packages/i18n/src/locales/fr.ts b/ui/packages/i18n/src/locales/fr.ts index 82f97af8218..e515204ec09 100644 --- a/ui/packages/i18n/src/locales/fr.ts +++ b/ui/packages/i18n/src/locales/fr.ts @@ -866,6 +866,19 @@ const fr = { savedMapping: "Correspondance enregistrée :", chooseSavedMapping: "Choisir une correspondance enregistrée…", manualMapping: "— Faire correspondre les colonnes manuellement —", + manageMappings: "Gérer", + sharedSave: "Enregistrer comme correspondance partagée", + sharedSaveHint: "Ensuite, toute personne qui importe {{object}} pourra la choisir dans « Correspondance enregistrée ». Elle conserve la correspondance des colonnes, le mode d’écriture et les champs de rapprochement ; les autres options ne s’appliquent qu’à cette importation.", + sharedLabel: "Nom de la correspondance", + sharedName: "Nom d’API", + sharedNameInvalid: "Utilisez uniquement des minuscules, des chiffres et des traits de soulignement, en commençant par une lettre, au moins 2 caractères.", + sharedNeedsMapping: "Faites correspondre au moins une colonne pour enregistrer une correspondance partagée.", + sharedNeedsMatchFields: "Choisissez les champs de rapprochement pour enregistrer une correspondance partagée.", + sharedAmbiguousHeaders: "Une correspondance partagée retrouve chaque colonne par son en-tête : chaque colonne associée doit donc avoir son propre en-tête. Renommez d’abord ceux-ci dans le fichier : {{headers}}", + sharedBlankHeader: "(sans en-tête)", + sharedSaving: "Enregistrement…", + sharedSaved: "« {{name}} » enregistrée. Elle figure maintenant dans « Correspondance enregistrée ».", + sharedSaveFailed: "La correspondance n’a pas été enregistrée : {{reason}}", transform: 'Transformation', savedMappingHint: "La correspondance « {{name}} » applique le renommage + les transformations + la conversion de type côté serveur. La correspondance des colonnes est en lecture seule.", savedMappingPreviewNote: "L'aperçu affiche vos colonnes source ; à l'import, la correspondance « {{name}} » applique le renommage, les transformations et la conversion de type côté serveur.", @@ -2939,6 +2952,9 @@ const fr = { importedToast_many: "{{count}} de lignes importées.", importedToast_other: "{{count}} lignes importées.", importedWithSkipped: "{{ok}} ligne(s) importée(s) ; {{skipped}} ignorée(s).", + sharedMappingNameTaken: "Une correspondance nommée « {{name}} » existe déjà. Choisissez un autre nom d’API.", + sharedMappingDraftPending: "Un brouillon non publié utilise déjà le nom « {{name}} » : rien n’a été enregistré. Choisissez un autre nom d’API.", + sharedMappingSystemApp: "Une correspondance partagée ne peut pas être enregistrée dans une application système : elle est fournie avec la plateforme et n’a pas de package pour vos modifications. Enregistrez-la plutôt lors d’un import dans l’une de vos applications métier.", createViewDesc: "Choisissez un type de vue et donnez-lui un nom. Tous les paramètres peuvent être modifiés ensuite.", cancel: "Annuler", create: "Créer", diff --git a/ui/packages/i18n/src/locales/ja.ts b/ui/packages/i18n/src/locales/ja.ts index 103d9922a75..76b9b63b596 100644 --- a/ui/packages/i18n/src/locales/ja.ts +++ b/ui/packages/i18n/src/locales/ja.ts @@ -847,6 +847,19 @@ const ja = { savedMapping: '保存済みマッピング:', chooseSavedMapping: '保存済みマッピングを選択…', manualMapping: '— 列を手動でマッピング —', + manageMappings: '管理', + sharedSave: '共有マッピングとして保存', + sharedSaveHint: '保存すると、{{object}} をインポートする全員が「保存済みマッピング」から選べます。列のマッピング、書き込みモード、照合フィールドが保存されます。その他のオプションは今回のインポートにのみ適用されます。', + sharedLabel: 'マッピング名', + sharedName: 'API 名', + sharedNameInvalid: '小文字、数字、アンダースコアのみ使用でき、先頭は文字、2 文字以上にしてください。', + sharedNeedsMapping: '共有マッピングを保存するには、列を 1 つ以上マッピングしてください。', + sharedNeedsMatchFields: '共有マッピングを保存するには、照合フィールドを選んでください。', + sharedAmbiguousHeaders: '共有マッピングは列を見出しで探すため、マッピングした列にはそれぞれ固有の見出しが必要です。先にファイルでこれらの見出しを変更してください:{{headers}}', + sharedBlankHeader: '(見出しなし)', + sharedSaving: '保存中…', + sharedSaved: '「{{name}}」を保存しました。「保存済みマッピング」に表示されます。', + sharedSaveFailed: 'マッピングは保存されませんでした:{{reason}}', transform: '変換', savedMappingHint: 'マッピング「{{name}}」はサーバー側でリネーム+変換+型変換を適用します。列マッピングは読み取り専用です。', savedMappingPreviewNote: 'プレビューは元の列を表示しています。インポート時、マッピング「{{name}}」がサーバー側でリネーム・変換・型変換を適用します。', @@ -2869,6 +2882,9 @@ const ja = { importedToast_one: "{{count}} 行をインポートしました。", importedToast_other: "{{count}} 行をインポートしました。", importedWithSkipped: "{{ok}} 行をインポートしました。{{skipped}} 行をスキップしました。", + sharedMappingNameTaken: "「{{name}}」という名前のマッピングは既にあります。別の API 名を選んでください。", + sharedMappingDraftPending: "「{{name}}」という名前は未公開の下書きが使っているため、保存しませんでした。別の API 名を選んでください。", + sharedMappingSystemApp: "システムアプリには共有マッピングを保存できません。システムアプリはプラットフォームに付属しており、変更を入れるパッケージがありません。業務アプリでインポートするときに保存してください。", createViewDesc: "ビュータイプを選択して名前を付けてください。設定は後で変更できます。", cancel: "キャンセル", create: "作成", diff --git a/ui/packages/i18n/src/locales/ko.ts b/ui/packages/i18n/src/locales/ko.ts index d5270bde760..37a61184e98 100644 --- a/ui/packages/i18n/src/locales/ko.ts +++ b/ui/packages/i18n/src/locales/ko.ts @@ -847,6 +847,19 @@ const ko = { savedMapping: '저장된 매핑:', chooseSavedMapping: '저장된 매핑 선택…', manualMapping: '— 열 수동 매핑 —', + manageMappings: '관리', + sharedSave: '공유 매핑으로 저장', + sharedSaveHint: '저장하면 {{object}}을(를) 가져오는 모든 사람이 「저장된 매핑」에서 선택할 수 있습니다. 열 매핑, 쓰기 모드, 일치 필드가 저장되며 다른 옵션은 이번 가져오기에만 적용됩니다.', + sharedLabel: '매핑 이름', + sharedName: 'API 이름', + sharedNameInvalid: '소문자, 숫자, 밑줄만 사용하고 문자로 시작하며 2자 이상이어야 합니다.', + sharedNeedsMapping: '공유 매핑을 저장하려면 열을 하나 이상 매핑하세요.', + sharedNeedsMatchFields: '공유 매핑을 저장하려면 일치 필드를 선택하세요.', + sharedAmbiguousHeaders: '공유 매핑은 머리글로 각 열을 찾으므로 매핑된 열마다 고유한 머리글이 필요합니다. 먼저 파일에서 다음 머리글을 바꾸세요: {{headers}}', + sharedBlankHeader: '(머리글 없음)', + sharedSaving: '저장 중…', + sharedSaved: '「{{name}}」을(를) 저장했습니다. 이제 「저장된 매핑」에 표시됩니다.', + sharedSaveFailed: '매핑을 저장하지 못했습니다: {{reason}}', transform: '변환', savedMappingHint: '매핑 "{{name}}"은(는) 서버에서 이름 변경 + 변환 + 형 변환을 적용합니다. 열 매핑은 읽기 전용입니다.', savedMappingPreviewNote: '미리보기에는 원본 열이 표시됩니다. 가져올 때 매핑 "{{name}}"이(가) 서버에서 이름 변경, 변환, 형 변환을 적용합니다.', @@ -2867,6 +2880,9 @@ const ko = { importedToast_one: "{{count}}개 행 가져옴.", importedToast_other: "{{count}}개 행 가져옴.", importedWithSkipped: "{{ok}}개 행 가져옴; {{skipped}}개 건너뜀.", + sharedMappingNameTaken: "「{{name}}」이라는 이름의 매핑이 이미 있습니다. 다른 API 이름을 선택하세요.", + sharedMappingDraftPending: "게시되지 않은 초안이 이미 「{{name}}」 이름을 사용하고 있어 저장하지 않았습니다. 다른 API 이름을 선택하세요.", + sharedMappingSystemApp: "시스템 앱에서는 공유 매핑을 저장할 수 없습니다. 시스템 앱은 플랫폼과 함께 제공되며 변경 사항을 담을 패키지가 없습니다. 업무 앱에서 가져올 때 저장하세요.", createViewDesc: "보기 유형을 선택하고 이름을 지정하세요. 모든 설정은 나중에 변경할 수 있습니다.", cancel: "취소", create: "생성", diff --git a/ui/packages/i18n/src/locales/pt-BR.ts b/ui/packages/i18n/src/locales/pt-BR.ts index 61c215f90cd..fc460bac2b7 100644 --- a/ui/packages/i18n/src/locales/pt-BR.ts +++ b/ui/packages/i18n/src/locales/pt-BR.ts @@ -866,6 +866,19 @@ const pt = { savedMapping: 'Mapeamento salvo:', chooseSavedMapping: 'Escolher um mapeamento salvo…', manualMapping: '— Mapear colunas manualmente —', + manageMappings: 'Gerenciar', + sharedSave: 'Salvar como mapeamento compartilhado', + sharedSaveHint: "Depois, todos que importarem {{object}} poderão escolhê-lo em \"Mapeamento salvo\". Ele guarda o mapeamento de colunas, o modo de gravação e os campos de correspondência; as demais opções valem só para esta importação.", + sharedLabel: 'Nome do mapeamento', + sharedName: 'Nome de API', + sharedNameInvalid: 'Use apenas letras minúsculas, dígitos e sublinhados, começando com uma letra, com pelo menos 2 caracteres.', + sharedNeedsMapping: 'Mapeie pelo menos uma coluna para salvar um mapeamento compartilhado.', + sharedNeedsMatchFields: 'Escolha os campos de correspondência para salvar um mapeamento compartilhado.', + sharedAmbiguousHeaders: 'Um mapeamento compartilhado encontra cada coluna pelo cabeçalho, então cada coluna mapeada precisa de um cabeçalho próprio. Renomeie estes no arquivo primeiro: {{headers}}', + sharedBlankHeader: '(sem cabeçalho)', + sharedSaving: 'Salvando…', + sharedSaved: "\"{{name}}\" salvo. Agora aparece em \"Mapeamento salvo\".", + sharedSaveFailed: 'O mapeamento não foi salvo: {{reason}}', transform: 'Transformação', savedMappingHint: 'O mapeamento "{{name}}" aplica renomeação + transformações + conversão de tipos no servidor. O mapeamento de colunas é somente leitura.', savedMappingPreviewNote: 'A pré-visualização mostra suas colunas de origem; na importação, o mapeamento "{{name}}" aplica renomeação, transformações e conversão de tipos no servidor.', @@ -2938,6 +2951,9 @@ const pt = { importedToast_many: "{{count}} de linhas importadas.", importedToast_other: "{{count}} linhas importadas.", importedWithSkipped: "{{ok}} linha(s) importada(s); {{skipped}} pulada(s).", + sharedMappingNameTaken: "Já existe um mapeamento chamado \"{{name}}\". Escolha outro nome de API.", + sharedMappingDraftPending: "Um rascunho não publicado já usa o nome \"{{name}}\", então nada foi salvo. Escolha outro nome de API.", + sharedMappingSystemApp: "Um mapeamento compartilhado não pode ser salvo em um aplicativo do sistema: ele vem com a plataforma e não tem um pacote para suas alterações. Salve-o ao importar em um dos seus aplicativos de negócio.", createViewDesc: "Escolha um tipo de exibição e dê um nome a ela. Todas as configurações podem ser alteradas depois.", cancel: "Cancelar", create: "Criar", diff --git a/ui/packages/i18n/src/locales/ru.ts b/ui/packages/i18n/src/locales/ru.ts index 68f3c1dcba8..4347e52d1e6 100644 --- a/ui/packages/i18n/src/locales/ru.ts +++ b/ui/packages/i18n/src/locales/ru.ts @@ -888,6 +888,19 @@ const ru = { savedMapping: 'Сохранённое сопоставление:', chooseSavedMapping: 'Выбрать сохранённое сопоставление…', manualMapping: '— Сопоставить столбцы вручную —', + manageMappings: 'Управлять', + sharedSave: 'Сохранить как общее сопоставление', + sharedSaveHint: 'После сохранения каждый, кто импортирует {{object}}, сможет выбрать его в разделе «Сохранённое сопоставление». Сохраняются сопоставление столбцов, режим записи и поля сопоставления; остальные параметры действуют только для этого импорта.', + sharedLabel: 'Название сопоставления', + sharedName: 'API-имя', + sharedNameInvalid: 'Только строчные латинские буквы, цифры и подчёркивания, начиная с буквы, не короче 2 символов.', + sharedNeedsMapping: 'Сопоставьте хотя бы один столбец, чтобы сохранить общее сопоставление.', + sharedNeedsMatchFields: 'Выберите поля сопоставления, чтобы сохранить общее сопоставление.', + sharedAmbiguousHeaders: 'Общее сопоставление находит каждый столбец по заголовку, поэтому у каждого сопоставленного столбца должен быть свой заголовок. Сначала переименуйте в файле: {{headers}}', + sharedBlankHeader: '(без заголовка)', + sharedSaving: 'Сохранение…', + sharedSaved: '«{{name}}» сохранено и теперь есть в списке «Сохранённое сопоставление».', + sharedSaveFailed: 'Сопоставление не сохранено: {{reason}}', transform: 'Преобразование', savedMappingHint: 'Сопоставление «{{name}}» применяет на сервере переименование + преобразования + приведение типов. Сопоставление столбцов доступно только для чтения.', savedMappingPreviewNote: 'В предпросмотре показаны исходные столбцы; при импорте сопоставление «{{name}}» применяет на сервере переименование, преобразования и приведение типов.', @@ -3024,6 +3037,9 @@ const ru = { importedToast_many: "Импортировано {{count}} строк.", importedToast_other: "Импортировано {{count}} строки.", importedWithSkipped: "{{ok}} строк импортировано; {{skipped}} пропущено.", + sharedMappingNameTaken: "Сопоставление с именем «{{name}}» уже существует. Выберите другое имя API.", + sharedMappingDraftPending: "Имя «{{name}}» уже занято неопубликованным черновиком, поэтому ничего не сохранено. Выберите другое имя API.", + sharedMappingSystemApp: "Общее сопоставление нельзя сохранить в системном приложении: оно поставляется с платформой, и в нём нет пакета для ваших изменений. Сохраните его при импорте в одном из ваших бизнес-приложений.", createViewDesc: "Выберите тип представления и задайте ему имя. Все настройки можно изменить позже.", cancel: "Отмена", create: "Создать", diff --git a/ui/packages/i18n/src/locales/zh-Hans.ts b/ui/packages/i18n/src/locales/zh-Hans.ts index e5d03488f63..cbd8045d00b 100644 --- a/ui/packages/i18n/src/locales/zh-Hans.ts +++ b/ui/packages/i18n/src/locales/zh-Hans.ts @@ -727,6 +727,19 @@ const zh = { savedMapping: '已保存的映射:', chooseSavedMapping: '选择已保存的映射…', manualMapping: '— 手动映射列 —', + manageMappings: '管理', + sharedSave: '保存为共享映射', + sharedSaveHint: '保存后,所有导入{{object}}的人都可以在「已保存的映射」中选用它。它会保存列映射、写入方式和匹配字段;其他选项只对这一次导入有效。', + sharedLabel: '映射名称', + sharedName: 'API 名称', + sharedNameInvalid: '只能用小写字母、数字和下划线,以字母开头,至少 2 个字符。', + sharedNeedsMapping: '请至少映射一列,才能保存为共享映射。', + sharedNeedsMatchFields: '请先选择匹配字段,才能保存为共享映射。', + sharedAmbiguousHeaders: '共享映射按列标题查找每一列,所以每个已映射的列都需要一个独有的标题。请先在文件中改掉这些标题:{{headers}}', + sharedBlankHeader: '(无标题)', + sharedSaving: '正在保存…', + sharedSaved: '已保存「{{name}}」,现在可以在「已保存的映射」中选用。', + sharedSaveFailed: '映射没有保存:{{reason}}', transform: '转换', savedMappingHint: '映射“{{name}}”将在服务端应用重命名 + 转换 + 类型强转,列映射为只读。', savedMappingPreviewNote: '预览显示的是原始列;导入时,映射“{{name}}”将在服务端应用重命名、转换与类型强转。', @@ -2987,6 +3000,9 @@ const zh = { importedToast_one: '成功导入 {{count}} 行。', importedToast_other: '成功导入 {{count}} 行。', importedWithSkipped: '已导入 {{ok}} 行;跳过 {{skipped}} 行。', + sharedMappingNameTaken: '已有名为「{{name}}」的映射,请换一个 API 名称。', + sharedMappingDraftPending: '名称「{{name}}」已被一份未发布的草稿占用,所以没有保存。请换一个 API 名称。', + sharedMappingSystemApp: '系统应用里不能保存共享映射:系统应用随平台提供,没有存放你改动的软件包。请在你的业务应用里导入时保存。', configureView: '配置视图', toolbarEnabledCount: '已启用 {{count}}/{{total}} 项', searchFields: '搜索字段…', diff --git a/ui/packages/i18n/src/locales/zh-Hant.ts b/ui/packages/i18n/src/locales/zh-Hant.ts index 554004f8f59..57ff90edef8 100644 --- a/ui/packages/i18n/src/locales/zh-Hant.ts +++ b/ui/packages/i18n/src/locales/zh-Hant.ts @@ -727,6 +727,19 @@ const zhHant = { savedMapping: '已儲存的對映:', chooseSavedMapping: '選擇已儲存的對映…', manualMapping: '— 手動對映列 —', + manageMappings: '管理', + sharedSave: '儲存為共享對映', + sharedSaveHint: '儲存後,所有匯入{{object}}的人都可以在「已儲存的對映」中選用它。它會儲存列對映、寫入方式和匹配欄位;其他選項只對這一次匯入有效。', + sharedLabel: '對映名稱', + sharedName: 'API 名稱', + sharedNameInvalid: '只能用小寫字母、數字和下劃線,以字母開頭,至少 2 個字元。', + sharedNeedsMapping: '請至少對映一列,才能儲存為共享對映。', + sharedNeedsMatchFields: '請先選擇匹配欄位,才能儲存為共享對映。', + sharedAmbiguousHeaders: '共享對映按列標題查詢每一列,所以每個已對映的列都需要一個獨有的標題。請先在檔案中改掉這些標題:{{headers}}', + sharedBlankHeader: '(無標題)', + sharedSaving: '正在儲存…', + sharedSaved: '已儲存「{{name}}」,現在可以在「已儲存的對映」中選用。', + sharedSaveFailed: '對映沒有儲存:{{reason}}', transform: '轉換', savedMappingHint: '對映“{{name}}”將在服務端應用重新命名 + 轉換 + 型別強轉,列對映為只讀。', savedMappingPreviewNote: '預覽顯示的是原始列;匯入時,對映“{{name}}”將在服務端應用重新命名、轉換與型別強轉。', @@ -2987,6 +3000,9 @@ const zhHant = { importedToast_one: '成功匯入 {{count}} 行。', importedToast_other: '成功匯入 {{count}} 行。', importedWithSkipped: '已匯入 {{ok}} 行;跳過 {{skipped}} 行。', + sharedMappingNameTaken: '已有名為「{{name}}」的對映,請換一個 API 名稱。', + sharedMappingDraftPending: '名稱「{{name}}」已被一份未釋出的草稿佔用,所以沒有儲存。請換一個 API 名稱。', + sharedMappingSystemApp: '系統應用裡不能儲存共享對映:系統應用隨平台提供,沒有存放你改動的軟體包。請在你的業務應用裡匯入時儲存。', configureView: '配置檢視', toolbarEnabledCount: '已啟用 {{count}}/{{total}} 項', searchFields: '搜尋欄位…', diff --git a/ui/packages/i18n/src/namespaces/studio/en.ts b/ui/packages/i18n/src/namespaces/studio/en.ts index ed8fa2ef47c..65d128872ee 100644 --- a/ui/packages/i18n/src/namespaces/studio/en.ts +++ b/ui/packages/i18n/src/namespaces/studio/en.ts @@ -4052,6 +4052,8 @@ const STUDIO_EN: Record = { 'engine.directory.customizations.tile': '{customized} customized', 'engine.directory.customizations.tileTitle': 'Customized items of this type: {customized}', 'engine.list.customizations.only': 'Only customizations ({marked})', + 'engine.list.targetObject': 'Object: {object}', + 'engine.list.targetObject.clear': 'Show every object (now {object})', 'engine.home.recent': 'Recently viewed', 'engine.diagnostics.title': 'Metadata Diagnostics', 'engine.diagnostics.description': diff --git a/ui/packages/i18n/src/namespaces/studio/zh.ts b/ui/packages/i18n/src/namespaces/studio/zh.ts index e4376947b11..b3789db1378 100644 --- a/ui/packages/i18n/src/namespaces/studio/zh.ts +++ b/ui/packages/i18n/src/namespaces/studio/zh.ts @@ -3586,6 +3586,8 @@ const STUDIO_ZH: Record = { 'engine.directory.customizations.tile': '已定制 {customized}', 'engine.directory.customizations.tileTitle': '此类型已定制的项:{customized}', 'engine.list.customizations.only': '仅看定制({marked})', + 'engine.list.targetObject': '对象:{object}', + 'engine.list.targetObject.clear': '显示所有对象(当前为 {object})', 'engine.home.recent': '最近访问', 'engine.diagnostics.title': '元数据诊断', 'engine.diagnostics.description': diff --git a/ui/packages/plugin-grid/src/ImportWizard.sharedMappingSave-37359.test.tsx b/ui/packages/plugin-grid/src/ImportWizard.sharedMappingSave-37359.test.tsx new file mode 100644 index 00000000000..d3cc9e19c90 --- /dev/null +++ b/ui/packages/plugin-grid/src/ImportWizard.sharedMappingSave-37359.test.tsx @@ -0,0 +1,222 @@ +/** + * ObjectUI – Copyright (c) 2024-present ObjectStack Inc. + * Licensed under MIT. + */ + +/** + * "Save as shared mapping" and "Manage" in the import wizard (objectstack#37359). + * + * An administrator who has just mapped a real file saves the column mapping, + * the write mode and the match fields as a shared `mapping` item, through the + * host's door, from the preview step where all three are known. These pins + * drive the real wizard: + * - no host door: no save control (a host offers it only to someone its + * metadata door lets write one); + * - the saved draft: header → field, the write mode, the match fields; + * - a mapped column whose header is shared with another column is refused + * before anything is sent; + * - a refused save keeps the form and shows the reason; a host that wrote + * nothing adds nothing; + * - a saved mapping joins the Saved mapping list; while a saved mapping is + * in use there is nothing to save; + * - "Manage" sits beside the Saved mapping list only when the host passes it. + */ +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import { render, screen, fireEvent, waitFor, act, within } from '@testing-library/react'; +import '@testing-library/jest-dom'; +import React from 'react'; + +import { ImportWizard } from './ImportWizard'; +import type { SavedMapping } from './savedMapping'; +import type { SharedMappingDraft } from './sharedMappingDraft'; + +beforeAll(() => { + // Radix Select reads these on open; happy-dom lacks them. + if (!Element.prototype.hasPointerCapture) { + Element.prototype.hasPointerCapture = vi.fn(() => false); + } + if (!Element.prototype.scrollIntoView) { + Element.prototype.scrollIntoView = vi.fn(); + } +}); + +type WizardProps = React.ComponentProps; + +const FIELDS: WizardProps['fields'] = [ + { name: 'company', label: 'Company', type: 'text', required: true }, + { name: 'email', label: 'Email', type: 'email' }, +]; + +const PASTED = 'Company\tEmail\nAcme\ta@acme.test\nGlobex\tg@globex.test'; + +/** Paste TSV into the upload step via the wizard's window-level handler. */ +function pasteRows(text: string) { + const evt = new Event('paste', { bubbles: true, cancelable: true }) as Event & { + clipboardData: { getData: (type: string) => string }; + }; + evt.clipboardData = { getData: (type: string) => (type === 'text/plain' ? text : '') }; + act(() => { window.dispatchEvent(evt); }); +} + +function wizard(props: Partial) { + return ( + {}} + templateStorage={null} + {...props} + /> + ); +} + +/** Paste the rows and move on to the preview step. */ +async function toPreview(text = PASTED) { + pasteRows(text); + const next = await screen.findByTestId('import-next-btn'); + await waitFor(() => expect(next).toBeEnabled()); + fireEvent.click(next); + await screen.findByTestId('import-options'); +} + +async function chooseOption(triggerTestId: string, name: string) { + fireEvent.pointerDown(screen.getByTestId(triggerTestId), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByRole('option', { name })); +} + +/** Open the save form, type a label and press Save. */ +async function saveAs(label: string) { + fireEvent.click(screen.getByTestId('import-shared-mapping-open')); + fireEvent.change(await screen.findByTestId('import-shared-mapping-label'), { target: { value: label } }); + fireEvent.click(screen.getByTestId('import-shared-mapping-confirm')); +} + +/** What a host's door answers: the draft, as the server would serve it back. */ +const echo = (draft: SharedMappingDraft): SavedMapping => ({ ...draft }); + +describe('ImportWizard: save as shared mapping (objectstack#37359)', () => { + it('no host door: the preview step offers no save', async () => { + render(wizard({})); + await toPreview(); + expect(screen.queryByTestId('import-shared-mapping-save')).not.toBeInTheDocument(); + }); + + it('an insert saves header → field for every mapped column, the mode, and no key', async () => { + const onSave = vi.fn(async (d: SharedMappingDraft) => echo(d)); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + await saveAs('Supplier list'); + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0]).toEqual({ + name: 'supplier_list', + label: 'Supplier list', + targetObject: 'crm_lead', + sourceFormat: 'csv', + fieldMapping: [{ source: 'Company', target: 'company' }, { source: 'Email', target: 'email' }], + mode: 'insert', + }); + expect(await screen.findByTestId('import-shared-mapping-saved')).toHaveTextContent('Supplier list'); + }); + + it('an upsert saves its match fields as upsertKey', async () => { + const onSave = vi.fn(async (d: SharedMappingDraft) => echo(d)); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + await chooseOption('import-writemode-select', 'Update if matched, else create'); + // No match field yet: the save says why it is off. + expect(screen.getByTestId('import-shared-mapping-open')).toBeDisabled(); + expect(screen.getByTestId('import-shared-mapping-refusal')).toHaveTextContent('Choose the match fields'); + fireEvent.click(within(screen.getByTestId('import-matchfield-email')).getByRole('checkbox')); + await saveAs('Lead upsert'); + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0]).toMatchObject({ mode: 'upsert', upsertKey: ['email'] }); + }); + + it('a mapped column whose header another column shares is refused before anything is sent', async () => { + const onSave = vi.fn(async (d: SharedMappingDraft) => echo(d)); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview('Company\tEmail\tCompany\nAcme\ta@acme.test\tx\nGlobex\tg@globex.test\ty'); + const open = screen.getByTestId('import-shared-mapping-open'); + expect(open).toBeDisabled(); + expect(screen.getByTestId('import-shared-mapping-refusal')).toHaveTextContent('“Company”'); + fireEvent.click(open); + expect(screen.queryByTestId('import-shared-mapping-label')).not.toBeInTheDocument(); + expect(onSave).not.toHaveBeenCalled(); + }); + + it('a name that breaks the identifier grammar cannot be sent', async () => { + const onSave = vi.fn(async (d: SharedMappingDraft) => echo(d)); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + fireEvent.click(screen.getByTestId('import-shared-mapping-open')); + fireEvent.change(await screen.findByTestId('import-shared-mapping-label'), { target: { value: 'Leads' } }); + fireEvent.change(screen.getByTestId('import-shared-mapping-name'), { target: { value: 'Leads Feed' } }); + expect(screen.getByTestId('import-shared-mapping-confirm')).toBeDisabled(); + expect(onSave).not.toHaveBeenCalled(); + }); + + it('a refused save keeps the form open and shows the reason', async () => { + const onSave = vi.fn(async () => { throw new Error('A mapping named supplier_list already exists.'); }); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + await saveAs('Supplier list'); + expect(await screen.findByTestId('import-shared-mapping-failure')).toHaveTextContent('already exists'); + expect(screen.getByTestId('import-shared-mapping-label')).toHaveValue('Supplier list'); + }); + + it('a saved mapping joins the Saved mapping list; one in use leaves nothing to save', async () => { + const onSave = vi.fn(async (d: SharedMappingDraft) => echo(d)); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + expect(screen.queryByTestId('import-saved-mapping-bar')).not.toBeInTheDocument(); + await saveAs('Supplier list'); + await screen.findByTestId('import-shared-mapping-saved'); + fireEvent.click(screen.getByRole('button', { name: /back/i })); + await screen.findByTestId('import-saved-mapping-bar'); + fireEvent.pointerDown(screen.getByTestId('import-saved-mapping-select'), { button: 0, ctrlKey: false, pointerType: 'mouse' }); + const listbox = await screen.findByRole('listbox'); + fireEvent.click(within(listbox).getByTestId('import-saved-mapping-option-supplier_list')); + await screen.findByTestId('import-saved-mapping-summary'); + fireEvent.click(screen.getByTestId('import-next-btn')); + await screen.findByTestId('import-saved-mapping-preview-note'); + expect(screen.queryByTestId('import-shared-mapping-save')).not.toBeInTheDocument(); + }); + + it('a host that wrote nothing adds nothing to the list', async () => { + const onSave = vi.fn(async () => null); + render(wizard({ onSaveSharedMapping: onSave })); + await toPreview(); + await saveAs('Supplier list'); + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(screen.queryByTestId('import-shared-mapping-saved')).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole('button', { name: /back/i })); + await screen.findByTestId('import-next-btn'); + expect(screen.queryByTestId('import-saved-mapping-bar')).not.toBeInTheDocument(); + }); +}); + +describe('ImportWizard: Manage beside Saved mapping (objectstack#37359)', () => { + const MAPPINGS: SavedMapping[] = [ + { name: 'lead_a', label: 'Lead A', targetObject: 'crm_lead', fieldMapping: [{ source: 'Company', target: 'company' }] }, + { name: 'lead_b', label: 'Lead B', targetObject: 'crm_lead', fieldMapping: [{ source: 'Company', target: 'company' }] }, + ]; + + it('opens the host door when it is passed', async () => { + const onManage = vi.fn(); + render(wizard({ savedMappings: MAPPINGS, onManageMappings: onManage })); + pasteRows(PASTED); + fireEvent.click(await screen.findByTestId('import-saved-mapping-manage')); + expect(onManage).toHaveBeenCalledTimes(1); + }); + + it('is absent without the door', async () => { + render(wizard({ savedMappings: MAPPINGS })); + pasteRows(PASTED); + await screen.findByTestId('import-saved-mapping-bar'); + expect(screen.queryByTestId('import-saved-mapping-manage')).not.toBeInTheDocument(); + }); +}); diff --git a/ui/packages/plugin-grid/src/ImportWizard.tsx b/ui/packages/plugin-grid/src/ImportWizard.tsx index 525be815d5b..7f687b41530 100644 --- a/ui/packages/plugin-grid/src/ImportWizard.tsx +++ b/ui/packages/plugin-grid/src/ImportWizard.tsx @@ -46,6 +46,10 @@ import { asSavedMapping, buildSourceRows, summarizeSavedMapping, savedMappingToDisplayIndexMap, type SavedMapping, } from './savedMapping'; +import { + buildSharedMappingDraft, isSharedMappingName, suggestSharedMappingName, + type SharedMappingDraft, type SharedMappingRefusal, +} from './sharedMappingDraft'; /** Default English fallback strings used when no I18nProvider is mounted * (standalone / unit-test usage). Mirrors the keys under `grid.import.*`. @@ -88,6 +92,19 @@ export const IMPORT_DEFAULT_TRANSLATIONS: Record = { 'grid.import.savedMapping': 'Saved mapping:', 'grid.import.chooseSavedMapping': 'Choose a saved mapping…', 'grid.import.manualMapping': '— Map columns manually —', + 'grid.import.manageMappings': 'Manage', + 'grid.import.sharedSave': 'Save as shared mapping', + 'grid.import.sharedSaveHint': 'Everyone who imports {{object}} can then pick it under Saved mapping. It keeps the column mapping, the write mode and the match fields; the other options apply to this import only.', + 'grid.import.sharedLabel': 'Mapping name', + 'grid.import.sharedName': 'API name', + 'grid.import.sharedNameInvalid': 'Use lowercase letters, digits and underscores, starting with a letter, at least 2 characters.', + 'grid.import.sharedNeedsMapping': 'Map at least one column to save a shared mapping.', + 'grid.import.sharedNeedsMatchFields': 'Choose the match fields to save a shared mapping.', + 'grid.import.sharedAmbiguousHeaders': 'A shared mapping finds each column by its header, so every mapped column needs a header of its own. Rename these in the file first: {{headers}}', + 'grid.import.sharedBlankHeader': '(no header)', + 'grid.import.sharedSaving': 'Saving…', + 'grid.import.sharedSaved': 'Saved “{{name}}”. It is now listed under Saved mapping.', + 'grid.import.sharedSaveFailed': 'The mapping was not saved: {{reason}}', 'grid.import.transform': 'Transform', 'grid.import.savedMappingHint': "Mapping “{{name}}” applies rename + transforms + type coercion on the server. Column mapping is read-only.", 'grid.import.savedMappingPreviewNote': "The preview shows your source columns; on import, mapping “{{name}}” applies rename, transforms and type coercion on the server.", @@ -437,6 +454,16 @@ export interface ImportWizardProps { * whose mode is not offered is listed disabled and cannot be picked. An * empty list is a host error and throws. */ writeModes?: readonly ImportWriteMode[]; + /** The host's door for saving the current column mapping, write mode and + * match fields as a shared `mapping` item (objectstack#37359). Left out, the + * preview step offers no "Save as shared mapping": a host offers it only to + * a person its metadata door lets write one. Resolves the mapping as saved, + * which joins the Saved mapping list, or `null` when the host wrote nothing + * and has told the person why; a rejection's message is shown. */ + onSaveSharedMapping?: (draft: SharedMappingDraft) => Promise; + /** Opens the place where this object's shared mappings are managed. Left + * out, the Saved mapping list offers no "Manage". */ + onManageMappings?: () => void; } /** Every write mode the generic import door accepts — the wizard's offer when @@ -1662,7 +1689,9 @@ const SavedMappingBar: React.FC<{ /** The write modes the target accepts; a mapping writing in any other mode * is listed disabled, its mode named, so it cannot be picked. */ writeModes: readonly ImportWriteMode[]; -}> = ({ mappings, activeName, onSelect, onClear, writeModes }) => { + /** The host's "Manage" door (`ImportWizardProps.onManageMappings`). */ + onManage?: () => void; +}> = ({ mappings, activeName, onSelect, onClear, writeModes, onManage }) => { const { t } = useImportTranslation(); if (mappings.length === 0) return null; return ( @@ -1695,6 +1724,18 @@ const SavedMappingBar: React.FC<{ })} + {onManage && ( + + )} ); }; @@ -1758,6 +1799,7 @@ const StepMapping: React.FC<{ activeMapping: SavedMapping | null; onSelectSavedMapping: (name: string) => void; onClearSavedMapping: () => void; + onManageMappings?: () => void; writeModes: readonly ImportWriteMode[]; /** Required fields with no column mapped — surfaced as an inline hint so the * disabled Next button always explains itself. */ @@ -1766,7 +1808,7 @@ const StepMapping: React.FC<{ * description (objectui#12303), so the reason is the control's, not only * text that happens to sit above it. */ missingRequiredHintId: string; -}> = ({ headers, fields, mapping, onMappingChange, inferredTypes, suggestions, templates, selectedTemplateId, onSelectTemplate, onSaveTemplate, onDeleteTemplate, savedMappings, activeMapping, onSelectSavedMapping, onClearSavedMapping, writeModes, missingRequired, missingRequiredHintId }) => { +}> = ({ headers, fields, mapping, onMappingChange, inferredTypes, suggestions, templates, selectedTemplateId, onSelectTemplate, onSaveTemplate, onDeleteTemplate, savedMappings, activeMapping, onSelectSavedMapping, onClearSavedMapping, onManageMappings, writeModes, missingRequired, missingRequiredHintId }) => { const { t } = useImportTranslation(); const usedFields = useMemo(() => new Set(Object.values(mapping)), [mapping]); const suggestionByCol = useMemo(() => { @@ -1794,6 +1836,7 @@ const StepMapping: React.FC<{ onSelect={onSelectSavedMapping} onClear={onClearSavedMapping} writeModes={writeModes} + onManage={onManageMappings} /> {activeMapping ? ( @@ -2165,6 +2208,166 @@ const ImportOptions: React.FC<{ ); }; +/** The reason a shared-mapping refusal shows, in the person's words. */ +function sharedMappingRefusalText( + t: (key: string, vars?: Record) => string, + refusal: SharedMappingRefusal, +): string { + switch (refusal.kind) { + case 'nothing-mapped': return t('grid.import.sharedNeedsMapping'); + case 'no-match-fields': return t('grid.import.sharedNeedsMatchFields'); + case 'ambiguous-headers': + return t('grid.import.sharedAmbiguousHeaders', { + headers: refusal.headers.map((h) => (h === '' ? t('grid.import.sharedBlankHeader') : `“${h}”`)).join(', '), + }); + } +} + +/** "Save as shared mapping" on the preview step (objectstack#37359): the column + * mapping, write mode and match fields above it, saved through the host's door + * as a `mapping` item everyone importing the object can pick. Shown only when + * the host passes that door and the columns are mapped by hand. */ +const SharedMappingSave: React.FC<{ + objectName: string; + objectLabel: string; + headers: string[]; + mapping: Record; + writeMode: ImportWriteMode; + matchFields: string[]; + onSave: (draft: SharedMappingDraft) => Promise; + onSaved: (mapping: SavedMapping) => void; +}> = ({ objectName, objectLabel, headers, mapping, writeMode, matchFields, onSave, onSaved }) => { + const { t } = useImportTranslation(); + const [open, setOpen] = useState(false); + const [label, setLabel] = useState(''); + const [name, setName] = useState(''); + // The name follows the label until the person edits it. + const [nameEdited, setNameEdited] = useState(false); + const [saving, setSaving] = useState(false); + const [failure, setFailure] = useState(null); + const [savedName, setSavedName] = useState(null); + const reasonId = React.useId(); + + // Judged on the state alone, with a placeholder name, so the button can say + // why it is off before the form opens. + const readiness = useMemo( + () => buildSharedMappingDraft({ objectName, headers, mapping, writeMode, matchFields, name: 'x', label: 'x' }), + [objectName, headers, mapping, writeMode, matchFields], + ); + const refusal = readiness.ok ? null : sharedMappingRefusalText(t, readiness.refusal); + const nameValid = isSharedMappingName(name); + + const changeLabel = (next: string) => { + setLabel(next); + if (!nameEdited) setName(next.trim() ? suggestSharedMappingName(next, objectName) : ''); + }; + const close = () => { + setOpen(false); setLabel(''); setName(''); setNameEdited(false); setFailure(null); + }; + const submit = async () => { + const built = buildSharedMappingDraft({ objectName, headers, mapping, writeMode, matchFields, name, label }); + if (!built.ok || !nameValid || !label.trim()) return; + setSaving(true); + setFailure(null); + try { + const saved = await onSave(built.draft); + if (saved) { + onSaved(saved); + setSavedName(saved.label || saved.name); + close(); + } + } catch (err) { + setFailure(err instanceof Error && err.message ? err.message : String(err)); + } finally { + setSaving(false); + } + }; + + return ( +
+ {!open ? ( +
+ + {refusal !== null && ( + + {refusal} + + )} + {refusal === null && savedName && ( + + {t('grid.import.sharedSaved', { name: savedName })} + + )} +
+ ) : ( +
+

{t('grid.import.sharedSaveHint', { object: objectLabel })}

+
+
+ + changeLabel(e.target.value)} + className="h-8 w-56 text-xs" + disabled={saving} + autoFocus + data-testid="import-shared-mapping-label" + /> +
+
+ + { setName(e.target.value); setNameEdited(true); }} + className="h-8 w-56 font-mono text-xs" + disabled={saving} + aria-invalid={name !== '' && !nameValid} + aria-describedby={name !== '' && !nameValid ? `${reasonId}-name-hint` : undefined} + data-testid="import-shared-mapping-name" + /> +
+ + +
+ {name !== '' && !nameValid && ( +

{t('grid.import.sharedNameInvalid')}

+ )} + {refusal !== null && ( +

{refusal}

+ )} + {failure && ( +

+ {t('grid.import.sharedSaveFailed', { reason: failure })} +

+ )} +
+ )} +
+ ); +}; + /** Colour intent for each import-job status badge. */ const IMPORT_JOB_STATUS_VARIANT: Record = { pending: 'outline', @@ -2351,7 +2554,7 @@ const ImportHistoryPanel: React.FC<{ export const ImportWizard: React.FC = ({ objectName, objectLabel, fields, dataSource, onComplete, onCancel, open, onOpenChange, onErrorMode = 'skip', templateStorageKey, templateStorage, savedMappings, initialFile, extraOptionsContent, renderResultExtra, - writeModes = ALL_WRITE_MODES, + writeModes = ALL_WRITE_MODES, onSaveSharedMapping, onManageMappings, }) => { if (writeModes.length === 0) { throw new Error('ImportWizard: `writeModes` must name at least one write mode the target accepts.'); @@ -2496,6 +2699,14 @@ export const ImportWizard: React.FC = ({ return () => { alive = false; }; }, [dataSource, objectName, savedMappings]); const availableMappings = savedMappings ?? fetchedMappings; + // A mapping just saved from the preview step joins the fetched list at once, + // replacing an entry of the same name. A host that supplies `savedMappings` + // owns that list and passes it again. + const handleSharedMappingSaved = useCallback((saved: SavedMapping) => { + const m = asSavedMapping(saved); + if (!m || m.targetObject !== objectName) return; + setFetchedMappings((prev) => [...prev.filter((p) => p.name !== m.name), m]); + }, [objectName]); const activeMapping = useMemo( () => availableMappings.find((m) => m.name === mappingName) ?? null, [availableMappings, mappingName], @@ -3235,6 +3446,7 @@ export const ImportWizard: React.FC = ({ activeMapping={activeMapping} onSelectSavedMapping={handleSelectSavedMapping} onClearSavedMapping={handleClearSavedMapping} + onManageMappings={onManageMappings} writeModes={writeModes} missingRequired={missingRequired} missingRequiredHintId={missingRequiredHintId} @@ -3265,6 +3477,18 @@ export const ImportWizard: React.FC = ({ onBackgroundImport={setBackgroundImport} /> )} + {!activeMapping && onSaveSharedMapping && ( + + )} {activeMapping && (
{ + it('an insert: one header → field rename per mapped column, in column order, no upsertKey', () => { + const r = buildSharedMappingDraft({ ...BASE, mapping: { 1: 'email', 0: 'company' }, writeMode: 'insert', matchFields: ['email'] }); + expect(r).toEqual({ + ok: true, + draft: { + name: 'lead_feed', + label: 'Lead feed', + targetObject: 'crm_lead', + sourceFormat: 'csv', + fieldMapping: [{ source: 'Company', target: 'company' }, { source: 'Email', target: 'email' }], + mode: 'insert', + }, + }); + }); + + it('an upsert carries its match fields as upsertKey, and the draft is a valid mapping item', () => { + const r = buildSharedMappingDraft({ ...BASE, mapping: { 0: 'company', 1: 'email' }, writeMode: 'upsert', matchFields: ['email'] }); + expect(r.ok).toBe(true); + if (!r.ok) return; + expect(r.draft.mode).toBe('upsert'); + expect(r.draft.upsertKey).toEqual(['email']); + expect(MappingSchema.safeParse(r.draft).success).toBe(true); + }); + + it('saves each header trimmed, as the import door trims it before the lookup', () => { + const r = buildSharedMappingDraft({ ...BASE, headers: [' Company', ' Email ', 'Notes'], mapping: { 0: 'company', 1: 'email' }, writeMode: 'insert', matchFields: [] }); + expect(r.ok && r.draft.fieldMapping).toEqual([ + { source: 'Company', target: 'company' }, + { source: 'Email', target: 'email' }, + ]); + }); + + it('a match field whose column is no longer mapped is not saved as a key', () => { + const r = buildSharedMappingDraft({ ...BASE, mapping: { 0: 'company' }, writeMode: 'update', matchFields: ['email'] }); + expect(r).toEqual({ ok: false, refusal: { kind: 'no-match-fields' } }); + }); + + it('nothing mapped is refused', () => { + expect(buildSharedMappingDraft({ ...BASE, mapping: {}, writeMode: 'insert', matchFields: [] })) + .toEqual({ ok: false, refusal: { kind: 'nothing-mapped' } }); + }); + + it('a mapped column whose header another column shares, or that has none, is refused, each header named once', () => { + const r = buildSharedMappingDraft({ + ...BASE, + headers: ['Company', 'Company ', '', 'Email'], + mapping: { 0: 'company', 2: 'notes', 3: 'email' }, + writeMode: 'insert', + matchFields: [], + }); + expect(r).toEqual({ ok: false, refusal: { kind: 'ambiguous-headers', headers: ['Company', ''] } }); + }); + + it('a duplicated header on an UNMAPPED column refuses nothing', () => { + const r = buildSharedMappingDraft({ ...BASE, headers: ['Company', 'Notes', 'Notes'], mapping: { 0: 'company' }, writeMode: 'insert', matchFields: [] }); + expect(r.ok).toBe(true); + }); +}); + +describe('the shared mapping name (objectstack#37359)', () => { + it('follows the spec identifier grammar', () => { + expect(isSharedMappingName('lead_feed')).toBe(true); + expect(isSharedMappingName('Lead feed')).toBe(false); + expect(isSharedMappingName('1_feed')).toBe(false); + expect(isSharedMappingName('a')).toBe(false); + }); + + it('is suggested from the label, or from the object when the label has no Latin letters', () => { + expect(suggestSharedMappingName('Supplier price list (2026)', 'crm_lead')).toBe('supplier_price_list_2026'); + expect(suggestSharedMappingName('Café réservations', 'crm_lead')).toBe('cafe_reservations'); + expect(suggestSharedMappingName('供应商价格表', 'crm_lead')).toBe('crm_lead_import'); + expect(suggestSharedMappingName('2026 list', 'crm_lead')).toBe('list'); + }); +}); diff --git a/ui/packages/plugin-grid/src/sharedMappingDraft.ts b/ui/packages/plugin-grid/src/sharedMappingDraft.ts new file mode 100644 index 00000000000..c7814b70d24 --- /dev/null +++ b/ui/packages/plugin-grid/src/sharedMappingDraft.ts @@ -0,0 +1,122 @@ +// A shared import mapping made in the import wizard (objectstack#37359): the +// columns the person mapped on a real file, the write mode and the match fields, +// turned into the `mapping` metadata item (`MappingSchema` in +// `@objectstack/spec/data`) that every later import of the object can pick by +// name. The wizard builds the draft; the host saves it through its own +// metadata door (`ImportWizardProps.onSaveSharedMapping`). + +import { SnakeCaseIdentifierSchema } from '@objectstack/spec/shared'; +import type { ImportWriteMode } from '@object-ui/types'; + +/** The body of a new shared `mapping` item, in the spec's own key names. */ +export interface SharedMappingDraft { + /** The item's name: lowercase snake_case (`SnakeCaseIdentifierSchema`). */ + name: string; + /** The name people pick it by in the wizard's Saved mapping list. */ + label: string; + targetObject: string; + /** Always `csv`: the import door applies a `csv` mapping to a CSV file, an + * Excel sheet and a paste alike, and the wizard sends such a mapping's rows + * as CSV text from every source (`assembleImportRequest`). */ + sourceFormat: 'csv'; + /** One rename per mapped column: the column's header text, trimmed as the import door trims it → the field. */ + fieldMapping: Array<{ source: string; target: string }>; + mode: ImportWriteMode; + /** The match fields; present exactly when `mode` consults them. */ + upsertKey?: string[]; +} + +/** Why the current wizard state cannot be saved as a shared mapping. */ +export type SharedMappingRefusal = + /** No column is mapped to a field. */ + | { kind: 'nothing-mapped' } + /** Update or upsert with no match field chosen. */ + | { kind: 'no-match-fields' } + /** A mapped column whose header is blank, or shared with another column: the + * import door finds a column by its header text, so such a mapping could + * not say which column it means. `headers` names each one once. */ + | { kind: 'ambiguous-headers'; headers: string[] }; + +export type SharedMappingDraftResult = + | { ok: true; draft: SharedMappingDraft } + | { ok: false; refusal: SharedMappingRefusal }; + +/** + * Build the shared mapping the wizard's current state describes, or say why it + * cannot be one. `mapping` is the wizard's own column index → field map. The + * draft carries only what a `mapping` item can hold: the per-import toggles + * (create missing options, skip blank match keys, background job) stay with + * the import that set them. + */ +export function buildSharedMappingDraft(input: { + objectName: string; + headers: readonly string[]; + mapping: Readonly>; + writeMode: ImportWriteMode; + matchFields: readonly string[]; + name: string; + label: string; +}): SharedMappingDraftResult { + const mapped = Object.entries(input.mapping) + .filter(([, field]) => typeof field === 'string' && field.length > 0) + .map(([idx, field]) => ({ idx: Number(idx), field })) + .sort((a, b) => a.idx - b.idx); + if (mapped.length === 0) return { ok: false, refusal: { kind: 'nothing-mapped' } }; + + const headerCount = new Map(); + for (const h of input.headers) { + const key = (h ?? '').trim(); + headerCount.set(key, (headerCount.get(key) ?? 0) + 1); + } + const ambiguous: string[] = []; + for (const { idx } of mapped) { + const header = (input.headers[idx] ?? '').trim(); + if ((header === '' || (headerCount.get(header) ?? 0) > 1) && !ambiguous.includes(header)) { + ambiguous.push(header); + } + } + if (ambiguous.length > 0) return { ok: false, refusal: { kind: 'ambiguous-headers', headers: ambiguous } }; + + const needsMatch = input.writeMode !== 'insert'; + const mappedFields = new Set(mapped.map((m) => m.field)); + const upsertKey = input.matchFields.filter((f) => mappedFields.has(f)); + if (needsMatch && upsertKey.length === 0) return { ok: false, refusal: { kind: 'no-match-fields' } }; + + return { + ok: true, + draft: { + name: input.name, + label: input.label.trim(), + targetObject: input.objectName, + sourceFormat: 'csv', + // The import door trims each header before it looks one up + // (`import-prepare.ts`), so the saved header is trimmed too. + fieldMapping: mapped.map(({ idx, field }) => ({ source: (input.headers[idx] ?? '').trim(), target: field })), + mode: input.writeMode, + ...(needsMatch ? { upsertKey } : {}), + }, + }; +} + +/** Is `name` a name a `mapping` item may carry (`SnakeCaseIdentifierSchema`)? */ +export function isSharedMappingName(name: string): boolean { + return SnakeCaseIdentifierSchema.safeParse(name).success; +} + +/** + * The name the save offers for a label: its Latin letters and digits in + * lowercase snake_case, or `_import` when the label has none (a label + * in Chinese, say). The person can change it before saving. + */ +export function suggestSharedMappingName(label: string, objectName: string): string { + const slug = label + .normalize('NFKD') + .replace(/[̀-ͯ]/g, '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '_') + .replace(/^_+|_+$/g, '') + .replace(/^[0-9_]+/, ''); + if (isSharedMappingName(slug)) return slug; + const fallback = `${objectName}_import`.toLowerCase().replace(/[^a-z0-9_]+/g, '_').replace(/^[0-9_]+/, ''); + return isSharedMappingName(fallback) ? fallback : 'import_mapping'; +}