@open-mercato/core 0.6.7-develop.6553.1.2ec7246e04 → 0.6.7-develop.6566.1.15385fa179

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.
Files changed (143) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/api/partitions/route.js.map +1 -1
  3. package/dist/modules/attachments/lib/reconcileOrganization.js +9 -7
  4. package/dist/modules/attachments/lib/reconcileOrganization.js.map +2 -2
  5. package/dist/modules/catalog/api/products/route.js.map +1 -1
  6. package/dist/modules/customers/api/companies/[id]/people/route.js +2 -2
  7. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  8. package/dist/modules/customers/api/deals/[id]/companies/route.js +2 -2
  9. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  10. package/dist/modules/customers/api/deals/[id]/people/route.js +2 -2
  11. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  12. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +4 -4
  13. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  14. package/dist/modules/customers/api/entity-roles-factory.js +3 -3
  15. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  16. package/dist/modules/customers/api/labels/assign/route.js +2 -2
  17. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  18. package/dist/modules/customers/api/labels/unassign/route.js +2 -2
  19. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  20. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +3 -7
  21. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  22. package/dist/modules/customers/api/people/[id]/companies/context.js +3 -3
  23. package/dist/modules/customers/api/people/[id]/companies/context.js.map +2 -2
  24. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +2 -2
  25. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  26. package/dist/modules/customers/api/todos/route.js +2 -2
  27. package/dist/modules/customers/api/todos/route.js.map +2 -2
  28. package/dist/modules/customers/commands/addresses.js +3 -3
  29. package/dist/modules/customers/commands/addresses.js.map +2 -2
  30. package/dist/modules/customers/commands/comments.js +3 -3
  31. package/dist/modules/customers/commands/comments.js.map +2 -2
  32. package/dist/modules/customers/commands/companies.js +2 -2
  33. package/dist/modules/customers/commands/companies.js.map +2 -2
  34. package/dist/modules/customers/commands/deals.js +3 -3
  35. package/dist/modules/customers/commands/deals.js.map +2 -2
  36. package/dist/modules/customers/commands/dictionaries.js +3 -3
  37. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  38. package/dist/modules/customers/commands/entity-roles.js +3 -3
  39. package/dist/modules/customers/commands/entity-roles.js.map +2 -2
  40. package/dist/modules/customers/commands/interactions.js +6 -6
  41. package/dist/modules/customers/commands/interactions.js.map +2 -2
  42. package/dist/modules/customers/commands/labels.js +7 -7
  43. package/dist/modules/customers/commands/labels.js.map +2 -2
  44. package/dist/modules/customers/commands/people.js +3 -3
  45. package/dist/modules/customers/commands/people.js.map +2 -2
  46. package/dist/modules/customers/commands/personCompanyLinks.js +6 -6
  47. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  48. package/dist/modules/customers/commands/pipeline-stages.js +3 -3
  49. package/dist/modules/customers/commands/pipeline-stages.js.map +2 -2
  50. package/dist/modules/customers/commands/pipelines.js +3 -3
  51. package/dist/modules/customers/commands/pipelines.js.map +2 -2
  52. package/dist/modules/customers/commands/shared.js +3 -3
  53. package/dist/modules/customers/commands/shared.js.map +2 -2
  54. package/dist/modules/customers/commands/tags.js +7 -7
  55. package/dist/modules/customers/commands/tags.js.map +2 -2
  56. package/dist/modules/customers/commands/todos.js +3 -3
  57. package/dist/modules/customers/commands/todos.js.map +2 -2
  58. package/dist/modules/customers/lib/personCompanies.js +4 -4
  59. package/dist/modules/customers/lib/personCompanies.js.map +2 -2
  60. package/dist/modules/perspectives/data/validators.js +4 -0
  61. package/dist/modules/perspectives/data/validators.js.map +2 -2
  62. package/dist/modules/sales/api/notes/route.js +2 -4
  63. package/dist/modules/sales/api/notes/route.js.map +2 -2
  64. package/dist/modules/sales/api/quotes/accept/route.js +2 -2
  65. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  66. package/dist/modules/sales/api/quotes/public/[token]/route.js +3 -7
  67. package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
  68. package/dist/modules/sales/api/quotes/send/route.js +2 -2
  69. package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
  70. package/dist/modules/sales/api/returns/[id]/route.js +2 -2
  71. package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
  72. package/dist/modules/sales/commands/configuration.js +11 -11
  73. package/dist/modules/sales/commands/configuration.js.map +2 -2
  74. package/dist/modules/sales/commands/documentAddresses.js +3 -3
  75. package/dist/modules/sales/commands/documentAddresses.js.map +2 -2
  76. package/dist/modules/sales/commands/documents.js +31 -39
  77. package/dist/modules/sales/commands/documents.js.map +2 -2
  78. package/dist/modules/sales/commands/notes.js +7 -7
  79. package/dist/modules/sales/commands/notes.js.map +2 -2
  80. package/dist/modules/sales/commands/payments.js +2 -2
  81. package/dist/modules/sales/commands/payments.js.map +2 -2
  82. package/dist/modules/sales/commands/returns.js +8 -8
  83. package/dist/modules/sales/commands/returns.js.map +2 -2
  84. package/dist/modules/sales/commands/shared.js +2 -2
  85. package/dist/modules/sales/commands/shared.js.map +2 -2
  86. package/dist/modules/sales/commands/shipments.js +5 -5
  87. package/dist/modules/sales/commands/shipments.js.map +2 -2
  88. package/dist/modules/sales/commands/statuses.js +2 -2
  89. package/dist/modules/sales/commands/statuses.js.map +2 -2
  90. package/dist/modules/sales/commands/tags.js +3 -3
  91. package/dist/modules/sales/commands/tags.js.map +2 -2
  92. package/package.json +8 -8
  93. package/src/modules/attachments/api/partitions/route.ts +1 -1
  94. package/src/modules/attachments/lib/reconcileOrganization.ts +16 -7
  95. package/src/modules/catalog/api/products/route.ts +1 -1
  96. package/src/modules/customer_accounts/i18n/de.json +12 -0
  97. package/src/modules/customer_accounts/i18n/en.json +12 -0
  98. package/src/modules/customer_accounts/i18n/es.json +34 -22
  99. package/src/modules/customer_accounts/i18n/pl.json +32 -20
  100. package/src/modules/customers/api/companies/[id]/people/route.ts +2 -2
  101. package/src/modules/customers/api/deals/[id]/companies/route.ts +2 -2
  102. package/src/modules/customers/api/deals/[id]/people/route.ts +2 -2
  103. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +4 -4
  104. package/src/modules/customers/api/entity-roles-factory.ts +3 -3
  105. package/src/modules/customers/api/labels/assign/route.ts +2 -2
  106. package/src/modules/customers/api/labels/unassign/route.ts +2 -2
  107. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +3 -7
  108. package/src/modules/customers/api/people/[id]/companies/context.ts +3 -3
  109. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +2 -2
  110. package/src/modules/customers/api/todos/route.ts +2 -2
  111. package/src/modules/customers/commands/addresses.ts +3 -3
  112. package/src/modules/customers/commands/comments.ts +3 -3
  113. package/src/modules/customers/commands/companies.ts +2 -2
  114. package/src/modules/customers/commands/deals.ts +3 -3
  115. package/src/modules/customers/commands/dictionaries.ts +3 -3
  116. package/src/modules/customers/commands/entity-roles.ts +3 -3
  117. package/src/modules/customers/commands/interactions.ts +6 -6
  118. package/src/modules/customers/commands/labels.ts +7 -7
  119. package/src/modules/customers/commands/people.ts +3 -3
  120. package/src/modules/customers/commands/personCompanyLinks.ts +6 -6
  121. package/src/modules/customers/commands/pipeline-stages.ts +3 -3
  122. package/src/modules/customers/commands/pipelines.ts +3 -3
  123. package/src/modules/customers/commands/shared.ts +3 -3
  124. package/src/modules/customers/commands/tags.ts +7 -7
  125. package/src/modules/customers/commands/todos.ts +3 -3
  126. package/src/modules/customers/lib/personCompanies.ts +4 -4
  127. package/src/modules/perspectives/data/validators.ts +4 -0
  128. package/src/modules/sales/api/notes/route.ts +2 -4
  129. package/src/modules/sales/api/quotes/accept/route.ts +2 -2
  130. package/src/modules/sales/api/quotes/public/[token]/route.ts +3 -7
  131. package/src/modules/sales/api/quotes/send/route.ts +2 -2
  132. package/src/modules/sales/api/returns/[id]/route.ts +2 -2
  133. package/src/modules/sales/commands/configuration.ts +11 -11
  134. package/src/modules/sales/commands/documentAddresses.ts +3 -3
  135. package/src/modules/sales/commands/documents.ts +23 -31
  136. package/src/modules/sales/commands/notes.ts +7 -7
  137. package/src/modules/sales/commands/payments.ts +2 -2
  138. package/src/modules/sales/commands/returns.ts +8 -8
  139. package/src/modules/sales/commands/shared.ts +2 -2
  140. package/src/modules/sales/commands/shipments.ts +5 -5
  141. package/src/modules/sales/commands/statuses.ts +2 -2
  142. package/src/modules/sales/commands/tags.ts +3 -3
  143. package/tsconfig.json +0 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/deals.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n requireId,\n normalizeAuthorUserId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { runCrudCommandWrite } from '@open-mercato/shared/lib/commands/runCrudCommandWrite'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerDeal,\n CustomerDealPersonLink,\n CustomerDealCompanyLink,\n CustomerDealStageTransition,\n CustomerPipelineStage,\n} from '../data/entities'\nimport {\n dealCreateSchema,\n dealUpdateSchema,\n type DealCreateInput,\n type DealUpdateInput,\n} from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireCustomerEntity,\n ensureSameScope,\n extractUndoPayload,\n ensureDictionaryEntry,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n type CustomFieldChangeSet,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isMissingDealStageTransitionTable, warnMissingDealStageTransitionTable } from '../lib/dealStageTransitionTable'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst DEAL_ENTITY_ID = 'customers:customer_deal'\nconst dealCrudIndexer: CrudIndexerConfig<CustomerDeal> = {\n entityType: E.customers.customer_deal,\n}\n\nconst dealCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'deal',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype PipelineStageSnapshot = {\n id: string\n pipelineId: string\n label: string\n order: number\n}\n\ntype DealStageTransitionSnapshot = {\n id: string\n pipelineId: string\n stageId: string\n stageLabel: string\n stageOrder: number\n transitionedAt: Date | string\n transitionedByUserId: string | null\n}\n\nfunction coerceSnapshotDate(value: Date | string | null | undefined, fieldName: string): Date | null {\n if (value === undefined || value === null) return null\n if (value instanceof Date) return value\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) {\n throw new Error(`[internal] Invalid ${fieldName} undo snapshot date: ${value}`)\n }\n return date\n}\n\nfunction coerceRequiredSnapshotDate(value: Date | string, fieldName: string): Date {\n const date = coerceSnapshotDate(value, fieldName)\n if (!date) {\n throw new Error(`[internal] Missing ${fieldName} undo snapshot date`)\n }\n return date\n}\n\nasync function loadPipelineStageSnapshot(\n em: EntityManager,\n pipelineStageId: string,\n tenantId: string,\n organizationId: string,\n): Promise<PipelineStageSnapshot | null> {\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, { id: pipelineStageId }, {}, { tenantId, organizationId })\n if (!stage) return null\n return {\n id: stage.id,\n pipelineId: stage.pipelineId,\n label: stage.label,\n order: stage.order,\n }\n}\n\nasync function resolvePipelineStageValue(\n em: EntityManager,\n pipelineStageId: string,\n tenantId: string,\n organizationId: string,\n): Promise<string | null> {\n const stage = await loadPipelineStageSnapshot(em, pipelineStageId, tenantId, organizationId)\n if (!stage) return null\n const entry = await ensureDictionaryEntry(em, {\n tenantId,\n organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n })\n return entry?.value ?? stage.label\n}\n\nfunction resolvePipelineAssignment(input: {\n pipelineId?: string | null\n pipelineStageId?: string | null\n stageSnapshot: PipelineStageSnapshot | null\n}): { pipelineId: string | null; pipelineStageId: string | null } {\n const requestedPipelineId = input.pipelineId ?? null\n const requestedPipelineStageId = input.pipelineStageId ?? null\n\n if (requestedPipelineStageId && !input.stageSnapshot) {\n throw new CrudHttpError(400, { error: 'Pipeline stage not found' })\n }\n\n if (\n requestedPipelineId &&\n input.stageSnapshot &&\n input.stageSnapshot.pipelineId !== requestedPipelineId\n ) {\n throw new CrudHttpError(400, {\n error: 'Pipeline stage does not belong to the selected pipeline',\n })\n }\n\n return {\n pipelineId: requestedPipelineId ?? input.stageSnapshot?.pipelineId ?? null,\n pipelineStageId: requestedPipelineStageId,\n }\n}\n\nasync function upsertDealStageTransition(\n em: EntityManager,\n input: {\n deal: CustomerDeal\n pipelineId: string\n stageId: string\n stageLabel: string\n stageOrder: number\n transitionedByUserId: string | null\n transitionedAt?: Date\n },\n): Promise<void> {\n let existing: CustomerDealStageTransition | null = null\n try {\n existing = await findOneWithDecryption(\n em,\n CustomerDealStageTransition,\n { deal: input.deal.id, stageId: input.stageId, deletedAt: null },\n {},\n { tenantId: input.deal.tenantId, organizationId: input.deal.organizationId },\n )\n } catch (error) {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.upsertTransition')\n return\n }\n const transitionedAt = input.transitionedAt ?? new Date()\n if (existing) {\n existing.pipelineId = input.pipelineId\n existing.stageLabel = input.stageLabel\n existing.stageOrder = input.stageOrder\n existing.transitionedAt = transitionedAt\n existing.transitionedByUserId = input.transitionedByUserId\n existing.deletedAt = null\n existing.isActive = true\n return\n }\n\n const transition = em.create(CustomerDealStageTransition, {\n organizationId: input.deal.organizationId,\n tenantId: input.deal.tenantId,\n deal: input.deal,\n pipelineId: input.pipelineId,\n stageId: input.stageId,\n stageLabel: input.stageLabel,\n stageOrder: input.stageOrder,\n transitionedAt,\n transitionedByUserId: input.transitionedByUserId,\n isActive: true,\n })\n em.persist(transition)\n}\n\nasync function deleteDealStageTransitions(em: EntityManager, deal: CustomerDeal): Promise<void> {\n try {\n await em.nativeDelete(CustomerDealStageTransition, { deal: deal.id })\n } catch (error) {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.deleteTransitions')\n }\n}\n\nasync function restoreDealStageTransitions(\n em: EntityManager,\n deal: CustomerDeal,\n transitions: DealStageTransitionSnapshot[],\n): Promise<void> {\n if (!transitions.length) return\n for (const transitionSnapshot of transitions) {\n const transition = em.create(CustomerDealStageTransition, {\n id: transitionSnapshot.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n deal,\n pipelineId: transitionSnapshot.pipelineId,\n stageId: transitionSnapshot.stageId,\n stageLabel: transitionSnapshot.stageLabel,\n stageOrder: transitionSnapshot.stageOrder,\n transitionedAt: coerceRequiredSnapshotDate(transitionSnapshot.transitionedAt, 'transitionedAt'),\n transitionedByUserId: transitionSnapshot.transitionedByUserId,\n isActive: true,\n })\n em.persist(transition)\n }\n}\n\ntype DealSnapshot = {\n deal: {\n id: string\n organizationId: string\n tenantId: string\n title: string\n description: string | null\n status: string\n pipelineStage: string | null\n pipelineId: string | null\n pipelineStageId: string | null\n valueAmount: string | null\n valueCurrency: string | null\n probability: number | null\n expectedCloseAt: Date | string | null\n ownerUserId: string | null\n source: string | null\n closureOutcome: string | null\n lossReasonId: string | null\n lossNotes: string | null\n }\n people: string[]\n companies: string[]\n transitions: DealStageTransitionSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype DealUndoPayload = {\n before?: DealSnapshot | null\n after?: DealSnapshot | null\n}\n\ntype DealChangeMap = Record<string, { from: unknown; to: unknown }> & {\n custom?: CustomFieldChangeSet\n}\n\nasync function loadDealSnapshot(em: EntityManager, id: string): Promise<DealSnapshot | null> {\n const deal = await findOneWithDecryption(em, CustomerDeal, { id, deletedAt: null })\n if (!deal) return null\n const decryptionScope = { tenantId: deal.tenantId ?? null, organizationId: deal.organizationId ?? null }\n const peopleLinks = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal },\n { populate: ['person'] },\n decryptionScope,\n )\n const companyLinks = await findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: deal },\n { populate: ['company'] },\n decryptionScope,\n )\n const transitions = await findWithDecryption(\n em,\n CustomerDealStageTransition,\n { deal: deal.id, deletedAt: null },\n { orderBy: { stageOrder: 'ASC', transitionedAt: 'ASC' } },\n decryptionScope,\n ).catch((error: unknown) => {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.loadSnapshot')\n return [] as CustomerDealStageTransition[]\n })\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n tenantId: deal.tenantId,\n organizationId: deal.organizationId,\n })\n return {\n deal: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n title: deal.title,\n description: deal.description ?? null,\n status: deal.status,\n pipelineStage: deal.pipelineStage ?? null,\n pipelineId: deal.pipelineId ?? null,\n pipelineStageId: deal.pipelineStageId ?? null,\n valueAmount: deal.valueAmount ?? null,\n valueCurrency: deal.valueCurrency ?? null,\n probability: deal.probability ?? null,\n expectedCloseAt: deal.expectedCloseAt ?? null,\n ownerUserId: deal.ownerUserId ?? null,\n source: deal.source ?? null,\n closureOutcome: deal.closureOutcome ?? null,\n lossReasonId: deal.lossReasonId ?? null,\n lossNotes: deal.lossNotes ?? null,\n },\n people: peopleLinks.map((link) =>\n typeof link.person === 'string' ? link.person : link.person.id\n ),\n companies: companyLinks.map((link) =>\n typeof link.company === 'string' ? link.company : link.company.id\n ),\n transitions: transitions.map((transition) => ({\n id: transition.id,\n pipelineId: transition.pipelineId,\n stageId: transition.stageId,\n stageLabel: transition.stageLabel,\n stageOrder: transition.stageOrder,\n transitionedAt: transition.transitionedAt,\n transitionedByUserId: transition.transitionedByUserId ?? null,\n })),\n custom,\n }\n}\n\nfunction toNumericString(value: number | null | undefined): string | null {\n if (value === undefined || value === null) return null\n return value.toString()\n}\n\nasync function syncDealPeople(\n em: EntityManager,\n deal: CustomerDeal,\n personIds: string[] | undefined | null\n): Promise<void> {\n if (personIds === undefined) return\n await em.nativeDelete(CustomerDealPersonLink, { deal })\n if (!personIds || !personIds.length) return\n const unique = Array.from(new Set(personIds))\n for (const personId of unique) {\n const person = await requireCustomerEntity(em, personId, { tenantId: deal.tenantId, organizationId: deal.organizationId }, 'person', 'Person not found')\n ensureSameScope(person, deal.organizationId, deal.tenantId)\n const link = em.create(CustomerDealPersonLink, {\n deal,\n person,\n })\n em.persist(link)\n }\n}\n\nasync function syncDealCompanies(\n em: EntityManager,\n deal: CustomerDeal,\n companyIds: string[] | undefined | null\n): Promise<void> {\n if (companyIds === undefined) return\n await em.nativeDelete(CustomerDealCompanyLink, { deal })\n if (!companyIds || !companyIds.length) return\n const unique = Array.from(new Set(companyIds))\n for (const companyId of unique) {\n const company = await requireCustomerEntity(em, companyId, { tenantId: deal.tenantId, organizationId: deal.organizationId }, 'company', 'Company not found')\n ensureSameScope(company, deal.organizationId, deal.tenantId)\n const link = em.create(CustomerDealCompanyLink, {\n deal,\n company,\n })\n em.persist(link)\n }\n}\n\nconst createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {\n id: 'customers.deals.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(dealCreateSchema, rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n let deal!: CustomerDeal\n let stageSnapshot: PipelineStageSnapshot | null = null\n let pipelineAssignment: { pipelineId: string | null; pipelineStageId: string | null } = {\n pipelineId: null,\n pipelineStageId: null,\n }\n let resolvedPipelineStageLabel: string | null = null\n await withAtomicFlush(em, [\n async () => {\n stageSnapshot = parsed.pipelineStageId\n ? await loadPipelineStageSnapshot(em, parsed.pipelineStageId, parsed.tenantId, parsed.organizationId)\n : null\n pipelineAssignment = resolvePipelineAssignment({\n pipelineId: parsed.pipelineId,\n pipelineStageId: parsed.pipelineStageId,\n stageSnapshot,\n })\n resolvedPipelineStageLabel = stageSnapshot\n ? (await ensureDictionaryEntry(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: 'pipeline_stage',\n value: stageSnapshot.label,\n }))?.value ?? stageSnapshot.label\n : parsed.pipelineStage ?? null\n },\n async () => {\n deal = em.create(CustomerDeal, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n title: parsed.title,\n description: parsed.description ?? null,\n status: parsed.status ?? 'open',\n pipelineStage: resolvedPipelineStageLabel,\n pipelineId: pipelineAssignment.pipelineId,\n pipelineStageId: pipelineAssignment.pipelineStageId,\n valueAmount: toNumericString(parsed.valueAmount),\n valueCurrency: parsed.valueCurrency ?? null,\n probability: parsed.probability ?? null,\n expectedCloseAt: parsed.expectedCloseAt ?? null,\n ownerUserId: parsed.ownerUserId ?? null,\n source: parsed.source ?? null,\n closureOutcome: parsed.closureOutcome ?? null,\n lossReasonId: parsed.lossReasonId ?? null,\n lossNotes: parsed.lossNotes ?? null,\n })\n em.persist(deal)\n await em.flush()\n },\n async () => {\n const snapshot = stageSnapshot\n if (!snapshot) return\n await upsertDealStageTransition(em, {\n deal,\n pipelineId: snapshot.pipelineId,\n stageId: snapshot.id,\n stageLabel: snapshot.label,\n stageOrder: snapshot.order,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, deal, parsed.personIds ?? []),\n () => syncDealCompanies(em, deal, parsed.companyIds ?? []),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: custom,\n notify: false,\n })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n return { dealId: deal.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadDealSnapshot(em, result.dealId)\n },\n buildLog: async ({ result, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, result.dealId)\n return {\n actionLabel: translate('customers.audit.deals.create', 'Create deal'),\n resourceKind: 'customers.deal',\n resourceId: result.dealId,\n tenantId: snapshot?.deal.tenantId ?? null,\n organizationId: snapshot?.deal.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n payload: {\n undo: {\n after: snapshot,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const dealId = logEntry?.resourceId\n if (!dealId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id: dealId })\n if (!deal) return\n await deleteDealStageTransitions(em, deal)\n await em.nativeDelete(CustomerDealPersonLink, { deal })\n await em.nativeDelete(CustomerDealCompanyLink, { deal })\n em.remove(deal)\n await em.flush()\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<DealSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for deal create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: after.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: after.deal.id,\n organizationId: after.deal.organizationId,\n tenantId: after.deal.tenantId,\n title: after.deal.title,\n description: after.deal.description,\n status: after.deal.status,\n pipelineStage: after.deal.pipelineStage,\n pipelineId: after.deal.pipelineId,\n pipelineStageId: after.deal.pipelineStageId,\n valueAmount: after.deal.valueAmount,\n valueCurrency: after.deal.valueCurrency,\n probability: after.deal.probability,\n expectedCloseAt: after.deal.expectedCloseAt,\n ownerUserId: after.deal.ownerUserId,\n source: after.deal.source,\n closureOutcome: after.deal.closureOutcome,\n lossReasonId: after.deal.lossReasonId,\n lossNotes: after.deal.lossNotes,\n })\n em.persist(deal)\n }\n const restoredDeal = deal\n await withAtomicFlush(em, [\n () => syncDealPeople(em, restoredDeal, after.people),\n () => syncDealCompanies(em, restoredDeal, after.companies),\n () => deleteDealStageTransitions(em, restoredDeal),\n () => restoreDealStageTransitions(em, restoredDeal, after.transitions),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: restoredDeal,\n identifiers: {\n id: restoredDeal.id,\n organizationId: restoredDeal.organizationId,\n tenantId: restoredDeal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const restoreValues = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(restoreValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: restoredDeal.id,\n organizationId: restoredDeal.organizationId,\n tenantId: restoredDeal.tenantId,\n values: restoreValues,\n notify: false,\n })\n }\n\n return { dealId: restoredDeal.id }\n },\n}\n\nconst updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {\n id: 'customers.deals.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(dealUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(dealUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id: parsed.id, deletedAt: null })\n const record = deal ?? null\n if (!record) throw new CrudHttpError(404, { error: 'Deal not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n const previousStatus = record.status\n const previousPipelineStageId = record.pipelineStageId ?? null\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n\n let nextStageSnapshot: PipelineStageSnapshot | null = null\n let nextPipelineAssignment: { pipelineId: string | null; pipelineStageId: string | null } = {\n pipelineId: record.pipelineId ?? null,\n pipelineStageId: record.pipelineStageId ?? null,\n }\n let nextPipelineStageLabel: string | null = null\n let resolvedCurrentPipelineStageLabel: string | null = null\n\n await runCrudCommandWrite({\n ctx,\n em,\n entityId: DEAL_ENTITY_ID,\n action: 'updated',\n scope: { tenantId: record.tenantId, organizationId: record.organizationId },\n customFields: custom,\n events: dealCrudEvents,\n indexer: dealCrudIndexer,\n sideEffect: () => ({\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n }),\n phases: [\n async () => {\n const pipelineAssignmentChanged =\n parsed.pipelineId !== undefined || parsed.pipelineStageId !== undefined\n const requestedPipelineStageId =\n parsed.pipelineStageId !== undefined\n ? parsed.pipelineStageId ?? null\n : record.pipelineStageId ?? null\n const requestedPipelineId =\n parsed.pipelineId !== undefined ? parsed.pipelineId ?? null : record.pipelineId ?? null\n\n nextStageSnapshot = requestedPipelineStageId && (pipelineAssignmentChanged || !record.pipelineStage)\n ? await loadPipelineStageSnapshot(em, requestedPipelineStageId, record.tenantId, record.organizationId)\n : null\n if (pipelineAssignmentChanged) {\n nextPipelineAssignment = resolvePipelineAssignment({\n pipelineId: requestedPipelineId,\n pipelineStageId: requestedPipelineStageId,\n stageSnapshot: nextStageSnapshot,\n })\n }\n nextPipelineStageLabel = nextStageSnapshot\n ? (await ensureDictionaryEntry(em, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n kind: 'pipeline_stage',\n value: nextStageSnapshot.label,\n }))?.value ?? nextStageSnapshot.label\n : null\n resolvedCurrentPipelineStageLabel =\n !nextStageSnapshot && record.pipelineStageId && (parsed.pipelineStageId !== undefined || !record.pipelineStage)\n ? await resolvePipelineStageValue(em, record.pipelineStageId, record.tenantId, record.organizationId)\n : null\n },\n () => {\n if (parsed.title !== undefined) record.title = parsed.title\n if (parsed.description !== undefined) record.description = parsed.description ?? null\n if (parsed.status !== undefined) record.status = parsed.status ?? record.status\n if (parsed.pipelineStage !== undefined) record.pipelineStage = parsed.pipelineStage ?? null\n if (parsed.pipelineId !== undefined || (parsed.pipelineStageId !== undefined && nextStageSnapshot)) {\n record.pipelineId = nextPipelineAssignment.pipelineId\n }\n if (parsed.pipelineStageId !== undefined) record.pipelineStageId = nextPipelineAssignment.pipelineStageId\n\n if (nextPipelineStageLabel && (parsed.pipelineStageId !== undefined || !record.pipelineStage)) {\n record.pipelineStage = nextPipelineStageLabel\n } else if (resolvedCurrentPipelineStageLabel && (parsed.pipelineStageId !== undefined || !record.pipelineStage)) {\n record.pipelineStage = resolvedCurrentPipelineStageLabel\n }\n\n if (parsed.valueAmount !== undefined) record.valueAmount = toNumericString(parsed.valueAmount)\n if (parsed.valueCurrency !== undefined) record.valueCurrency = parsed.valueCurrency ?? null\n if (parsed.probability !== undefined) record.probability = parsed.probability ?? null\n if (parsed.expectedCloseAt !== undefined) record.expectedCloseAt = parsed.expectedCloseAt ?? null\n if (parsed.ownerUserId !== undefined) record.ownerUserId = parsed.ownerUserId ?? null\n if (parsed.source !== undefined) record.source = parsed.source ?? null\n if (parsed.closureOutcome !== undefined) record.closureOutcome = parsed.closureOutcome ?? null\n if (parsed.lossReasonId !== undefined) record.lossReasonId = parsed.lossReasonId ?? null\n if (parsed.lossNotes !== undefined) record.lossNotes = parsed.lossNotes ?? null\n },\n async () => {\n // CRITICAL: persist the scalar mutations above before any further `em.findOne` / sync\n // helpers run inside this transaction. MikroORM v7's identity-map silently discards\n // pending scalar changes on `record` if a query (such as the stage-transition lookup\n // inside `upsertDealStageTransition`, or the linked-entity finds inside\n // `syncDealPeople` / `syncDealCompanies`) executes on the same `EntityManager`\n // before we explicitly flush. Without this flush, the entire kanban drag-and-drop\n // returns 200 OK but never actually updates `customer_deals` rows \u2014 the card\n // snaps back to its source lane on the next refetch (see SPEC-018).\n await em.flush()\n },\n async () => {\n const snapshot = nextStageSnapshot\n if (!snapshot) return\n const shouldRecord =\n parsed.pipelineStageId !== undefined &&\n parsed.pipelineStageId !== null &&\n parsed.pipelineStageId !== previousPipelineStageId\n if (!shouldRecord) return\n await upsertDealStageTransition(em, {\n deal: record,\n pipelineId: snapshot.pipelineId,\n stageId: snapshot.id,\n stageLabel: nextPipelineStageLabel ?? snapshot.label,\n stageOrder: snapshot.order,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, record, parsed.personIds),\n () => syncDealCompanies(em, record, parsed.companyIds),\n ],\n })\n\n // Emit a lifecycle event for deal won/lost status changes; the notifications\n // subscriber translates these into recipient notifications.\n const newStatus = record.status\n const normalizedStatus = newStatus === 'win' ? 'won' : newStatus === 'loose' ? 'lost' : newStatus\n if (previousStatus !== newStatus && (normalizedStatus === 'won' || normalizedStatus === 'lost')) {\n const closureEvent = normalizedStatus === 'won' ? 'customers.deal.won' : 'customers.deal.lost'\n try {\n const eventBus = ctx.container.resolve('eventBus') as { emitEvent(event: string, payload: unknown, options?: unknown): Promise<void> } | undefined\n if (eventBus) {\n await eventBus.emitEvent(\n closureEvent,\n {\n id: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n ownerUserId: record.ownerUserId ?? null,\n title: record.title,\n valueAmount: record.valueAmount ?? null,\n valueCurrency: record.valueCurrency ?? null,\n },\n { persistent: true },\n )\n }\n } catch (err) {\n logger.warn('Deal closure event emit failed', { component: 'deals.update', closureEvent, err })\n }\n }\n\n return { dealId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadDealSnapshot(em, result.dealId)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as DealSnapshot | undefined\n if (!before) return null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterSnapshot = await loadDealSnapshot(em, result.dealId)\n return {\n actionLabel: translate('customers.audit.deals.update', 'Update deal'),\n resourceKind: 'customers.deal',\n resourceId: before.deal.id,\n tenantId: before.deal.tenantId,\n organizationId: before.deal.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<DealUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: before.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: before.deal.id,\n organizationId: before.deal.organizationId,\n tenantId: before.deal.tenantId,\n title: before.deal.title,\n description: before.deal.description,\n status: before.deal.status,\n pipelineStage: before.deal.pipelineStage,\n pipelineId: before.deal.pipelineId,\n pipelineStageId: before.deal.pipelineStageId,\n valueAmount: before.deal.valueAmount,\n valueCurrency: before.deal.valueCurrency,\n probability: before.deal.probability,\n expectedCloseAt: coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt'),\n ownerUserId: before.deal.ownerUserId,\n source: before.deal.source,\n closureOutcome: before.deal.closureOutcome,\n lossReasonId: before.deal.lossReasonId,\n lossNotes: before.deal.lossNotes,\n })\n em.persist(deal)\n }\n const revertedStageSnapshot = before.deal.pipelineStageId\n ? await loadPipelineStageSnapshot(em, before.deal.pipelineStageId, before.deal.tenantId, before.deal.organizationId)\n : null\n const existingTransition = before.deal.pipelineStageId\n ? before.transitions.find((transition) => transition.stageId === before.deal.pipelineStageId) ?? null\n : null\n const shouldRecordRevertTransition =\n before.deal.pipelineStageId !== (payload?.after?.deal.pipelineStageId ?? null) &&\n !!before.deal.pipelineStageId &&\n !!(revertedStageSnapshot?.pipelineId ?? before.deal.pipelineId ?? existingTransition?.pipelineId) &&\n !!(revertedStageSnapshot?.label ?? before.deal.pipelineStage ?? existingTransition?.stageLabel)\n\n await withAtomicFlush(em, [\n () => {\n deal.title = before.deal.title\n deal.description = before.deal.description\n deal.status = before.deal.status\n deal.pipelineStage = before.deal.pipelineStage\n deal.pipelineId = before.deal.pipelineId\n deal.pipelineStageId = before.deal.pipelineStageId\n deal.valueAmount = before.deal.valueAmount\n deal.valueCurrency = before.deal.valueCurrency\n deal.probability = before.deal.probability\n deal.expectedCloseAt = coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt')\n deal.ownerUserId = before.deal.ownerUserId\n deal.source = before.deal.source\n deal.closureOutcome = before.deal.closureOutcome\n deal.lossReasonId = before.deal.lossReasonId\n deal.lossNotes = before.deal.lossNotes\n },\n async () => {\n // Mirror of the fix applied to the forward `execute` path: persist the scalar\n // mutations on `deal` before any further `em.findOne` (the transition lookup\n // inside `upsertDealStageTransition`) or sync-helper queries run on the same EM.\n // MikroORM v7 silently discards the pending scalar changes if we don't flush here\n // (see SPEC-018), which would make an undo of a kanban stage move silently no-op.\n await em.flush()\n },\n async () => {\n if (!shouldRecordRevertTransition || !before.deal.pipelineStageId) return\n const pipelineId = revertedStageSnapshot?.pipelineId ?? before.deal.pipelineId ?? existingTransition?.pipelineId\n const stageLabel = revertedStageSnapshot?.label ?? before.deal.pipelineStage ?? existingTransition?.stageLabel\n if (!pipelineId || !stageLabel) return\n await upsertDealStageTransition(em, {\n deal,\n pipelineId,\n stageId: before.deal.pipelineStageId,\n stageLabel,\n stageOrder: revertedStageSnapshot?.order ?? existingTransition?.stageOrder ?? 0,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, deal, before.people),\n () => syncDealCompanies(em, deal, before.companies),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const resetValues = buildCustomFieldResetMap(before.custom, payload?.after?.custom)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: resetValues,\n notify: false,\n })\n }\n },\n}\n\nconst deleteDealCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { dealId: string }> =\n {\n id: 'customers.deals.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Deal id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Deal id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id, deletedAt: null })\n const record = deal ?? null\n if (!record) throw new CrudHttpError(404, { error: 'Deal not found' })\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n await deleteDealStageTransitions(em, record)\n await em.nativeDelete(CustomerDealPersonLink, { deal: record })\n await em.nativeDelete(CustomerDealCompanyLink, { deal: record })\n em.remove(record)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n return { dealId: record.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as DealSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.deals.delete', 'Delete deal'),\n resourceKind: 'customers.deal',\n resourceId: before.deal.id,\n tenantId: before.deal.tenantId,\n organizationId: before.deal.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<DealUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: before.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: before.deal.id,\n organizationId: before.deal.organizationId,\n tenantId: before.deal.tenantId,\n title: before.deal.title,\n description: before.deal.description,\n status: before.deal.status,\n pipelineStage: before.deal.pipelineStage,\n pipelineId: before.deal.pipelineId,\n pipelineStageId: before.deal.pipelineStageId,\n valueAmount: before.deal.valueAmount,\n valueCurrency: before.deal.valueCurrency,\n probability: before.deal.probability,\n expectedCloseAt: coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt'),\n ownerUserId: before.deal.ownerUserId,\n source: before.deal.source,\n closureOutcome: before.deal.closureOutcome,\n lossReasonId: before.deal.lossReasonId,\n lossNotes: before.deal.lossNotes,\n })\n em.persist(deal)\n }\n await withAtomicFlush(em, [\n () => syncDealPeople(em, deal, before.people),\n () => syncDealCompanies(em, deal, before.companies),\n () => deleteDealStageTransitions(em, deal),\n () => restoreDealStageTransitions(em, deal, before.transitions),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const resetValues = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: resetValues,\n notify: false,\n })\n }\n },\n }\n\nregisterCommand(createDealCommand)\nregisterCommand(updateDealCommand)\nregisterCommand(deleteDealCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAGpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,qBAAqB;AAE9B,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D,S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C5B,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,aAAa;AAAA,QACX,IAAI,KAAK;AAAA,QACT,gBAAgB,KAAK;AAAA,QACrB,UAAU,KAAK;AAAA,MACjB;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,IACV,CAAC;AAED,UAAM,cAAc,yBAAyB,OAAO,QAAQ,MAAS;AACrE,QAAI,OAAO,KAAK,WAAW,EAAE,QAAQ;AACnC,YAAM,qBAAqB;AAAA,QACzB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK;AAAA,QACrB,UAAU,KAAK;AAAA,QACf,QAAQ;AAAA,QACR,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEF,gBAAgB,iBAAiB;AACjC,gBAAgB,iBAAiB;AACjC,gBAAgB,iBAAiB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport {\n parseWithCustomFields,\n setCustomFieldsIfAny,\n emitCrudSideEffects,\n emitCrudUndoSideEffects,\n requireId,\n normalizeAuthorUserId,\n} from '@open-mercato/shared/lib/commands/helpers'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { runCrudCommandWrite } from '@open-mercato/shared/lib/commands/runCrudCommandWrite'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerDeal,\n CustomerDealPersonLink,\n CustomerDealCompanyLink,\n CustomerDealStageTransition,\n CustomerPipelineStage,\n} from '../data/entities'\nimport {\n dealCreateSchema,\n dealUpdateSchema,\n type DealCreateInput,\n type DealUpdateInput,\n} from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireCustomerEntity,\n ensureSameScope,\n extractUndoPayload,\n ensureDictionaryEntry,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n loadCustomFieldSnapshot,\n buildCustomFieldResetMap,\n type CustomFieldChangeSet,\n} from '@open-mercato/shared/lib/commands/customFieldSnapshots'\nimport { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isMissingDealStageTransitionTable, warnMissingDealStageTransitionTable } from '../lib/dealStageTransitionTable'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst DEAL_ENTITY_ID = 'customers:customer_deal'\nconst dealCrudIndexer: CrudIndexerConfig<CustomerDeal> = {\n entityType: E.customers.customer_deal,\n}\n\nconst dealCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'deal',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype PipelineStageSnapshot = {\n id: string\n pipelineId: string\n label: string\n order: number\n}\n\ntype DealStageTransitionSnapshot = {\n id: string\n pipelineId: string\n stageId: string\n stageLabel: string\n stageOrder: number\n transitionedAt: Date | string\n transitionedByUserId: string | null\n}\n\nfunction coerceSnapshotDate(value: Date | string | null | undefined, fieldName: string): Date | null {\n if (value === undefined || value === null) return null\n if (value instanceof Date) return value\n const date = new Date(value)\n if (Number.isNaN(date.getTime())) {\n throw new Error(`[internal] Invalid ${fieldName} undo snapshot date: ${value}`)\n }\n return date\n}\n\nfunction coerceRequiredSnapshotDate(value: Date | string, fieldName: string): Date {\n const date = coerceSnapshotDate(value, fieldName)\n if (!date) {\n throw new Error(`[internal] Missing ${fieldName} undo snapshot date`)\n }\n return date\n}\n\nasync function loadPipelineStageSnapshot(\n em: EntityManager,\n pipelineStageId: string,\n tenantId: string,\n organizationId: string,\n): Promise<PipelineStageSnapshot | null> {\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, { id: pipelineStageId }, {}, { tenantId, organizationId })\n if (!stage) return null\n return {\n id: stage.id,\n pipelineId: stage.pipelineId,\n label: stage.label,\n order: stage.order,\n }\n}\n\nasync function resolvePipelineStageValue(\n em: EntityManager,\n pipelineStageId: string,\n tenantId: string,\n organizationId: string,\n): Promise<string | null> {\n const stage = await loadPipelineStageSnapshot(em, pipelineStageId, tenantId, organizationId)\n if (!stage) return null\n const entry = await ensureDictionaryEntry(em, {\n tenantId,\n organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n })\n return entry?.value ?? stage.label\n}\n\nfunction resolvePipelineAssignment(input: {\n pipelineId?: string | null\n pipelineStageId?: string | null\n stageSnapshot: PipelineStageSnapshot | null\n}): { pipelineId: string | null; pipelineStageId: string | null } {\n const requestedPipelineId = input.pipelineId ?? null\n const requestedPipelineStageId = input.pipelineStageId ?? null\n\n if (requestedPipelineStageId && !input.stageSnapshot) {\n throw new CrudHttpError(400, { error: 'Pipeline stage not found' })\n }\n\n if (\n requestedPipelineId &&\n input.stageSnapshot &&\n input.stageSnapshot.pipelineId !== requestedPipelineId\n ) {\n throw new CrudHttpError(400, {\n error: 'Pipeline stage does not belong to the selected pipeline',\n })\n }\n\n return {\n pipelineId: requestedPipelineId ?? input.stageSnapshot?.pipelineId ?? null,\n pipelineStageId: requestedPipelineStageId,\n }\n}\n\nasync function upsertDealStageTransition(\n em: EntityManager,\n input: {\n deal: CustomerDeal\n pipelineId: string\n stageId: string\n stageLabel: string\n stageOrder: number\n transitionedByUserId: string | null\n transitionedAt?: Date\n },\n): Promise<void> {\n let existing: CustomerDealStageTransition | null = null\n try {\n existing = await findOneWithDecryption(\n em,\n CustomerDealStageTransition,\n { deal: input.deal.id, stageId: input.stageId, deletedAt: null },\n {},\n { tenantId: input.deal.tenantId, organizationId: input.deal.organizationId },\n )\n } catch (error) {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.upsertTransition')\n return\n }\n const transitionedAt = input.transitionedAt ?? new Date()\n if (existing) {\n existing.pipelineId = input.pipelineId\n existing.stageLabel = input.stageLabel\n existing.stageOrder = input.stageOrder\n existing.transitionedAt = transitionedAt\n existing.transitionedByUserId = input.transitionedByUserId\n existing.deletedAt = null\n existing.isActive = true\n return\n }\n\n const transition = em.create(CustomerDealStageTransition, {\n organizationId: input.deal.organizationId,\n tenantId: input.deal.tenantId,\n deal: input.deal,\n pipelineId: input.pipelineId,\n stageId: input.stageId,\n stageLabel: input.stageLabel,\n stageOrder: input.stageOrder,\n transitionedAt,\n transitionedByUserId: input.transitionedByUserId,\n isActive: true,\n })\n em.persist(transition)\n}\n\nasync function deleteDealStageTransitions(em: EntityManager, deal: CustomerDeal): Promise<void> {\n try {\n await em.nativeDelete(CustomerDealStageTransition, { deal: deal.id })\n } catch (error) {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.deleteTransitions')\n }\n}\n\nasync function restoreDealStageTransitions(\n em: EntityManager,\n deal: CustomerDeal,\n transitions: DealStageTransitionSnapshot[],\n): Promise<void> {\n if (!transitions.length) return\n for (const transitionSnapshot of transitions) {\n const transition = em.create(CustomerDealStageTransition, {\n id: transitionSnapshot.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n deal,\n pipelineId: transitionSnapshot.pipelineId,\n stageId: transitionSnapshot.stageId,\n stageLabel: transitionSnapshot.stageLabel,\n stageOrder: transitionSnapshot.stageOrder,\n transitionedAt: coerceRequiredSnapshotDate(transitionSnapshot.transitionedAt, 'transitionedAt'),\n transitionedByUserId: transitionSnapshot.transitionedByUserId,\n isActive: true,\n })\n em.persist(transition)\n }\n}\n\ntype DealSnapshot = {\n deal: {\n id: string\n organizationId: string\n tenantId: string\n title: string\n description: string | null\n status: string\n pipelineStage: string | null\n pipelineId: string | null\n pipelineStageId: string | null\n valueAmount: string | null\n valueCurrency: string | null\n probability: number | null\n expectedCloseAt: Date | string | null\n ownerUserId: string | null\n source: string | null\n closureOutcome: string | null\n lossReasonId: string | null\n lossNotes: string | null\n }\n people: string[]\n companies: string[]\n transitions: DealStageTransitionSnapshot[]\n custom?: Record<string, unknown>\n}\n\ntype DealUndoPayload = {\n before?: DealSnapshot | null\n after?: DealSnapshot | null\n}\n\ntype DealChangeMap = Record<string, { from: unknown; to: unknown }> & {\n custom?: CustomFieldChangeSet\n}\n\nasync function loadDealSnapshot(em: EntityManager, id: string): Promise<DealSnapshot | null> {\n const deal = await findOneWithDecryption(em, CustomerDeal, { id, deletedAt: null })\n if (!deal) return null\n const decryptionScope = { tenantId: deal.tenantId ?? null, organizationId: deal.organizationId ?? null }\n const peopleLinks = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal },\n { populate: ['person'] },\n decryptionScope,\n )\n const companyLinks = await findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: deal },\n { populate: ['company'] },\n decryptionScope,\n )\n const transitions = await findWithDecryption(\n em,\n CustomerDealStageTransition,\n { deal: deal.id, deletedAt: null },\n { orderBy: { stageOrder: 'ASC', transitionedAt: 'ASC' } },\n decryptionScope,\n ).catch((error: unknown) => {\n if (!isMissingDealStageTransitionTable(error)) {\n throw error\n }\n warnMissingDealStageTransitionTable('customers.commands.deals.loadSnapshot')\n return [] as CustomerDealStageTransition[]\n })\n const custom = await loadCustomFieldSnapshot(em, {\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n tenantId: deal.tenantId,\n organizationId: deal.organizationId,\n })\n return {\n deal: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n title: deal.title,\n description: deal.description ?? null,\n status: deal.status,\n pipelineStage: deal.pipelineStage ?? null,\n pipelineId: deal.pipelineId ?? null,\n pipelineStageId: deal.pipelineStageId ?? null,\n valueAmount: deal.valueAmount ?? null,\n valueCurrency: deal.valueCurrency ?? null,\n probability: deal.probability ?? null,\n expectedCloseAt: deal.expectedCloseAt ?? null,\n ownerUserId: deal.ownerUserId ?? null,\n source: deal.source ?? null,\n closureOutcome: deal.closureOutcome ?? null,\n lossReasonId: deal.lossReasonId ?? null,\n lossNotes: deal.lossNotes ?? null,\n },\n people: peopleLinks.map((link) =>\n typeof link.person === 'string' ? link.person : link.person.id\n ),\n companies: companyLinks.map((link) =>\n typeof link.company === 'string' ? link.company : link.company.id\n ),\n transitions: transitions.map((transition) => ({\n id: transition.id,\n pipelineId: transition.pipelineId,\n stageId: transition.stageId,\n stageLabel: transition.stageLabel,\n stageOrder: transition.stageOrder,\n transitionedAt: transition.transitionedAt,\n transitionedByUserId: transition.transitionedByUserId ?? null,\n })),\n custom,\n }\n}\n\nfunction toNumericString(value: number | null | undefined): string | null {\n if (value === undefined || value === null) return null\n return value.toString()\n}\n\nasync function syncDealPeople(\n em: EntityManager,\n deal: CustomerDeal,\n personIds: string[] | undefined | null\n): Promise<void> {\n if (personIds === undefined) return\n await em.nativeDelete(CustomerDealPersonLink, { deal })\n if (!personIds || !personIds.length) return\n const unique = Array.from(new Set(personIds))\n for (const personId of unique) {\n const person = await requireCustomerEntity(em, personId, { tenantId: deal.tenantId, organizationId: deal.organizationId }, 'person', 'Person not found')\n ensureSameScope(person, deal.organizationId, deal.tenantId)\n const link = em.create(CustomerDealPersonLink, {\n deal,\n person,\n })\n em.persist(link)\n }\n}\n\nasync function syncDealCompanies(\n em: EntityManager,\n deal: CustomerDeal,\n companyIds: string[] | undefined | null\n): Promise<void> {\n if (companyIds === undefined) return\n await em.nativeDelete(CustomerDealCompanyLink, { deal })\n if (!companyIds || !companyIds.length) return\n const unique = Array.from(new Set(companyIds))\n for (const companyId of unique) {\n const company = await requireCustomerEntity(em, companyId, { tenantId: deal.tenantId, organizationId: deal.organizationId }, 'company', 'Company not found')\n ensureSameScope(company, deal.organizationId, deal.tenantId)\n const link = em.create(CustomerDealCompanyLink, {\n deal,\n company,\n })\n em.persist(link)\n }\n}\n\nconst createDealCommand: CommandHandler<DealCreateInput, { dealId: string }> = {\n id: 'customers.deals.create',\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(dealCreateSchema, rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n let deal!: CustomerDeal\n let stageSnapshot: PipelineStageSnapshot | null = null\n let pipelineAssignment: { pipelineId: string | null; pipelineStageId: string | null } = {\n pipelineId: null,\n pipelineStageId: null,\n }\n let resolvedPipelineStageLabel: string | null = null\n await withAtomicFlush(em, [\n async () => {\n stageSnapshot = parsed.pipelineStageId\n ? await loadPipelineStageSnapshot(em, parsed.pipelineStageId, parsed.tenantId, parsed.organizationId)\n : null\n pipelineAssignment = resolvePipelineAssignment({\n pipelineId: parsed.pipelineId,\n pipelineStageId: parsed.pipelineStageId,\n stageSnapshot,\n })\n resolvedPipelineStageLabel = stageSnapshot\n ? (await ensureDictionaryEntry(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: 'pipeline_stage',\n value: stageSnapshot.label,\n }))?.value ?? stageSnapshot.label\n : parsed.pipelineStage ?? null\n },\n async () => {\n deal = em.create(CustomerDeal, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n title: parsed.title,\n description: parsed.description ?? null,\n status: parsed.status ?? 'open',\n pipelineStage: resolvedPipelineStageLabel,\n pipelineId: pipelineAssignment.pipelineId,\n pipelineStageId: pipelineAssignment.pipelineStageId,\n valueAmount: toNumericString(parsed.valueAmount),\n valueCurrency: parsed.valueCurrency ?? null,\n probability: parsed.probability ?? null,\n expectedCloseAt: parsed.expectedCloseAt ?? null,\n ownerUserId: parsed.ownerUserId ?? null,\n source: parsed.source ?? null,\n closureOutcome: parsed.closureOutcome ?? null,\n lossReasonId: parsed.lossReasonId ?? null,\n lossNotes: parsed.lossNotes ?? null,\n })\n em.persist(deal)\n await em.flush()\n },\n async () => {\n const snapshot = stageSnapshot\n if (!snapshot) return\n await upsertDealStageTransition(em, {\n deal,\n pipelineId: snapshot.pipelineId,\n stageId: snapshot.id,\n stageLabel: snapshot.label,\n stageOrder: snapshot.order,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, deal, parsed.personIds ?? []),\n () => syncDealCompanies(em, deal, parsed.companyIds ?? []),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: custom,\n notify: false,\n })\n\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n return { dealId: deal.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadDealSnapshot(em, result.dealId)\n },\n buildLog: async ({ result, ctx }) => {\n const { translate } = await resolveTranslations()\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, result.dealId)\n return {\n actionLabel: translate('customers.audit.deals.create', 'Create deal'),\n resourceKind: 'customers.deal',\n resourceId: result.dealId,\n tenantId: snapshot?.deal.tenantId ?? null,\n organizationId: snapshot?.deal.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n payload: {\n undo: {\n after: snapshot,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const dealId = logEntry?.resourceId\n if (!dealId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id: dealId })\n if (!deal) return\n await deleteDealStageTransitions(em, deal)\n await em.nativeDelete(CustomerDealPersonLink, { deal })\n await em.nativeDelete(CustomerDealCompanyLink, { deal })\n em.remove(deal)\n await em.flush()\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<DealSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for deal create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: after.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: after.deal.id,\n organizationId: after.deal.organizationId,\n tenantId: after.deal.tenantId,\n title: after.deal.title,\n description: after.deal.description,\n status: after.deal.status,\n pipelineStage: after.deal.pipelineStage,\n pipelineId: after.deal.pipelineId,\n pipelineStageId: after.deal.pipelineStageId,\n valueAmount: after.deal.valueAmount,\n valueCurrency: after.deal.valueCurrency,\n probability: after.deal.probability,\n expectedCloseAt: after.deal.expectedCloseAt,\n ownerUserId: after.deal.ownerUserId,\n source: after.deal.source,\n closureOutcome: after.deal.closureOutcome,\n lossReasonId: after.deal.lossReasonId,\n lossNotes: after.deal.lossNotes,\n })\n em.persist(deal)\n }\n const restoredDeal = deal\n await withAtomicFlush(em, [\n () => syncDealPeople(em, restoredDeal, after.people),\n () => syncDealCompanies(em, restoredDeal, after.companies),\n () => deleteDealStageTransitions(em, restoredDeal),\n () => restoreDealStageTransitions(em, restoredDeal, after.transitions),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: restoredDeal,\n identifiers: {\n id: restoredDeal.id,\n organizationId: restoredDeal.organizationId,\n tenantId: restoredDeal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const restoreValues = buildCustomFieldResetMap(after.custom, undefined)\n if (Object.keys(restoreValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: restoredDeal.id,\n organizationId: restoredDeal.organizationId,\n tenantId: restoredDeal.tenantId,\n values: restoreValues,\n notify: false,\n })\n }\n\n return { dealId: restoredDeal.id }\n },\n}\n\nconst updateDealCommand: CommandHandler<DealUpdateInput, { dealId: string }> = {\n id: 'customers.deals.update',\n async prepare(rawInput, ctx) {\n const { parsed } = parseWithCustomFields(dealUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const { parsed, custom } = parseWithCustomFields(dealUpdateSchema, rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id: parsed.id, deletedAt: null })\n const record = deal ?? null\n if (!record) throw notFound('Deal not found')\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n\n const previousStatus = record.status\n const previousPipelineStageId = record.pipelineStageId ?? null\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n\n let nextStageSnapshot: PipelineStageSnapshot | null = null\n let nextPipelineAssignment: { pipelineId: string | null; pipelineStageId: string | null } = {\n pipelineId: record.pipelineId ?? null,\n pipelineStageId: record.pipelineStageId ?? null,\n }\n let nextPipelineStageLabel: string | null = null\n let resolvedCurrentPipelineStageLabel: string | null = null\n\n await runCrudCommandWrite({\n ctx,\n em,\n entityId: DEAL_ENTITY_ID,\n action: 'updated',\n scope: { tenantId: record.tenantId, organizationId: record.organizationId },\n customFields: custom,\n events: dealCrudEvents,\n indexer: dealCrudIndexer,\n sideEffect: () => ({\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n }),\n phases: [\n async () => {\n const pipelineAssignmentChanged =\n parsed.pipelineId !== undefined || parsed.pipelineStageId !== undefined\n const requestedPipelineStageId =\n parsed.pipelineStageId !== undefined\n ? parsed.pipelineStageId ?? null\n : record.pipelineStageId ?? null\n const requestedPipelineId =\n parsed.pipelineId !== undefined ? parsed.pipelineId ?? null : record.pipelineId ?? null\n\n nextStageSnapshot = requestedPipelineStageId && (pipelineAssignmentChanged || !record.pipelineStage)\n ? await loadPipelineStageSnapshot(em, requestedPipelineStageId, record.tenantId, record.organizationId)\n : null\n if (pipelineAssignmentChanged) {\n nextPipelineAssignment = resolvePipelineAssignment({\n pipelineId: requestedPipelineId,\n pipelineStageId: requestedPipelineStageId,\n stageSnapshot: nextStageSnapshot,\n })\n }\n nextPipelineStageLabel = nextStageSnapshot\n ? (await ensureDictionaryEntry(em, {\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n kind: 'pipeline_stage',\n value: nextStageSnapshot.label,\n }))?.value ?? nextStageSnapshot.label\n : null\n resolvedCurrentPipelineStageLabel =\n !nextStageSnapshot && record.pipelineStageId && (parsed.pipelineStageId !== undefined || !record.pipelineStage)\n ? await resolvePipelineStageValue(em, record.pipelineStageId, record.tenantId, record.organizationId)\n : null\n },\n () => {\n if (parsed.title !== undefined) record.title = parsed.title\n if (parsed.description !== undefined) record.description = parsed.description ?? null\n if (parsed.status !== undefined) record.status = parsed.status ?? record.status\n if (parsed.pipelineStage !== undefined) record.pipelineStage = parsed.pipelineStage ?? null\n if (parsed.pipelineId !== undefined || (parsed.pipelineStageId !== undefined && nextStageSnapshot)) {\n record.pipelineId = nextPipelineAssignment.pipelineId\n }\n if (parsed.pipelineStageId !== undefined) record.pipelineStageId = nextPipelineAssignment.pipelineStageId\n\n if (nextPipelineStageLabel && (parsed.pipelineStageId !== undefined || !record.pipelineStage)) {\n record.pipelineStage = nextPipelineStageLabel\n } else if (resolvedCurrentPipelineStageLabel && (parsed.pipelineStageId !== undefined || !record.pipelineStage)) {\n record.pipelineStage = resolvedCurrentPipelineStageLabel\n }\n\n if (parsed.valueAmount !== undefined) record.valueAmount = toNumericString(parsed.valueAmount)\n if (parsed.valueCurrency !== undefined) record.valueCurrency = parsed.valueCurrency ?? null\n if (parsed.probability !== undefined) record.probability = parsed.probability ?? null\n if (parsed.expectedCloseAt !== undefined) record.expectedCloseAt = parsed.expectedCloseAt ?? null\n if (parsed.ownerUserId !== undefined) record.ownerUserId = parsed.ownerUserId ?? null\n if (parsed.source !== undefined) record.source = parsed.source ?? null\n if (parsed.closureOutcome !== undefined) record.closureOutcome = parsed.closureOutcome ?? null\n if (parsed.lossReasonId !== undefined) record.lossReasonId = parsed.lossReasonId ?? null\n if (parsed.lossNotes !== undefined) record.lossNotes = parsed.lossNotes ?? null\n },\n async () => {\n // CRITICAL: persist the scalar mutations above before any further `em.findOne` / sync\n // helpers run inside this transaction. MikroORM v7's identity-map silently discards\n // pending scalar changes on `record` if a query (such as the stage-transition lookup\n // inside `upsertDealStageTransition`, or the linked-entity finds inside\n // `syncDealPeople` / `syncDealCompanies`) executes on the same `EntityManager`\n // before we explicitly flush. Without this flush, the entire kanban drag-and-drop\n // returns 200 OK but never actually updates `customer_deals` rows \u2014 the card\n // snaps back to its source lane on the next refetch (see SPEC-018).\n await em.flush()\n },\n async () => {\n const snapshot = nextStageSnapshot\n if (!snapshot) return\n const shouldRecord =\n parsed.pipelineStageId !== undefined &&\n parsed.pipelineStageId !== null &&\n parsed.pipelineStageId !== previousPipelineStageId\n if (!shouldRecord) return\n await upsertDealStageTransition(em, {\n deal: record,\n pipelineId: snapshot.pipelineId,\n stageId: snapshot.id,\n stageLabel: nextPipelineStageLabel ?? snapshot.label,\n stageOrder: snapshot.order,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, record, parsed.personIds),\n () => syncDealCompanies(em, record, parsed.companyIds),\n ],\n })\n\n // Emit a lifecycle event for deal won/lost status changes; the notifications\n // subscriber translates these into recipient notifications.\n const newStatus = record.status\n const normalizedStatus = newStatus === 'win' ? 'won' : newStatus === 'loose' ? 'lost' : newStatus\n if (previousStatus !== newStatus && (normalizedStatus === 'won' || normalizedStatus === 'lost')) {\n const closureEvent = normalizedStatus === 'won' ? 'customers.deal.won' : 'customers.deal.lost'\n try {\n const eventBus = ctx.container.resolve('eventBus') as { emitEvent(event: string, payload: unknown, options?: unknown): Promise<void> } | undefined\n if (eventBus) {\n await eventBus.emitEvent(\n closureEvent,\n {\n id: record.id,\n tenantId: record.tenantId,\n organizationId: record.organizationId,\n ownerUserId: record.ownerUserId ?? null,\n title: record.title,\n valueAmount: record.valueAmount ?? null,\n valueCurrency: record.valueCurrency ?? null,\n },\n { persistent: true },\n )\n }\n } catch (err) {\n logger.warn('Deal closure event emit failed', { component: 'deals.update', closureEvent, err })\n }\n }\n\n return { dealId: record.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadDealSnapshot(em, result.dealId)\n },\n buildLog: async ({ result, snapshots, ctx }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as DealSnapshot | undefined\n if (!before) return null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const afterSnapshot = await loadDealSnapshot(em, result.dealId)\n return {\n actionLabel: translate('customers.audit.deals.update', 'Update deal'),\n resourceKind: 'customers.deal',\n resourceId: before.deal.id,\n tenantId: before.deal.tenantId,\n organizationId: before.deal.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<DealUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const normalizedTransitionAuthorUserId = normalizeAuthorUserId(null, ctx.auth)\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: before.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: before.deal.id,\n organizationId: before.deal.organizationId,\n tenantId: before.deal.tenantId,\n title: before.deal.title,\n description: before.deal.description,\n status: before.deal.status,\n pipelineStage: before.deal.pipelineStage,\n pipelineId: before.deal.pipelineId,\n pipelineStageId: before.deal.pipelineStageId,\n valueAmount: before.deal.valueAmount,\n valueCurrency: before.deal.valueCurrency,\n probability: before.deal.probability,\n expectedCloseAt: coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt'),\n ownerUserId: before.deal.ownerUserId,\n source: before.deal.source,\n closureOutcome: before.deal.closureOutcome,\n lossReasonId: before.deal.lossReasonId,\n lossNotes: before.deal.lossNotes,\n })\n em.persist(deal)\n }\n const revertedStageSnapshot = before.deal.pipelineStageId\n ? await loadPipelineStageSnapshot(em, before.deal.pipelineStageId, before.deal.tenantId, before.deal.organizationId)\n : null\n const existingTransition = before.deal.pipelineStageId\n ? before.transitions.find((transition) => transition.stageId === before.deal.pipelineStageId) ?? null\n : null\n const shouldRecordRevertTransition =\n before.deal.pipelineStageId !== (payload?.after?.deal.pipelineStageId ?? null) &&\n !!before.deal.pipelineStageId &&\n !!(revertedStageSnapshot?.pipelineId ?? before.deal.pipelineId ?? existingTransition?.pipelineId) &&\n !!(revertedStageSnapshot?.label ?? before.deal.pipelineStage ?? existingTransition?.stageLabel)\n\n await withAtomicFlush(em, [\n () => {\n deal.title = before.deal.title\n deal.description = before.deal.description\n deal.status = before.deal.status\n deal.pipelineStage = before.deal.pipelineStage\n deal.pipelineId = before.deal.pipelineId\n deal.pipelineStageId = before.deal.pipelineStageId\n deal.valueAmount = before.deal.valueAmount\n deal.valueCurrency = before.deal.valueCurrency\n deal.probability = before.deal.probability\n deal.expectedCloseAt = coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt')\n deal.ownerUserId = before.deal.ownerUserId\n deal.source = before.deal.source\n deal.closureOutcome = before.deal.closureOutcome\n deal.lossReasonId = before.deal.lossReasonId\n deal.lossNotes = before.deal.lossNotes\n },\n async () => {\n // Mirror of the fix applied to the forward `execute` path: persist the scalar\n // mutations on `deal` before any further `em.findOne` (the transition lookup\n // inside `upsertDealStageTransition`) or sync-helper queries run on the same EM.\n // MikroORM v7 silently discards the pending scalar changes if we don't flush here\n // (see SPEC-018), which would make an undo of a kanban stage move silently no-op.\n await em.flush()\n },\n async () => {\n if (!shouldRecordRevertTransition || !before.deal.pipelineStageId) return\n const pipelineId = revertedStageSnapshot?.pipelineId ?? before.deal.pipelineId ?? existingTransition?.pipelineId\n const stageLabel = revertedStageSnapshot?.label ?? before.deal.pipelineStage ?? existingTransition?.stageLabel\n if (!pipelineId || !stageLabel) return\n await upsertDealStageTransition(em, {\n deal,\n pipelineId,\n stageId: before.deal.pipelineStageId,\n stageLabel,\n stageOrder: revertedStageSnapshot?.order ?? existingTransition?.stageOrder ?? 0,\n transitionedByUserId: normalizedTransitionAuthorUserId,\n })\n },\n () => syncDealPeople(em, deal, before.people),\n () => syncDealCompanies(em, deal, before.companies),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const resetValues = buildCustomFieldResetMap(before.custom, payload?.after?.custom)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: resetValues,\n notify: false,\n })\n }\n },\n}\n\nconst deleteDealCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { dealId: string }> =\n {\n id: 'customers.deals.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Deal id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadDealSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Deal id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const deal = await findOneWithDecryption(em, CustomerDeal, { id, deletedAt: null })\n const record = deal ?? null\n if (!record) throw notFound('Deal not found')\n ensureTenantScope(ctx, record.tenantId)\n ensureOrganizationScope(ctx, record.organizationId)\n await deleteDealStageTransitions(em, record)\n await em.nativeDelete(CustomerDealPersonLink, { deal: record })\n await em.nativeDelete(CustomerDealCompanyLink, { deal: record })\n em.remove(record)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: record,\n identifiers: {\n id: record.id,\n organizationId: record.organizationId,\n tenantId: record.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n return { dealId: record.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as DealSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.deals.delete', 'Delete deal'),\n resourceKind: 'customers.deal',\n resourceId: before.deal.id,\n tenantId: before.deal.tenantId,\n organizationId: before.deal.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies DealUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<DealUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let deal = await findOneWithDecryption(em, CustomerDeal, { id: before.deal.id })\n if (!deal) {\n deal = em.create(CustomerDeal, {\n id: before.deal.id,\n organizationId: before.deal.organizationId,\n tenantId: before.deal.tenantId,\n title: before.deal.title,\n description: before.deal.description,\n status: before.deal.status,\n pipelineStage: before.deal.pipelineStage,\n pipelineId: before.deal.pipelineId,\n pipelineStageId: before.deal.pipelineStageId,\n valueAmount: before.deal.valueAmount,\n valueCurrency: before.deal.valueCurrency,\n probability: before.deal.probability,\n expectedCloseAt: coerceSnapshotDate(before.deal.expectedCloseAt, 'expectedCloseAt'),\n ownerUserId: before.deal.ownerUserId,\n source: before.deal.source,\n closureOutcome: before.deal.closureOutcome,\n lossReasonId: before.deal.lossReasonId,\n lossNotes: before.deal.lossNotes,\n })\n em.persist(deal)\n }\n await withAtomicFlush(em, [\n () => syncDealPeople(em, deal, before.people),\n () => syncDealCompanies(em, deal, before.companies),\n () => deleteDealStageTransitions(em, deal),\n () => restoreDealStageTransitions(em, deal, before.transitions),\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: deal,\n identifiers: {\n id: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n },\n indexer: dealCrudIndexer,\n events: dealCrudEvents,\n })\n\n const resetValues = buildCustomFieldResetMap(before.custom, undefined)\n if (Object.keys(resetValues).length) {\n await setCustomFieldsIfAny({\n dataEngine: de,\n entityId: DEAL_ENTITY_ID,\n recordId: deal.id,\n organizationId: deal.organizationId,\n tenantId: deal.tenantId,\n values: resetValues,\n notify: false,\n })\n }\n },\n }\n\nregisterCommand(createDealCommand)\nregisterCommand(updateDealCommand)\nregisterCommand(deleteDealCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AAGpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,OAEK;AACP,SAAS,eAAe,gBAAgB;AAExC,SAAS,SAAS;AAClB,SAAS,oBAAoB,6BAA6B;AAC1D,SAAS,mCAAmC,2CAA2C;AACvF,S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;AAAA,QACT,gBAAgB,KAAK;AAAA,QACrB,UAAU,KAAK;AAAA,MACjB;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,IACV,CAAC;AAED,UAAM,cAAc,yBAAyB,OAAO,QAAQ,MAAS;AACrE,QAAI,OAAO,KAAK,WAAW,EAAE,QAAQ;AACnC,YAAM,qBAAqB;AAAA,QACzB,YAAY;AAAA,QACZ,UAAU;AAAA,QACV,UAAU,KAAK;AAAA,QACf,gBAAgB,KAAK;AAAA,QACrB,UAAU,KAAK;AAAA,QACf,QAAQ;AAAA,QACR,QAAQ;AAAA,MACV,CAAC;AAAA,IACH;AAAA,EACF;AACF;AAEF,gBAAgB,iBAAiB;AACjC,gBAAgB,iBAAiB;AACjC,gBAAgB,iBAAiB;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import { registerCommand } from "@open-mercato/shared/lib/commands";
2
2
  import { buildChanges } from "@open-mercato/shared/lib/commands/helpers";
3
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
4
4
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
5
  import { invalidateDictionaryCache } from "../api/dictionaries/cache.js";
6
6
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
@@ -346,7 +346,7 @@ const updateDictionaryEntryCommand = {
346
346
  }
347
347
  );
348
348
  if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {
349
- throw new CrudHttpError(404, { error: "Dictionary entry not found" });
349
+ throw notFound("Dictionary entry not found");
350
350
  }
351
351
  let changed = false;
352
352
  if (parsed.value !== void 0) {
@@ -520,7 +520,7 @@ const deleteDictionaryEntryCommand = {
520
520
  }
521
521
  );
522
522
  if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {
523
- throw new CrudHttpError(404, { error: "Dictionary entry not found" });
523
+ throw notFound("Dictionary entry not found");
524
524
  }
525
525
  if (entry.kind === "person_company_role") {
526
526
  const usage = await loadRoleTypeUsage(em, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/dictionaries.ts"],
4
- "sourcesContent": ["import { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { buildChanges } from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { invalidateDictionaryCache } from '../api/dictionaries/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { loadRoleTypeUsage } from '../lib/roleTypeUsage'\nimport {\n customerDictionaryEntryCreateSchema,\n customerDictionaryEntryDeleteSchema,\n customerDictionaryEntryUpdateSchema,\n type CustomerDictionaryEntryCreateInput,\n type CustomerDictionaryEntryDeleteInput,\n type CustomerDictionaryEntryUpdateInput,\n} from '../data/validators'\nimport { CustomerDictionaryEntry } from '../data/entities'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n normalizeDictionaryColor,\n normalizeDictionaryIcon,\n} from './shared'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\ntype CustomerDictionaryEntrySnapshot = {\n id: string\n tenantId: string\n organizationId: string\n kind: string\n value: string\n normalizedValue: string\n label: string\n color: string | null\n icon: string | null\n}\n\ntype CustomerDictionaryEntryUndoPayload = {\n before?: CustomerDictionaryEntrySnapshot | null\n after?: CustomerDictionaryEntrySnapshot | null\n}\n\nfunction buildRoleTypeInUseError(usageCount: number, ownerAssignments: number, relationshipAssignments: number) {\n return new CrudHttpError(409, {\n code: 'role_type_in_use',\n error: 'Role type is in use',\n usageCount,\n ownerAssignments,\n relationshipAssignments,\n })\n}\n\nfunction normalizeValue(input: string): { value: string; normalized: string } {\n const trimmed = input.trim()\n if (!trimmed) {\n throw new CrudHttpError(400, { error: 'Dictionary entry value is required' })\n }\n return { value: trimmed, normalized: trimmed.toLowerCase() }\n}\n\nfunction sanitizeColor(input: string | null | undefined): string | null | undefined {\n if (input === undefined) return undefined\n if (input === null) return null\n return normalizeDictionaryColor(input)\n}\n\nfunction sanitizeIcon(input: string | null | undefined): string | null | undefined {\n if (input === undefined) return undefined\n if (input === null) return null\n return normalizeDictionaryIcon(input)\n}\n\nfunction toSnapshot(entry: CustomerDictionaryEntry): CustomerDictionaryEntrySnapshot {\n return {\n id: entry.id,\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n kind: entry.kind,\n value: entry.value,\n normalizedValue: entry.normalizedValue,\n label: entry.label,\n color: entry.color ?? null,\n icon: entry.icon ?? null,\n }\n}\n\nasync function loadSnapshot(\n em: EntityManager,\n id: string,\n scope: { tenantId: string | null; organizationId: string | null },\n): Promise<CustomerDictionaryEntrySnapshot | null> {\n const entry = await findOneWithDecryption(em, CustomerDictionaryEntry, { id }, {}, scope)\n return entry ? toSnapshot(entry) : null\n}\n\nfunction applySnapshot(entry: CustomerDictionaryEntry, snapshot: CustomerDictionaryEntrySnapshot): void {\n entry.tenantId = snapshot.tenantId\n entry.organizationId = snapshot.organizationId\n entry.kind = snapshot.kind\n entry.value = snapshot.value\n entry.normalizedValue = snapshot.normalizedValue\n entry.label = snapshot.label\n entry.color = snapshot.color\n entry.icon = snapshot.icon\n}\n\nasync function invalidateCache(\n ctx: CommandRuntimeContext,\n snapshot: CustomerDictionaryEntrySnapshot | null | undefined\n) {\n if (!snapshot) return\n let cache: CacheStrategy | undefined\n try {\n cache = (ctx.container.resolve('cache') as CacheStrategy)\n } catch (err) {\n logger.warn('cache resolve failed; skipping invalidation', { component: 'commands.dictionaries', err })\n cache = undefined\n }\n if (!cache) return\n await invalidateDictionaryCache(cache, {\n tenantId: snapshot.tenantId,\n mappedKind: snapshot.kind,\n organizationIds: [snapshot.organizationId],\n })\n}\n\ntype CreateResult = {\n entryId: string\n tenantId: string\n organizationId: string\n mode: 'created' | 'updated' | 'unchanged'\n before?: CustomerDictionaryEntrySnapshot | null\n}\n\nconst createDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryCreateInput, CreateResult> = {\n id: 'customers.dictionaryEntries.create',\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const value = normalizeValue(parsed.value)\n const label = parsed.label?.trim() || value.value\n const color = sanitizeColor(parsed.color)\n const icon = sanitizeIcon(parsed.icon)\n\n const existing = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n normalizedValue: value.normalized,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n\n if (existing) {\n const before = toSnapshot(existing)\n let changed = false\n\n if (parsed.label !== undefined && existing.label !== label) {\n existing.label = label\n changed = true\n }\n if (color !== undefined && existing.color !== color) {\n existing.color = color ?? null\n changed = true\n }\n if (icon !== undefined && existing.icon !== icon) {\n existing.icon = icon ?? null\n changed = true\n }\n\n if (changed) {\n existing.updatedAt = new Date()\n await em.flush()\n return {\n entryId: existing.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'updated',\n before,\n }\n }\n\n return {\n entryId: existing.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'unchanged',\n before,\n }\n }\n\n const entry = em.create(CustomerDictionaryEntry, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n value: value.value,\n normalizedValue: value.normalized,\n label,\n color: color ?? null,\n icon: icon ?? null,\n })\n em.persist(entry)\n await em.flush()\n\n return {\n entryId: entry.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'created',\n }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadSnapshot(em, result.entryId, {\n tenantId: result.tenantId,\n organizationId: result.organizationId,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CustomerDictionaryEntrySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n\n if (result.mode === 'created') {\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.create', 'Add dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n }\n\n if (result.mode === 'updated') {\n const before = result.before ?? null\n if (!before) return null\n const changes = buildChanges(\n before as unknown as Record<string, unknown>,\n after as unknown as Record<string, unknown>,\n ['label', 'color', 'icon']\n )\n if (!changes || Object.keys(changes).length === 0) return null\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.update', 'Update dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes,\n payload: {\n undo: { before, after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n }\n\n return null\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n if (!undo) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const after =\n undo.after ??\n (logEntry?.snapshotAfter as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n\n if (after && !undo.before) {\n ensureTenantScope(ctx, after.tenantId)\n ensureOrganizationScope(ctx, after.organizationId)\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: after.id },\n {},\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (entry) {\n await em.remove(entry).flush()\n await invalidateCache(ctx, after)\n return\n }\n await em.nativeDelete(CustomerDictionaryEntry, { id: after.id })\n await invalidateCache(ctx, after)\n return\n }\n\n const before =\n undo.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n\n if (before) {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n }\n },\n redo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const after = resolveRedoSnapshot<CustomerDictionaryEntrySnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for dictionary entry create' })\n }\n ensureTenantScope(ctx, after.tenantId)\n ensureOrganizationScope(ctx, after.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: after.id },\n {},\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n kind: after.kind,\n value: after.value,\n normalizedValue: after.normalizedValue,\n label: after.label,\n color: after.color,\n icon: after.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, after)\n entry.updatedAt = new Date()\n }\n await em.flush()\n await invalidateCache(ctx, after)\n\n return {\n entryId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n mode: undo?.before ? 'updated' : 'created',\n ...(undo?.before ? { before: undo.before } : {}),\n } satisfies CreateResult\n },\n}\n\ntype UpdateResult = {\n entryId: string\n tenantId: string\n organizationId: string\n changed: boolean\n}\n\nconst updateDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryUpdateInput, UpdateResult> = {\n id: 'customers.dictionaryEntries.update',\n async prepare(rawInput, ctx) {\n const parsed = customerDictionaryEntryUpdateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadSnapshot(em, parsed.id, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryUpdateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: parsed.id },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n\n let changed = false\n\n if (parsed.value !== undefined) {\n const value = normalizeValue(parsed.value)\n if (value.normalized !== entry.normalizedValue) {\n if (entry.kind === 'person_company_role') {\n const usage = await loadRoleTypeUsage(em, {\n tenantId: parsed.tenantId,\n organizationId: entry.organizationId,\n value: entry.value,\n })\n if (usage.total > 0) {\n throw buildRoleTypeInUseError(\n usage.total,\n usage.ownerAssignments,\n usage.relationshipAssignments,\n )\n }\n }\n const duplicate = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n {\n id: { $ne: entry.id },\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n normalizedValue: value.normalized,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (duplicate) {\n throw new CrudHttpError(409, { error: 'An entry with this value already exists' })\n }\n entry.value = value.value\n entry.normalizedValue = value.normalized\n if (parsed.label === undefined) {\n entry.label = value.value\n }\n changed = true\n }\n }\n\n if (parsed.label !== undefined) {\n const label = parsed.label.trim() || entry.value\n if (entry.label !== label) {\n entry.label = label\n changed = true\n }\n }\n\n if (parsed.color !== undefined) {\n const color = sanitizeColor(parsed.color)\n if (entry.color !== (color ?? null)) {\n entry.color = color ?? null\n changed = true\n }\n }\n\n if (parsed.icon !== undefined) {\n const icon = sanitizeIcon(parsed.icon)\n if (entry.icon !== (icon ?? null)) {\n entry.icon = icon ?? null\n changed = true\n }\n }\n\n if (changed) {\n entry.updatedAt = new Date()\n await em.flush()\n }\n\n return {\n entryId: entry.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n changed,\n }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadSnapshot(em, result.entryId, {\n tenantId: result.tenantId,\n organizationId: result.organizationId,\n })\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as CustomerDictionaryEntrySnapshot | undefined\n const after = snapshots.after as CustomerDictionaryEntrySnapshot | undefined\n if (!before || !after || !result.changed) return null\n const changes = buildChanges(\n before as unknown as Record<string, unknown>,\n after as unknown as Record<string, unknown>,\n ['value', 'label', 'color', 'icon']\n )\n if (!changes || Object.keys(changes).length === 0) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.update', 'Update dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes,\n payload: {\n undo: { before, after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const before =\n undo?.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n if (!before) return\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n },\n}\n\nconst deleteDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryDeleteInput, { entryId: string }> = {\n id: 'customers.dictionaryEntries.delete',\n async prepare(rawInput, ctx) {\n const parsed = customerDictionaryEntryDeleteSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadSnapshot(em, parsed.id, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryDeleteSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: parsed.id },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {\n throw new CrudHttpError(404, { error: 'Dictionary entry not found' })\n }\n if (entry.kind === 'person_company_role') {\n const usage = await loadRoleTypeUsage(em, {\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n value: entry.value,\n })\n if (usage.total > 0) {\n throw buildRoleTypeInUseError(\n usage.total,\n usage.ownerAssignments,\n usage.relationshipAssignments,\n )\n }\n }\n em.remove(entry)\n await em.flush()\n return { entryId: entry.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CustomerDictionaryEntrySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.delete', 'Delete dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const before =\n undo?.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n if (!before) return\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n },\n}\n\nregisterCommand(createDictionaryEntryCommand)\nregisterCommand(updateDictionaryEntryCommand)\nregisterCommand(deleteDictionaryEntryCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAA4C;AAErD,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AAEpC,SAAS,iCAAiC;AAE1C,SAAS,6BAA6B;AACtC,SAAS,yBAAyB;AAClC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAmBvC,SAAS,wBAAwB,YAAoB,kBAA0B,yBAAiC;AAC9G,SAAO,IAAI,cAAc,KAAK;AAAA,IAC5B,MAAM;AAAA,IACN,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AACH;AAEA,SAAS,eAAe,OAAsD;AAC5E,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,SAAS;AACZ,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,qCAAqC,CAAC;AAAA,EAC9E;AACA,SAAO,EAAE,OAAO,SAAS,YAAY,QAAQ,YAAY,EAAE;AAC7D;AAEA,SAAS,cAAc,OAA6D;AAClF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,UAAU,KAAM,QAAO;AAC3B,SAAO,yBAAyB,KAAK;AACvC;AAEA,SAAS,aAAa,OAA6D;AACjF,MAAI,UAAU,OAAW,QAAO;AAChC,MAAI,UAAU,KAAM,QAAO;AAC3B,SAAO,wBAAwB,KAAK;AACtC;AAEA,SAAS,WAAW,OAAiE;AACnF,SAAO;AAAA,IACL,IAAI,MAAM;AAAA,IACV,UAAU,MAAM;A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,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;",
4
+ "sourcesContent": ["import { registerCommand, type CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { buildChanges } from '@open-mercato/shared/lib/commands/helpers'\nimport { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { invalidateDictionaryCache } from '../api/dictionaries/cache'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { loadRoleTypeUsage } from '../lib/roleTypeUsage'\nimport {\n customerDictionaryEntryCreateSchema,\n customerDictionaryEntryDeleteSchema,\n customerDictionaryEntryUpdateSchema,\n type CustomerDictionaryEntryCreateInput,\n type CustomerDictionaryEntryDeleteInput,\n type CustomerDictionaryEntryUpdateInput,\n} from '../data/validators'\nimport { CustomerDictionaryEntry } from '../data/entities'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n normalizeDictionaryColor,\n normalizeDictionaryIcon,\n} from './shared'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\ntype CustomerDictionaryEntrySnapshot = {\n id: string\n tenantId: string\n organizationId: string\n kind: string\n value: string\n normalizedValue: string\n label: string\n color: string | null\n icon: string | null\n}\n\ntype CustomerDictionaryEntryUndoPayload = {\n before?: CustomerDictionaryEntrySnapshot | null\n after?: CustomerDictionaryEntrySnapshot | null\n}\n\nfunction buildRoleTypeInUseError(usageCount: number, ownerAssignments: number, relationshipAssignments: number) {\n return new CrudHttpError(409, {\n code: 'role_type_in_use',\n error: 'Role type is in use',\n usageCount,\n ownerAssignments,\n relationshipAssignments,\n })\n}\n\nfunction normalizeValue(input: string): { value: string; normalized: string } {\n const trimmed = input.trim()\n if (!trimmed) {\n throw new CrudHttpError(400, { error: 'Dictionary entry value is required' })\n }\n return { value: trimmed, normalized: trimmed.toLowerCase() }\n}\n\nfunction sanitizeColor(input: string | null | undefined): string | null | undefined {\n if (input === undefined) return undefined\n if (input === null) return null\n return normalizeDictionaryColor(input)\n}\n\nfunction sanitizeIcon(input: string | null | undefined): string | null | undefined {\n if (input === undefined) return undefined\n if (input === null) return null\n return normalizeDictionaryIcon(input)\n}\n\nfunction toSnapshot(entry: CustomerDictionaryEntry): CustomerDictionaryEntrySnapshot {\n return {\n id: entry.id,\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n kind: entry.kind,\n value: entry.value,\n normalizedValue: entry.normalizedValue,\n label: entry.label,\n color: entry.color ?? null,\n icon: entry.icon ?? null,\n }\n}\n\nasync function loadSnapshot(\n em: EntityManager,\n id: string,\n scope: { tenantId: string | null; organizationId: string | null },\n): Promise<CustomerDictionaryEntrySnapshot | null> {\n const entry = await findOneWithDecryption(em, CustomerDictionaryEntry, { id }, {}, scope)\n return entry ? toSnapshot(entry) : null\n}\n\nfunction applySnapshot(entry: CustomerDictionaryEntry, snapshot: CustomerDictionaryEntrySnapshot): void {\n entry.tenantId = snapshot.tenantId\n entry.organizationId = snapshot.organizationId\n entry.kind = snapshot.kind\n entry.value = snapshot.value\n entry.normalizedValue = snapshot.normalizedValue\n entry.label = snapshot.label\n entry.color = snapshot.color\n entry.icon = snapshot.icon\n}\n\nasync function invalidateCache(\n ctx: CommandRuntimeContext,\n snapshot: CustomerDictionaryEntrySnapshot | null | undefined\n) {\n if (!snapshot) return\n let cache: CacheStrategy | undefined\n try {\n cache = (ctx.container.resolve('cache') as CacheStrategy)\n } catch (err) {\n logger.warn('cache resolve failed; skipping invalidation', { component: 'commands.dictionaries', err })\n cache = undefined\n }\n if (!cache) return\n await invalidateDictionaryCache(cache, {\n tenantId: snapshot.tenantId,\n mappedKind: snapshot.kind,\n organizationIds: [snapshot.organizationId],\n })\n}\n\ntype CreateResult = {\n entryId: string\n tenantId: string\n organizationId: string\n mode: 'created' | 'updated' | 'unchanged'\n before?: CustomerDictionaryEntrySnapshot | null\n}\n\nconst createDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryCreateInput, CreateResult> = {\n id: 'customers.dictionaryEntries.create',\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const value = normalizeValue(parsed.value)\n const label = parsed.label?.trim() || value.value\n const color = sanitizeColor(parsed.color)\n const icon = sanitizeIcon(parsed.icon)\n\n const existing = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n normalizedValue: value.normalized,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n\n if (existing) {\n const before = toSnapshot(existing)\n let changed = false\n\n if (parsed.label !== undefined && existing.label !== label) {\n existing.label = label\n changed = true\n }\n if (color !== undefined && existing.color !== color) {\n existing.color = color ?? null\n changed = true\n }\n if (icon !== undefined && existing.icon !== icon) {\n existing.icon = icon ?? null\n changed = true\n }\n\n if (changed) {\n existing.updatedAt = new Date()\n await em.flush()\n return {\n entryId: existing.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'updated',\n before,\n }\n }\n\n return {\n entryId: existing.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'unchanged',\n before,\n }\n }\n\n const entry = em.create(CustomerDictionaryEntry, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n value: value.value,\n normalizedValue: value.normalized,\n label,\n color: color ?? null,\n icon: icon ?? null,\n })\n em.persist(entry)\n await em.flush()\n\n return {\n entryId: entry.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n mode: 'created',\n }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadSnapshot(em, result.entryId, {\n tenantId: result.tenantId,\n organizationId: result.organizationId,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const after = snapshots.after as CustomerDictionaryEntrySnapshot | undefined\n if (!after) return null\n const { translate } = await resolveTranslations()\n\n if (result.mode === 'created') {\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.create', 'Add dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotAfter: after,\n payload: {\n undo: { after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n }\n\n if (result.mode === 'updated') {\n const before = result.before ?? null\n if (!before) return null\n const changes = buildChanges(\n before as unknown as Record<string, unknown>,\n after as unknown as Record<string, unknown>,\n ['label', 'color', 'icon']\n )\n if (!changes || Object.keys(changes).length === 0) return null\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.update', 'Update dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes,\n payload: {\n undo: { before, after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n }\n\n return null\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n if (!undo) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const after =\n undo.after ??\n (logEntry?.snapshotAfter as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n\n if (after && !undo.before) {\n ensureTenantScope(ctx, after.tenantId)\n ensureOrganizationScope(ctx, after.organizationId)\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: after.id },\n {},\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (entry) {\n await em.remove(entry).flush()\n await invalidateCache(ctx, after)\n return\n }\n await em.nativeDelete(CustomerDictionaryEntry, { id: after.id })\n await invalidateCache(ctx, after)\n return\n }\n\n const before =\n undo.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n\n if (before) {\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n }\n },\n redo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const after = resolveRedoSnapshot<CustomerDictionaryEntrySnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for dictionary entry create' })\n }\n ensureTenantScope(ctx, after.tenantId)\n ensureOrganizationScope(ctx, after.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: after.id },\n {},\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n kind: after.kind,\n value: after.value,\n normalizedValue: after.normalizedValue,\n label: after.label,\n color: after.color,\n icon: after.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, after)\n entry.updatedAt = new Date()\n }\n await em.flush()\n await invalidateCache(ctx, after)\n\n return {\n entryId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n mode: undo?.before ? 'updated' : 'created',\n ...(undo?.before ? { before: undo.before } : {}),\n } satisfies CreateResult\n },\n}\n\ntype UpdateResult = {\n entryId: string\n tenantId: string\n organizationId: string\n changed: boolean\n}\n\nconst updateDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryUpdateInput, UpdateResult> = {\n id: 'customers.dictionaryEntries.update',\n async prepare(rawInput, ctx) {\n const parsed = customerDictionaryEntryUpdateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadSnapshot(em, parsed.id, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryUpdateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: parsed.id },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {\n throw notFound('Dictionary entry not found')\n }\n\n let changed = false\n\n if (parsed.value !== undefined) {\n const value = normalizeValue(parsed.value)\n if (value.normalized !== entry.normalizedValue) {\n if (entry.kind === 'person_company_role') {\n const usage = await loadRoleTypeUsage(em, {\n tenantId: parsed.tenantId,\n organizationId: entry.organizationId,\n value: entry.value,\n })\n if (usage.total > 0) {\n throw buildRoleTypeInUseError(\n usage.total,\n usage.ownerAssignments,\n usage.relationshipAssignments,\n )\n }\n }\n const duplicate = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n {\n id: { $ne: entry.id },\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: parsed.kind,\n normalizedValue: value.normalized,\n },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (duplicate) {\n throw new CrudHttpError(409, { error: 'An entry with this value already exists' })\n }\n entry.value = value.value\n entry.normalizedValue = value.normalized\n if (parsed.label === undefined) {\n entry.label = value.value\n }\n changed = true\n }\n }\n\n if (parsed.label !== undefined) {\n const label = parsed.label.trim() || entry.value\n if (entry.label !== label) {\n entry.label = label\n changed = true\n }\n }\n\n if (parsed.color !== undefined) {\n const color = sanitizeColor(parsed.color)\n if (entry.color !== (color ?? null)) {\n entry.color = color ?? null\n changed = true\n }\n }\n\n if (parsed.icon !== undefined) {\n const icon = sanitizeIcon(parsed.icon)\n if (entry.icon !== (icon ?? null)) {\n entry.icon = icon ?? null\n changed = true\n }\n }\n\n if (changed) {\n entry.updatedAt = new Date()\n await em.flush()\n }\n\n return {\n entryId: entry.id,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n changed,\n }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return loadSnapshot(em, result.entryId, {\n tenantId: result.tenantId,\n organizationId: result.organizationId,\n })\n },\n buildLog: async ({ snapshots, result }) => {\n const before = snapshots.before as CustomerDictionaryEntrySnapshot | undefined\n const after = snapshots.after as CustomerDictionaryEntrySnapshot | undefined\n if (!before || !after || !result.changed) return null\n const changes = buildChanges(\n before as unknown as Record<string, unknown>,\n after as unknown as Record<string, unknown>,\n ['value', 'label', 'color', 'icon']\n )\n if (!changes || Object.keys(changes).length === 0) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.update', 'Update dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: after.id,\n tenantId: after.tenantId,\n organizationId: after.organizationId,\n snapshotBefore: before,\n snapshotAfter: after,\n changes,\n payload: {\n undo: { before, after } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const before =\n undo?.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n if (!before) return\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n },\n}\n\nconst deleteDictionaryEntryCommand: CommandHandler<CustomerDictionaryEntryDeleteInput, { entryId: string }> = {\n id: 'customers.dictionaryEntries.delete',\n async prepare(rawInput, ctx) {\n const parsed = customerDictionaryEntryDeleteSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadSnapshot(em, parsed.id, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = customerDictionaryEntryDeleteSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: parsed.id },\n {},\n {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n },\n )\n if (!entry || entry.organizationId !== parsed.organizationId || entry.tenantId !== parsed.tenantId || entry.kind !== parsed.kind) {\n throw notFound('Dictionary entry not found')\n }\n if (entry.kind === 'person_company_role') {\n const usage = await loadRoleTypeUsage(em, {\n tenantId: entry.tenantId,\n organizationId: entry.organizationId,\n value: entry.value,\n })\n if (usage.total > 0) {\n throw buildRoleTypeInUseError(\n usage.total,\n usage.ownerAssignments,\n usage.relationshipAssignments,\n )\n }\n }\n em.remove(entry)\n await em.flush()\n return { entryId: entry.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CustomerDictionaryEntrySnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.dictionaryEntries.delete', 'Delete dictionary entry'),\n resourceKind: 'customers.dictionary_entry',\n resourceId: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: { before } satisfies CustomerDictionaryEntryUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const undo = extractUndoPayload<CustomerDictionaryEntryUndoPayload>(logEntry)\n const before =\n undo?.before ??\n (logEntry?.snapshotBefore as CustomerDictionaryEntrySnapshot | null | undefined) ??\n null\n if (!before) return\n ensureTenantScope(ctx, before.tenantId)\n ensureOrganizationScope(ctx, before.organizationId)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let entry = await findOneWithDecryption(\n em,\n CustomerDictionaryEntry,\n { id: before.id },\n {},\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!entry) {\n entry = em.create(CustomerDictionaryEntry, {\n id: before.id,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n kind: before.kind,\n value: before.value,\n normalizedValue: before.normalizedValue,\n label: before.label,\n color: before.color,\n icon: before.icon,\n })\n em.persist(entry)\n } else {\n applySnapshot(entry, before)\n }\n await em.flush()\n await invalidateCache(ctx, before)\n },\n}\n\nregisterCommand(createDictionaryEntryCommand)\nregisterCommand(updateDictionaryEntryCommand)\nregisterCommand(deleteDictionaryEnt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O;AAAA,MACnB,UAAU,OAAO;AAAA,MACjB,gBAAgB,OAAO;AAAA,MACvB,gBAAgB;AAAA,MAChB,SAAS;AAAA,QACP,MAAM,EAAE,OAAO;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AAAA,EACA,MAAM,OAAO,EAAE,UAAU,IAAI,MAAM;AACjC,UAAM,OAAO,mBAAuD,QAAQ;AAC5E,UAAM,SACJ,MAAM,UACL,UAAU,kBACX;AACF,QAAI,CAAC,OAAQ;AACb,sBAAkB,KAAK,OAAO,QAAQ;AACtC,4BAAwB,KAAK,OAAO,cAAc;AAClD,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAC/D,QAAI,QAAQ,MAAM;AAAA,MAChB;AAAA,MACA;AAAA,MACA,EAAE,IAAI,OAAO,GAAG;AAAA,MAChB,CAAC;AAAA,MACD,EAAE,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,IACrE;AACA,QAAI,CAAC,OAAO;AACV,cAAQ,GAAG,OAAO,yBAAyB;AAAA,QACzC,IAAI,OAAO;AAAA,QACX,UAAU,OAAO;AAAA,QACjB,gBAAgB,OAAO;AAAA,QACvB,MAAM,OAAO;AAAA,QACb,OAAO,OAAO;AAAA,QACd,iBAAiB,OAAO;AAAA,QACxB,OAAO,OAAO;AAAA,QACd,OAAO,OAAO;AAAA,QACd,MAAM,OAAO;AAAA,MACf,CAAC;AACD,SAAG,QAAQ,KAAK;AAAA,IAClB,OAAO;AACL,oBAAc,OAAO,MAAM;AAAA,IAC7B;AACA,UAAM,GAAG,MAAM;AACf,UAAM,gBAAgB,KAAK,MAAM;AAAA,EACnC;AACF;AAEA,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;AAC5C,gBAAgB,4BAA4B;",
6
6
  "names": []
7
7
  }
@@ -1,6 +1,6 @@
1
1
  import { registerCommand } from "@open-mercato/shared/lib/commands";
2
2
  import { emitCrudSideEffects, emitCrudUndoSideEffects } from "@open-mercato/shared/lib/commands/helpers";
3
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
3
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
4
4
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
5
5
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
6
6
  import { CustomerEntity, CustomerEntityRole } from "../data/entities.js";
@@ -277,7 +277,7 @@ const updateEntityRoleCommand = {
277
277
  { tenantId: parsed.tenantId, organizationId: parsed.organizationId }
278
278
  );
279
279
  if (!role) {
280
- throw new CrudHttpError(404, { error: "Role not found" });
280
+ throw notFound("Role not found");
281
281
  }
282
282
  role.userId = parsed.userId;
283
283
  await em.flush();
@@ -373,7 +373,7 @@ const deleteEntityRoleCommand = {
373
373
  { tenantId: parsed.tenantId, organizationId: parsed.organizationId }
374
374
  );
375
375
  if (!role) {
376
- throw new CrudHttpError(404, { error: "Role not found" });
376
+ throw notFound("Role not found");
377
377
  }
378
378
  role.deletedAt = /* @__PURE__ */ new Date();
379
379
  await em.flush();