@open-mercato/core 0.7.1-develop.7195.1.b5efd1d51a → 0.7.1-develop.7201.1.9bd6c88e3d
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/dist/modules/auth/lib/setup-app.js +1 -0
- package/dist/modules/auth/lib/setup-app.js.map +2 -2
- package/dist/modules/catalog/components/products/ProductUomSection.js +27 -22
- package/dist/modules/catalog/components/products/ProductUomSection.js.map +2 -2
- package/dist/modules/entities/lib/field-definitions.js +9 -0
- package/dist/modules/entities/lib/field-definitions.js.map +2 -2
- package/dist/modules/entities/lib/install-from-ce.js +1 -0
- package/dist/modules/entities/lib/install-from-ce.js.map +2 -2
- package/dist/modules/eudr/search.js +3 -5
- package/dist/modules/eudr/search.js.map +2 -2
- package/dist/modules/sales/components/documents/PaymentDialog.js +14 -11
- package/dist/modules/sales/components/documents/PaymentDialog.js.map +2 -2
- package/dist/modules/sales/lib/lineSnapshots.js +3 -0
- package/dist/modules/sales/lib/lineSnapshots.js.map +2 -2
- package/dist/modules/wms/components/backend/AdjustInventoryDialog.js +8 -6
- package/dist/modules/wms/components/backend/AdjustInventoryDialog.js.map +2 -2
- package/dist/modules/wms/search.js +4 -4
- package/dist/modules/wms/search.js.map +2 -2
- package/package.json +7 -7
- package/src/modules/auth/lib/setup-app.ts +6 -0
- package/src/modules/catalog/components/products/ProductUomSection.tsx +31 -21
- package/src/modules/entities/lib/field-definitions.ts +15 -0
- package/src/modules/entities/lib/install-from-ce.ts +1 -0
- package/src/modules/eudr/i18n/de.json +4 -1
- package/src/modules/eudr/i18n/en.json +4 -1
- package/src/modules/eudr/i18n/es.json +4 -1
- package/src/modules/eudr/i18n/ko.json +4 -1
- package/src/modules/eudr/i18n/pl.json +4 -1
- package/src/modules/eudr/search.ts +3 -5
- package/src/modules/sales/components/documents/PaymentDialog.tsx +18 -11
- package/src/modules/sales/i18n/de.json +1 -0
- package/src/modules/sales/i18n/en.json +1 -0
- package/src/modules/sales/i18n/es.json +1 -0
- package/src/modules/sales/i18n/ko.json +1 -0
- package/src/modules/sales/i18n/pl.json +1 -0
- package/src/modules/sales/lib/lineSnapshots.ts +22 -3
- package/src/modules/wms/components/backend/AdjustInventoryDialog.tsx +6 -5
- package/src/modules/wms/i18n/de.json +4 -0
- package/src/modules/wms/i18n/en.json +4 -0
- package/src/modules/wms/i18n/es.json +4 -0
- package/src/modules/wms/i18n/ko.json +4 -0
- package/src/modules/wms/i18n/pl.json +4 -0
- package/src/modules/wms/search.ts +4 -4
|
@@ -14,6 +14,7 @@ const CONFIG_PASSTHROUGH_KEYS = [
|
|
|
14
14
|
"formEditable",
|
|
15
15
|
"listVisible",
|
|
16
16
|
"indexed",
|
|
17
|
+
"encrypted",
|
|
17
18
|
"priority",
|
|
18
19
|
"editor",
|
|
19
20
|
"input",
|
|
@@ -38,6 +39,11 @@ function normalizeValue(value) {
|
|
|
38
39
|
function configEquals(a, b) {
|
|
39
40
|
return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null));
|
|
40
41
|
}
|
|
42
|
+
function hasEncryptionEnabled(definition) {
|
|
43
|
+
const config = definition?.configJson;
|
|
44
|
+
if (!config || typeof config !== "object") return false;
|
|
45
|
+
return config.encrypted === true;
|
|
46
|
+
}
|
|
41
47
|
async function ensureCustomFieldDefinitions(em, sets, scope) {
|
|
42
48
|
let created = 0;
|
|
43
49
|
let updated = 0;
|
|
@@ -65,6 +71,9 @@ async function ensureCustomFieldDefinitions(em, sets, scope) {
|
|
|
65
71
|
const value = field[key];
|
|
66
72
|
if (value !== void 0) configJson[key] = value;
|
|
67
73
|
}
|
|
74
|
+
if (configJson.encrypted === void 0 && hasEncryptionEnabled(existing)) {
|
|
75
|
+
configJson.encrypted = true;
|
|
76
|
+
}
|
|
68
77
|
if (!existing) {
|
|
69
78
|
if (!scope.dryRun) {
|
|
70
79
|
const createdDef = em.create(CustomFieldDef, {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/entities/lib/field-definitions.ts"],
|
|
4
|
-
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomFieldDef } from '../data/entities'\nimport type { CustomFieldDefinition } from '@open-mercato/shared/modules/entities'\n\nexport type FieldSetInput = {\n entity: string\n fields: CustomFieldDefinition[]\n source?: string\n}\n\nexport type EnsureFieldDefinitionsOptions = {\n organizationId: string | null\n tenantId: string | null\n dryRun?: boolean\n createOnly?: boolean\n}\n\nexport type EnsureFieldDefinitionsResult = {\n created: number\n updated: number\n unchanged: number\n}\n\nconst CONFIG_PASSTHROUGH_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'fieldset',\n 'fieldsets',\n 'group',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'dictionaryId',\n 'dictionaryInlineCreate',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n 'sourceMetadata',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction configEquals(a: unknown, b: unknown): boolean {\n return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null))\n}\n\nexport async function ensureCustomFieldDefinitions(\n em: EntityManager,\n sets: FieldSetInput[],\n scope: EnsureFieldDefinitionsOptions\n): Promise<EnsureFieldDefinitionsResult> {\n let created = 0\n let updated = 0\n let unchanged = 0\n\n // Prefetch every existing definition the batch could touch in a single query,\n // then index by composite key so the nested loop never issues per-field lookups.\n const entityIds = Array.from(new Set(sets.map((set) => set.entity)))\n const fieldKeys = Array.from(new Set(sets.flatMap((set) => set.fields.map((field) => field.key))))\n const existingByKey = new Map<string, CustomFieldDef>()\n if (entityIds.length > 0 && fieldKeys.length > 0) {\n const existingDefs = await em.find(CustomFieldDef, {\n entityId: { $in: entityIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: { $in: fieldKeys },\n })\n for (const def of existingDefs) {\n existingByKey.set(`${def.entityId}|${def.key}`, def)\n }\n }\n\n let dirty = false\n\n for (const set of sets) {\n for (const field of set.fields) {\n const existing = existingByKey.get(`${set.entity}|${field.key}`) ?? null\n const configJson: Record<string, unknown> = {}\n\n for (const key of CONFIG_PASSTHROUGH_KEYS) {\n const value = field[key]\n if (value !== undefined) configJson[key] = value as unknown\n }\n\n if (!existing) {\n if (!scope.dryRun) {\n const createdDef = em.create(CustomFieldDef, {\n entityId: set.entity,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: field.key,\n kind: field.kind,\n configJson,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(createdDef)\n // Track so duplicate (entity, key) pairs within the batch update in memory instead of double-inserting.\n existingByKey.set(`${set.entity}|${field.key}`, createdDef)\n dirty = true\n }\n created++\n continue\n }\n\n const kindChanged = existing.kind !== field.kind\n const configChanged = !configEquals(existing.configJson ?? null, configJson)\n const needsActivation = existing.isActive !== true || existing.deletedAt != null\n if (scope.createOnly) {\n unchanged++\n continue\n }\n if (!kindChanged && !configChanged && !needsActivation) {\n unchanged++\n continue\n }\n\n if (!scope.dryRun) {\n existing.kind = field.kind\n ;(existing as any).configJson = configJson\n existing.isActive = true\n existing.updatedAt = new Date()\n if (existing.deletedAt) existing.deletedAt = null\n em.persist(existing)\n dirty = true\n }\n updated++\n }\n }\n\n if (dirty) {\n // Single flush for the whole batch instead of one round trip per field.\n await em.flush()\n }\n\n return { created, updated, unchanged }\n}\n"],
|
|
5
|
-
"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AAA,MACF;AACA,UAAI,CAAC,eAAe,CAAC,iBAAiB,CAAC,iBAAiB;AACtD;AACA;AAAA,MACF;AAEA,UAAI,CAAC,MAAM,QAAQ;AACjB,iBAAS,OAAO,MAAM;AACrB,QAAC,SAAiB,aAAa;AAChC,iBAAS,WAAW;AACpB,iBAAS,YAAY,oBAAI,KAAK;AAC9B,YAAI,SAAS,UAAW,UAAS,YAAY;AAC7C,WAAG,QAAQ,QAAQ;AACnB,gBAAQ;AAAA,MACV;AACA;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO;AAET,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO,EAAE,SAAS,SAAS,UAAU;AACvC;",
|
|
4
|
+
"sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomFieldDef } from '../data/entities'\nimport type { CustomFieldDefinition } from '@open-mercato/shared/modules/entities'\n\nexport type FieldSetInput = {\n entity: string\n fields: CustomFieldDefinition[]\n source?: string\n}\n\nexport type EnsureFieldDefinitionsOptions = {\n organizationId: string | null\n tenantId: string | null\n dryRun?: boolean\n createOnly?: boolean\n}\n\nexport type EnsureFieldDefinitionsResult = {\n created: number\n updated: number\n unchanged: number\n}\n\nconst CONFIG_PASSTHROUGH_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'fieldset',\n 'fieldsets',\n 'group',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'encrypted',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'dictionaryId',\n 'dictionaryInlineCreate',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n 'sourceMetadata',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction configEquals(a: unknown, b: unknown): boolean {\n return JSON.stringify(normalizeValue(a ?? null)) === JSON.stringify(normalizeValue(b ?? null))\n}\n\nfunction hasEncryptionEnabled(definition: CustomFieldDef | null): boolean {\n const config = definition?.configJson\n if (!config || typeof config !== 'object') return false\n return (config as Record<string, unknown>).encrypted === true\n}\n\nexport async function ensureCustomFieldDefinitions(\n em: EntityManager,\n sets: FieldSetInput[],\n scope: EnsureFieldDefinitionsOptions\n): Promise<EnsureFieldDefinitionsResult> {\n let created = 0\n let updated = 0\n let unchanged = 0\n\n // Prefetch every existing definition the batch could touch in a single query,\n // then index by composite key so the nested loop never issues per-field lookups.\n const entityIds = Array.from(new Set(sets.map((set) => set.entity)))\n const fieldKeys = Array.from(new Set(sets.flatMap((set) => set.fields.map((field) => field.key))))\n const existingByKey = new Map<string, CustomFieldDef>()\n if (entityIds.length > 0 && fieldKeys.length > 0) {\n const existingDefs = await em.find(CustomFieldDef, {\n entityId: { $in: entityIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: { $in: fieldKeys },\n })\n for (const def of existingDefs) {\n existingByKey.set(`${def.entityId}|${def.key}`, def)\n }\n }\n\n let dirty = false\n\n for (const set of sets) {\n for (const field of set.fields) {\n const existing = existingByKey.get(`${set.entity}|${field.key}`) ?? null\n const configJson: Record<string, unknown> = {}\n\n for (const key of CONFIG_PASSTHROUGH_KEYS) {\n const value = field[key]\n if (value !== undefined) configJson[key] = value as unknown\n }\n\n // configJson is rebuilt from the declaration, so a field encrypted through the\n // definitions API would lose the flag on the next install while its stored\n // values stay ciphertext the read path no longer decrypts. Keep an enabled flag\n // unless the declaration turns it off with an explicit `encrypted: false`.\n if (configJson.encrypted === undefined && hasEncryptionEnabled(existing)) {\n configJson.encrypted = true\n }\n\n if (!existing) {\n if (!scope.dryRun) {\n const createdDef = em.create(CustomFieldDef, {\n entityId: set.entity,\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n key: field.key,\n kind: field.kind,\n configJson,\n isActive: true,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(createdDef)\n // Track so duplicate (entity, key) pairs within the batch update in memory instead of double-inserting.\n existingByKey.set(`${set.entity}|${field.key}`, createdDef)\n dirty = true\n }\n created++\n continue\n }\n\n const kindChanged = existing.kind !== field.kind\n const configChanged = !configEquals(existing.configJson ?? null, configJson)\n const needsActivation = existing.isActive !== true || existing.deletedAt != null\n if (scope.createOnly) {\n unchanged++\n continue\n }\n if (!kindChanged && !configChanged && !needsActivation) {\n unchanged++\n continue\n }\n\n if (!scope.dryRun) {\n existing.kind = field.kind\n ;(existing as any).configJson = configJson\n existing.isActive = true\n existing.updatedAt = new Date()\n if (existing.deletedAt) existing.deletedAt = null\n em.persist(existing)\n dirty = true\n }\n updated++\n }\n }\n\n if (dirty) {\n // Single flush for the whole batch instead of one round trip per field.\n await em.flush()\n }\n\n return { created, updated, unchanged }\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,sBAAsB;AAsB/B,MAAM,0BAA8D;AAAA,EAClE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AACzE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,KAAK,KAAgC,EAChD,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC,EACjC,OAAg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AAI,OAAO;AAET,UAAM,GAAG,MAAM;AAAA,EACjB;AAEA,SAAO,EAAE,SAAS,SAAS,UAAU;AACvC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/entities/lib/install-from-ce.ts"],
|
|
4
|
-
"sourcesContent": ["import crypto from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache/types'\nimport type { CustomFieldDefinition, CustomFieldSet, CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport { Tenant } from '@open-mercato/core/modules/directory/data/entities'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { ensureCustomFieldDefinitions } from './field-definitions'\nimport { upsertCustomEntity, type UpsertCustomEntityResult } from './register'\nimport { invalidateDefinitionsCache } from '../api/definitions.cache'\n\ntype InstallScope = {\n tenantId: string | null\n}\n\nexport type InstallEntitiesOptions = {\n tenantIds?: string[]\n entityIds?: string[]\n includeGlobal?: boolean\n dryRun?: boolean\n createOnly?: boolean\n force?: boolean\n logger?: (message: string) => void\n}\n\nexport type InstallEntitiesResult = {\n processed: number\n synchronized: number\n skipped: number\n fieldChanges: number\n}\n\nexport type AggregatedEntityConfig = {\n entityId: string\n moduleIds: Set<string>\n spec?: CustomEntitySpec\n fieldSets: CustomFieldSet[]\n}\n\nconst FIELD_DETAIL_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction computeChecksum(payload: unknown): string {\n return crypto.createHash('md5').update(JSON.stringify(normalizeValue(payload))).digest('hex')\n}\n\nfunction systemEntityIds(): Set<string> {\n const ids = new Set<string>()\n const GeneratedEntities = getEntityIds()\n for (const moduleEntities of Object.values(GeneratedEntities)) {\n for (const id of Object.values(moduleEntities as Record<string, string>)) {\n ids.add(id)\n }\n }\n return ids\n}\n\nfunction buildAggregatedConfigs(): AggregatedEntityConfig[] {\n const map = new Map<string, AggregatedEntityConfig>()\n const modules = getModules()\n for (const mod of modules) {\n const moduleId = mod.id\n const entitySpecs = ((mod as any).customEntities as CustomEntitySpec[] | undefined) ?? []\n for (const spec of entitySpecs) {\n const existing = map.get(spec.id) ?? { entityId: spec.id, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n if (!existing.spec) existing.spec = spec\n map.set(spec.id, existing)\n }\n const fieldSets = ((mod as any).customFieldSets as CustomFieldSet[] | undefined) ?? []\n for (const set of fieldSets) {\n const existing = map.get(set.entity) ?? { entityId: set.entity, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n existing.fieldSets.push(set)\n map.set(set.entity, existing)\n }\n }\n return Array.from(map.values())\n}\n\nexport function resolveFields(fieldSets: CustomFieldSet[]): CustomFieldDefinition[] {\n const byKey = new Map<string, CustomFieldDefinition>()\n const declarationOrder = new Map<string, number>()\n for (const set of fieldSets) {\n for (const field of set.fields ?? []) {\n if (!declarationOrder.has(field.key)) declarationOrder.set(field.key, declarationOrder.size)\n byKey.set(field.key, { ...field })\n }\n }\n // Declaration order is the author's intent, so it drives `priority` (and the\n // resulting render order) unless a field states its own. Sorting alphabetically\n // by key here would silently discard that intent (#4378).\n const resolved = Array.from(byKey.values()).map((field) => (\n typeof field.priority === 'number'\n ? field\n : { ...field, priority: declarationOrder.get(field.key) ?? 0 }\n ))\n return resolved.sort((a, b) => {\n const byPriority = (a.priority ?? 0) - (b.priority ?? 0)\n if (byPriority !== 0) return byPriority\n return (declarationOrder.get(a.key) ?? 0) - (declarationOrder.get(b.key) ?? 0)\n })\n}\n\nfunction normalizeField(field: CustomFieldDefinition) {\n const payload: Record<string, unknown> = {\n key: field.key,\n kind: field.kind,\n }\n for (const key of FIELD_DETAIL_KEYS) {\n const value = field[key]\n if (value !== undefined) payload[key] = value as unknown\n }\n if (field.id) payload.id = field.id\n return payload\n}\n\nfunction buildChecksumPayload(params: {\n entityId: string\n scope: InstallScope\n spec: CustomEntitySpec | undefined\n global: boolean\n fields: CustomFieldDefinition[]\n}) {\n const { entityId, scope, spec, global, fields } = params\n return {\n entityId,\n scope,\n global,\n label: spec?.label ?? null,\n description: spec?.description ?? null,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n fields: fields.map((f) => normalizeField(f)),\n }\n}\n\nexport async function installCustomEntitiesFromModules(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: InstallEntitiesOptions = {}\n): Promise<InstallEntitiesResult> {\n const requestedEntityIds = options.entityIds\n ? new Set(options.entityIds.filter((id): id is string => typeof id === 'string' && id.length > 0))\n : null\n const aggregated = buildAggregatedConfigs().filter((entry) => {\n if (!requestedEntityIds) return true\n return requestedEntityIds.has(entry.entityId)\n })\n const systemIds = systemEntityIds()\n const includeGlobal = options.includeGlobal !== false\n const dryRun = options.dryRun === true\n const createOnly = options.createOnly === true\n const force = options.force === true\n const logger = options.logger\n\n let tenantIds: string[] | undefined\n if (options.tenantIds !== undefined) {\n tenantIds = Array.from(new Set(options.tenantIds.filter((id): id is string => typeof id === 'string' && id.length > 0)))\n }\n\n const ensureTenantIds = async (): Promise<string[]> => {\n if (tenantIds !== undefined) return tenantIds\n const rows = await em.find(Tenant, { deletedAt: null } as any, { fields: ['id'] as any })\n tenantIds = rows.map((row) => row.id)\n return tenantIds ?? []\n }\n\n let processed = 0\n let synchronized = 0\n let skipped = 0\n let fieldChanges = 0\n\n for (const entry of aggregated) {\n const { entityId } = entry\n const spec = entry.spec\n const fields = resolveFields(entry.fieldSets)\n const isSystem = systemIds.has(entityId)\n const registerEntity = !isSystem && !!spec\n const isGlobal = spec?.global === true\n\n const scopes: InstallScope[] = []\n if (isGlobal) {\n if (includeGlobal) scopes.push({ tenantId: null })\n } else {\n const ids = await ensureTenantIds()\n if (!ids.length) {\n skipped++\n continue\n }\n for (const tenantId of ids) scopes.push({ tenantId })\n }\n\n if (!scopes.length && fields.length === 0 && !registerEntity) {\n skipped++\n continue\n }\n\n for (const scope of scopes) {\n processed++\n const scopeKey = scope.tenantId ? `tenant:${scope.tenantId}` : 'global'\n const checksumPayload = buildChecksumPayload({\n entityId,\n scope,\n spec,\n global: isGlobal,\n fields,\n })\n const checksum = computeChecksum(checksumPayload)\n const cacheKey = `custom-entities:v1:${scopeKey}:${entityId}`\n\n if (!dryRun && !force && cache) {\n try {\n const cached = await cache.get(cacheKey)\n if (typeof cached === 'string' && cached === checksum) {\n skipped++\n continue\n }\n } catch {}\n }\n\n let entityResult: UpsertCustomEntityResult = 'unchanged'\n if (registerEntity) {\n entityResult = await upsertCustomEntity(em, entityId, {\n label: spec?.label ?? entityId,\n description: spec?.description ?? null,\n organizationId: null,\n tenantId: scope.tenantId,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n isActive: true,\n dryRun,\n createOnly,\n })\n }\n\n let fieldResult = { created: 0, updated: 0, unchanged: 0 }\n if (fields.length) {\n fieldResult = await ensureCustomFieldDefinitions(\n em,\n [{ entity: entityId, fields }],\n { organizationId: null, tenantId: scope.tenantId, dryRun, createOnly }\n )\n }\n\n const changed = (entityResult !== 'unchanged') || fieldResult.created > 0 || fieldResult.updated > 0\n const shouldInvalidateDefinitions = !dryRun && (changed || force)\n if (shouldInvalidateDefinitions) {\n await invalidateDefinitionsCache(cache ?? undefined, {\n tenantId: scope.tenantId,\n organizationId: null,\n entityIds: [entityId],\n })\n }\n\n if (changed) {\n synchronized++\n fieldChanges += fieldResult.created + fieldResult.updated\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n if (logger) {\n const parts: string[] = []\n if (entityResult !== 'unchanged') parts.push(`entity ${entityResult}`)\n if (fieldResult.created || fieldResult.updated) {\n parts.push(`fields +${fieldResult.created} / ~${fieldResult.updated}`)\n }\n logger(`Synced ${entityId} for ${scopeKey}${parts.length ? ` (${parts.join(', ')})` : ''}`)\n }\n } else {\n skipped++\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n }\n }\n }\n\n return { processed, synchronized, skipped, fieldChanges }\n}\n\nexport function listCustomEntityIds(): string[] {\n return buildAggregatedConfigs().map((entry) => entry.entityId)\n}\n\nexport function getAggregatedCustomEntityConfigs(): AggregatedEntityConfig[] {\n return buildAggregatedConfigs()\n}\n"],
|
|
5
|
-
"mappings": "AAAA,OAAO,YAAY;AAInB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,0BAAyD;AAClE,SAAS,kCAAkC;AA8B3C,MAAM,oBAAwD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AA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Q,EAAE,EAAE,CAAC;AAAA,UAChH,QAAQ;AAAA,UAAC;AAAA,QACX;AACA,YAAI,QAAQ;AACV,gBAAM,QAAkB,CAAC;AACzB,cAAI,iBAAiB,YAAa,OAAM,KAAK,UAAU,YAAY,EAAE;AACrE,cAAI,YAAY,WAAW,YAAY,SAAS;AAC9C,kBAAM,KAAK,WAAW,YAAY,OAAO,OAAO,YAAY,OAAO,EAAE;AAAA,UACvE;AACA,iBAAO,UAAU,QAAQ,QAAQ,QAAQ,GAAG,MAAM,SAAS,KAAK,MAAM,KAAK,IAAI,CAAC,MAAM,EAAE,EAAE;AAAA,QAC5F;AAAA,MACF,OAAO;AACL;AACA,YAAI,CAAC,UAAU,OAAO;AACpB,cAAI;AACF,kBAAM,MAAM,IAAI,UAAU,UAAU,EAAE,MAAM,CAAC,iBAAiB,QAAQ,IAAI,uBAAuB,QAAQ,EAAE,EAAE,CAAC;AAAA,UAChH,QAAQ;AAAA,UAAC;AAAA,QACX;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,cAAc,SAAS,aAAa;AAC1D;AAEO,SAAS,sBAAgC;AAC9C,SAAO,uBAAuB,EAAE,IAAI,CAAC,UAAU,MAAM,QAAQ;AAC/D;AAEO,SAAS,mCAA6D;AAC3E,SAAO,uBAAuB;AAChC;",
|
|
4
|
+
"sourcesContent": ["import crypto from 'node:crypto'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache/types'\nimport type { CustomFieldDefinition, CustomFieldSet, CustomEntitySpec } from '@open-mercato/shared/modules/entities'\nimport { Tenant } from '@open-mercato/core/modules/directory/data/entities'\nimport { getModules } from '@open-mercato/shared/lib/i18n/server'\nimport { getEntityIds } from '@open-mercato/shared/lib/encryption/entityIds'\nimport { ensureCustomFieldDefinitions } from './field-definitions'\nimport { upsertCustomEntity, type UpsertCustomEntityResult } from './register'\nimport { invalidateDefinitionsCache } from '../api/definitions.cache'\n\ntype InstallScope = {\n tenantId: string | null\n}\n\nexport type InstallEntitiesOptions = {\n tenantIds?: string[]\n entityIds?: string[]\n includeGlobal?: boolean\n dryRun?: boolean\n createOnly?: boolean\n force?: boolean\n logger?: (message: string) => void\n}\n\nexport type InstallEntitiesResult = {\n processed: number\n synchronized: number\n skipped: number\n fieldChanges: number\n}\n\nexport type AggregatedEntityConfig = {\n entityId: string\n moduleIds: Set<string>\n spec?: CustomEntitySpec\n fieldSets: CustomFieldSet[]\n}\n\nconst FIELD_DETAIL_KEYS: Array<keyof CustomFieldDefinition> = [\n 'label',\n 'description',\n 'options',\n 'optionsUrl',\n 'defaultValue',\n 'required',\n 'multi',\n 'filterable',\n 'formEditable',\n 'listVisible',\n 'indexed',\n 'encrypted',\n 'priority',\n 'editor',\n 'input',\n 'relatedEntityId',\n 'validation',\n 'maxAttachmentSizeMb',\n 'acceptExtensions',\n]\n\nfunction normalizeValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => normalizeValue(item))\n if (value && typeof value === 'object') {\n return Object.keys(value as Record<string, unknown>)\n .sort((a, b) => a.localeCompare(b))\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = normalizeValue((value as Record<string, unknown>)[key])\n return acc\n }, {})\n }\n return value\n}\n\nfunction computeChecksum(payload: unknown): string {\n return crypto.createHash('md5').update(JSON.stringify(normalizeValue(payload))).digest('hex')\n}\n\nfunction systemEntityIds(): Set<string> {\n const ids = new Set<string>()\n const GeneratedEntities = getEntityIds()\n for (const moduleEntities of Object.values(GeneratedEntities)) {\n for (const id of Object.values(moduleEntities as Record<string, string>)) {\n ids.add(id)\n }\n }\n return ids\n}\n\nfunction buildAggregatedConfigs(): AggregatedEntityConfig[] {\n const map = new Map<string, AggregatedEntityConfig>()\n const modules = getModules()\n for (const mod of modules) {\n const moduleId = mod.id\n const entitySpecs = ((mod as any).customEntities as CustomEntitySpec[] | undefined) ?? []\n for (const spec of entitySpecs) {\n const existing = map.get(spec.id) ?? { entityId: spec.id, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n if (!existing.spec) existing.spec = spec\n map.set(spec.id, existing)\n }\n const fieldSets = ((mod as any).customFieldSets as CustomFieldSet[] | undefined) ?? []\n for (const set of fieldSets) {\n const existing = map.get(set.entity) ?? { entityId: set.entity, moduleIds: new Set<string>(), spec: undefined, fieldSets: [] }\n existing.moduleIds.add(moduleId)\n existing.fieldSets.push(set)\n map.set(set.entity, existing)\n }\n }\n return Array.from(map.values())\n}\n\nexport function resolveFields(fieldSets: CustomFieldSet[]): CustomFieldDefinition[] {\n const byKey = new Map<string, CustomFieldDefinition>()\n const declarationOrder = new Map<string, number>()\n for (const set of fieldSets) {\n for (const field of set.fields ?? []) {\n if (!declarationOrder.has(field.key)) declarationOrder.set(field.key, declarationOrder.size)\n byKey.set(field.key, { ...field })\n }\n }\n // Declaration order is the author's intent, so it drives `priority` (and the\n // resulting render order) unless a field states its own. Sorting alphabetically\n // by key here would silently discard that intent (#4378).\n const resolved = Array.from(byKey.values()).map((field) => (\n typeof field.priority === 'number'\n ? field\n : { ...field, priority: declarationOrder.get(field.key) ?? 0 }\n ))\n return resolved.sort((a, b) => {\n const byPriority = (a.priority ?? 0) - (b.priority ?? 0)\n if (byPriority !== 0) return byPriority\n return (declarationOrder.get(a.key) ?? 0) - (declarationOrder.get(b.key) ?? 0)\n })\n}\n\nfunction normalizeField(field: CustomFieldDefinition) {\n const payload: Record<string, unknown> = {\n key: field.key,\n kind: field.kind,\n }\n for (const key of FIELD_DETAIL_KEYS) {\n const value = field[key]\n if (value !== undefined) payload[key] = value as unknown\n }\n if (field.id) payload.id = field.id\n return payload\n}\n\nfunction buildChecksumPayload(params: {\n entityId: string\n scope: InstallScope\n spec: CustomEntitySpec | undefined\n global: boolean\n fields: CustomFieldDefinition[]\n}) {\n const { entityId, scope, spec, global, fields } = params\n return {\n entityId,\n scope,\n global,\n label: spec?.label ?? null,\n description: spec?.description ?? null,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n fields: fields.map((f) => normalizeField(f)),\n }\n}\n\nexport async function installCustomEntitiesFromModules(\n em: EntityManager,\n cache: CacheStrategy | null | undefined,\n options: InstallEntitiesOptions = {}\n): Promise<InstallEntitiesResult> {\n const requestedEntityIds = options.entityIds\n ? new Set(options.entityIds.filter((id): id is string => typeof id === 'string' && id.length > 0))\n : null\n const aggregated = buildAggregatedConfigs().filter((entry) => {\n if (!requestedEntityIds) return true\n return requestedEntityIds.has(entry.entityId)\n })\n const systemIds = systemEntityIds()\n const includeGlobal = options.includeGlobal !== false\n const dryRun = options.dryRun === true\n const createOnly = options.createOnly === true\n const force = options.force === true\n const logger = options.logger\n\n let tenantIds: string[] | undefined\n if (options.tenantIds !== undefined) {\n tenantIds = Array.from(new Set(options.tenantIds.filter((id): id is string => typeof id === 'string' && id.length > 0)))\n }\n\n const ensureTenantIds = async (): Promise<string[]> => {\n if (tenantIds !== undefined) return tenantIds\n const rows = await em.find(Tenant, { deletedAt: null } as any, { fields: ['id'] as any })\n tenantIds = rows.map((row) => row.id)\n return tenantIds ?? []\n }\n\n let processed = 0\n let synchronized = 0\n let skipped = 0\n let fieldChanges = 0\n\n for (const entry of aggregated) {\n const { entityId } = entry\n const spec = entry.spec\n const fields = resolveFields(entry.fieldSets)\n const isSystem = systemIds.has(entityId)\n const registerEntity = !isSystem && !!spec\n const isGlobal = spec?.global === true\n\n const scopes: InstallScope[] = []\n if (isGlobal) {\n if (includeGlobal) scopes.push({ tenantId: null })\n } else {\n const ids = await ensureTenantIds()\n if (!ids.length) {\n skipped++\n continue\n }\n for (const tenantId of ids) scopes.push({ tenantId })\n }\n\n if (!scopes.length && fields.length === 0 && !registerEntity) {\n skipped++\n continue\n }\n\n for (const scope of scopes) {\n processed++\n const scopeKey = scope.tenantId ? `tenant:${scope.tenantId}` : 'global'\n const checksumPayload = buildChecksumPayload({\n entityId,\n scope,\n spec,\n global: isGlobal,\n fields,\n })\n const checksum = computeChecksum(checksumPayload)\n const cacheKey = `custom-entities:v1:${scopeKey}:${entityId}`\n\n if (!dryRun && !force && cache) {\n try {\n const cached = await cache.get(cacheKey)\n if (typeof cached === 'string' && cached === checksum) {\n skipped++\n continue\n }\n } catch {}\n }\n\n let entityResult: UpsertCustomEntityResult = 'unchanged'\n if (registerEntity) {\n entityResult = await upsertCustomEntity(em, entityId, {\n label: spec?.label ?? entityId,\n description: spec?.description ?? null,\n organizationId: null,\n tenantId: scope.tenantId,\n showInSidebar: spec?.showInSidebar ?? false,\n accessRestricted: spec?.accessRestricted ?? false,\n labelField: spec?.labelField ?? null,\n defaultEditor: spec?.defaultEditor ?? null,\n isActive: true,\n dryRun,\n createOnly,\n })\n }\n\n let fieldResult = { created: 0, updated: 0, unchanged: 0 }\n if (fields.length) {\n fieldResult = await ensureCustomFieldDefinitions(\n em,\n [{ entity: entityId, fields }],\n { organizationId: null, tenantId: scope.tenantId, dryRun, createOnly }\n )\n }\n\n const changed = (entityResult !== 'unchanged') || fieldResult.created > 0 || fieldResult.updated > 0\n const shouldInvalidateDefinitions = !dryRun && (changed || force)\n if (shouldInvalidateDefinitions) {\n await invalidateDefinitionsCache(cache ?? undefined, {\n tenantId: scope.tenantId,\n organizationId: null,\n entityIds: [entityId],\n })\n }\n\n if (changed) {\n synchronized++\n fieldChanges += fieldResult.created + fieldResult.updated\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n if (logger) {\n const parts: string[] = []\n if (entityResult !== 'unchanged') parts.push(`entity ${entityResult}`)\n if (fieldResult.created || fieldResult.updated) {\n parts.push(`fields +${fieldResult.created} / ~${fieldResult.updated}`)\n }\n logger(`Synced ${entityId} for ${scopeKey}${parts.length ? ` (${parts.join(', ')})` : ''}`)\n }\n } else {\n skipped++\n if (!dryRun && cache) {\n try {\n await cache.set(cacheKey, checksum, { tags: [`custom-entity:${entityId}`, `custom-entity-scope:${scopeKey}`] })\n } catch {}\n }\n }\n }\n }\n\n return { processed, synchronized, skipped, fieldChanges }\n}\n\nexport function listCustomEntityIds(): string[] {\n return buildAggregatedConfigs().map((entry) => entry.entityId)\n}\n\nexport function getAggregatedCustomEntityConfigs(): AggregatedEntityConfig[] {\n return buildAggregatedConfigs()\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,YAAY;AAInB,SAAS,cAAc;AACvB,SAAS,kBAAkB;AAC3B,SAAS,oBAAoB;AAC7B,SAAS,oCAAoC;AAC7C,SAAS,0BAAyD;AAClE,SAAS,kCAAkC;AA8B3C,MAAM,oBAAwD;AAAA,EAC5D;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,SAAS,eAAe,OAAyB;AAC/C,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO,MAAM,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AACzE,MAAI,SAAS,OAAO,UAAU,UAAU;AACtC,WAAO,OAAO,KAAK,KAAgC,EAChD,KAAK,CAAC,GAAG,MAAM,EAAE,cAAc,CAAC,CAAC,EACjC,OAAgC,CAAC,KAAK,QAAQ;AAC7C,UAAI,GAAG,IAAI,eAAgB,MAAkC,GAAG,CAAC;AACjE,aAAO;AAAA,IACT,GAAG,CAAC,CAAC;AAAA,EACT;AACA,SAAO;AACT;AAEA,SAAS,gBAAgB,SAA0B;AACjD,SAAO,OAAO,WAAW,KAAK,EAAE,OAAO,KAAK,UAAU,eAAe,OAAO,CAAC,CAAC,EAAE,OAAO,KAAK;AAC9F;AAEA,SAAS,kBAA+B;AACtC,QAAM,MAAM,oBAAI,I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AAA,IACF;AAAA,EACF;AAEA,SAAO,EAAE,WAAW,cAAc,SAAS,aAAa;AAC1D;AAEO,SAAS,sBAAgC;AAC9C,SAAO,uBAAuB,EAAE,IAAI,CAAC,UAAU,MAAM,QAAQ;AAC/D;AAEO,SAAS,mCAA6D;AAC3E,SAAO,uBAAuB;AAChC;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -69,22 +69,20 @@ function resolveSupplierName(record) {
|
|
|
69
69
|
return readObjectText(snapshot, "display_name", "displayName", "name");
|
|
70
70
|
}
|
|
71
71
|
function buildStatementPresenter(translate, record) {
|
|
72
|
-
const label = translate("eudr.search.badge.statement", "DDS statement");
|
|
73
72
|
const title = readRecordText(record, "title") ?? translate("eudr.common.recordUnavailable");
|
|
74
73
|
const subtitle = formatSubtitle(
|
|
75
74
|
readRecordText(record, "reference_number", "referenceNumber"),
|
|
76
75
|
translateToken(translate, "eudr.commodity", readRecordText(record, "commodity"))
|
|
77
76
|
);
|
|
78
|
-
return { title, subtitle, icon: "file-check"
|
|
77
|
+
return { title, subtitle, icon: "file-check" };
|
|
79
78
|
}
|
|
80
79
|
function buildPlotPresenter(translate, record) {
|
|
81
|
-
const label = translate("eudr.search.badge.plot", "Plot");
|
|
82
80
|
const title = readRecordText(record, "name") ?? translate("eudr.common.recordUnavailable");
|
|
83
81
|
const subtitle = formatSubtitle(
|
|
84
82
|
readRecordText(record, "origin_country", "originCountry"),
|
|
85
83
|
translateToken(translate, "eudr.plotType", readRecordText(record, "plot_type", "plotType"))
|
|
86
84
|
);
|
|
87
|
-
return { title, subtitle, icon: "map-pin"
|
|
85
|
+
return { title, subtitle, icon: "map-pin" };
|
|
88
86
|
}
|
|
89
87
|
function buildSubmissionPresenter(translate, record) {
|
|
90
88
|
const label = translate("eudr.search.badge.submission", "Evidence submission");
|
|
@@ -95,7 +93,7 @@ function buildSubmissionPresenter(translate, record) {
|
|
|
95
93
|
supplierName,
|
|
96
94
|
translateToken(translate, "eudr.submissionStatus", readRecordText(record, "status"))
|
|
97
95
|
);
|
|
98
|
-
return { title, subtitle, icon: "package"
|
|
96
|
+
return { title, subtitle, icon: "package" };
|
|
99
97
|
}
|
|
100
98
|
const searchConfig = {
|
|
101
99
|
entities: [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/modules/eudr/search.ts"],
|
|
4
|
-
"sourcesContent": ["import type { SearchBuildContext, SearchIndexSource, SearchModuleConfig, SearchResultPresenter } from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst EUDR_STATEMENTS_URL = '/backend/eudr/statements'\nconst EUDR_PLOTS_URL = '/backend/eudr/plots'\nconst EUDR_EVIDENCE_SUBMISSIONS_URL = '/backend/eudr/evidence-submissions'\n\nfunction assertTenantContext(ctx: SearchBuildContext): void {\n if (typeof ctx.tenantId !== 'string' || ctx.tenantId.length === 0) {\n throw new Error('[internal] [search.eudr] Missing tenantId in search build context')\n }\n}\n\nfunction normalizeText(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return null\n}\n\nfunction readRecordText(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const text = normalizeText(record[key])\n if (text) return text\n }\n return null\n}\n\nfunction readObjectText(source: unknown, ...keys: string[]): string | null {\n if (!source || typeof source !== 'object') return null\n return readRecordText(source as Record<string, unknown>, ...keys)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const text = parts\n .map((part) => normalizeText(part))\n .filter((value): value is string => Boolean(value))\n if (!text.length) return undefined\n return text.join(' \u00B7 ')\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n const text = normalizeText(value)\n if (!text) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction friendlyLabel(input: string): string {\n return input\n .replace(/^cf:/, '')\n .replace(/_/g, ' ')\n .replace(/([a-z])([A-Z])/g, (_match, firstChar, secondChar) => `${firstChar} ${secondChar}`)\n .replace(/\\b\\w/g, (character) => character.toUpperCase())\n}\n\nfunction appendCustomFieldLines(lines: string[], customFields: Record<string, unknown>) {\n for (const [key, value] of Object.entries(customFields)) {\n if (value === null || value === undefined) continue\n appendLine(lines, friendlyLabel(key), value)\n }\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n appendCustomFieldLines(lines, ctx.customFields)\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildRecordUrl(baseUrl: string, record: Record<string, unknown>): string | null {\n const recordId = readRecordText(record, 'id')\n return recordId ? `${baseUrl}/${encodeURIComponent(recordId)}` : null\n}\n\nfunction translateToken(translate: TranslateFn, prefix: string, value: string | null): string | null {\n if (!value) return null\n return translate(`${prefix}.${value}`, value)\n}\n\nfunction resolveSupplierName(record: Record<string, unknown>): string | null {\n const snapshot = record.supplier_snapshot ?? record.supplierSnapshot\n return readObjectText(snapshot, 'display_name', 'displayName', 'name')\n}\n\nfunction buildStatementPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const
|
|
5
|
-
"mappings": "AAEA,SAAS,2BAA2B;AAEpC,MAAM,sBAAsB;AAC5B,MAAM,iBAAiB;AACvB,MAAM,gCAAgC;AAEtC,SAAS,oBAAoB,KAA+B;AAC1D,MAAI,OAAO,IAAI,aAAa,YAAY,IAAI,SAAS,WAAW,GAAG;AACjE,UAAM,IAAI,MAAM,mEAAmE;AAAA,EACrF;AACF;AAEA,SAAS,cAAc,OAA+B;AACpD,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,MAAI,OAAO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AG,GAAG,KAAK;AAAA,EAC7C;AACF;AAEA,SAAS,iBACP,KACA,WACA,OAC0B;AAC1B,yBAAuB,OAAO,IAAI,YAAY;AAC9C,MAAI,CAAC,MAAM,OAAQ,QAAO;AAC1B,SAAO;AAAA,IACL,MAAM;AAAA,IACN;AAAA,IACA,gBAAgB,EAAE,QAAQ,IAAI,QAAQ,cAAc,IAAI,aAAa;AAAA,EACvE;AACF;AAEA,SAAS,eAAe,SAAiB,QAAgD;AACvF,QAAM,WAAW,eAAe,QAAQ,IAAI;AAC5C,SAAO,WAAW,GAAG,OAAO,IAAI,mBAAmB,QAAQ,CAAC,KAAK;AACnE;AAEA,SAAS,eAAe,WAAwB,QAAgB,OAAqC;AACnG,MAAI,CAAC,MAAO,QAAO;AACnB,SAAO,UAAU,GAAG,MAAM,IAAI,KAAK,IAAI,KAAK;AAC9C;AAEA,SAAS,oBAAoB,QAAgD;AAC3E,QAAM,WAAW,OAAO,qBAAqB,OAAO;AACpD,SAAO,eAAe,UAAU,gBAAgB,eAAe,MAAM;AACvE;AAEA,SAAS,wBAAwB,WAAwB,QAAwD;AAC/G,QAAM,QAAQ,
|
|
4
|
+
"sourcesContent": ["import type { SearchBuildContext, SearchIndexSource, SearchModuleConfig, SearchResultPresenter } from '@open-mercato/shared/modules/search'\nimport type { TranslateFn } from '@open-mercato/shared/lib/i18n/context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\n\nconst EUDR_STATEMENTS_URL = '/backend/eudr/statements'\nconst EUDR_PLOTS_URL = '/backend/eudr/plots'\nconst EUDR_EVIDENCE_SUBMISSIONS_URL = '/backend/eudr/evidence-submissions'\n\nfunction assertTenantContext(ctx: SearchBuildContext): void {\n if (typeof ctx.tenantId !== 'string' || ctx.tenantId.length === 0) {\n throw new Error('[internal] [search.eudr] Missing tenantId in search build context')\n }\n}\n\nfunction normalizeText(value: unknown): string | null {\n if (value === null || value === undefined) return null\n if (typeof value === 'string') {\n const trimmed = value.trim()\n return trimmed.length > 0 ? trimmed : null\n }\n if (value instanceof Date) return value.toISOString()\n if (typeof value === 'number' || typeof value === 'boolean') return String(value)\n return null\n}\n\nfunction readRecordText(record: Record<string, unknown>, ...keys: string[]): string | null {\n for (const key of keys) {\n const text = normalizeText(record[key])\n if (text) return text\n }\n return null\n}\n\nfunction readObjectText(source: unknown, ...keys: string[]): string | null {\n if (!source || typeof source !== 'object') return null\n return readRecordText(source as Record<string, unknown>, ...keys)\n}\n\nfunction formatSubtitle(...parts: Array<unknown>): string | undefined {\n const text = parts\n .map((part) => normalizeText(part))\n .filter((value): value is string => Boolean(value))\n if (!text.length) return undefined\n return text.join(' \u00B7 ')\n}\n\nfunction appendLine(lines: string[], label: string, value: unknown) {\n const text = normalizeText(value)\n if (!text) return\n lines.push(`${label}: ${text}`)\n}\n\nfunction friendlyLabel(input: string): string {\n return input\n .replace(/^cf:/, '')\n .replace(/_/g, ' ')\n .replace(/([a-z])([A-Z])/g, (_match, firstChar, secondChar) => `${firstChar} ${secondChar}`)\n .replace(/\\b\\w/g, (character) => character.toUpperCase())\n}\n\nfunction appendCustomFieldLines(lines: string[], customFields: Record<string, unknown>) {\n for (const [key, value] of Object.entries(customFields)) {\n if (value === null || value === undefined) continue\n appendLine(lines, friendlyLabel(key), value)\n }\n}\n\nfunction buildIndexSource(\n ctx: SearchBuildContext,\n presenter: SearchResultPresenter,\n lines: string[],\n): SearchIndexSource | null {\n appendCustomFieldLines(lines, ctx.customFields)\n if (!lines.length) return null\n return {\n text: lines,\n presenter,\n checksumSource: { record: ctx.record, customFields: ctx.customFields },\n }\n}\n\nfunction buildRecordUrl(baseUrl: string, record: Record<string, unknown>): string | null {\n const recordId = readRecordText(record, 'id')\n return recordId ? `${baseUrl}/${encodeURIComponent(recordId)}` : null\n}\n\nfunction translateToken(translate: TranslateFn, prefix: string, value: string | null): string | null {\n if (!value) return null\n return translate(`${prefix}.${value}`, value)\n}\n\nfunction resolveSupplierName(record: Record<string, unknown>): string | null {\n const snapshot = record.supplier_snapshot ?? record.supplierSnapshot\n return readObjectText(snapshot, 'display_name', 'displayName', 'name')\n}\n\nfunction buildStatementPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const title = readRecordText(record, 'title') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'reference_number', 'referenceNumber'),\n translateToken(translate, 'eudr.commodity', readRecordText(record, 'commodity')),\n )\n return { title, subtitle, icon: 'file-check' }\n}\n\nfunction buildPlotPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const title = readRecordText(record, 'name') ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n readRecordText(record, 'origin_country', 'originCountry'),\n translateToken(translate, 'eudr.plotType', readRecordText(record, 'plot_type', 'plotType')),\n )\n return { title, subtitle, icon: 'map-pin' }\n}\n\nfunction buildSubmissionPresenter(translate: TranslateFn, record: Record<string, unknown>): SearchResultPresenter {\n const label = translate('eudr.search.badge.submission', 'Evidence submission')\n const batchNumber = readRecordText(record, 'batch_number', 'batchNumber')\n const supplierName = resolveSupplierName(record)\n const title = batchNumber\n ? `${label} ${batchNumber}`\n : supplierName ?? translate('eudr.common.recordUnavailable')\n const subtitle = formatSubtitle(\n supplierName,\n translateToken(translate, 'eudr.submissionStatus', readRecordText(record, 'status')),\n )\n return { title, subtitle, icon: 'package' }\n}\n\nexport const searchConfig: SearchModuleConfig = {\n entities: [\n {\n entityId: 'eudr:eudr_due_diligence_statement',\n enabled: true,\n priority: 8,\n fieldPolicy: {\n searchable: ['title', 'reference_number', 'commodity'],\n excluded: ['notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Title', record.title)\n appendLine(lines, 'Reference number', record.reference_number ?? record.referenceNumber)\n appendLine(lines, 'Commodity', record.commodity)\n return buildIndexSource(ctx, buildStatementPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildStatementPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_STATEMENTS_URL, ctx.record),\n aclFeatures: ['eudr.statements.view'],\n },\n {\n entityId: 'eudr:eudr_plot',\n enabled: true,\n priority: 7,\n fieldPolicy: {\n searchable: ['name', 'external_id', 'origin_country'],\n excluded: ['producer_name'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Name', record.name)\n appendLine(lines, 'External ID', record.external_id ?? record.externalId)\n appendLine(lines, 'Origin country', record.origin_country ?? record.originCountry)\n return buildIndexSource(ctx, buildPlotPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildPlotPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_PLOTS_URL, ctx.record),\n aclFeatures: ['eudr.plots.view'],\n },\n {\n entityId: 'eudr:eudr_evidence_submission',\n enabled: true,\n priority: 6,\n fieldPolicy: {\n searchable: ['batch_number', 'commodity'],\n excluded: ['producer_name', 'notes'],\n },\n buildSource: async (ctx) => {\n assertTenantContext(ctx)\n const { t: translate } = await resolveTranslations()\n const record = ctx.record\n const lines: string[] = []\n appendLine(lines, 'Batch number', record.batch_number ?? record.batchNumber)\n appendLine(lines, 'Commodity', record.commodity)\n appendLine(lines, 'Supplier', resolveSupplierName(record))\n return buildIndexSource(ctx, buildSubmissionPresenter(translate, record), lines)\n },\n formatResult: async (ctx) => {\n const { t: translate } = await resolveTranslations()\n return buildSubmissionPresenter(translate, ctx.record)\n },\n resolveUrl: async (ctx) => buildRecordUrl(EUDR_EVIDENCE_SUBMISSIONS_URL, ctx.record),\n aclFeatures: ['eudr.submissions.view'],\n },\n ],\n}\n\nexport default searchConfig\nexport const config = searchConfig\n"],
|
|
5
|
+
"mappings": "AAEA,SAAS,2BAA2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B;AACnD,cAAM,SAAS,IAAI;AACnB,cAAM,QAAkB,CAAC;AACzB,mBAAW,OAAO,gBAAgB,OAAO,gBAAgB,OAAO,WAAW;AAC3E,mBAAW,OAAO,aAAa,OAAO,SAAS;AAC/C,mBAAW,OAAO,YAAY,oBAAoB,MAAM,CAAC;AACzD,eAAO,iBAAiB,KAAK,yBAAyB,WAAW,MAAM,GAAG,KAAK;AAAA,MACjF;AAAA,MACA,cAAc,OAAO,QAAQ;AAC3B,cAAM,EAAE,GAAG,UAAU,IAAI,MAAM,oBAAoB;AACnD,eAAO,yBAAyB,WAAW,IAAI,MAAM;AAAA,MACvD;AAAA,MACA,YAAY,OAAO,QAAQ,eAAe,+BAA+B,IAAI,MAAM;AAAA,MACnF,aAAa,CAAC,uBAAuB;AAAA,IACvC;AAAA,EACF;AACF;AAEA,IAAO,iBAAQ;AACR,MAAM,SAAS;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -15,17 +15,16 @@ import { useDialogKeyHandler } from "@open-mercato/ui/hooks/useDialogKeyHandler"
|
|
|
15
15
|
import { Input } from "@open-mercato/ui/primitives/input";
|
|
16
16
|
import { Spinner } from "@open-mercato/ui/primitives/spinner";
|
|
17
17
|
import { E } from "../../../../generated/entities.ids.generated.js";
|
|
18
|
-
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
18
|
+
import { useT, useLocale } from "@open-mercato/shared/lib/i18n/context";
|
|
19
|
+
import { parseLocaleNumber } from "@open-mercato/shared/lib/number";
|
|
19
20
|
import { normalizeCustomFieldSubmitValue, extractCustomFieldValues } from "./customFieldHelpers.js";
|
|
20
21
|
import { createLogger } from "@open-mercato/shared/lib/logger";
|
|
21
22
|
const logger = createLogger("sales");
|
|
22
|
-
const
|
|
23
|
-
if (typeof value === "number"
|
|
24
|
-
if (typeof value
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
}
|
|
28
|
-
return 0;
|
|
23
|
+
const parseAmountInput = (value, locale) => {
|
|
24
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : null;
|
|
25
|
+
if (typeof value !== "string") return 0;
|
|
26
|
+
if (!value.trim()) return 0;
|
|
27
|
+
return parseLocaleNumber(value, locale);
|
|
29
28
|
};
|
|
30
29
|
function PaymentDialog({
|
|
31
30
|
open,
|
|
@@ -40,6 +39,7 @@ function PaymentDialog({
|
|
|
40
39
|
onSaved
|
|
41
40
|
}) {
|
|
42
41
|
const t = useT();
|
|
42
|
+
const locale = useLocale();
|
|
43
43
|
const dialogContentRef = React.useRef(null);
|
|
44
44
|
const [formResetKey, setFormResetKey] = React.useState(0);
|
|
45
45
|
const [paymentMethods, setPaymentMethods] = React.useState([]);
|
|
@@ -261,9 +261,8 @@ function PaymentDialog({
|
|
|
261
261
|
/* @__PURE__ */ jsx(
|
|
262
262
|
Input,
|
|
263
263
|
{
|
|
264
|
-
type: "
|
|
264
|
+
type: "text",
|
|
265
265
|
inputMode: "decimal",
|
|
266
|
-
step: "0.01",
|
|
267
266
|
value: normalized,
|
|
268
267
|
onChange: (event) => setValue(event.target.value),
|
|
269
268
|
placeholder: "0.00"
|
|
@@ -397,10 +396,14 @@ function PaymentDialog({
|
|
|
397
396
|
const handleSubmit = React.useCallback(
|
|
398
397
|
async (values) => {
|
|
399
398
|
const resolvedCurrency = currencyCode ? currencyCode.toUpperCase() : "";
|
|
400
|
-
const amountValue =
|
|
399
|
+
const amountValue = parseAmountInput(values.amount, locale);
|
|
401
400
|
if (!resolvedCurrency.trim()) {
|
|
402
401
|
throw createCrudFormError(t("sales.documents.payments.currencyRequired", "Currency is required."));
|
|
403
402
|
}
|
|
403
|
+
if (amountValue === null) {
|
|
404
|
+
const message = t("sales.documents.payments.amountInvalid", "Enter the amount as a number.");
|
|
405
|
+
throw createCrudFormError(message, { amount: message });
|
|
406
|
+
}
|
|
404
407
|
if (amountValue <= 0) {
|
|
405
408
|
throw createCrudFormError(t("sales.documents.payments.amountRequired", "Enter a positive amount."), {
|
|
406
409
|
amount: t("sales.documents.payments.amountRequired", "Enter a positive amount.")
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../../src/modules/sales/components/documents/PaymentDialog.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { CreditCard } from 'lucide-react'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { LookupSelect, type LookupSelectItem } from '@open-mercato/ui/backend/inputs'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { createCrud, updateCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { handleSectionMutationError } from './optimisticLock'\nimport { Dialog, DialogContent, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { E } from '#generated/entities.ids.generated'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { normalizeCustomFieldSubmitValue, extractCustomFieldValues } from './customFieldHelpers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sales')\n\nexport type PaymentTotals = {\n paidTotalAmount?: number | null\n refundedTotalAmount?: number | null\n outstandingAmount?: number | null\n}\n\nexport type PaymentFormData = {\n id?: string | null\n updatedAt?: string | null\n amount?: number | string | null\n paymentMethodId?: string | null\n paymentReference?: string | null\n receivedAt?: string | null\n currencyCode?: string | null\n statusEntryId?: string | null\n customValues?: Record<string, unknown> | null\n customFieldSetId?: string | null\n}\n\ntype PaymentMethodOption = {\n id: string\n name: string\n code: string\n}\n\ntype StatusOption = {\n id: string\n value: string\n label: string\n color: string | null\n}\n\ntype PaymentDialogProps = {\n open: boolean\n mode: 'create' | 'edit'\n payment?: PaymentFormData | null\n currencyCode: string | null | undefined\n orderId: string\n organizationId: string | null\n tenantId: string | null\n documentUpdatedAt?: string | null\n onOpenChange: (open: boolean) => void\n onSaved?: (totals?: PaymentTotals | null) => void | Promise<void>\n}\n\nconst normalizeNumber = (value: unknown): number => {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (!Number.isNaN(parsed)) return parsed\n }\n return 0\n}\n\nexport function PaymentDialog({\n open,\n mode,\n payment,\n currencyCode,\n orderId,\n organizationId,\n tenantId,\n documentUpdatedAt,\n onOpenChange,\n onSaved,\n}: PaymentDialogProps) {\n const t = useT()\n const dialogContentRef = React.useRef<HTMLDivElement | null>(null)\n const [formResetKey, setFormResetKey] = React.useState(0)\n const [paymentMethods, setPaymentMethods] = React.useState<PaymentMethodOption[]>([])\n const [methodsLoading, setMethodsLoading] = React.useState(false)\n const [paymentStatuses, setPaymentStatuses] = React.useState<StatusOption[]>([])\n const [paymentStatusLoading, setPaymentStatusLoading] = React.useState(false)\n const [documentStatuses, setDocumentStatuses] = React.useState<StatusOption[]>([])\n const [documentStatusLoading, setDocumentStatusLoading] = React.useState(false)\n\n const currencyLabel = React.useMemo(() => {\n const code = currencyCode ? currencyCode.toUpperCase() : ''\n if (!code) return t('sales.documents.detail.empty', 'Not set')\n return code\n }, [currencyCode, t])\n\n const initialValues = React.useMemo(\n () => ({\n amount: payment?.amount ?? '',\n paymentMethodId: payment?.paymentMethodId ?? '',\n paymentReference: payment?.paymentReference ?? '',\n receivedAt: payment?.receivedAt ? payment.receivedAt.slice(0, 10) : '',\n statusEntryId: payment?.statusEntryId ?? '',\n documentStatusEntryId: '',\n customFieldSetId: payment?.customFieldSetId ?? '',\n ...extractCustomFieldValues(payment),\n }),\n [\n payment?.amount,\n payment?.customFieldSetId,\n payment?.customValues,\n payment?.paymentMethodId,\n payment?.paymentReference,\n payment?.receivedAt,\n payment?.statusEntryId,\n ],\n )\n\n const loadPaymentMethods = React.useCallback(\n async (query?: string): Promise<PaymentMethodOption[]> => {\n setMethodsLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100', isActive: 'true' })\n if (query && query.trim().length) params.set('search', query.trim())\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/payment-methods?${params.toString()}`,\n undefined,\n { fallback: { items: [] } }\n )\n if (response.ok && Array.isArray(response.result?.items)) {\n const options = response.result.items\n .map((item) => {\n const id = typeof item.id === 'string' ? item.id : null\n if (!id) return null\n const name = typeof item.name === 'string' ? item.name : null\n const code = typeof item.code === 'string' ? item.code : null\n return {\n id,\n name: name ?? code ?? id,\n code: code ?? id,\n }\n })\n .filter((entry): entry is PaymentMethodOption => !!entry)\n if (!query) setPaymentMethods(options)\n return options\n }\n if (!query) setPaymentMethods([])\n return []\n } catch (err) {\n logger.error('sales.payments.methods.load', { err })\n return []\n } finally {\n setMethodsLoading(false)\n }\n },\n []\n )\n\n const fetchPaymentMethodItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n paymentMethods.length && !query\n ? paymentMethods\n : await loadPaymentMethods(query)\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.name.toLowerCase().includes(term) ||\n option.code.toLowerCase().includes(term)\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.name,\n subtitle: option.code,\n icon: <CreditCard className=\"h-4 w-4 text-muted-foreground\" />,\n }))\n },\n [loadPaymentMethods, paymentMethods]\n )\n\n const shortcutLabel = t('sales.documents.payments.saveShortcut', 'Save \u2318\u23CE / Ctrl+Enter')\n const renderStatusIcon = React.useCallback(\n (color?: string | null) => (\n <span\n className=\"h-2.5 w-2.5 rounded-full border border-border/70\"\n style={color ? { backgroundColor: color, borderColor: color } : undefined}\n />\n ),\n [],\n )\n\n const loadDocumentStatuses = React.useCallback(async (): Promise<StatusOption[]> => {\n setDocumentStatusLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100' })\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/order-statuses?${params.toString()}`,\n undefined,\n { fallback: { items: [] } },\n )\n const items = Array.isArray(response.result?.items) ? response.result.items : []\n const mapped = items\n .map((entry) => {\n const id = typeof entry.id === 'string' ? entry.id : null\n const value = typeof entry.value === 'string' ? entry.value : null\n if (!id || !value) return null\n const label =\n typeof entry.label === 'string' && entry.label.trim().length\n ? entry.label\n : value\n const color =\n typeof entry.color === 'string' && entry.color.trim().length ? entry.color : null\n return { id, value, label, color }\n })\n .filter((entry): entry is StatusOption => Boolean(entry))\n setDocumentStatuses(mapped)\n return mapped\n } catch (err) {\n logger.error('sales.payments.statuses.load', { err })\n setDocumentStatuses([])\n return []\n } finally {\n setDocumentStatusLoading(false)\n }\n }, [])\n\n const loadPaymentStatuses = React.useCallback(async (): Promise<StatusOption[]> => {\n setPaymentStatusLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100' })\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/payment-statuses?${params.toString()}`,\n undefined,\n { fallback: { items: [] } },\n )\n const items = Array.isArray(response.result?.items) ? response.result.items : []\n const mapped = items\n .map((entry) => {\n const id = typeof entry.id === 'string' ? entry.id : null\n const value = typeof entry.value === 'string' ? entry.value : null\n if (!id || !value) return null\n const label =\n typeof entry.label === 'string' && entry.label.trim().length\n ? entry.label\n : value\n const color =\n typeof entry.color === 'string' && entry.color.trim().length ? entry.color : null\n return { id, value, label, color }\n })\n .filter((entry): entry is StatusOption => Boolean(entry))\n setPaymentStatuses(mapped)\n return mapped\n } catch (err) {\n logger.error('sales.payments.statuses.load', { err })\n setPaymentStatuses([])\n return []\n } finally {\n setPaymentStatusLoading(false)\n }\n }, [])\n\n React.useEffect(() => {\n if (!open) return\n setFormResetKey((prev) => prev + 1)\n if (!paymentMethods.length) {\n void loadPaymentMethods()\n }\n if (!paymentStatuses.length) {\n void loadPaymentStatuses()\n }\n if (mode === 'create') {\n if (!documentStatuses.length) {\n void loadDocumentStatuses()\n }\n }\n }, [\n documentStatuses.length,\n loadDocumentStatuses,\n loadPaymentStatuses,\n loadPaymentMethods,\n mode,\n open,\n payment?.id,\n paymentStatuses.length,\n paymentMethods.length,\n ])\n\n const fetchDocumentStatusItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n documentStatuses.length && !query ? documentStatuses : await loadDocumentStatuses()\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.label.toLowerCase().includes(term) ||\n option.value.toLowerCase().includes(term),\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.label,\n subtitle: option.value,\n icon: renderStatusIcon(option.color),\n }))\n },\n [documentStatuses, loadDocumentStatuses, renderStatusIcon],\n )\n\n const fetchPaymentStatusItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n paymentStatuses.length && !query ? paymentStatuses : await loadPaymentStatuses()\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.label.toLowerCase().includes(term) ||\n option.value.toLowerCase().includes(term),\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.label,\n subtitle: option.value,\n icon: renderStatusIcon(option.color),\n }))\n },\n [loadPaymentStatuses, paymentStatuses, renderStatusIcon],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => [\n {\n id: 'amount',\n label: t('sales.documents.payments.amount', 'Amount'),\n type: 'custom',\n required: true,\n component: ({ value, setValue }) => {\n const normalized = typeof value === 'number' ? value : typeof value === 'string' ? value : ''\n return (\n <div className=\"flex items-center gap-2\">\n <Input\n type=\"number\"\n inputMode=\"decimal\"\n step=\"0.01\"\n value={normalized as string | number}\n onChange={(event) => setValue(event.target.value)}\n placeholder=\"0.00\"\n />\n <span className=\"rounded-full border border-border/70 bg-muted/50 px-3 py-1 text-xs font-semibold uppercase text-foreground\">\n {currencyLabel}\n </span>\n </div>\n )\n },\n },\n {\n id: 'paymentMethodId',\n label: t('sales.documents.payments.method', 'Method'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchPaymentMethodItems}\n searchPlaceholder={t('sales.documents.payments.methodPlaceholder', 'Search payment method')}\n emptyLabel={t('sales.documents.payments.methodsEmpty', 'No payment methods')}\n loadingLabel={t('sales.documents.payments.loadingMethods', 'Loading payment methods\u2026')}\n selectedHintLabel={(id) =>\n t('sales.documents.payments.methodSelected', 'Selected method: {{id}}', { id })\n }\n minQuery={0}\n />\n )\n },\n },\n {\n id: 'statusEntryId',\n label: t('sales.documents.payments.status', 'Status'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchPaymentStatusItems}\n placeholder={t('sales.documents.payments.statusPlaceholder', 'Select status')}\n loading={paymentStatusLoading}\n minQuery={0}\n />\n )\n },\n },\n ...(mode === 'create'\n ? ([\n {\n id: 'documentStatusEntryId',\n label: t('sales.documents.status.changeDocument', 'Change order/quote status'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchDocumentStatusItems}\n placeholder={t(\n 'sales.documents.status.documentPlaceholder',\n 'Select new order/quote status',\n )}\n loading={documentStatusLoading}\n minQuery={0}\n />\n )\n },\n },\n ] as CrudField[])\n : []),\n {\n id: 'paymentReference',\n label: t('sales.documents.payments.reference', 'Reference'),\n type: 'text',\n placeholder: t('sales.documents.payments.referencePlaceholder', 'External reference or note'),\n },\n {\n id: 'receivedAt',\n label: t('sales.documents.payments.receivedAt', 'Received at'),\n type: 'date',\n },\n ],\n [\n currencyLabel,\n documentStatusLoading,\n fetchPaymentStatusItems,\n fetchDocumentStatusItems,\n fetchPaymentMethodItems,\n paymentStatusLoading,\n mode,\n t,\n ],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => {\n const base: CrudFormGroup[] = [\n {\n id: 'paymentDetails',\n title: t('sales.documents.payments.form.title', 'Payment details'),\n column: 1,\n fields: ['amount', 'paymentMethodId', 'statusEntryId'],\n },\n ]\n if (mode === 'create') {\n base.push({\n id: 'statusChanges',\n title: t('sales.documents.status.sectionTitle', 'Status changes'),\n column: 1,\n fields: ['documentStatusEntryId'],\n })\n }\n base.push({\n id: 'paymentReference',\n title: t('sales.documents.payments.reference', 'Reference'),\n column: 2,\n fields: ['paymentReference', 'receivedAt'],\n })\n base.push({\n id: 'paymentCustomFields',\n title: t('entities.customFields.title', 'Custom fields'),\n column: 2,\n kind: 'customFields',\n })\n return base\n },\n [mode, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: Record<string, unknown>) => {\n const resolvedCurrency = currencyCode ? currencyCode.toUpperCase() : ''\n const amountValue = normalizeNumber(values.amount)\n if (!resolvedCurrency.trim()) {\n throw createCrudFormError(t('sales.documents.payments.currencyRequired', 'Currency is required.'))\n }\n if (amountValue <= 0) {\n throw createCrudFormError(t('sales.documents.payments.amountRequired', 'Enter a positive amount.'), {\n amount: t('sales.documents.payments.amountRequired', 'Enter a positive amount.'),\n })\n }\n\n const payload: Record<string, unknown> = {\n orderId,\n amount: amountValue,\n currencyCode: resolvedCurrency,\n paymentReference:\n typeof values.paymentReference === 'string' && values.paymentReference.trim().length\n ? values.paymentReference.trim()\n : undefined,\n paymentMethodId:\n typeof values.paymentMethodId === 'string' && values.paymentMethodId.trim().length\n ? values.paymentMethodId\n : undefined,\n statusEntryId:\n typeof values.statusEntryId === 'string' && values.statusEntryId.trim().length\n ? values.statusEntryId\n : undefined,\n customFieldSetId:\n typeof values.customFieldSetId === 'string' && values.customFieldSetId.trim().length\n ? values.customFieldSetId.trim()\n : undefined,\n organizationId: organizationId ?? undefined,\n tenantId: tenantId ?? undefined,\n }\n const documentStatusEntryId =\n typeof values.documentStatusEntryId === 'string' && values.documentStatusEntryId.trim().length\n ? values.documentStatusEntryId\n : null\n if (documentStatusEntryId) {\n payload.documentStatusEntryId = documentStatusEntryId\n }\n if (typeof values.receivedAt === 'string' && values.receivedAt.trim().length) {\n payload.receivedAt = new Date(values.receivedAt)\n }\n const customFields = collectCustomFieldValues(values, {\n transform: normalizeCustomFieldSubmitValue,\n })\n if (Object.keys(customFields).length) payload.customFields = customFields\n\n const action = payment?.id ? updateCrud : createCrud\n try {\n const result = await withScopedApiRequestHeaders(\n // The server guards the PARENT order's aggregate version (Gap A) for\n // both create and update, so send the order's `updated_at`.\n buildOptimisticLockHeader(documentUpdatedAt ?? undefined),\n () =>\n action(\n 'sales/payments',\n payment?.id ? { id: payment.id, ...payload } : payload,\n {\n errorMessage: t('sales.documents.payments.errorSave', 'Failed to save payment.'),\n }\n )\n )\n if (result.ok) {\n const totals = (result.result as any)?.orderTotals as PaymentTotals | undefined\n if (onSaved) {\n await onSaved(totals ?? null)\n }\n setFormResetKey((prev) => prev + 1)\n onOpenChange(false)\n }\n } catch (err) {\n if (\n handleSectionMutationError(err, t, () => {\n if (onSaved) void onSaved()\n })\n ) {\n onOpenChange(false)\n return\n }\n throw err\n }\n },\n [currencyCode, documentUpdatedAt, mode, onOpenChange, onSaved, orderId, organizationId, payment?.id, t, tenantId]\n )\n\n const handleSubmitForm = React.useCallback(\n () => dialogContentRef.current?.querySelector('form')?.requestSubmit(),\n [],\n )\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: handleSubmitForm,\n onCancel: () => onOpenChange(false),\n })\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n ref={dialogContentRef}\n className=\"sm:max-w-5xl\"\n onKeyDown={handleKeyDown}\n >\n <DialogHeader>\n <DialogTitle>\n {mode === 'edit'\n ? t('sales.documents.payments.edit', 'Edit payment')\n : t('sales.documents.payments.add', 'Add payment')}\n </DialogTitle>\n </DialogHeader>\n <CrudForm\n key={formResetKey}\n embedded\n entityId={E.sales.sales_payment}\n fields={fields}\n groups={groups}\n initialValues={initialValues}\n customFieldsetBindings={{ [E.sales.sales_payment]: { valueKey: 'customFieldSetId' } }}\n submitLabel={shortcutLabel}\n onSubmit={handleSubmit}\n loadingMessage={t('sales.documents.payments.loading', 'Loading payments\u2026')}\n customFieldsLoadingMessage={t('ui.forms.loading', 'Loading data...')}\n contentHeader={\n methodsLoading ? (\n <p className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <Spinner className=\"h-3.5 w-3.5 animate-spin\" />\n {t('sales.documents.payments.loadingMethods', 'Loading payment methods\u2026')}\n </p>\n ) : null\n }\n />\n </DialogContent>\n </Dialog>\n )\n}\n"],
|
|
5
|
-
"mappings": ";AAyLgB,cAuKJ,YAvKI;AAvLhB,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAC3B,SAAS,gBAAoD;AAC7D,SAAS,oBAA2C;AACpD,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,gCAAgC;AACzC,SAAS,YAAY,kBAAkB;AACvC,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,QAAQ,eAAe,cAAc,mBAAmB;AACjE,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,SAAS;AAClB,SAAS,YAAY;AACrB,SAAS,iCAAiC,gCAAgC;AAC1E,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,OAAO;AA+CnC,MAAM,kBAAkB,CAAC,UAA2B;AAClD,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,YAAY,MAA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,CAAC;AAAA,EACH;AACA,QAAM,gBAAgB,oBAAoB;AAAA,IACxC,WAAW;AAAA,IACX,UAAU,MAAM,aAAa,KAAK;AAAA,EACpC,CAAC;AAED,SACE,oBAAC,UAAO,MAAY,cAClB;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,WAAU;AAAA,MACV,WAAW;AAAA,MAEX;AAAA,4BAAC,gBACC,8BAAC,eACE,mBAAS,SACN,EAAE,iCAAiC,cAAc,IACjD,EAAE,gCAAgC,aAAa,GACrD,GACF;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YAEC,UAAQ;AAAA,YACR,UAAU,EAAE,MAAM;AAAA,YAClB;AAAA,YACA;AAAA,YACA;AAAA,YACA,wBAAwB,EAAE,CAAC,EAAE,MAAM,aAAa,GAAG,EAAE,UAAU,mBAAmB,EAAE;AAAA,YACpF,aAAa;AAAA,YACb,UAAU;AAAA,YACV,gBAAgB,EAAE,oCAAoC,wBAAmB;AAAA,YACzE,4BAA4B,EAAE,oBAAoB,iBAAiB;AAAA,YACnE,eACE,iBACE,qBAAC,OAAE,WAAU,yDACX;AAAA,kCAAC,WAAQ,WAAU,4BAA2B;AAAA,cAC7C,EAAE,2CAA2C,+BAA0B;AAAA,eAC1E,IACE;AAAA;AAAA,UAjBD;AAAA,QAmBP;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;",
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { CreditCard } from 'lucide-react'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { LookupSelect, type LookupSelectItem } from '@open-mercato/ui/backend/inputs'\nimport { apiCall, withScopedApiRequestHeaders } from '@open-mercato/ui/backend/utils/apiCall'\nimport { buildOptimisticLockHeader } from '@open-mercato/ui/backend/utils/optimisticLock'\nimport { collectCustomFieldValues } from '@open-mercato/ui/backend/utils/customFieldValues'\nimport { createCrud, updateCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { handleSectionMutationError } from './optimisticLock'\nimport { Dialog, DialogContent, DialogHeader, DialogTitle } from '@open-mercato/ui/primitives/dialog'\nimport { useDialogKeyHandler } from '@open-mercato/ui/hooks/useDialogKeyHandler'\nimport { Input } from '@open-mercato/ui/primitives/input'\nimport { Spinner } from '@open-mercato/ui/primitives/spinner'\nimport { E } from '#generated/entities.ids.generated'\nimport { useT, useLocale } from '@open-mercato/shared/lib/i18n/context'\nimport { parseLocaleNumber } from '@open-mercato/shared/lib/number'\nimport { normalizeCustomFieldSubmitValue, extractCustomFieldValues } from './customFieldHelpers'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('sales')\n\nexport type PaymentTotals = {\n paidTotalAmount?: number | null\n refundedTotalAmount?: number | null\n outstandingAmount?: number | null\n}\n\nexport type PaymentFormData = {\n id?: string | null\n updatedAt?: string | null\n amount?: number | string | null\n paymentMethodId?: string | null\n paymentReference?: string | null\n receivedAt?: string | null\n currencyCode?: string | null\n statusEntryId?: string | null\n customValues?: Record<string, unknown> | null\n customFieldSetId?: string | null\n}\n\ntype PaymentMethodOption = {\n id: string\n name: string\n code: string\n}\n\ntype StatusOption = {\n id: string\n value: string\n label: string\n color: string | null\n}\n\ntype PaymentDialogProps = {\n open: boolean\n mode: 'create' | 'edit'\n payment?: PaymentFormData | null\n currencyCode: string | null | undefined\n orderId: string\n organizationId: string | null\n tenantId: string | null\n documentUpdatedAt?: string | null\n onOpenChange: (open: boolean) => void\n onSaved?: (totals?: PaymentTotals | null) => void | Promise<void>\n}\n\n// The amount field is a hand-rolled text input, so the raw string a user typed reaches\n// the submit handler carrying the separator the surrounding UI displays \u2014 `110,70` under\n// Polish (issue #5828, same defect class as #5552). A blank/absent value keeps the old\n// \"must be a positive amount\" message; only genuinely unparseable input returns null.\nconst parseAmountInput = (value: unknown, locale?: string): number | null => {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value !== 'string') return 0\n if (!value.trim()) return 0\n return parseLocaleNumber(value, locale)\n}\n\nexport function PaymentDialog({\n open,\n mode,\n payment,\n currencyCode,\n orderId,\n organizationId,\n tenantId,\n documentUpdatedAt,\n onOpenChange,\n onSaved,\n}: PaymentDialogProps) {\n const t = useT()\n const locale = useLocale()\n const dialogContentRef = React.useRef<HTMLDivElement | null>(null)\n const [formResetKey, setFormResetKey] = React.useState(0)\n const [paymentMethods, setPaymentMethods] = React.useState<PaymentMethodOption[]>([])\n const [methodsLoading, setMethodsLoading] = React.useState(false)\n const [paymentStatuses, setPaymentStatuses] = React.useState<StatusOption[]>([])\n const [paymentStatusLoading, setPaymentStatusLoading] = React.useState(false)\n const [documentStatuses, setDocumentStatuses] = React.useState<StatusOption[]>([])\n const [documentStatusLoading, setDocumentStatusLoading] = React.useState(false)\n\n const currencyLabel = React.useMemo(() => {\n const code = currencyCode ? currencyCode.toUpperCase() : ''\n if (!code) return t('sales.documents.detail.empty', 'Not set')\n return code\n }, [currencyCode, t])\n\n const initialValues = React.useMemo(\n () => ({\n amount: payment?.amount ?? '',\n paymentMethodId: payment?.paymentMethodId ?? '',\n paymentReference: payment?.paymentReference ?? '',\n receivedAt: payment?.receivedAt ? payment.receivedAt.slice(0, 10) : '',\n statusEntryId: payment?.statusEntryId ?? '',\n documentStatusEntryId: '',\n customFieldSetId: payment?.customFieldSetId ?? '',\n ...extractCustomFieldValues(payment),\n }),\n [\n payment?.amount,\n payment?.customFieldSetId,\n payment?.customValues,\n payment?.paymentMethodId,\n payment?.paymentReference,\n payment?.receivedAt,\n payment?.statusEntryId,\n ],\n )\n\n const loadPaymentMethods = React.useCallback(\n async (query?: string): Promise<PaymentMethodOption[]> => {\n setMethodsLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100', isActive: 'true' })\n if (query && query.trim().length) params.set('search', query.trim())\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/payment-methods?${params.toString()}`,\n undefined,\n { fallback: { items: [] } }\n )\n if (response.ok && Array.isArray(response.result?.items)) {\n const options = response.result.items\n .map((item) => {\n const id = typeof item.id === 'string' ? item.id : null\n if (!id) return null\n const name = typeof item.name === 'string' ? item.name : null\n const code = typeof item.code === 'string' ? item.code : null\n return {\n id,\n name: name ?? code ?? id,\n code: code ?? id,\n }\n })\n .filter((entry): entry is PaymentMethodOption => !!entry)\n if (!query) setPaymentMethods(options)\n return options\n }\n if (!query) setPaymentMethods([])\n return []\n } catch (err) {\n logger.error('sales.payments.methods.load', { err })\n return []\n } finally {\n setMethodsLoading(false)\n }\n },\n []\n )\n\n const fetchPaymentMethodItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n paymentMethods.length && !query\n ? paymentMethods\n : await loadPaymentMethods(query)\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.name.toLowerCase().includes(term) ||\n option.code.toLowerCase().includes(term)\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.name,\n subtitle: option.code,\n icon: <CreditCard className=\"h-4 w-4 text-muted-foreground\" />,\n }))\n },\n [loadPaymentMethods, paymentMethods]\n )\n\n const shortcutLabel = t('sales.documents.payments.saveShortcut', 'Save \u2318\u23CE / Ctrl+Enter')\n const renderStatusIcon = React.useCallback(\n (color?: string | null) => (\n <span\n className=\"h-2.5 w-2.5 rounded-full border border-border/70\"\n style={color ? { backgroundColor: color, borderColor: color } : undefined}\n />\n ),\n [],\n )\n\n const loadDocumentStatuses = React.useCallback(async (): Promise<StatusOption[]> => {\n setDocumentStatusLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100' })\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/order-statuses?${params.toString()}`,\n undefined,\n { fallback: { items: [] } },\n )\n const items = Array.isArray(response.result?.items) ? response.result.items : []\n const mapped = items\n .map((entry) => {\n const id = typeof entry.id === 'string' ? entry.id : null\n const value = typeof entry.value === 'string' ? entry.value : null\n if (!id || !value) return null\n const label =\n typeof entry.label === 'string' && entry.label.trim().length\n ? entry.label\n : value\n const color =\n typeof entry.color === 'string' && entry.color.trim().length ? entry.color : null\n return { id, value, label, color }\n })\n .filter((entry): entry is StatusOption => Boolean(entry))\n setDocumentStatuses(mapped)\n return mapped\n } catch (err) {\n logger.error('sales.payments.statuses.load', { err })\n setDocumentStatuses([])\n return []\n } finally {\n setDocumentStatusLoading(false)\n }\n }, [])\n\n const loadPaymentStatuses = React.useCallback(async (): Promise<StatusOption[]> => {\n setPaymentStatusLoading(true)\n try {\n const params = new URLSearchParams({ page: '1', pageSize: '100' })\n const response = await apiCall<{ items?: Array<Record<string, unknown>> }>(\n `/api/sales/payment-statuses?${params.toString()}`,\n undefined,\n { fallback: { items: [] } },\n )\n const items = Array.isArray(response.result?.items) ? response.result.items : []\n const mapped = items\n .map((entry) => {\n const id = typeof entry.id === 'string' ? entry.id : null\n const value = typeof entry.value === 'string' ? entry.value : null\n if (!id || !value) return null\n const label =\n typeof entry.label === 'string' && entry.label.trim().length\n ? entry.label\n : value\n const color =\n typeof entry.color === 'string' && entry.color.trim().length ? entry.color : null\n return { id, value, label, color }\n })\n .filter((entry): entry is StatusOption => Boolean(entry))\n setPaymentStatuses(mapped)\n return mapped\n } catch (err) {\n logger.error('sales.payments.statuses.load', { err })\n setPaymentStatuses([])\n return []\n } finally {\n setPaymentStatusLoading(false)\n }\n }, [])\n\n React.useEffect(() => {\n if (!open) return\n setFormResetKey((prev) => prev + 1)\n if (!paymentMethods.length) {\n void loadPaymentMethods()\n }\n if (!paymentStatuses.length) {\n void loadPaymentStatuses()\n }\n if (mode === 'create') {\n if (!documentStatuses.length) {\n void loadDocumentStatuses()\n }\n }\n }, [\n documentStatuses.length,\n loadDocumentStatuses,\n loadPaymentStatuses,\n loadPaymentMethods,\n mode,\n open,\n payment?.id,\n paymentStatuses.length,\n paymentMethods.length,\n ])\n\n const fetchDocumentStatusItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n documentStatuses.length && !query ? documentStatuses : await loadDocumentStatuses()\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.label.toLowerCase().includes(term) ||\n option.value.toLowerCase().includes(term),\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.label,\n subtitle: option.value,\n icon: renderStatusIcon(option.color),\n }))\n },\n [documentStatuses, loadDocumentStatuses, renderStatusIcon],\n )\n\n const fetchPaymentStatusItems = React.useCallback(\n async (query?: string): Promise<LookupSelectItem[]> => {\n const options =\n paymentStatuses.length && !query ? paymentStatuses : await loadPaymentStatuses()\n const term = query?.trim().toLowerCase() ?? ''\n return options\n .filter(\n (option) =>\n !term.length ||\n option.label.toLowerCase().includes(term) ||\n option.value.toLowerCase().includes(term),\n )\n .map<LookupSelectItem>((option) => ({\n id: option.id,\n title: option.label,\n subtitle: option.value,\n icon: renderStatusIcon(option.color),\n }))\n },\n [loadPaymentStatuses, paymentStatuses, renderStatusIcon],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => [\n {\n id: 'amount',\n label: t('sales.documents.payments.amount', 'Amount'),\n type: 'custom',\n required: true,\n component: ({ value, setValue }) => {\n const normalized = typeof value === 'number' ? value : typeof value === 'string' ? value : ''\n return (\n <div className=\"flex items-center gap-2\">\n <Input\n type=\"text\"\n inputMode=\"decimal\"\n value={normalized as string | number}\n onChange={(event) => setValue(event.target.value)}\n placeholder=\"0.00\"\n />\n <span className=\"rounded-full border border-border/70 bg-muted/50 px-3 py-1 text-xs font-semibold uppercase text-foreground\">\n {currencyLabel}\n </span>\n </div>\n )\n },\n },\n {\n id: 'paymentMethodId',\n label: t('sales.documents.payments.method', 'Method'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchPaymentMethodItems}\n searchPlaceholder={t('sales.documents.payments.methodPlaceholder', 'Search payment method')}\n emptyLabel={t('sales.documents.payments.methodsEmpty', 'No payment methods')}\n loadingLabel={t('sales.documents.payments.loadingMethods', 'Loading payment methods\u2026')}\n selectedHintLabel={(id) =>\n t('sales.documents.payments.methodSelected', 'Selected method: {{id}}', { id })\n }\n minQuery={0}\n />\n )\n },\n },\n {\n id: 'statusEntryId',\n label: t('sales.documents.payments.status', 'Status'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchPaymentStatusItems}\n placeholder={t('sales.documents.payments.statusPlaceholder', 'Select status')}\n loading={paymentStatusLoading}\n minQuery={0}\n />\n )\n },\n },\n ...(mode === 'create'\n ? ([\n {\n id: 'documentStatusEntryId',\n label: t('sales.documents.status.changeDocument', 'Change order/quote status'),\n type: 'custom',\n component: ({ value, setValue }) => {\n const currentValue = typeof value === 'string' && value.length ? value : null\n return (\n <LookupSelect\n value={currentValue}\n onChange={(next) => setValue(next ?? '')}\n fetchItems={fetchDocumentStatusItems}\n placeholder={t(\n 'sales.documents.status.documentPlaceholder',\n 'Select new order/quote status',\n )}\n loading={documentStatusLoading}\n minQuery={0}\n />\n )\n },\n },\n ] as CrudField[])\n : []),\n {\n id: 'paymentReference',\n label: t('sales.documents.payments.reference', 'Reference'),\n type: 'text',\n placeholder: t('sales.documents.payments.referencePlaceholder', 'External reference or note'),\n },\n {\n id: 'receivedAt',\n label: t('sales.documents.payments.receivedAt', 'Received at'),\n type: 'date',\n },\n ],\n [\n currencyLabel,\n documentStatusLoading,\n fetchPaymentStatusItems,\n fetchDocumentStatusItems,\n fetchPaymentMethodItems,\n paymentStatusLoading,\n mode,\n t,\n ],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => {\n const base: CrudFormGroup[] = [\n {\n id: 'paymentDetails',\n title: t('sales.documents.payments.form.title', 'Payment details'),\n column: 1,\n fields: ['amount', 'paymentMethodId', 'statusEntryId'],\n },\n ]\n if (mode === 'create') {\n base.push({\n id: 'statusChanges',\n title: t('sales.documents.status.sectionTitle', 'Status changes'),\n column: 1,\n fields: ['documentStatusEntryId'],\n })\n }\n base.push({\n id: 'paymentReference',\n title: t('sales.documents.payments.reference', 'Reference'),\n column: 2,\n fields: ['paymentReference', 'receivedAt'],\n })\n base.push({\n id: 'paymentCustomFields',\n title: t('entities.customFields.title', 'Custom fields'),\n column: 2,\n kind: 'customFields',\n })\n return base\n },\n [mode, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: Record<string, unknown>) => {\n const resolvedCurrency = currencyCode ? currencyCode.toUpperCase() : ''\n const amountValue = parseAmountInput(values.amount, locale)\n if (!resolvedCurrency.trim()) {\n throw createCrudFormError(t('sales.documents.payments.currencyRequired', 'Currency is required.'))\n }\n if (amountValue === null) {\n const message = t('sales.documents.payments.amountInvalid', 'Enter the amount as a number.')\n throw createCrudFormError(message, { amount: message })\n }\n if (amountValue <= 0) {\n throw createCrudFormError(t('sales.documents.payments.amountRequired', 'Enter a positive amount.'), {\n amount: t('sales.documents.payments.amountRequired', 'Enter a positive amount.'),\n })\n }\n\n const payload: Record<string, unknown> = {\n orderId,\n amount: amountValue,\n currencyCode: resolvedCurrency,\n paymentReference:\n typeof values.paymentReference === 'string' && values.paymentReference.trim().length\n ? values.paymentReference.trim()\n : undefined,\n paymentMethodId:\n typeof values.paymentMethodId === 'string' && values.paymentMethodId.trim().length\n ? values.paymentMethodId\n : undefined,\n statusEntryId:\n typeof values.statusEntryId === 'string' && values.statusEntryId.trim().length\n ? values.statusEntryId\n : undefined,\n customFieldSetId:\n typeof values.customFieldSetId === 'string' && values.customFieldSetId.trim().length\n ? values.customFieldSetId.trim()\n : undefined,\n organizationId: organizationId ?? undefined,\n tenantId: tenantId ?? undefined,\n }\n const documentStatusEntryId =\n typeof values.documentStatusEntryId === 'string' && values.documentStatusEntryId.trim().length\n ? values.documentStatusEntryId\n : null\n if (documentStatusEntryId) {\n payload.documentStatusEntryId = documentStatusEntryId\n }\n if (typeof values.receivedAt === 'string' && values.receivedAt.trim().length) {\n payload.receivedAt = new Date(values.receivedAt)\n }\n const customFields = collectCustomFieldValues(values, {\n transform: normalizeCustomFieldSubmitValue,\n })\n if (Object.keys(customFields).length) payload.customFields = customFields\n\n const action = payment?.id ? updateCrud : createCrud\n try {\n const result = await withScopedApiRequestHeaders(\n // The server guards the PARENT order's aggregate version (Gap A) for\n // both create and update, so send the order's `updated_at`.\n buildOptimisticLockHeader(documentUpdatedAt ?? undefined),\n () =>\n action(\n 'sales/payments',\n payment?.id ? { id: payment.id, ...payload } : payload,\n {\n errorMessage: t('sales.documents.payments.errorSave', 'Failed to save payment.'),\n }\n )\n )\n if (result.ok) {\n const totals = (result.result as any)?.orderTotals as PaymentTotals | undefined\n if (onSaved) {\n await onSaved(totals ?? null)\n }\n setFormResetKey((prev) => prev + 1)\n onOpenChange(false)\n }\n } catch (err) {\n if (\n handleSectionMutationError(err, t, () => {\n if (onSaved) void onSaved()\n })\n ) {\n onOpenChange(false)\n return\n }\n throw err\n }\n },\n [currencyCode, documentUpdatedAt, mode, onOpenChange, onSaved, orderId, organizationId, payment?.id, t, tenantId]\n )\n\n const handleSubmitForm = React.useCallback(\n () => dialogContentRef.current?.querySelector('form')?.requestSubmit(),\n [],\n )\n const handleKeyDown = useDialogKeyHandler({\n onConfirm: handleSubmitForm,\n onCancel: () => onOpenChange(false),\n })\n\n return (\n <Dialog open={open} onOpenChange={onOpenChange}>\n <DialogContent\n ref={dialogContentRef}\n className=\"sm:max-w-5xl\"\n onKeyDown={handleKeyDown}\n >\n <DialogHeader>\n <DialogTitle>\n {mode === 'edit'\n ? t('sales.documents.payments.edit', 'Edit payment')\n : t('sales.documents.payments.add', 'Add payment')}\n </DialogTitle>\n </DialogHeader>\n <CrudForm\n key={formResetKey}\n embedded\n entityId={E.sales.sales_payment}\n fields={fields}\n groups={groups}\n initialValues={initialValues}\n customFieldsetBindings={{ [E.sales.sales_payment]: { valueKey: 'customFieldSetId' } }}\n submitLabel={shortcutLabel}\n onSubmit={handleSubmit}\n loadingMessage={t('sales.documents.payments.loading', 'Loading payments\u2026')}\n customFieldsLoadingMessage={t('ui.forms.loading', 'Loading data...')}\n contentHeader={\n methodsLoading ? (\n <p className=\"flex items-center gap-2 text-xs text-muted-foreground\">\n <Spinner className=\"h-3.5 w-3.5 animate-spin\" />\n {t('sales.documents.payments.loadingMethods', 'Loading payment methods\u2026')}\n </p>\n ) : null\n }\n />\n </DialogContent>\n </Dialog>\n )\n}\n"],
|
|
5
|
+
"mappings": ";AA6LgB,cAuKJ,YAvKI;AA3LhB,YAAY,WAAW;AACvB,SAAS,kBAAkB;AAC3B,SAAS,gBAAoD;AAC7D,SAAS,oBAA2C;AACpD,SAAS,SAAS,mCAAmC;AACrD,SAAS,iCAAiC;AAC1C,SAAS,gCAAgC;AACzC,SAAS,YAAY,kBAAkB;AACvC,SAAS,2BAA2B;AACpC,SAAS,kCAAkC;AAC3C,SAAS,QAAQ,eAAe,cAAc,mBAAmB;AACjE,SAAS,2BAA2B;AACpC,SAAS,aAAa;AACtB,SAAS,eAAe;AACxB,SAAS,SAAS;AAClB,SAAS,MAAM,iBAAiB;AAChC,SAAS,yBAAyB;AAClC,SAAS,iCAAiC,gCAAgC;AAC1E,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,OAAO;AAmDnC,MAAM,mBAAmB,CAAC,OAAgB,WAAmC;AAC3E,MAAI,OAAO,UAAU,SAAU,QAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AACvE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,CAAC,MAAM,KAAK,EAAG,QAAO;AAC1B,SAAO,kBAAkB,OAAO,MAAM;AACxC;AAEO,SAAS,cAAc;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA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AAK;AAAA,EACpC,CAAC;AAED,SACE,oBAAC,UAAO,MAAY,cAClB;AAAA,IAAC;AAAA;AAAA,MACC,KAAK;AAAA,MACL,WAAU;AAAA,MACV,WAAW;AAAA,MAEX;AAAA,4BAAC,gBACC,8BAAC,eACE,mBAAS,SACN,EAAE,iCAAiC,cAAc,IACjD,EAAE,gCAAgC,aAAa,GACrD,GACF;AAAA,QACA;AAAA,UAAC;AAAA;AAAA,YAEC,UAAQ;AAAA,YACR,UAAU,EAAE,MAAM;AAAA,YAClB;AAAA,YACA;AAAA,YACA;AAAA,YACA,wBAAwB,EAAE,CAAC,EAAE,MAAM,aAAa,GAAG,EAAE,UAAU,mBAAmB,EAAE;AAAA,YACpF,aAAa;AAAA,YACb,UAAU;AAAA,YACV,gBAAgB,EAAE,oCAAoC,wBAAmB;AAAA,YACzE,4BAA4B,EAAE,oBAAoB,iBAAiB;AAAA,YACnE,eACE,iBACE,qBAAC,OAAE,WAAU,yDACX;AAAA,kCAAC,WAAQ,WAAU,4BAA2B;AAAA,cAC7C,EAAE,2CAA2C,+BAA0B;AAAA,eAC1E,IACE;AAAA;AAAA,UAjBD;AAAA,QAmBP;AAAA;AAAA;AAAA,EACF,GACF;AAEJ;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -10,6 +10,9 @@ function toNumeric(value) {
|
|
|
10
10
|
function mapPersistedLine(line) {
|
|
11
11
|
return {
|
|
12
12
|
id: line.id,
|
|
13
|
+
statusEntryId: line.statusEntryId ?? null,
|
|
14
|
+
catalogSnapshot: line.catalogSnapshot ? cloneJson(line.catalogSnapshot) : null,
|
|
15
|
+
promotionSnapshot: line.promotionSnapshot ? cloneJson(line.promotionSnapshot) : null,
|
|
13
16
|
lineNumber: line.lineNumber,
|
|
14
17
|
kind: line.kind,
|
|
15
18
|
productId: line.productId ?? null,
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../../src/modules/sales/lib/lineSnapshots.ts"],
|
|
4
|
-
"sourcesContent": ["import type { SalesOrderLine, SalesQuoteLine } from '../data/entities'\nimport { cloneJson } from './json'\nimport type { SalesLineDiscountBasis, SalesLineSnapshot } from './types'\n\nfunction toNumeric(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\nfunction mapPersistedLine(line: SalesOrderLine | SalesQuoteLine):
|
|
5
|
-
"mappings": "AACA,SAAS,iBAAiB;AAG1B,SAAS,UAAU,OAAwB;AACzC,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,QAAQ;AACpD,UAAM,SAAS,OAAO,KAAK;AAC3B,QAAI,OAAO,SAAS,MAAM,EAAG,QAAO;AAAA,EACtC;AACA,SAAO;AACT;
|
|
4
|
+
"sourcesContent": ["import type { SalesOrderLine, SalesQuoteLine } from '../data/entities'\nimport { cloneJson } from './json'\nimport type { SalesLineDiscountBasis, SalesLineSnapshot } from './types'\n\nfunction toNumeric(value: unknown): number {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim().length) {\n const parsed = Number(value)\n if (Number.isFinite(parsed)) return parsed\n }\n return 0\n}\n\n/**\n * A snapshot rebuilt from a persisted row, plus the columns the calculation\n * engine never reads but the write paths must carry back to the row.\n *\n * The line upsert, line delete and adjustment write paths all rebuild *every*\n * line of the document from these snapshots and then `Object.assign` the result\n * onto the existing entities. Anything the mapper drops is therefore not merely\n * absent from the calculation \u2014 it is written back as `null` over the stored\n * value of lines the caller never touched (#5911).\n */\nexport type SalesPersistedLineSnapshot = SalesLineSnapshot & {\n statusEntryId: string | null\n catalogSnapshot: Record<string, unknown> | null\n promotionSnapshot: Record<string, unknown> | null\n}\n\nfunction mapPersistedLine(line: SalesOrderLine | SalesQuoteLine): SalesPersistedLineSnapshot {\n return {\n id: line.id,\n statusEntryId: line.statusEntryId ?? null,\n catalogSnapshot: line.catalogSnapshot ? cloneJson(line.catalogSnapshot) : null,\n promotionSnapshot: line.promotionSnapshot ? cloneJson(line.promotionSnapshot) : null,\n lineNumber: line.lineNumber,\n kind: line.kind,\n productId: line.productId ?? null,\n productVariantId: line.productVariantId ?? null,\n name: line.name ?? null,\n description: line.description ?? null,\n comment: line.comment ?? null,\n quantity: toNumeric(line.quantity),\n quantityUnit: line.quantityUnit ?? null,\n normalizedQuantity: toNumeric(line.normalizedQuantity ?? line.quantity),\n normalizedUnit: line.normalizedUnit ?? line.quantityUnit ?? null,\n uomSnapshot: line.uomSnapshot ? cloneJson(line.uomSnapshot) : null,\n currencyCode: line.currencyCode,\n unitPriceNet: toNumeric(line.unitPriceNet),\n unitPriceGross: toNumeric(line.unitPriceGross),\n discountAmount: toNumeric(line.discountAmount),\n // The persisted column holds the discount for the whole line, so the\n // calculation engine must not multiply it out by quantity again. This flag\n // is the only thing standing between a round trip and a compounding\n // re-inflation, and it is why mappers must never set `discountAmountBasis`\n // instead \u2014 that one means \"a caller asserted this\".\n discountAmountFromStoredRow: true,\n discountPercent: toNumeric(line.discountPercent),\n taxRate: toNumeric(line.taxRate),\n taxAmount: toNumeric(line.taxAmount),\n // The totals below are the engine's own previous output read back off the\n // row, not something a caller asserted, so they are not reconciled against\n // the recomputed net (#5644) \u2014 on a legacy row that divergence is the\n // discount contract healing itself, not a caller mistake.\n totalsFromStoredRow: true,\n totalNetAmount: toNumeric(line.totalNetAmount),\n totalGrossAmount: toNumeric(line.totalGrossAmount),\n configuration: line.configuration ? cloneJson(line.configuration) : null,\n promotionCode: line.promotionCode ?? null,\n metadata: line.metadata ? cloneJson(line.metadata) : null,\n customFieldSetId: line.customFieldSetId ?? null,\n }\n}\n\n/**\n * Rebuild a calculation snapshot from a persisted order line.\n *\n * Shared by `commands/documents.ts` and `commands/returns.ts` on purpose: the\n * two files used to carry byte-identical copies, and that duplication is why\n * the return flows kept the discount defect after the order flows were fixed.\n */\nexport function mapOrderLineEntityToSnapshot(line: SalesOrderLine): SalesPersistedLineSnapshot {\n return mapPersistedLine(line)\n}\n\nexport function mapQuoteLineEntityToSnapshot(line: SalesQuoteLine): SalesPersistedLineSnapshot {\n return mapPersistedLine(line)\n}\n\ntype UpsertDiscountFields = Pick<\n SalesLineSnapshot,\n 'discountAmount' | 'discountAmountBasis' | 'discountAmountFromStoredRow'\n>\n\n/**\n * Decide the discount fields of an upsert payload one operand at a time.\n *\n * A line upsert can source its amount from two places with opposite meanings: a\n * caller value, which is per unit unless the caller says otherwise, and the\n * stored row, which is always a line total. Collapsing them into a single\n * `caller ?? stored` expression means whichever origin the merged result is\n * tagged with is wrong half the time \u2014 and the half that breaks is the\n * upsert-existing path, which then re-inflates by a further factor of quantity\n * while looking perfectly correct.\n *\n * Keeping `null` rather than `0` for \"nothing supplied\" is deliberate too: the\n * column cannot represent that distinction, but the payload can, and the\n * calculation engine needs it to tell a suppressing zero from an absent value.\n */\nexport function resolveUpsertDiscountFields(\n callerAmount: number | null | undefined,\n callerBasis: SalesLineDiscountBasis | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'discountAmount'> | null | undefined,\n): UpsertDiscountFields {\n if (callerAmount !== null && callerAmount !== undefined) {\n return { discountAmount: callerAmount, discountAmountBasis: callerBasis ?? 'unit' }\n }\n return {\n discountAmount: existingSnapshot?.discountAmount ?? null,\n discountAmountFromStoredRow: existingSnapshot != null,\n }\n}\n\n/**\n * Decide whether the `totalNetAmount` an upsert payload ends up carrying is a\n * caller assertion or a value that came back off the stored row.\n *\n * The upsert merges caller input over the existing snapshot, so the merged\n * total has two possible origins and only the caller one is worth reconciling\n * against the recomputed net (#5644): a value read back off the row is what the\n * engine itself wrote last time, and on a legacy row it is exactly what\n * recalculation is supposed to heal.\n */\nexport function resolveUpsertTotalsOrigin(\n callerTotalNetAmount: number | null | undefined,\n existingSnapshot: Pick<SalesLineSnapshot, 'totalNetAmount'> | null | undefined,\n): Pick<SalesLineSnapshot, 'totalsFromStoredRow'> {\n if (callerTotalNetAmount !== null && callerTotalNetAmount !== undefined) return {}\n return existingSnapshot != null ? { totalsFromStoredRow: true } : {}\n}\n"],
|
|
5
|
+
"mappings": "AACA,SAAS,iBAAiB;AAG1B,SAAS,UAAU,OAAwB;AACzC,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,QAAQ;AACpD,UAAM,SAAS,OAAO,KAAK;AAC3B,QAAI,OAAO,SAAS,MAAM,EAAG,QAAO;AAAA,EACtC;AACA,SAAO;AACT;AAkBA,SAAS,iBAAiB,MAAmE;AAC3F,SAAO;AAAA,IACL,IAAI,KAAK;AAAA,IACT,eAAe,KAAK,iBAAiB;AAAA,IACrC,iBAAiB,KAAK,kBAAkB,UAAU,KAAK,eAAe,IAAI;AAAA,IAC1E,mBAAmB,KAAK,oBAAoB,UAAU,KAAK,iBAAiB,IAAI;AAAA,IAChF,YAAY,KAAK;AAAA,IACjB,MAAM,KAAK;AAAA,IACX,WAAW,KAAK,aAAa;AAAA,IAC7B,kBAAkB,KAAK,oBAAoB;AAAA,IAC3C,MAAM,KAAK,QAAQ;AAAA,IACnB,aAAa,KAAK,eAAe;AAAA,IACjC,SAAS,KAAK,WAAW;AAAA,IACzB,UAAU,UAAU,KAAK,QAAQ;AAAA,IACjC,cAAc,KAAK,gBAAgB;AAAA,IACnC,oBAAoB,UAAU,KAAK,sBAAsB,KAAK,QAAQ;AAAA,IACtE,gBAAgB,KAAK,kBAAkB,KAAK,gBAAgB;AAAA,IAC5D,aAAa,KAAK,cAAc,UAAU,KAAK,WAAW,IAAI;AAAA,IAC9D,cAAc,KAAK;AAAA,IACnB,cAAc,UAAU,KAAK,YAAY;AAAA,IACzC,gBAAgB,UAAU,KAAK,cAAc;AAAA,IAC7C,gBAAgB,UAAU,KAAK,c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