@open-mercato/core 0.11.1-develop.8557.1.e615240a3e → 0.11.1-develop.8567.1.a167594505
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +1 -1
- package/dist/modules/api_keys/di.js +6 -2
- package/dist/modules/api_keys/di.js.map +2 -2
- package/dist/modules/api_keys/services/oneTimeIssuerService.js +47 -0
- package/dist/modules/api_keys/services/oneTimeIssuerService.js.map +7 -0
- package/dist/modules/audit_logs/di.js +2 -1
- package/dist/modules/audit_logs/di.js.map +2 -2
- package/dist/modules/audit_logs/services/actionLogService.js +65 -1
- package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
- package/dist/modules/auth/cli.js +1 -0
- package/dist/modules/auth/cli.js.map +2 -2
- package/dist/modules/auth/commands/users.js +10 -2
- package/dist/modules/auth/commands/users.js.map +2 -2
- package/dist/modules/auth/lib/setup-app.js +19 -5
- package/dist/modules/auth/lib/setup-app.js.map +2 -2
- package/dist/modules/configs/cli.js +26 -29
- package/dist/modules/configs/cli.js.map +2 -2
- package/dist/modules/configs/di.js +3 -1
- package/dist/modules/configs/di.js.map +2 -2
- package/dist/modules/configs/lib/instance-config-initializer.js +44 -0
- package/dist/modules/configs/lib/instance-config-initializer.js.map +7 -0
- package/dist/modules/configs/lib/instance-defaults.js +204 -0
- package/dist/modules/configs/lib/instance-defaults.js.map +7 -0
- package/dist/modules/configs/lib/module-config-service.js +115 -1
- package/dist/modules/configs/lib/module-config-service.js.map +2 -2
- package/dist/modules/entities/api/definitions.batch.js +55 -25
- package/dist/modules/entities/api/definitions.batch.js.map +2 -2
- package/dist/modules/entities/api/definitions.js +35 -8
- package/dist/modules/entities/api/definitions.js.map +2 -2
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js +14 -8
- package/dist/modules/entities/backend/entities/user/[entityId]/page.js.map +2 -2
- package/dist/modules/notifications/lib/deliveryConfig.js +19 -12
- package/dist/modules/notifications/lib/deliveryConfig.js.map +2 -2
- package/dist/modules/notifications/setup.js +10 -0
- package/dist/modules/notifications/setup.js.map +2 -2
- package/dist/modules/translations/components/TranslationManager.js +47 -10
- package/dist/modules/translations/components/TranslationManager.js.map +2 -2
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js +8 -1
- package/dist/modules/wms/components/backend/CompletePutawayTaskDialog.js.map +2 -2
- package/dist/modules/workflows/ai-tools/authoring-pack.js +1 -1
- package/dist/modules/workflows/ai-tools/authoring-pack.js.map +2 -2
- package/dist/modules/workflows/api/instances/[id]/advance/route.js +1 -0
- package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/route.js +1 -1
- package/dist/modules/workflows/api/instances/route.js.map +2 -2
- package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
- package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
- package/dist/modules/workflows/di.js +3 -1
- package/dist/modules/workflows/di.js.map +2 -2
- package/dist/modules/workflows/lib/activity-executor.js +35 -7
- package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
- package/dist/modules/workflows/lib/condition-handler.js +1 -1
- package/dist/modules/workflows/lib/condition-handler.js.map +2 -2
- package/dist/modules/workflows/lib/error-handler.js +1 -1
- package/dist/modules/workflows/lib/error-handler.js.map +2 -2
- package/dist/modules/workflows/lib/event-trigger-service.js +1 -1
- package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
- package/dist/modules/workflows/lib/example-definition-authoring.js +90 -0
- package/dist/modules/workflows/lib/example-definition-authoring.js.map +7 -0
- package/dist/modules/workflows/lib/named-rules.js +42 -0
- package/dist/modules/workflows/lib/named-rules.js.map +7 -0
- package/dist/modules/workflows/lib/owned-definition.js +2 -0
- package/dist/modules/workflows/lib/owned-definition.js.map +2 -2
- package/dist/modules/workflows/lib/parallel-handler.js +1 -1
- package/dist/modules/workflows/lib/parallel-handler.js.map +2 -2
- package/dist/modules/workflows/lib/signal-handler.js +1 -0
- package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
- package/dist/modules/workflows/lib/start-validator.js +87 -85
- package/dist/modules/workflows/lib/start-validator.js.map +2 -2
- package/dist/modules/workflows/lib/step-handler.js +1 -1
- package/dist/modules/workflows/lib/step-handler.js.map +2 -2
- package/dist/modules/workflows/lib/task-handler.js +1 -0
- package/dist/modules/workflows/lib/task-handler.js.map +2 -2
- package/dist/modules/workflows/lib/timer-handler.js +1 -0
- package/dist/modules/workflows/lib/timer-handler.js.map +2 -2
- package/dist/modules/workflows/lib/transition-handler.js +48 -166
- package/dist/modules/workflows/lib/transition-handler.js.map +3 -3
- package/dist/modules/workflows/lib/workflow-executor.js +3 -2
- package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
- package/package.json +8 -8
- package/src/modules/api_keys/di.ts +7 -2
- package/src/modules/api_keys/services/oneTimeIssuerService.ts +61 -0
- package/src/modules/audit_logs/di.ts +1 -0
- package/src/modules/audit_logs/services/actionLogService.ts +132 -1
- package/src/modules/auth/cli.ts +1 -0
- package/src/modules/auth/commands/users.ts +10 -2
- package/src/modules/auth/i18n/de.json +2 -0
- package/src/modules/auth/i18n/en.json +2 -0
- package/src/modules/auth/i18n/es.json +2 -0
- package/src/modules/auth/i18n/ko.json +2 -0
- package/src/modules/auth/i18n/pl.json +2 -0
- package/src/modules/auth/lib/setup-app.ts +30 -7
- package/src/modules/configs/cli.ts +39 -37
- package/src/modules/configs/di.ts +2 -0
- package/src/modules/configs/lib/instance-config-initializer.ts +56 -0
- package/src/modules/configs/lib/instance-defaults.ts +262 -0
- package/src/modules/configs/lib/module-config-service.ts +156 -0
- package/src/modules/entities/api/definitions.batch.ts +65 -27
- package/src/modules/entities/api/definitions.ts +40 -11
- package/src/modules/entities/backend/entities/user/[entityId]/page.tsx +14 -7
- package/src/modules/notifications/lib/deliveryConfig.ts +20 -11
- package/src/modules/notifications/setup.ts +11 -0
- package/src/modules/translations/components/TranslationManager.tsx +49 -10
- package/src/modules/translations/i18n/de.json +1 -0
- package/src/modules/translations/i18n/en.json +1 -0
- package/src/modules/translations/i18n/es.json +1 -0
- package/src/modules/translations/i18n/ko.json +1 -0
- package/src/modules/translations/i18n/pl.json +1 -0
- package/src/modules/wms/components/backend/CompletePutawayTaskDialog.tsx +8 -1
- package/src/modules/wms/i18n/de.json +1 -0
- package/src/modules/wms/i18n/en.json +1 -0
- package/src/modules/wms/i18n/es.json +1 -0
- package/src/modules/wms/i18n/ko.json +1 -0
- package/src/modules/wms/i18n/pl.json +1 -0
- package/src/modules/workflows/ai-tools/authoring-pack.ts +3 -1
- package/src/modules/workflows/api/instances/[id]/advance/route.ts +1 -0
- package/src/modules/workflows/api/instances/route.ts +1 -1
- package/src/modules/workflows/api/instances/validate-start/route.ts +3 -1
- package/src/modules/workflows/di.ts +2 -0
- package/src/modules/workflows/lib/activity-executor.ts +48 -30
- package/src/modules/workflows/lib/condition-handler.ts +1 -1
- package/src/modules/workflows/lib/error-handler.ts +1 -1
- package/src/modules/workflows/lib/event-trigger-service.ts +1 -1
- package/src/modules/workflows/lib/example-definition-authoring.ts +114 -0
- package/src/modules/workflows/lib/named-rules.ts +54 -0
- package/src/modules/workflows/lib/owned-definition.ts +4 -1
- package/src/modules/workflows/lib/parallel-handler.ts +1 -1
- package/src/modules/workflows/lib/signal-handler.ts +1 -0
- package/src/modules/workflows/lib/start-validator.ts +96 -94
- package/src/modules/workflows/lib/step-handler.ts +1 -1
- package/src/modules/workflows/lib/task-handler.ts +1 -0
- package/src/modules/workflows/lib/timer-handler.ts +1 -0
- package/src/modules/workflows/lib/transition-handler.ts +74 -238
- package/src/modules/workflows/lib/workflow-executor.ts +7 -4
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../../../src/modules/entities/backend/entities/user/%5BentityId%5D/page.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\nimport React, { useEffect, useMemo, useState } from 'react'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { invalidateCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { upsertCustomEntitySchema, upsertCustomFieldDefSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { z } from 'zod'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport Link from 'next/link'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { loadGeneratedFieldRegistrations } from '@open-mercato/ui/backend/fields/registry'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { createCrudFormError, raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { FieldDefinitionsEditor, type FieldDefinition, type FieldDefinitionError } from '@open-mercato/ui/backend/custom-fields/FieldDefinitionsEditor'\nimport { useT, type TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'\nimport { extensionPoints } from '@open-mercato/core/modules/entities/extension-points'\n\ntype Def = FieldDefinition\nexport type EntitySource = 'code' | 'custom'\ntype EntitiesListResponse = { items?: Array<Record<string, unknown>> }\ntype FieldsetGroup = { code: string; title?: string; hint?: string }\ntype FieldsetDefinition = { code: string; label: string; icon?: string; description?: string; groups?: FieldsetGroup[] }\ntype DefinitionsManageResponse = { items?: any[]; deletedKeys?: string[]; fieldsets?: FieldsetDefinition[]; settings?: { singleFieldsetPerRecord?: boolean }; version?: string | null }\ntype DefinitionsBatchResponse = { ok?: boolean; version?: string | null }\n\nfunction readVersionToken(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\ntype DefErrors = FieldDefinitionError\n\n\nexport default function EditDefinitionsPage({ params }: { params?: { entityId?: string } }) {\n React.useEffect(() => { loadGeneratedFieldRegistrations().catch(() => {}) }, [])\n const router = useRouter()\n const searchParams = useSearchParams()\n const t = useT()\n const queryClient = useQueryClient()\n const entityId = useMemo(() => decodeURIComponent((params?.entityId as any) || ''), [params])\n const [label, setLabel] = useState('')\n const [entitySource, setEntitySource] = useState<EntitySource>('custom')\n const [entityFormLoading, setEntityFormLoading] = useState(true)\n const [entityInitial, setEntityInitial] = useState<{ label?: string; description?: string; labelField?: string; defaultEditor?: string; showInSidebar?: boolean; accessRestricted?: boolean; updatedAt?: string }>({})\n const [defs, setDefs] = useState<Def[]>([])\n const [defsVersion, setDefsVersion] = useState<string | null>(null)\n const [orderDirty, setOrderDirty] = useState(false)\n const [orderSaving, setOrderSaving] = useState(false)\n const listRef = React.useRef<HTMLDivElement | null>(null)\n const [loading, setLoading] = useState(true)\n const [saving, setSaving] = useState(false)\n const [error, setError] = useState<string | null>(null)\n const [deletedKeys, setDeletedKeys] = useState<string[]>([])\n const [defErrors, setDefErrors] = useState<Record<number, DefErrors>>({})\n const [fieldsets, setFieldsets] = useState<FieldsetDefinition[]>([])\n const [activeFieldset, setActiveFieldset] = useState<string | null>(null)\n const [singleFieldsetPerRecord, setSingleFieldsetPerRecord] = useState(true)\n const requestedFieldset = React.useMemo(() => {\n const raw = searchParams?.get('fieldset')\n return raw && raw.trim().length ? raw.trim() : null\n }, [searchParams])\n const embedFieldsetView = React.useMemo(() => searchParams?.get('view') === 'fieldset', [searchParams])\n const normalizeGroupPayload = React.useCallback((value: unknown) => {\n if (!value) return null\n if (typeof value === 'string') {\n const code = value.trim()\n return code ? { code } : null\n }\n if (typeof value !== 'object') return null\n const entry = value as Record<string, unknown>\n const code = typeof entry.code === 'string' ? entry.code.trim() : ''\n if (!code) return null\n const group: FieldsetGroup = { code }\n if (typeof entry.title === 'string' && entry.title.trim()) group.title = entry.title.trim()\n if (typeof entry.hint === 'string' && entry.hint.trim()) group.hint = entry.hint.trim()\n return group\n }, [])\n\n const buildFieldsetPayload = React.useCallback(() => {\n const groupMap = new Map<string, FieldsetGroup[]>()\n defs.forEach((definition) => {\n const code = typeof definition.configJson?.fieldset === 'string' ? definition.configJson.fieldset : null\n if (!code) return\n const normalized = normalizeGroupPayload(definition.configJson?.group)\n if (!normalized) return\n const list = groupMap.get(code) ?? []\n if (!list.some((entry) => entry.code === normalized.code)) {\n list.push(normalized)\n groupMap.set(code, list)\n }\n })\n return fieldsets.map((fs) => ({\n ...fs,\n groups: groupMap.get(fs.code) ?? [],\n }))\n }, [defs, fieldsets, normalizeGroupPayload])\n\n const validateDef = React.useCallback((d: Def): DefErrors => {\n const parsed = upsertCustomFieldDefSchema.safeParse({ entityId, key: d.key, kind: d.kind, configJson: d.configJson, isActive: d.isActive })\n if (parsed.success) return {}\n const errs: DefErrors = {}\n for (const issue of parsed.error.issues) {\n if ((issue.path || []).includes('key')) errs.key = issue.message\n if ((issue.path || []).includes('kind')) errs.kind = issue.message\n }\n return errs\n }, [entityId, requestedFieldset])\n\n const validateAndSetErrorAt = (index: number, d: Def) => {\n const errs = validateDef(d)\n setDefErrors((prev) => ({ ...prev, [index]: errs }))\n return !errs.key && !errs.kind\n }\n\n const validateAll = () => {\n const nextErrors: Record<number, DefErrors> = {}\n defs.forEach((d, i) => {\n nextErrors[i] = validateDef(d)\n })\n setDefErrors(nextErrors)\n return Object.values(nextErrors).every(e => !e.key && !e.kind)\n }\n\n useEffect(() => {\n let mounted = true\n async function load() {\n setLoading(true)\n try {\n const entJson = await readApiResultOrThrow<EntitiesListResponse>(\n '/api/entities/entities',\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.loadMetadataFailed', 'Failed to load entity metadata'), fallback: { items: [] } },\n )\n const ent = (entJson.items || []).find((x: any) => x.entityId === entityId)\n if (mounted) {\n const record = ent as Record<string, unknown> | undefined\n const labelValue =\n typeof record?.label === 'string' && record.label.trim().length > 0 ? record.label : entityId\n const descriptionValue = typeof record?.description === 'string' ? record.description : ''\n const labelFieldValue =\n typeof record?.labelField === 'string' && record.labelField.length > 0 ? record.labelField : 'name'\n const defaultEditorValue =\n typeof record?.defaultEditor === 'string' ? record.defaultEditor : ''\n const showInSidebarValue = record?.showInSidebar === true\n const accessRestrictedValue = record?.accessRestricted === true\n const updatedAtValue =\n typeof record?.updatedAt === 'string' && record.updatedAt.length > 0 ? record.updatedAt : undefined\n setLabel(labelValue)\n if (record?.source === 'code' || record?.source === 'custom') setEntitySource(record.source)\n setEntityInitial({\n label: labelValue,\n description: descriptionValue,\n labelField: labelFieldValue,\n defaultEditor: defaultEditorValue,\n showInSidebar: showInSidebarValue,\n accessRestricted: accessRestrictedValue,\n updatedAt: updatedAtValue,\n })\n setEntityFormLoading(false)\n }\n const json = await readApiResultOrThrow<DefinitionsManageResponse>(\n `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.loadDefinitionsFailed', 'Failed to load entity definitions'), fallback: { items: [], deletedKeys: [] } },\n )\n if (mounted) {\n const loaded: Def[] = (json.items || []).map((d: any) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }))\n loaded.sort(\n (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)\n )\n setDefs(loaded)\n setDefsVersion(readVersionToken(json.version))\n setDefErrors({})\n setDeletedKeys(Array.isArray(json.deletedKeys) ? json.deletedKeys : [])\n const loadedFieldsets = Array.isArray(json.fieldsets) ? json.fieldsets : []\n setFieldsets(loadedFieldsets)\n setActiveFieldset((prev) => {\n if (requestedFieldset && loadedFieldsets.some((fs) => fs.code === requestedFieldset)) {\n return requestedFieldset\n }\n if (prev && loadedFieldsets.some((fs) => fs.code === prev)) return prev\n return loadedFieldsets[0]?.code ?? null\n })\n setSingleFieldsetPerRecord(json.settings?.singleFieldsetPerRecord !== false)\n }\n } catch (e: any) {\n if (mounted) setError(e.message || t('entities.userEntities.edit.errors.loadFailed', 'Failed to load'))\n } finally {\n if (mounted) setLoading(false)\n }\n }\n if (entityId) load()\n return () => { mounted = false }\n }, [entityId, t])\n\n function addField() {\n setDefs((arr) => [\n ...arr,\n {\n key: '',\n kind: 'text',\n configJson: activeFieldset ? { fieldset: activeFieldset } : {},\n isActive: true,\n },\n ])\n }\n\n async function restoreField(key: string) {\n try {\n const call = await apiCall('/api/entities/definitions.restore', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, key }),\n })\n if (!call.ok) {\n await raiseCrudError(call.response, t('entities.userEntities.edit.errors.restoreFieldFailed', 'Failed to restore field'))\n }\n // Reload definitions & deleted keys\n const j2 = await readApiResultOrThrow<DefinitionsManageResponse>(\n `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.reloadDefinitionsFailed', 'Failed to reload field definitions'), fallback: { items: [], deletedKeys: [] } },\n )\n const loaded: Def[] = (j2.items || []).map((d: any) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }))\n loaded.sort(\n (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)\n )\n setDefs(loaded)\n setDefsVersion(readVersionToken(j2.version))\n setDeletedKeys(Array.isArray(j2.deletedKeys) ? j2.deletedKeys : [])\n flash(t('entities.userEntities.edit.flash.restoredField', 'Restored {{key}}', { key }), 'success')\n await invalidateCustomFieldDefs(queryClient, entityId)\n } catch (e: any) {\n flash(e?.message || t('entities.userEntities.edit.errors.restoreFieldFailed', 'Failed to restore field'), 'error')\n }\n }\n\n async function saveAll() {\n setSaving(true)\n setError(null)\n try {\n if (!validateAll()) {\n flash(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'), 'error')\n throw new Error(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n }\n const payload = {\n entityId,\n definitions: defs.filter(d => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n }\n const call = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }),\n )\n if (!call.ok) {\n if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return\n await raiseCrudError(call.response, t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n }\n setDefsVersion(readVersionToken(call.result?.version))\n await invalidateCustomFieldDefs(queryClient, entityId)\n router.push(`/backend/entities/user?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`)\n } catch (e: any) {\n setError(e.message || t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n } finally {\n setSaving(false)\n }\n }\n\n async function removeField(idx: number) {\n const def = defs[idx]\n if (!def) return\n if (def.key) {\n try {\n const call = await apiCall<DefinitionsBatchResponse>('/api/entities/definitions', {\n method: 'DELETE',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, key: def.key }),\n })\n if (!call.ok) {\n await raiseCrudError(call.response, t('entities.customFields.errors.deleteFailed', 'Failed to delete field.'))\n }\n // Keep the optimistic-lock token in sync after an out-of-band delete so a\n // later Save does not falsely 409 against our own change (issue #3152).\n setDefsVersion(readVersionToken(call.result?.version))\n } catch (error) {\n const message = error instanceof Error ? error.message : t('entities.customFields.errors.deleteFailed', 'Failed to delete field.')\n flash(message, 'error')\n return\n }\n }\n setDefs((arr) => arr.filter((_, i) => i !== idx))\n setOrderDirty(true)\n if (def.key) {\n await invalidateCustomFieldDefs(queryClient, entityId)\n }\n }\n\n const handleFieldsetCodeChange = React.useCallback((previousCode: string, nextCode: string) => {\n if (!previousCode || !nextCode || previousCode === nextCode) return\n setDefs((arr) =>\n arr.map((entry) => {\n const current = typeof entry.configJson?.fieldset === 'string' ? entry.configJson.fieldset : undefined\n if (current !== previousCode) return entry\n const nextConfig = { ...(entry.configJson || {}) }\n nextConfig.fieldset = nextCode\n return { ...entry, configJson: nextConfig }\n })\n )\n setActiveFieldset((current) => (current === previousCode ? nextCode : current))\n }, [])\n\n const handleFieldsetRemoved = React.useCallback((code: string) => {\n if (!code) return\n setDefs((arr) =>\n arr.map((entry) => {\n const current = typeof entry.configJson?.fieldset === 'string' ? entry.configJson.fieldset : undefined\n if (current !== code) return entry\n const nextConfig = { ...(entry.configJson || {}) }\n delete nextConfig.fieldset\n delete nextConfig.group\n return { ...entry, configJson: nextConfig }\n })\n )\n }, [])\n\n async function saveOrderIfDirty() {\n if (!orderDirty) return\n setOrderSaving(true)\n try {\n // Do not save order when there are invalid keys/kinds\n if (!validateAll()) throw new Error(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n const payload = {\n entityId,\n definitions: defs.filter(d => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n }\n const call = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),\n }),\n )\n if (!call.ok) {\n // A stale reorder auto-save (another tab changed the schema first) returns a\n // 409; surface the shared conflict bar and stop the retry loop instead of a\n // generic flash (issue #3152).\n if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) {\n setOrderDirty(false)\n return\n }\n await raiseCrudError(call.response, t('entities.userEntities.edit.errors.saveOrderFailed', 'Failed to save order'))\n }\n setDefsVersion(readVersionToken(call.result?.version))\n setOrderDirty(false)\n flash(t('entities.userEntities.edit.flash.orderSaved', 'Order saved'), 'success')\n await invalidateCustomFieldDefs(queryClient, entityId)\n } catch (e: any) {\n flash(e?.message || t('entities.userEntities.edit.errors.saveOrderFailed', 'Failed to save order'), 'error')\n } finally {\n setOrderSaving(false)\n }\n }\n\n // Unify loader via CrudForm isLoading; do not return early here\n\n // Schema for inline field-level validation in CrudForm\n const entityFormSchema = upsertCustomEntitySchema\n .pick({ label: true, description: true, defaultEditor: true as any })\n .extend({\n // Allow empty string in the UI select, treat as undefined later\n defaultEditor: z.union([z.enum(['markdown','simpleMarkdown','htmlRichText','plain']).optional(), z.literal('')]).optional(),\n // Include showInSidebar so CrudForm doesn't strip it on submit\n showInSidebar: z.boolean().optional(),\n accessRestricted: z.boolean().optional(),\n }) as z.ZodType<Record<string, unknown>>\n\n const metadataFieldsReadOnly = entitySource === 'code'\n const fields: CrudField[] = [\n { id: 'label', label: t('entities.userEntities.form.label.label', 'Label'), type: 'text', required: true, readOnly: metadataFieldsReadOnly },\n { id: 'description', label: t('entities.userEntities.form.description.label', 'Description'), type: 'textarea', readOnly: metadataFieldsReadOnly },\n {\n id: 'defaultEditor',\n label: t('entities.userEntities.form.defaultEditor.label', 'Default Editor (multiline)'),\n type: 'select',\n readOnly: metadataFieldsReadOnly,\n options: [\n { value: '', label: t('entities.userEntities.form.defaultEditor.options.default', 'Default (Markdown)') },\n { value: 'markdown', label: t('entities.userEntities.form.defaultEditor.options.markdown', 'Markdown (UIW)') },\n { value: 'simpleMarkdown', label: t('entities.userEntities.form.defaultEditor.options.simpleMarkdown', 'Simple Markdown') },\n { value: 'htmlRichText', label: t('entities.userEntities.form.defaultEditor.options.htmlRichText', 'HTML Rich Text') },\n { value: 'plain', label: t('entities.userEntities.form.defaultEditor.options.plain', 'Plain textarea') },\n ],\n } as any,\n ...(entitySource === 'custom' ? [{ id: 'showInSidebar', label: t('entities.userEntities.form.showInSidebar.label', 'Show in sidebar'), type: 'checkbox' }] : []),\n ...(entitySource === 'custom' ? [{\n id: 'accessRestricted',\n label: t('entities.userEntities.form.accessRestricted.label', 'Restrict record access'),\n type: 'checkbox',\n description: t('entities.userEntities.form.accessRestricted.help', 'Require an explicit per-entity permission to view or manage this entity\u2019s records. Leave off to allow anyone with the general records permission.'),\n }] : []),\n ]\n const renderFieldDefinitions = React.useCallback(() => (\n <FieldDefinitionsEditor\n definitions={defs}\n errors={defErrors}\n deletedKeys={deletedKeys}\n fieldsets={fieldsets}\n activeFieldset={activeFieldset}\n onActiveFieldsetChange={setActiveFieldset}\n onFieldsetsChange={(next) => {\n setFieldsets(next)\n if (!next.some((fs) => fs.code === activeFieldset)) {\n setActiveFieldset(next[0]?.code ?? null)\n }\n }}\n onFieldsetCodeChange={handleFieldsetCodeChange}\n onFieldsetRemoved={handleFieldsetRemoved}\n singleFieldsetPerRecord={singleFieldsetPerRecord}\n onSingleFieldsetPerRecordChange={setSingleFieldsetPerRecord}\n onAddField={addField}\n onRemoveField={(index) => { void removeField(index) }}\n onDefinitionChange={(index, nextDef) => {\n setDefs((arr) => arr.map((entry, idx) => (idx === index ? nextDef : entry)))\n validateAndSetErrorAt(index, nextDef)\n }}\n renderFieldActions={(definition) => (\n <InjectionSpot\n spotId={extensionPoints.hosts.fieldDefinitionActions.spotId}\n context={{ entityId, definition }}\n />\n )}\n onRestoreField={(key) => { void restoreField(key) }}\n onReorder={(from, to) => {\n setDefs((arr) => {\n const next = [...arr]\n const [moved] = next.splice(from, 1)\n next.splice(to, 0, moved)\n return next\n })\n setOrderDirty(true)\n }}\n orderNotice={orderDirty ? { dirty: true, saving: orderSaving, message: t('entities.userEntities.edit.orderNotice', 'Reordered - will auto-save on blur') } : undefined}\n addButtonLabel={t('entities.customFields.editor.addField', 'Add Field')}\n translate={t}\n listRef={listRef}\n listProps={{\n tabIndex: -1,\n onBlur: (event) => {\n const current = listRef.current\n const next = event.relatedTarget as Node | null\n if (!current) return\n if (!next || !current.contains(next)) {\n void saveOrderIfDirty()\n }\n },\n }}\n />\n ),\n [entityId, defs, defErrors, deletedKeys, fieldsets, activeFieldset, singleFieldsetPerRecord, orderDirty, orderSaving, addField, removeField, restoreField, saveOrderIfDirty, t])\n\n const definitionsGroup: CrudFormGroup = { id: 'definitions', title: t('entities.userEntities.edit.groups.definitions', 'Field Definitions'), column: 1, component: renderFieldDefinitions }\n\n const groups: CrudFormGroup[] = [\n {\n id: 'settings',\n title: t('entities.userEntities.edit.groups.settings', 'Entity Settings'),\n column: 1,\n description: getEntitySettingsNotice(entitySource, t),\n fields: entitySource === 'custom'\n ? ['label', 'description', 'defaultEditor', 'showInSidebar', 'accessRestricted']\n : ['label', 'description', 'defaultEditor'],\n },\n definitionsGroup,\n ]\n\n const handleCrudFormSubmit = React.useCallback(async (vals: Record<string, unknown>) => {\n if (!entityId) {\n throw createCrudFormError(t('entities.userEntities.edit.errors.invalidEntityId', 'Invalid entity ID'))\n }\n if (!validateAll()) {\n flash(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'), 'error')\n throw createCrudFormError(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'))\n }\n // Code-declared system entities are not registered as custom entities \u2014 their\n // metadata is owned by code and `POST /api/entities/entities` is fail-closed for\n // ORM-backed system ids (#3115). Only their field definitions are user-editable, so\n // skip the registration call and persist definitions below.\n if (shouldRegisterEntityMetadata(entitySource)) {\n const entityPayload = buildEntityMetadataPayload(entitySource, vals)\n if (!entityPayload) throw createCrudFormError(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n const callEntity = await apiCall('/api/entities/entities', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, ...entityPayload }),\n })\n if (!callEntity.ok) {\n await raiseCrudError(callEntity.response, t('entities.userEntities.edit.errors.saveEntityFailed', 'Failed to save entity'))\n }\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n }\n const defsPayload = buildDefinitionsBatchPayload({\n entityId,\n defs,\n fieldsets: buildFieldsetPayload(),\n singleFieldsetPerRecord,\n })\n // Send the aggregate schema version so a concurrent edit is rejected with a 409\n // instead of silently overwriting the other tab (issue #3152). CrudForm's submit\n // catch detects the optimistic-lock conflict and shows the shared conflict bar.\n const callDefs = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(defsPayload),\n }),\n )\n if (!callDefs.ok) {\n await raiseCrudError(callDefs.response, t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n }\n setDefsVersion(readVersionToken(callDefs.result?.version))\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n await invalidateCustomFieldDefs(queryClient, entityId)\n flash(t('entities.customFields.flash.saved', 'Definitions saved'), 'success')\n }, [buildFieldsetPayload, defs, defsVersion, entityId, entitySource, queryClient, singleFieldsetPerRecord, t, validateAll])\n\n if (!entityId) {\n return (\n <Page>\n <PageBody>\n <div className=\"p-6\">\n <Alert status=\"error\">\n <AlertTitle>{t('entities.userEntities.edit.errors.invalidEntityTitle', 'Invalid entity')}</AlertTitle>\n <AlertDescription>{t('entities.userEntities.edit.errors.invalidEntityDescription', 'The requested entity ID is missing or invalid.')}</AlertDescription>\n </Alert>\n </div>\n </PageBody>\n </Page>\n )\n }\n\n if (embedFieldsetView) {\n return (\n <div className=\"p-4\">\n <CrudForm\n schema={entityFormSchema}\n title={t('entities.userEntities.edit.fieldsetTitle', 'Edit fieldset: {{name}}', { name: requestedFieldset ?? entityId })}\n fields={[]}\n groups={[definitionsGroup]}\n initialValues={entityInitial as any}\n isLoading={entityFormLoading || loading}\n submitLabel={t('entities.userEntities.records.form.submitSave', 'Save')}\n deleteVisible={false}\n backHref={undefined}\n cancelHref={undefined}\n embedded\n onSubmit={handleCrudFormSubmit}\n />\n </div>\n )\n }\n\n return (\n <Page>\n <PageBody>\n <CrudForm\n schema={entityFormSchema}\n title={t('entities.userEntities.edit.title', 'Edit Entity: {{entityId}}', { entityId })}\n titleHeadingLevel={1}\n backHref={entitySource === 'code' ? \"/backend/entities/system\" : \"/backend/entities/user\"}\n fields={fields}\n groups={groups}\n initialValues={entityInitial as any}\n isLoading={entityFormLoading || loading}\n submitLabel={t('entities.userEntities.records.form.submitSave', 'Save')}\n deleteVisible={entitySource === 'custom'}\n extraActions={entitySource === 'custom' ? (\n <Button variant=\"outline\" asChild>\n <Link href={`/backend/entities/user/${encodeURIComponent(entityId)}/records`}>\n {t('entities.userEntities.edit.showRecords', 'Show Records')}\n </Link>\n </Button>\n ) : null}\n cancelHref={entitySource === 'code' ? \"/backend/entities/system\" : \"/backend/entities/user\"}\n successRedirect={entitySource === 'code'\n ? `/backend/entities/system?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`\n : `/backend/entities/user?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`}\n onSubmit={handleCrudFormSubmit}\n onDelete={entitySource === 'custom' ? async () => {\n const callDelete = await apiCall('/api/entities/entities', { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ entityId }) })\n if (!callDelete.ok) {\n await raiseCrudError(callDelete.response, t('entities.userEntities.edit.errors.deleteEntityFailed', 'Failed to delete entity'))\n }\n flash(t('entities.userEntities.edit.flash.entityDeleted', 'Entity deleted'), 'success')\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n } : undefined}\n />\n </PageBody>\n </Page>\n )\n}\n\nexport function shouldRegisterEntityMetadata(entitySource: EntitySource): boolean {\n return entitySource === 'custom'\n}\n\nconst SYSTEM_ENTITY_SETTINGS_NOTICE_FALLBACK =\n 'This is a system entity defined in code. Its label and description are managed in code and cannot be edited here \u2014 only the field definitions below are editable.'\n\nexport function getEntitySettingsNotice(entitySource: EntitySource, t: TranslateFn): string | undefined {\n return shouldRegisterEntityMetadata(entitySource)\n ? undefined\n : t('entities.userEntities.form.systemEntityNotice', SYSTEM_ENTITY_SETTINGS_NOTICE_FALLBACK)\n}\n\nexport function buildDefinitionsBatchPayload(options: {\n entityId: string\n defs: Array<Pick<Def, 'key' | 'kind' | 'configJson' | 'isActive'>>\n fieldsets: FieldsetDefinition[]\n singleFieldsetPerRecord: boolean\n}) {\n return {\n entityId: options.entityId,\n definitions: options.defs.filter((d) => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n fieldsets: options.fieldsets,\n singleFieldsetPerRecord: options.singleFieldsetPerRecord,\n }\n}\n\nexport function buildEntityMetadataPayload(\n entitySource: EntitySource,\n vals: Record<string, unknown>,\n): Record<string, unknown> | null {\n const partial = entitySource === 'custom'\n ? upsertCustomEntitySchema\n .pick({ label: true, description: true, labelField: true as any, defaultEditor: true as any })\n .extend({ showInSidebar: z.boolean().optional(), accessRestricted: z.boolean().optional() }) as unknown as z.ZodTypeAny\n : upsertCustomEntitySchema\n .pick({ label: true, description: true, defaultEditor: true as any }) as unknown as z.ZodTypeAny\n const normalized = {\n ...vals,\n defaultEditor: typeof vals.defaultEditor === 'string' && vals.defaultEditor ? vals.defaultEditor : undefined,\n }\n const parsed = partial.safeParse(normalized)\n return parsed.success ? (parsed.data as Record<string, unknown>) : null\n}\n"],
|
|
5
|
-
"mappings": ";AA4bU,cAyGE,YAzGF;AA3bV,OAAO,SAAS,WAAW,SAAS,gBAAgB;AACpD,SAAS,WAAW,uBAAuB;AAC3C,SAAS,sBAAsB;AAC/B,SAAS,gBAAoD;AAC7D,SAAS,aAAa;AACtB,SAAS,SAAS,sBAAsB,mCAAmC;AAC3E,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,OAAO,UAAU;AACjB,SAAS,cAAc;AACvB,SAAS,uCAAuC;AAEhD,SAAS,qBAAqB,sBAAsB;AACpD,SAAS,8BAA+E;AACxF,SAAS,YAA8B;AACvC,SAAS,qBAAq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AAU,QAAQ;AAAA,IAClB,aAAa,QAAQ,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO;AAAA,MAC3D,KAAK,EAAE;AAAA,MACP,MAAM,EAAE;AAAA,MACR,YAAY,EAAE;AAAA,MACd,UAAU,EAAE,aAAa;AAAA,IAC3B,EAAE;AAAA,IACF,WAAW,QAAQ;AAAA,IACnB,yBAAyB,QAAQ;AAAA,EACnC;AACF;AAEO,SAAS,2BACd,cACA,MACgC;AAChC,QAAM,UAAU,iBAAiB,WAC7B,yBACG,KAAK,EAAE,OAAO,MAAM,aAAa,MAAM,YAAY,MAAa,eAAe,KAAY,CAAC,EAC5F,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,SAAS,GAAG,kBAAkB,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,IAC7F,yBACG,KAAK,EAAE,OAAO,MAAM,aAAa,MAAM,eAAe,KAAY,CAAC;AAC1E,QAAM,aAAa;AAAA,IACjB,GAAG;AAAA,IACH,eAAe,OAAO,KAAK,kBAAkB,YAAY,KAAK,gBAAgB,KAAK,gBAAgB;AAAA,EACrG;AACA,QAAM,SAAS,QAAQ,UAAU,UAAU;AAC3C,SAAO,OAAO,UAAW,OAAO,OAAmC;AACrE;",
|
|
4
|
+
"sourcesContent": ["\"use client\"\nimport React, { useEffect, useMemo, useState } from 'react'\nimport { useRouter, useSearchParams } from 'next/navigation'\nimport { useQueryClient } from '@tanstack/react-query'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { apiCall, readApiResultOrThrow, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { surfaceRecordConflict } from '@open-mercato/ui/backend/conflicts'\nimport { invalidateCustomFieldDefs } from '@open-mercato/ui/backend/utils/customFieldDefs'\nimport { upsertCustomEntitySchema, upsertCustomFieldDefSchema } from '@open-mercato/core/modules/entities/data/validators'\nimport { z } from 'zod'\nimport { Page, PageBody } from '@open-mercato/ui/backend/Page'\nimport { Alert, AlertDescription, AlertTitle } from '@open-mercato/ui/primitives/alert'\nimport Link from 'next/link'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport { loadGeneratedFieldRegistrations } from '@open-mercato/ui/backend/fields/registry'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { createCrudFormError, raiseCrudError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { FieldDefinitionsEditor, type FieldDefinition, type FieldDefinitionError } from '@open-mercato/ui/backend/custom-fields/FieldDefinitionsEditor'\nimport { useT, type TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { InjectionSpot } from '@open-mercato/ui/backend/injection/InjectionSpot'\nimport { extensionPoints } from '@open-mercato/core/modules/entities/extension-points'\n\ntype Def = FieldDefinition\nexport type EntitySource = 'code' | 'custom'\ntype EntitiesListResponse = { items?: Array<Record<string, unknown>> }\ntype FieldsetGroup = { code: string; title?: string; hint?: string }\ntype FieldsetDefinition = { code: string; label: string; icon?: string; description?: string; groups?: FieldsetGroup[] }\ntype DefinitionsManageResponse = { items?: any[]; deletedKeys?: string[]; fieldsets?: FieldsetDefinition[]; settings?: { singleFieldsetPerRecord?: boolean }; version?: string | null }\ntype DefinitionsBatchResponse = { ok?: boolean; version?: string | null }\n\nfunction readVersionToken(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\ntype DefErrors = FieldDefinitionError\n\n\nexport default function EditDefinitionsPage({ params }: { params?: { entityId?: string } }) {\n React.useEffect(() => { loadGeneratedFieldRegistrations().catch(() => {}) }, [])\n const router = useRouter()\n const searchParams = useSearchParams()\n const t = useT()\n const queryClient = useQueryClient()\n const entityId = useMemo(() => decodeURIComponent((params?.entityId as any) || ''), [params])\n const [label, setLabel] = useState('')\n const [entitySource, setEntitySource] = useState<EntitySource>('custom')\n const [entityFormLoading, setEntityFormLoading] = useState(true)\n const [entityInitial, setEntityInitial] = useState<{ label?: string; description?: string; labelField?: string; defaultEditor?: string; showInSidebar?: boolean; accessRestricted?: boolean; updatedAt?: string }>({})\n const [defs, setDefs] = useState<Def[]>([])\n const [defsVersion, setDefsVersion] = useState<string | null>(null)\n const [orderDirty, setOrderDirty] = useState(false)\n const [orderSaving, setOrderSaving] = useState(false)\n const listRef = React.useRef<HTMLDivElement | null>(null)\n const [loading, setLoading] = useState(true)\n const [saving, setSaving] = useState(false)\n const [error, setError] = useState<string | null>(null)\n const [deletedKeys, setDeletedKeys] = useState<string[]>([])\n const [defErrors, setDefErrors] = useState<Record<number, DefErrors>>({})\n const [fieldsets, setFieldsets] = useState<FieldsetDefinition[]>([])\n const [activeFieldset, setActiveFieldset] = useState<string | null>(null)\n const [singleFieldsetPerRecord, setSingleFieldsetPerRecord] = useState(true)\n const requestedFieldset = React.useMemo(() => {\n const raw = searchParams?.get('fieldset')\n return raw && raw.trim().length ? raw.trim() : null\n }, [searchParams])\n const embedFieldsetView = React.useMemo(() => searchParams?.get('view') === 'fieldset', [searchParams])\n const normalizeGroupPayload = React.useCallback((value: unknown) => {\n if (!value) return null\n if (typeof value === 'string') {\n const code = value.trim()\n return code ? { code } : null\n }\n if (typeof value !== 'object') return null\n const entry = value as Record<string, unknown>\n const code = typeof entry.code === 'string' ? entry.code.trim() : ''\n if (!code) return null\n const group: FieldsetGroup = { code }\n if (typeof entry.title === 'string' && entry.title.trim()) group.title = entry.title.trim()\n if (typeof entry.hint === 'string' && entry.hint.trim()) group.hint = entry.hint.trim()\n return group\n }, [])\n\n const buildFieldsetPayload = React.useCallback(() => {\n const groupMap = new Map<string, FieldsetGroup[]>()\n defs.forEach((definition) => {\n const code = typeof definition.configJson?.fieldset === 'string' ? definition.configJson.fieldset : null\n if (!code) return\n const normalized = normalizeGroupPayload(definition.configJson?.group)\n if (!normalized) return\n const list = groupMap.get(code) ?? []\n if (!list.some((entry) => entry.code === normalized.code)) {\n list.push(normalized)\n groupMap.set(code, list)\n }\n })\n return fieldsets.map((fs) => ({\n ...fs,\n groups: groupMap.get(fs.code) ?? [],\n }))\n }, [defs, fieldsets, normalizeGroupPayload])\n\n const validateDef = React.useCallback((d: Def): DefErrors => {\n const parsed = upsertCustomFieldDefSchema.safeParse({ entityId, key: d.key, kind: d.kind, configJson: d.configJson, isActive: d.isActive })\n if (parsed.success) return {}\n const errs: DefErrors = {}\n for (const issue of parsed.error.issues) {\n if ((issue.path || []).includes('key')) errs.key = issue.message\n if ((issue.path || []).includes('kind')) errs.kind = issue.message\n }\n return errs\n }, [entityId, requestedFieldset])\n\n const validateAndSetErrorAt = (index: number, d: Def) => {\n const errs = validateDef(d)\n setDefErrors((prev) => ({ ...prev, [index]: errs }))\n return !errs.key && !errs.kind\n }\n\n const validateAll = () => {\n const nextErrors: Record<number, DefErrors> = {}\n defs.forEach((d, i) => {\n nextErrors[i] = validateDef(d)\n })\n setDefErrors(nextErrors)\n return Object.values(nextErrors).every(e => !e.key && !e.kind)\n }\n\n useEffect(() => {\n let mounted = true\n async function load() {\n setLoading(true)\n try {\n const entJson = await readApiResultOrThrow<EntitiesListResponse>(\n '/api/entities/entities',\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.loadMetadataFailed', 'Failed to load entity metadata'), fallback: { items: [] } },\n )\n const ent = (entJson.items || []).find((x: any) => x.entityId === entityId)\n if (mounted) {\n const record = ent as Record<string, unknown> | undefined\n const labelValue =\n typeof record?.label === 'string' && record.label.trim().length > 0 ? record.label : entityId\n const descriptionValue = typeof record?.description === 'string' ? record.description : ''\n const labelFieldValue =\n typeof record?.labelField === 'string' && record.labelField.length > 0 ? record.labelField : 'name'\n const defaultEditorValue =\n typeof record?.defaultEditor === 'string' ? record.defaultEditor : ''\n const showInSidebarValue = record?.showInSidebar === true\n const accessRestrictedValue = record?.accessRestricted === true\n const updatedAtValue =\n typeof record?.updatedAt === 'string' && record.updatedAt.length > 0 ? record.updatedAt : undefined\n setLabel(labelValue)\n if (record?.source === 'code' || record?.source === 'custom') setEntitySource(record.source)\n setEntityInitial({\n label: labelValue,\n description: descriptionValue,\n labelField: labelFieldValue,\n defaultEditor: defaultEditorValue,\n showInSidebar: showInSidebarValue,\n accessRestricted: accessRestrictedValue,\n updatedAt: updatedAtValue,\n })\n setEntityFormLoading(false)\n }\n const json = await readApiResultOrThrow<DefinitionsManageResponse>(\n `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.loadDefinitionsFailed', 'Failed to load entity definitions'), fallback: { items: [], deletedKeys: [] } },\n )\n if (mounted) {\n const loaded: Def[] = (json.items || []).map((d: any) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }))\n loaded.sort(\n (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)\n )\n setDefs(loaded)\n setDefsVersion(readVersionToken(json.version))\n setDefErrors({})\n setDeletedKeys(Array.isArray(json.deletedKeys) ? json.deletedKeys : [])\n const loadedFieldsets = Array.isArray(json.fieldsets) ? json.fieldsets : []\n setFieldsets(loadedFieldsets)\n setActiveFieldset((prev) => {\n if (requestedFieldset && loadedFieldsets.some((fs) => fs.code === requestedFieldset)) {\n return requestedFieldset\n }\n if (prev && loadedFieldsets.some((fs) => fs.code === prev)) return prev\n return loadedFieldsets[0]?.code ?? null\n })\n setSingleFieldsetPerRecord(json.settings?.singleFieldsetPerRecord !== false)\n }\n } catch (e: any) {\n if (mounted) setError(e.message || t('entities.userEntities.edit.errors.loadFailed', 'Failed to load'))\n } finally {\n if (mounted) setLoading(false)\n }\n }\n if (entityId) load()\n return () => { mounted = false }\n }, [entityId, t])\n\n function addField() {\n setDefs((arr) => [\n ...arr,\n {\n key: '',\n kind: 'text',\n configJson: activeFieldset ? { fieldset: activeFieldset } : {},\n isActive: true,\n },\n ])\n }\n\n async function restoreField(key: string) {\n try {\n const call = await apiCall('/api/entities/definitions.restore', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, key }),\n })\n if (!call.ok) {\n await raiseCrudError(call.response, t('entities.userEntities.edit.errors.restoreFieldFailed', 'Failed to restore field'))\n }\n // Reload definitions & deleted keys\n const j2 = await readApiResultOrThrow<DefinitionsManageResponse>(\n `/api/entities/definitions.manage?entityId=${encodeURIComponent(entityId)}`,\n undefined,\n { errorMessage: t('entities.userEntities.edit.errors.reloadDefinitionsFailed', 'Failed to reload field definitions'), fallback: { items: [], deletedKeys: [] } },\n )\n const loaded: Def[] = (j2.items || []).map((d: any) => ({ key: d.key, kind: d.kind, configJson: d.configJson || {}, isActive: d.isActive !== false }))\n loaded.sort(\n (a, b) => Number(a.configJson?.priority ?? 0) - Number(b.configJson?.priority ?? 0)\n )\n setDefs(loaded)\n setDefsVersion(readVersionToken(j2.version))\n setDeletedKeys(Array.isArray(j2.deletedKeys) ? j2.deletedKeys : [])\n flash(t('entities.userEntities.edit.flash.restoredField', 'Restored {{key}}', { key }), 'success')\n await invalidateCustomFieldDefs(queryClient, entityId)\n } catch (e: any) {\n flash(e?.message || t('entities.userEntities.edit.errors.restoreFieldFailed', 'Failed to restore field'), 'error')\n }\n }\n\n async function saveAll() {\n setSaving(true)\n setError(null)\n try {\n if (!validateAll()) {\n flash(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'), 'error')\n throw new Error(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n }\n const payload = {\n entityId,\n definitions: defs.filter(d => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n }\n const call = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(payload),\n }),\n )\n if (!call.ok) {\n if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return\n await raiseCrudError(call.response, t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n }\n setDefsVersion(readVersionToken(call.result?.version))\n await invalidateCustomFieldDefs(queryClient, entityId)\n router.push(`/backend/entities/user?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`)\n } catch (e: any) {\n setError(e.message || t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n } finally {\n setSaving(false)\n }\n }\n\n async function removeField(idx: number) {\n const def = defs[idx]\n if (!def) return\n if (def.key) {\n try {\n const call = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions', {\n method: 'DELETE',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, key: def.key }),\n }),\n )\n if (!call.ok) {\n if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) return\n await raiseCrudError(call.response, t('entities.customFields.errors.deleteFailed', 'Failed to delete field.'))\n }\n // Keep the optimistic-lock token in sync after an out-of-band delete so a\n // later Save does not falsely 409 against our own change (issue #3152).\n setDefsVersion(readVersionToken(call.result?.version))\n } catch (error) {\n const message = error instanceof Error ? error.message : t('entities.customFields.errors.deleteFailed', 'Failed to delete field.')\n flash(message, 'error')\n return\n }\n }\n setDefs((arr) => arr.filter((_, i) => i !== idx))\n if (def.key) {\n await invalidateCustomFieldDefs(queryClient, entityId)\n }\n }\n\n const handleFieldsetCodeChange = React.useCallback((previousCode: string, nextCode: string) => {\n if (!previousCode || !nextCode || previousCode === nextCode) return\n setDefs((arr) =>\n arr.map((entry) => {\n const current = typeof entry.configJson?.fieldset === 'string' ? entry.configJson.fieldset : undefined\n if (current !== previousCode) return entry\n const nextConfig = { ...(entry.configJson || {}) }\n nextConfig.fieldset = nextCode\n return { ...entry, configJson: nextConfig }\n })\n )\n setActiveFieldset((current) => (current === previousCode ? nextCode : current))\n }, [])\n\n const handleFieldsetRemoved = React.useCallback((code: string) => {\n if (!code) return\n setDefs((arr) =>\n arr.map((entry) => {\n const current = typeof entry.configJson?.fieldset === 'string' ? entry.configJson.fieldset : undefined\n if (current !== code) return entry\n const nextConfig = { ...(entry.configJson || {}) }\n delete nextConfig.fieldset\n delete nextConfig.group\n return { ...entry, configJson: nextConfig }\n })\n )\n }, [])\n\n async function saveOrderIfDirty() {\n if (!orderDirty) return\n setOrderSaving(true)\n try {\n // Do not save order when there are invalid keys/kinds\n if (!validateAll()) throw new Error(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n const payload = {\n entityId,\n definitions: defs.filter(d => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n }\n const call = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(payload),\n }),\n )\n if (!call.ok) {\n // A stale reorder auto-save (another tab changed the schema first) returns a\n // 409; surface the shared conflict bar and stop the retry loop instead of a\n // generic flash (issue #3152).\n if (surfaceRecordConflict({ status: call.status, body: call.result }, t)) {\n setOrderDirty(false)\n return\n }\n await raiseCrudError(call.response, t('entities.userEntities.edit.errors.saveOrderFailed', 'Failed to save order'))\n }\n setDefsVersion(readVersionToken(call.result?.version))\n setOrderDirty(false)\n flash(t('entities.userEntities.edit.flash.orderSaved', 'Order saved'), 'success')\n await invalidateCustomFieldDefs(queryClient, entityId)\n } catch (e: any) {\n flash(e?.message || t('entities.userEntities.edit.errors.saveOrderFailed', 'Failed to save order'), 'error')\n } finally {\n setOrderSaving(false)\n }\n }\n\n // Unify loader via CrudForm isLoading; do not return early here\n\n // Schema for inline field-level validation in CrudForm\n const entityFormSchema = upsertCustomEntitySchema\n .pick({ label: true, description: true, defaultEditor: true as any })\n .extend({\n // Allow empty string in the UI select, treat as undefined later\n defaultEditor: z.union([z.enum(['markdown','simpleMarkdown','htmlRichText','plain']).optional(), z.literal('')]).optional(),\n // Include showInSidebar so CrudForm doesn't strip it on submit\n showInSidebar: z.boolean().optional(),\n accessRestricted: z.boolean().optional(),\n }) as z.ZodType<Record<string, unknown>>\n\n const metadataFieldsReadOnly = entitySource === 'code'\n const fields: CrudField[] = [\n { id: 'label', label: t('entities.userEntities.form.label.label', 'Label'), type: 'text', required: true, readOnly: metadataFieldsReadOnly },\n { id: 'description', label: t('entities.userEntities.form.description.label', 'Description'), type: 'textarea', readOnly: metadataFieldsReadOnly },\n {\n id: 'defaultEditor',\n label: t('entities.userEntities.form.defaultEditor.label', 'Default Editor (multiline)'),\n type: 'select',\n readOnly: metadataFieldsReadOnly,\n options: [\n { value: '', label: t('entities.userEntities.form.defaultEditor.options.default', 'Default (Markdown)') },\n { value: 'markdown', label: t('entities.userEntities.form.defaultEditor.options.markdown', 'Markdown (UIW)') },\n { value: 'simpleMarkdown', label: t('entities.userEntities.form.defaultEditor.options.simpleMarkdown', 'Simple Markdown') },\n { value: 'htmlRichText', label: t('entities.userEntities.form.defaultEditor.options.htmlRichText', 'HTML Rich Text') },\n { value: 'plain', label: t('entities.userEntities.form.defaultEditor.options.plain', 'Plain textarea') },\n ],\n } as any,\n ...(entitySource === 'custom' ? [{ id: 'showInSidebar', label: t('entities.userEntities.form.showInSidebar.label', 'Show in sidebar'), type: 'checkbox' }] : []),\n ...(entitySource === 'custom' ? [{\n id: 'accessRestricted',\n label: t('entities.userEntities.form.accessRestricted.label', 'Restrict record access'),\n type: 'checkbox',\n description: t('entities.userEntities.form.accessRestricted.help', 'Require an explicit per-entity permission to view or manage this entity\u2019s records. Leave off to allow anyone with the general records permission.'),\n }] : []),\n ]\n const renderFieldDefinitions = React.useCallback(() => (\n <FieldDefinitionsEditor\n definitions={defs}\n errors={defErrors}\n deletedKeys={deletedKeys}\n fieldsets={fieldsets}\n activeFieldset={activeFieldset}\n onActiveFieldsetChange={setActiveFieldset}\n onFieldsetsChange={(next) => {\n setFieldsets(next)\n if (!next.some((fs) => fs.code === activeFieldset)) {\n setActiveFieldset(next[0]?.code ?? null)\n }\n }}\n onFieldsetCodeChange={handleFieldsetCodeChange}\n onFieldsetRemoved={handleFieldsetRemoved}\n singleFieldsetPerRecord={singleFieldsetPerRecord}\n onSingleFieldsetPerRecordChange={setSingleFieldsetPerRecord}\n onAddField={addField}\n onRemoveField={(index) => { void removeField(index) }}\n onDefinitionChange={(index, nextDef) => {\n setDefs((arr) => arr.map((entry, idx) => (idx === index ? nextDef : entry)))\n validateAndSetErrorAt(index, nextDef)\n }}\n renderFieldActions={(definition) => (\n <InjectionSpot\n spotId={extensionPoints.hosts.fieldDefinitionActions.spotId}\n context={{ entityId, definition }}\n />\n )}\n onRestoreField={(key) => { void restoreField(key) }}\n onReorder={(from, to) => {\n setDefs((arr) => {\n const next = [...arr]\n const [moved] = next.splice(from, 1)\n next.splice(to, 0, moved)\n return next\n })\n setOrderDirty(true)\n }}\n orderNotice={orderDirty ? { dirty: true, saving: orderSaving, message: t('entities.userEntities.edit.orderNotice', 'Reordered - will auto-save on blur') } : undefined}\n addButtonLabel={t('entities.customFields.editor.addField', 'Add Field')}\n translate={t}\n listRef={listRef}\n listProps={{\n tabIndex: -1,\n onBlur: (event) => {\n const current = listRef.current\n const next = event.relatedTarget as Node | null\n if (!current) return\n if (!next || !current.contains(next)) {\n void saveOrderIfDirty()\n }\n },\n }}\n />\n ),\n [entityId, defs, defErrors, deletedKeys, fieldsets, activeFieldset, singleFieldsetPerRecord, orderDirty, orderSaving, addField, removeField, restoreField, saveOrderIfDirty, t])\n\n const definitionsGroup: CrudFormGroup = { id: 'definitions', title: t('entities.userEntities.edit.groups.definitions', 'Field Definitions'), column: 1, component: renderFieldDefinitions }\n\n const groups: CrudFormGroup[] = [\n {\n id: 'settings',\n title: t('entities.userEntities.edit.groups.settings', 'Entity Settings'),\n column: 1,\n description: getEntitySettingsNotice(entitySource, t),\n fields: entitySource === 'custom'\n ? ['label', 'description', 'defaultEditor', 'showInSidebar', 'accessRestricted']\n : ['label', 'description', 'defaultEditor'],\n },\n definitionsGroup,\n ]\n\n const handleCrudFormSubmit = React.useCallback(async (vals: Record<string, unknown>) => {\n if (!entityId) {\n throw createCrudFormError(t('entities.userEntities.edit.errors.invalidEntityId', 'Invalid entity ID'))\n }\n if (!validateAll()) {\n flash(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'), 'error')\n throw createCrudFormError(t('entities.customFields.errors.validation', 'Please fix validation errors in field definitions.'))\n }\n // Code-declared system entities are not registered as custom entities \u2014 their\n // metadata is owned by code and `POST /api/entities/entities` is fail-closed for\n // ORM-backed system ids (#3115). Only their field definitions are user-editable, so\n // skip the registration call and persist definitions below.\n if (shouldRegisterEntityMetadata(entitySource)) {\n const entityPayload = buildEntityMetadataPayload(entitySource, vals)\n if (!entityPayload) throw createCrudFormError(t('entities.userEntities.edit.errors.validationFailed', 'Validation failed'))\n const callEntity = await apiCall('/api/entities/entities', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ entityId, ...entityPayload }),\n })\n if (!callEntity.ok) {\n await raiseCrudError(callEntity.response, t('entities.userEntities.edit.errors.saveEntityFailed', 'Failed to save entity'))\n }\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n }\n const defsPayload = buildDefinitionsBatchPayload({\n entityId,\n defs,\n fieldsets: buildFieldsetPayload(),\n singleFieldsetPerRecord,\n preserveOrder: !orderDirty,\n })\n // Send the aggregate schema version so a concurrent edit is rejected with a 409\n // instead of silently overwriting the other tab (issue #3152). CrudForm's submit\n // catch detects the optimistic-lock conflict and shows the shared conflict bar.\n const callDefs = await withScopedApiRequestHeaders(\n buildOptimisticLockHeader(defsVersion),\n () => apiCall<DefinitionsBatchResponse>('/api/entities/definitions.batch', {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(defsPayload),\n }),\n )\n if (!callDefs.ok) {\n await raiseCrudError(callDefs.response, t('entities.customFields.errors.saveFailed', 'Failed to save field definitions.'))\n }\n setDefsVersion(readVersionToken(callDefs.result?.version))\n setOrderDirty(false)\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n await invalidateCustomFieldDefs(queryClient, entityId)\n flash(t('entities.customFields.flash.saved', 'Definitions saved'), 'success')\n }, [buildFieldsetPayload, defs, defsVersion, entityId, entitySource, orderDirty, queryClient, singleFieldsetPerRecord, t, validateAll])\n\n if (!entityId) {\n return (\n <Page>\n <PageBody>\n <div className=\"p-6\">\n <Alert status=\"error\">\n <AlertTitle>{t('entities.userEntities.edit.errors.invalidEntityTitle', 'Invalid entity')}</AlertTitle>\n <AlertDescription>{t('entities.userEntities.edit.errors.invalidEntityDescription', 'The requested entity ID is missing or invalid.')}</AlertDescription>\n </Alert>\n </div>\n </PageBody>\n </Page>\n )\n }\n\n if (embedFieldsetView) {\n return (\n <div className=\"p-4\">\n <CrudForm\n schema={entityFormSchema}\n title={t('entities.userEntities.edit.fieldsetTitle', 'Edit fieldset: {{name}}', { name: requestedFieldset ?? entityId })}\n fields={[]}\n groups={[definitionsGroup]}\n initialValues={entityInitial as any}\n isLoading={entityFormLoading || loading}\n submitLabel={t('entities.userEntities.records.form.submitSave', 'Save')}\n deleteVisible={false}\n backHref={undefined}\n cancelHref={undefined}\n embedded\n onSubmit={handleCrudFormSubmit}\n />\n </div>\n )\n }\n\n return (\n <Page>\n <PageBody>\n <CrudForm\n schema={entityFormSchema}\n title={t('entities.userEntities.edit.title', 'Edit Entity: {{entityId}}', { entityId })}\n titleHeadingLevel={1}\n backHref={entitySource === 'code' ? \"/backend/entities/system\" : \"/backend/entities/user\"}\n fields={fields}\n groups={groups}\n initialValues={entityInitial as any}\n isLoading={entityFormLoading || loading}\n submitLabel={t('entities.userEntities.records.form.submitSave', 'Save')}\n deleteVisible={entitySource === 'custom'}\n extraActions={entitySource === 'custom' ? (\n <Button variant=\"outline\" asChild>\n <Link href={`/backend/entities/user/${encodeURIComponent(entityId)}/records`}>\n {t('entities.userEntities.edit.showRecords', 'Show Records')}\n </Link>\n </Button>\n ) : null}\n cancelHref={entitySource === 'code' ? \"/backend/entities/system\" : \"/backend/entities/user\"}\n successRedirect={entitySource === 'code'\n ? `/backend/entities/system?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`\n : `/backend/entities/user?flash=${encodeURIComponent(t('entities.customFields.flash.saved', 'Definitions saved'))}&type=success`}\n onSubmit={handleCrudFormSubmit}\n onDelete={entitySource === 'custom' ? async () => {\n const callDelete = await apiCall('/api/entities/entities', { method: 'DELETE', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ entityId }) })\n if (!callDelete.ok) {\n await raiseCrudError(callDelete.response, t('entities.userEntities.edit.errors.deleteEntityFailed', 'Failed to delete entity'))\n }\n flash(t('entities.userEntities.edit.flash.entityDeleted', 'Entity deleted'), 'success')\n try { window.dispatchEvent(new Event('om:refresh-sidebar')) } catch {}\n } : undefined}\n />\n </PageBody>\n </Page>\n )\n}\n\nexport function shouldRegisterEntityMetadata(entitySource: EntitySource): boolean {\n return entitySource === 'custom'\n}\n\nconst SYSTEM_ENTITY_SETTINGS_NOTICE_FALLBACK =\n 'This is a system entity defined in code. Its label and description are managed in code and cannot be edited here \u2014 only the field definitions below are editable.'\n\nexport function getEntitySettingsNotice(entitySource: EntitySource, t: TranslateFn): string | undefined {\n return shouldRegisterEntityMetadata(entitySource)\n ? undefined\n : t('entities.userEntities.form.systemEntityNotice', SYSTEM_ENTITY_SETTINGS_NOTICE_FALLBACK)\n}\n\nexport function buildDefinitionsBatchPayload(options: {\n entityId: string\n defs: Array<Pick<Def, 'key' | 'kind' | 'configJson' | 'isActive'>>\n fieldsets: FieldsetDefinition[]\n singleFieldsetPerRecord: boolean\n preserveOrder?: boolean\n}) {\n return {\n entityId: options.entityId,\n ...(options.preserveOrder !== undefined && { preserveOrder: options.preserveOrder }),\n definitions: options.defs.filter((d) => !!d.key).map((d) => ({\n key: d.key,\n kind: d.kind,\n configJson: d.configJson,\n isActive: d.isActive !== false,\n })),\n fieldsets: options.fieldsets,\n singleFieldsetPerRecord: options.singleFieldsetPerRecord,\n }\n}\n\nexport function buildEntityMetadataPayload(\n entitySource: EntitySource,\n vals: Record<string, unknown>,\n): Record<string, unknown> | null {\n const partial = entitySource === 'custom'\n ? upsertCustomEntitySchema\n .pick({ label: true, description: true, labelField: true as any, defaultEditor: true as any })\n .extend({ showInSidebar: z.boolean().optional(), accessRestricted: z.boolean().optional() }) as unknown as z.ZodTypeAny\n : upsertCustomEntitySchema\n .pick({ label: true, description: true, defaultEditor: true as any }) as unknown as z.ZodTypeAny\n const normalized = {\n ...vals,\n defaultEditor: typeof vals.defaultEditor === 'string' && vals.defaultEditor ? vals.defaultEditor : undefined,\n }\n const parsed = partial.safeParse(normalized)\n return parsed.success ? (parsed.data as Record<string, unknown>) : null\n}\n"],
|
|
5
|
+
"mappings": ";AA+bU,cA2GE,YA3GF;AA9bV,OAAO,SAAS,WAAW,SAAS,gBAAgB;AACpD,SAAS,WAAW,uBAAuB;AAC3C,SAAS,sBAAsB;AAC/B,SAAS,gBAAoD;AAC7D,SAAS,aAAa;AACtB,SAAS,SAAS,sBAAsB,mCAAmC;AAC3E,SAAS,iCAAiC;AAC1C,SAAS,6BAA6B;AACtC,SAAS,iCAAiC;AAC1C,SAAS,0BAA0B,kCAAkC;AACrE,SAAS,SAAS;AAClB,SAAS,MAAM,gBAAgB;AAC/B,SAAS,OAAO,kBAAkB,kBAAkB;AACpD,OAAO,UAAU;AACjB,SAAS,cAAc;AACvB,SAAS,uCAAuC;AAEhD,SAAS,qBAAqB,sBAAsB;AACpD,SAAS,8BAA+E;AACxF,SAAS,YAA8B;AACvC,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAUhC,SAAS,iBAAiB,OAA+B;AACvD,SAAO,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,QAAQ;AACjE;AAKe,SAAR,oBAAqC,EAAE,OAAO,GAAuC;AAC1F,QAAM,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,UAAU,QAAQ;AAAA,IAClB,GAAI,QAAQ,kBAAkB,UAAa,EAAE,eAAe,QAAQ,cAAc;AAAA,IAClF,aAAa,QAAQ,KAAK,OAAO,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,CAAC,OAAO;AAAA,MAC3D,KAAK,EAAE;AAAA,MACP,MAAM,EAAE;AAAA,MACR,YAAY,EAAE;AAAA,MACd,UAAU,EAAE,aAAa;AAAA,IAC3B,EAAE;AAAA,IACF,WAAW,QAAQ;AAAA,IACnB,yBAAyB,QAAQ;AAAA,EACnC;AACF;AAEO,SAAS,2BACd,cACA,MACgC;AAChC,QAAM,UAAU,iBAAiB,WAC7B,yBACG,KAAK,EAAE,OAAO,MAAM,aAAa,MAAM,YAAY,MAAa,eAAe,KAAY,CAAC,EAC5F,OAAO,EAAE,eAAe,EAAE,QAAQ,EAAE,SAAS,GAAG,kBAAkB,EAAE,QAAQ,EAAE,SAAS,EAAE,CAAC,IAC7F,yBACG,KAAK,EAAE,OAAO,MAAM,aAAa,MAAM,eAAe,KAAY,CAAC;AAC1E,QAAM,aAAa;AAAA,IACjB,GAAG;AAAA,IACH,eAAe,OAAO,KAAK,kBAAkB,YAAY,KAAK,gBAAgB,KAAK,gBAAgB;AAAA,EACrG;AACA,QAAM,SAAS,QAAQ,UAAU,UAAU;AAC3C,SAAO,OAAO,UAAW,OAAO,OAAmC;AACrE;",
|
|
6
6
|
"names": ["code", "error"]
|
|
7
7
|
}
|
|
@@ -38,7 +38,7 @@ const resolveEnvDefaults = () => {
|
|
|
38
38
|
emailSubjectPrefix
|
|
39
39
|
};
|
|
40
40
|
};
|
|
41
|
-
|
|
41
|
+
function resolveDefaultNotificationDeliveryConfig() {
|
|
42
42
|
const env = resolveEnvDefaults();
|
|
43
43
|
return {
|
|
44
44
|
appUrl: env.appUrl,
|
|
@@ -54,18 +54,23 @@ const DEFAULT_NOTIFICATION_DELIVERY_CONFIG = (() => {
|
|
|
54
54
|
custom: {}
|
|
55
55
|
}
|
|
56
56
|
};
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
...
|
|
62
|
-
|
|
63
|
-
...
|
|
64
|
-
|
|
65
|
-
|
|
57
|
+
}
|
|
58
|
+
function resolveStoredDefaultNotificationDeliveryConfig() {
|
|
59
|
+
const defaults = resolveDefaultNotificationDeliveryConfig();
|
|
60
|
+
return {
|
|
61
|
+
...defaults,
|
|
62
|
+
strategies: {
|
|
63
|
+
...defaults.strategies,
|
|
64
|
+
email: {
|
|
65
|
+
...defaults.strategies.email,
|
|
66
|
+
from: void 0,
|
|
67
|
+
replyTo: resolveStoredSenderAddress(defaults.strategies.email.replyTo)
|
|
68
|
+
}
|
|
66
69
|
}
|
|
67
|
-
}
|
|
68
|
-
}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const DEFAULT_NOTIFICATION_DELIVERY_CONFIG = resolveDefaultNotificationDeliveryConfig();
|
|
73
|
+
const STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG = resolveStoredDefaultNotificationDeliveryConfig();
|
|
69
74
|
const parseDeliveryConfig = (input) => {
|
|
70
75
|
const parsed = notificationDeliveryConfigSchema.safeParse(input);
|
|
71
76
|
const onlyPanelPathInvalid = !parsed.success && parsed.error.issues.every((issue) => issue.path[0] === "panelPath");
|
|
@@ -136,8 +141,10 @@ export {
|
|
|
136
141
|
DEFAULT_NOTIFICATION_DELIVERY_CONFIG,
|
|
137
142
|
NOTIFICATIONS_DELIVERY_CONFIG_KEY,
|
|
138
143
|
STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG,
|
|
144
|
+
resolveDefaultNotificationDeliveryConfig,
|
|
139
145
|
resolveNotificationDeliveryConfig,
|
|
140
146
|
resolveNotificationPanelUrl,
|
|
147
|
+
resolveStoredDefaultNotificationDeliveryConfig,
|
|
141
148
|
saveNotificationDeliveryConfig
|
|
142
149
|
};
|
|
143
150
|
//# sourceMappingURL=deliveryConfig.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/notifications/lib/deliveryConfig.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleConfigService } from '@open-mercato/core/modules/configs/lib/module-config-service'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { resolveDefaultEmailFromAddress } from '@open-mercato/shared/lib/email/config'\nimport { notificationDeliveryConfigSchema, type NotificationDeliveryConfigInput } from '../data/validators'\n\nexport const NOTIFICATIONS_DELIVERY_CONFIG_KEY = 'delivery_strategies'\n\nexport type NotificationDeliveryStrategyState = {\n enabled: boolean\n}\n\nexport type NotificationCustomDeliveryConfig = {\n enabled?: boolean\n config?: unknown\n}\n\nexport type NotificationEmailDeliveryConfig = NotificationDeliveryStrategyState & {\n from?: string\n replyTo?: string\n subjectPrefix?: string\n}\n\nexport type NotificationDeliveryConfig = {\n appUrl?: string\n panelPath: string\n strategies: {\n database: NotificationDeliveryStrategyState\n email: NotificationEmailDeliveryConfig\n custom?: Record<string, NotificationCustomDeliveryConfig>\n }\n}\n\nconst envString = (value: string | undefined | null) => {\n if (!value) return undefined\n const trimmed = value.trim()\n return trimmed.length ? trimmed : undefined\n}\n\nconst PLACEHOLDER_EMAIL_DOMAINS = new Set(['your-domain.com'])\n\nconst EMAIL_DOMAIN_PATTERN = /@([^@\\s<>]+)>?\\s*$/\n\nfunction isPlaceholderEmailAddress(value: string | undefined | null): boolean {\n const address = envString(value)\n if (!address) return false\n const domain = EMAIL_DOMAIN_PATTERN.exec(address)?.[1]?.toLowerCase()\n return domain ? PLACEHOLDER_EMAIL_DOMAINS.has(domain) : false\n}\n\nconst resolveStoredSenderAddress = (value: string | undefined): string | undefined => {\n const address = envString(value)\n if (!address || isPlaceholderEmailAddress(address)) return undefined\n return address\n}\n\nconst resolveEnvDefaults = () => {\n const appUrl = envString(\n process.env.NOTIFICATIONS_APP_URL ||\n process.env.APPLICATION_URL ||\n process.env.NEXT_PUBLIC_APP_URL ||\n process.env.APP_URL\n )\n const panelPath = envString(process.env.NOTIFICATIONS_PANEL_PATH)\n const emailEnabled = parseBooleanWithDefault(process.env.NOTIFICATIONS_EMAIL_ENABLED, true)\n const emailFrom = resolveDefaultEmailFromAddress()\n const emailReplyTo = envString(process.env.NOTIFICATIONS_EMAIL_REPLY_TO || process.env.ADMIN_EMAIL)\n const emailSubjectPrefix = envString(process.env.NOTIFICATIONS_EMAIL_SUBJECT_PREFIX)\n\n return {\n appUrl,\n panelPath,\n emailEnabled,\n emailFrom,\n emailReplyTo,\n emailSubjectPrefix,\n }\n}\n\nexport
|
|
5
|
-
"mappings": "AACA,SAAS,+BAA+B;AACxC,SAAS,sCAAsC;AAC/C,SAAS,wCAA8E;AAEhF,MAAM,oCAAoC;AA2BjD,MAAM,YAAY,CAAC,UAAqC;AACtD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,UAAU;AACpC;AAEA,MAAM,4BAA4B,oBAAI,IAAI,CAAC,iBAAiB,CAAC;AAE7D,MAAM,uBAAuB;AAE7B,SAAS,0BAA0B,OAA2C;AAC5E,QAAM,UAAU,UAAU,KAAK;AAC/B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,SAAS,qBAAqB,KAAK,OAAO,IAAI,CAAC,GAAG,YAAY;AACpE,SAAO,SAAS,0BAA0B,IAAI,MAAM,IAAI;AAC1D;AAEA,MAAM,6BAA6B,CAAC,UAAkD;AACpF,QAAM,UAAU,UAAU,KAAK;AAC/B,MAAI,CAAC,WAAW,0BAA0B,OAAO,EAAG,QAAO;AAC3D,SAAO;AACT;AAEA,MAAM,qBAAqB,MAAM;AAC/B,QAAM,SAAS;AAAA,IACb,QAAQ,IAAI,yBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI;AAAA,EACd;AACA,QAAM,YAAY,UAAU,QAAQ,IAAI,wBAAwB;AAChE,QAAM,eAAe,wBAAwB,QAAQ,IAAI,6BAA6B,IAAI;AAC1F,QAAM,YAAY,+BAA+B;AACjD,QAAM,eAAe,UAAU,QAAQ,IAAI,gCAAgC,QAAQ,IAAI,WAAW;AAClG,QAAM,qBAAqB,UAAU,QAAQ,IAAI,kCAAkC;AAEnF,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,
|
|
4
|
+
"sourcesContent": ["import type { ModuleConfigService } from '@open-mercato/core/modules/configs/lib/module-config-service'\nimport { parseBooleanWithDefault } from '@open-mercato/shared/lib/boolean'\nimport { resolveDefaultEmailFromAddress } from '@open-mercato/shared/lib/email/config'\nimport { notificationDeliveryConfigSchema, type NotificationDeliveryConfigInput } from '../data/validators'\n\nexport const NOTIFICATIONS_DELIVERY_CONFIG_KEY = 'delivery_strategies'\n\nexport type NotificationDeliveryStrategyState = {\n enabled: boolean\n}\n\nexport type NotificationCustomDeliveryConfig = {\n enabled?: boolean\n config?: unknown\n}\n\nexport type NotificationEmailDeliveryConfig = NotificationDeliveryStrategyState & {\n from?: string\n replyTo?: string\n subjectPrefix?: string\n}\n\nexport type NotificationDeliveryConfig = {\n appUrl?: string\n panelPath: string\n strategies: {\n database: NotificationDeliveryStrategyState\n email: NotificationEmailDeliveryConfig\n custom?: Record<string, NotificationCustomDeliveryConfig>\n }\n}\n\nconst envString = (value: string | undefined | null) => {\n if (!value) return undefined\n const trimmed = value.trim()\n return trimmed.length ? trimmed : undefined\n}\n\nconst PLACEHOLDER_EMAIL_DOMAINS = new Set(['your-domain.com'])\n\nconst EMAIL_DOMAIN_PATTERN = /@([^@\\s<>]+)>?\\s*$/\n\nfunction isPlaceholderEmailAddress(value: string | undefined | null): boolean {\n const address = envString(value)\n if (!address) return false\n const domain = EMAIL_DOMAIN_PATTERN.exec(address)?.[1]?.toLowerCase()\n return domain ? PLACEHOLDER_EMAIL_DOMAINS.has(domain) : false\n}\n\nconst resolveStoredSenderAddress = (value: string | undefined): string | undefined => {\n const address = envString(value)\n if (!address || isPlaceholderEmailAddress(address)) return undefined\n return address\n}\n\nconst resolveEnvDefaults = () => {\n const appUrl = envString(\n process.env.NOTIFICATIONS_APP_URL ||\n process.env.APPLICATION_URL ||\n process.env.NEXT_PUBLIC_APP_URL ||\n process.env.APP_URL\n )\n const panelPath = envString(process.env.NOTIFICATIONS_PANEL_PATH)\n const emailEnabled = parseBooleanWithDefault(process.env.NOTIFICATIONS_EMAIL_ENABLED, true)\n const emailFrom = resolveDefaultEmailFromAddress()\n const emailReplyTo = envString(process.env.NOTIFICATIONS_EMAIL_REPLY_TO || process.env.ADMIN_EMAIL)\n const emailSubjectPrefix = envString(process.env.NOTIFICATIONS_EMAIL_SUBJECT_PREFIX)\n\n return {\n appUrl,\n panelPath,\n emailEnabled,\n emailFrom,\n emailReplyTo,\n emailSubjectPrefix,\n }\n}\n\nexport function resolveDefaultNotificationDeliveryConfig(): NotificationDeliveryConfig {\n const env = resolveEnvDefaults()\n return {\n appUrl: env.appUrl,\n panelPath: env.panelPath ?? '/backend/notifications',\n strategies: {\n database: { enabled: true },\n email: {\n enabled: env.emailEnabled,\n from: env.emailFrom,\n replyTo: env.emailReplyTo,\n subjectPrefix: env.emailSubjectPrefix,\n },\n custom: {},\n },\n }\n}\n\nexport function resolveStoredDefaultNotificationDeliveryConfig(): NotificationDeliveryConfig {\n const defaults = resolveDefaultNotificationDeliveryConfig()\n return {\n ...defaults,\n strategies: {\n ...defaults.strategies,\n email: {\n ...defaults.strategies.email,\n from: undefined,\n replyTo: resolveStoredSenderAddress(defaults.strategies.email.replyTo),\n },\n },\n }\n}\n\nexport const DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig =\n resolveDefaultNotificationDeliveryConfig()\n\nexport const STORED_DEFAULT_NOTIFICATION_DELIVERY_CONFIG: NotificationDeliveryConfig =\n resolveStoredDefaultNotificationDeliveryConfig()\n\nconst parseDeliveryConfig = (input: unknown) => {\n const parsed = notificationDeliveryConfigSchema.safeParse(input)\n const onlyPanelPathInvalid = !parsed.success\n && parsed.error.issues.every((issue) => issue.path[0] === 'panelPath')\n if (!onlyPanelPathInvalid || typeof input !== 'object' || input === null) {\n return parsed\n }\n const withoutPanelPath: Record<string, unknown> = { ...input }\n delete withoutPanelPath.panelPath\n return notificationDeliveryConfigSchema.safeParse(withoutPanelPath)\n}\n\nconst normalizeDeliveryConfig = (input?: unknown | null): NotificationDeliveryConfig => {\n const parsed = parseDeliveryConfig(input ?? {})\n if (!parsed.success) {\n return { ...DEFAULT_NOTIFICATION_DELIVERY_CONFIG }\n }\n\n const value = parsed.data ?? {}\n const strategies = value.strategies ?? {}\n\n return {\n appUrl: value.appUrl,\n panelPath: value.panelPath ?? DEFAULT_NOTIFICATION_DELIVERY_CONFIG.panelPath,\n strategies: {\n database: {\n enabled: DEFAULT_NOTIFICATION_DELIVERY_CONFIG.strategies.database.enabled,\n },\n email: {\n enabled: strategies.email?.enabled ?? DEFAULT_NOTIFICATION_DELIVERY_CONFIG.strategies.email.enabled,\n from: resolveStoredSenderAddress(strategies.email?.from),\n replyTo: resolveStoredSenderAddress(strategies.email?.replyTo),\n subjectPrefix: strategies.email?.subjectPrefix,\n },\n custom: strategies.custom ?? {},\n },\n }\n}\n\ntype Resolver = {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport async function resolveNotificationDeliveryConfig(\n resolver: Resolver,\n options?: { defaultValue?: NotificationDeliveryConfig }\n): Promise<NotificationDeliveryConfig> {\n const fallback = options?.defaultValue ?? DEFAULT_NOTIFICATION_DELIVERY_CONFIG\n let service: ModuleConfigService\n try {\n service = resolver.resolve<ModuleConfigService>('moduleConfigService')\n } catch {\n return { ...fallback }\n }\n try {\n const value = await service.getValue('notifications', NOTIFICATIONS_DELIVERY_CONFIG_KEY, { defaultValue: fallback })\n return normalizeDeliveryConfig(value)\n } catch {\n return { ...fallback }\n }\n}\n\nexport async function saveNotificationDeliveryConfig(\n resolver: Resolver,\n config: NotificationDeliveryConfigInput\n): Promise<void> {\n let service: ModuleConfigService\n try {\n service = resolver.resolve<ModuleConfigService>('moduleConfigService')\n } catch {\n throw new Error('Configuration service unavailable')\n }\n\n const normalized = normalizeDeliveryConfig(config)\n await service.setValue('notifications', NOTIFICATIONS_DELIVERY_CONFIG_KEY, normalized)\n}\n\nexport function resolveNotificationPanelUrl(config: NotificationDeliveryConfig): string | null {\n const base = config.appUrl\n || process.env.APPLICATION_URL\n || process.env.NEXT_PUBLIC_APP_URL\n || process.env.APP_URL\n if (!base || !base.trim()) {\n return null\n }\n return `${base.replace(/\\/$/, '')}${config.panelPath}`\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,+BAA+B;AACxC,SAAS,sCAAsC;AAC/C,SAAS,wCAA8E;AAEhF,MAAM,oCAAoC;AA2BjD,MAAM,YAAY,CAAC,UAAqC;AACtD,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,UAAU,MAAM,KAAK;AAC3B,SAAO,QAAQ,SAAS,UAAU;AACpC;AAEA,MAAM,4BAA4B,oBAAI,IAAI,CAAC,iBAAiB,CAAC;AAE7D,MAAM,uBAAuB;AAE7B,SAAS,0BAA0B,OAA2C;AAC5E,QAAM,UAAU,UAAU,KAAK;AAC/B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,SAAS,qBAAqB,KAAK,OAAO,IAAI,CAAC,GAAG,YAAY;AACpE,SAAO,SAAS,0BAA0B,IAAI,MAAM,IAAI;AAC1D;AAEA,MAAM,6BAA6B,CAAC,UAAkD;AACpF,QAAM,UAAU,UAAU,KAAK;AAC/B,MAAI,CAAC,WAAW,0BAA0B,OAAO,EAAG,QAAO;AAC3D,SAAO;AACT;AAEA,MAAM,qBAAqB,MAAM;AAC/B,QAAM,SAAS;AAAA,IACb,QAAQ,IAAI,yBACZ,QAAQ,IAAI,mBACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI;AAAA,EACd;AACA,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,EACvE,QAAQ;AACN,UAAM,IAAI,MAAM,mCAAmC;AAAA,EACrD;AAEA,QAAM,aAAa,wBAAwB,MAAM;AACjD,QAAM,QAAQ,SAAS,iBAAiB,mCAAmC,UAAU;AACvF;AAEO,SAAS,4BAA4B,QAAmD;AAC7F,QAAM,OAAO,OAAO,UACf,QAAQ,IAAI,mBACZ,QAAQ,IAAI,uBACZ,QAAQ,IAAI;AACjB,MAAI,CAAC,QAAQ,CAAC,KAAK,KAAK,GAAG;AACzB,WAAO;AAAA,EACT;AACA,SAAO,GAAG,KAAK,QAAQ,OAAO,EAAE,CAAC,GAAG,OAAO,SAAS;AACtD;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,17 @@
|
|
|
1
1
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
2
2
|
import { TYPE_REGISTRY_SYNC_EVENT } from "./events.js";
|
|
3
|
+
import {
|
|
4
|
+
NOTIFICATIONS_DELIVERY_CONFIG_KEY,
|
|
5
|
+
resolveStoredDefaultNotificationDeliveryConfig
|
|
6
|
+
} from "./lib/deliveryConfig.js";
|
|
3
7
|
const logger = createLogger("notifications");
|
|
4
8
|
const setup = {
|
|
9
|
+
instanceConfigDefaults: () => [
|
|
10
|
+
{
|
|
11
|
+
name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,
|
|
12
|
+
value: resolveStoredDefaultNotificationDeliveryConfig()
|
|
13
|
+
}
|
|
14
|
+
],
|
|
5
15
|
defaultRoleFeatures: {
|
|
6
16
|
superadmin: ["notifications.*"],
|
|
7
17
|
admin: ["notifications.*"],
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/notifications/setup.ts"],
|
|
4
|
-
"sourcesContent": ["import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { TYPE_REGISTRY_SYNC_EVENT } from './events'\n\nconst logger = createLogger('notifications')\n\nexport const setup: ModuleSetupConfig = {\n defaultRoleFeatures: {\n superadmin: ['notifications.*'],\n admin: ['notifications.*'],\n employee: ['notifications.view', 'notifications.manage_preferences'],\n },\n\n async seedDefaults({ container, tenantId, organizationId }) {\n // Best-effort: nudge the type catalogue into the DB at init time. The\n // `GET /api/notifications/types` lazy reconcile is the reliable fallback, so\n // a failure here must never break tenant initialization.\n try {\n const eventBus = container.resolve('eventBus') as {\n emit: (event: string, payload: unknown, options?: unknown) => Promise<void>\n }\n await eventBus.emit(\n TYPE_REGISTRY_SYNC_EVENT,\n { tenantId, organizationId },\n { tenantId, organizationId, persistent: true },\n )\n } catch (err) {\n logger.warn('type_registry.sync emit skipped during seedDefaults', { err })\n }\n },\n}\n\nexport default setup\n"],
|
|
5
|
-
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;
|
|
4
|
+
"sourcesContent": ["import type { ModuleSetupConfig } from '@open-mercato/shared/modules/setup'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { TYPE_REGISTRY_SYNC_EVENT } from './events'\nimport {\n NOTIFICATIONS_DELIVERY_CONFIG_KEY,\n resolveStoredDefaultNotificationDeliveryConfig,\n} from './lib/deliveryConfig'\n\nconst logger = createLogger('notifications')\n\nexport const setup: ModuleSetupConfig = {\n instanceConfigDefaults: () => [\n {\n name: NOTIFICATIONS_DELIVERY_CONFIG_KEY,\n value: resolveStoredDefaultNotificationDeliveryConfig(),\n },\n ],\n\n defaultRoleFeatures: {\n superadmin: ['notifications.*'],\n admin: ['notifications.*'],\n employee: ['notifications.view', 'notifications.manage_preferences'],\n },\n\n async seedDefaults({ container, tenantId, organizationId }) {\n // Best-effort: nudge the type catalogue into the DB at init time. The\n // `GET /api/notifications/types` lazy reconcile is the reliable fallback, so\n // a failure here must never break tenant initialization.\n try {\n const eventBus = container.resolve('eventBus') as {\n emit: (event: string, payload: unknown, options?: unknown) => Promise<void>\n }\n await eventBus.emit(\n TYPE_REGISTRY_SYNC_EVENT,\n { tenantId, organizationId },\n { tenantId, organizationId, persistent: true },\n )\n } catch (err) {\n logger.warn('type_registry.sync emit skipped during seedDefaults', { err })\n }\n },\n}\n\nexport default setup\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,oBAAoB;AAC7B,SAAS,gCAAgC;AACzC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,SAAS,aAAa,eAAe;AAEpC,MAAM,QAA2B;AAAA,EACtC,wBAAwB,MAAM;AAAA,IAC5B;AAAA,MACE,MAAM;AAAA,MACN,OAAO,+CAA+C;AAAA,IACxD;AAAA,EACF;AAAA,EAEA,qBAAqB;AAAA,IACnB,YAAY,CAAC,iBAAiB;AAAA,IAC9B,OAAO,CAAC,iBAAiB;AAAA,IACzB,UAAU,CAAC,sBAAsB,kCAAkC;AAAA,EACrE;AAAA,EAEA,MAAM,aAAa,EAAE,WAAW,UAAU,eAAe,GAAG;AAI1D,QAAI;AACF,YAAM,WAAW,UAAU,QAAQ,UAAU;AAG7C,YAAM,SAAS;AAAA,QACb;AAAA,QACA,EAAE,UAAU,eAAe;AAAA,QAC3B,EAAE,UAAU,gBAAgB,YAAY,KAAK;AAAA,MAC/C;AAAA,IACF,SAAS,KAAK;AACZ,aAAO,KAAK,uDAAuD,EAAE,IAAI,CAAC;AAAA,IAC5E;AAAA,EACF;AACF;AAEA,IAAO,gBAAQ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -18,6 +18,8 @@ import { raiseCrudError } from "@open-mercato/ui/backend/utils/serverErrors";
|
|
|
18
18
|
import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
|
|
19
19
|
import { useCustomFieldDefs } from "@open-mercato/ui/backend/utils/customFieldDefs";
|
|
20
20
|
import { Save, Plus, X } from "lucide-react";
|
|
21
|
+
import { parseSelectedOrganizationCookie, parseSelectedTenantCookie } from "@open-mercato/core/modules/directory/utils/scopeCookies";
|
|
22
|
+
import { readRequestOrganizationScope } from "@open-mercato/shared/lib/frontend/organizationEvents";
|
|
21
23
|
import { useOrganizationScopeVersion } from "@open-mercato/shared/lib/frontend/useOrganizationScope";
|
|
22
24
|
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
23
25
|
import { defaultLocale, locales as defaultLocales } from "@open-mercato/shared/lib/i18n/config";
|
|
@@ -28,6 +30,14 @@ import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
|
28
30
|
const logger = createLogger("translations").child({ component: "TranslationManager" });
|
|
29
31
|
const TRANSLATION_MUTATION_CONTEXT_ID = "translations.entity-translations";
|
|
30
32
|
const SUPPORTED_LOCALES_MUTATION_CONTEXT_ID = "translations.supported-locales";
|
|
33
|
+
function readTranslationRequestScopeKey() {
|
|
34
|
+
const cookies = typeof document === "undefined" ? null : document.cookie;
|
|
35
|
+
return JSON.stringify([
|
|
36
|
+
parseSelectedTenantCookie(cookies),
|
|
37
|
+
parseSelectedOrganizationCookie(cookies),
|
|
38
|
+
readRequestOrganizationScope() !== null
|
|
39
|
+
]);
|
|
40
|
+
}
|
|
31
41
|
function useTranslationLocales() {
|
|
32
42
|
return useQuery({
|
|
33
43
|
queryKey: ["translation-locales"],
|
|
@@ -53,6 +63,15 @@ function TranslationManager({
|
|
|
53
63
|
const t = useT();
|
|
54
64
|
const scopeVersion = useOrganizationScopeVersion();
|
|
55
65
|
const isEmbedded = mode === "embedded";
|
|
66
|
+
const [openedScopeKey] = React.useState(readTranslationRequestScopeKey);
|
|
67
|
+
const hasEditorScopeChanged = () => isEmbedded && readTranslationRequestScopeKey() !== openedScopeKey;
|
|
68
|
+
const scopeChangedMessage = t(
|
|
69
|
+
"translations.manager.errors.organizationChanged",
|
|
70
|
+
"The organization selection changed. Close and reopen the translation editor to continue."
|
|
71
|
+
);
|
|
72
|
+
const assertEditorScope = () => {
|
|
73
|
+
if (hasEditorScopeChanged()) throw new Error(scopeChangedMessage);
|
|
74
|
+
};
|
|
56
75
|
const [selectedEntityType, setSelectedEntityType] = React.useState(propEntityType ?? "");
|
|
57
76
|
const [selectedRecordId, setSelectedRecordId] = React.useState(propRecordId ?? "");
|
|
58
77
|
const [activeLocale, setActiveLocale] = React.useState("");
|
|
@@ -147,9 +166,10 @@ function TranslationManager({
|
|
|
147
166
|
isError: translationError,
|
|
148
167
|
refetch: refetchTranslation
|
|
149
168
|
} = useQuery({
|
|
150
|
-
queryKey: ["entity-translation", entityType, recordId, scopeVersion],
|
|
169
|
+
queryKey: ["entity-translation", entityType, recordId, scopeVersion, isEmbedded ? openedScopeKey : null],
|
|
151
170
|
enabled: !!entityType && !!recordId,
|
|
152
171
|
queryFn: async () => {
|
|
172
|
+
assertEditorScope();
|
|
153
173
|
const res = await apiCall(
|
|
154
174
|
`/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`
|
|
155
175
|
);
|
|
@@ -191,6 +211,14 @@ function TranslationManager({
|
|
|
191
211
|
}
|
|
192
212
|
}, [translationSignature, translationData]);
|
|
193
213
|
const { runMutation, retryLastMutation } = useGuardedMutation({ contextId: TRANSLATION_MUTATION_CONTEXT_ID });
|
|
214
|
+
const retryInEditorScope = async () => {
|
|
215
|
+
if (!hasEditorScopeChanged()) {
|
|
216
|
+
const succeeded = await retryLastMutation();
|
|
217
|
+
if (succeeded || !hasEditorScopeChanged()) return succeeded;
|
|
218
|
+
}
|
|
219
|
+
flash(scopeChangedMessage, "error");
|
|
220
|
+
return false;
|
|
221
|
+
};
|
|
194
222
|
const mutation = useMutation({
|
|
195
223
|
mutationFn: async () => {
|
|
196
224
|
if (!entityType || !recordId) {
|
|
@@ -212,18 +240,22 @@ function TranslationManager({
|
|
|
212
240
|
logger.warn("Save skipped: payload is empty \u2014 no locale contains any non-empty field");
|
|
213
241
|
throw new Error(t("translations.manager.errors.nothingToSave", "Nothing to save \u2014 enter a translation first"));
|
|
214
242
|
}
|
|
243
|
+
assertEditorScope();
|
|
215
244
|
return runMutation({
|
|
216
245
|
operation: async () => {
|
|
217
246
|
const res = await withScopedApiRequestHeaders(
|
|
218
247
|
buildOptimisticLockHeader(translationRowUpdatedAt),
|
|
219
|
-
() =>
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
248
|
+
() => {
|
|
249
|
+
assertEditorScope();
|
|
250
|
+
return apiCall(
|
|
251
|
+
`/api/translations/${encodeURIComponent(entityType)}/${encodeURIComponent(recordId)}`,
|
|
252
|
+
{
|
|
253
|
+
method: "PUT",
|
|
254
|
+
headers: { "content-type": "application/json" },
|
|
255
|
+
body: JSON.stringify(body)
|
|
256
|
+
}
|
|
257
|
+
);
|
|
258
|
+
}
|
|
227
259
|
);
|
|
228
260
|
if (!res.ok) {
|
|
229
261
|
await raiseCrudError(res.response, t("translations.manager.errors.save", "Failed to save translations"));
|
|
@@ -237,7 +269,7 @@ function TranslationManager({
|
|
|
237
269
|
resourceKind: "translation",
|
|
238
270
|
resourceId: recordId,
|
|
239
271
|
data: translationData ?? null,
|
|
240
|
-
retryLastMutation
|
|
272
|
+
retryLastMutation: isEmbedded ? retryInEditorScope : retryLastMutation
|
|
241
273
|
},
|
|
242
274
|
mutationPayload: body
|
|
243
275
|
});
|
|
@@ -249,6 +281,10 @@ function TranslationManager({
|
|
|
249
281
|
await refetchTranslation();
|
|
250
282
|
},
|
|
251
283
|
onError: (err) => {
|
|
284
|
+
if (hasEditorScopeChanged()) {
|
|
285
|
+
flash(scopeChangedMessage, "error");
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
252
288
|
if (surfaceRecordConflict(err, t)) return;
|
|
253
289
|
const message = err instanceof Error ? err.message : t("translations.manager.errors.save", "Failed to save translations");
|
|
254
290
|
flash(message, "error");
|
|
@@ -314,6 +350,7 @@ function TranslationManager({
|
|
|
314
350
|
);
|
|
315
351
|
}
|
|
316
352
|
if (translationError) {
|
|
353
|
+
if (hasEditorScopeChanged()) return /* @__PURE__ */ jsx(ErrorMessage, { label: scopeChangedMessage });
|
|
317
354
|
return /* @__PURE__ */ jsx(
|
|
318
355
|
ErrorMessage,
|
|
319
356
|
{
|