@open-mercato/core 0.6.7-develop.6552.1.5208a19369 → 0.6.7-develop.6565.1.1026d85fff

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 (141) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/attachments/lib/reconcileOrganization.js +9 -7
  3. package/dist/modules/attachments/lib/reconcileOrganization.js.map +2 -2
  4. package/dist/modules/customers/api/companies/[id]/people/route.js +2 -2
  5. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  6. package/dist/modules/customers/api/deals/[id]/companies/route.js +2 -2
  7. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  8. package/dist/modules/customers/api/deals/[id]/people/route.js +2 -2
  9. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  10. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +4 -4
  11. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  12. package/dist/modules/customers/api/entity-roles-factory.js +3 -3
  13. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  14. package/dist/modules/customers/api/labels/assign/route.js +2 -2
  15. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  16. package/dist/modules/customers/api/labels/unassign/route.js +2 -2
  17. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  18. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +3 -7
  19. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +2 -2
  20. package/dist/modules/customers/api/people/[id]/companies/context.js +3 -3
  21. package/dist/modules/customers/api/people/[id]/companies/context.js.map +2 -2
  22. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +2 -2
  23. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  24. package/dist/modules/customers/api/todos/route.js +2 -2
  25. package/dist/modules/customers/api/todos/route.js.map +2 -2
  26. package/dist/modules/customers/commands/addresses.js +3 -3
  27. package/dist/modules/customers/commands/addresses.js.map +2 -2
  28. package/dist/modules/customers/commands/comments.js +3 -3
  29. package/dist/modules/customers/commands/comments.js.map +2 -2
  30. package/dist/modules/customers/commands/companies.js +2 -2
  31. package/dist/modules/customers/commands/companies.js.map +2 -2
  32. package/dist/modules/customers/commands/deals.js +3 -3
  33. package/dist/modules/customers/commands/deals.js.map +2 -2
  34. package/dist/modules/customers/commands/dictionaries.js +3 -3
  35. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  36. package/dist/modules/customers/commands/entity-roles.js +3 -3
  37. package/dist/modules/customers/commands/entity-roles.js.map +2 -2
  38. package/dist/modules/customers/commands/interactions.js +6 -6
  39. package/dist/modules/customers/commands/interactions.js.map +2 -2
  40. package/dist/modules/customers/commands/labels.js +7 -7
  41. package/dist/modules/customers/commands/labels.js.map +2 -2
  42. package/dist/modules/customers/commands/people.js +3 -3
  43. package/dist/modules/customers/commands/people.js.map +2 -2
  44. package/dist/modules/customers/commands/personCompanyLinks.js +6 -6
  45. package/dist/modules/customers/commands/personCompanyLinks.js.map +2 -2
  46. package/dist/modules/customers/commands/pipeline-stages.js +3 -3
  47. package/dist/modules/customers/commands/pipeline-stages.js.map +2 -2
  48. package/dist/modules/customers/commands/pipelines.js +3 -3
  49. package/dist/modules/customers/commands/pipelines.js.map +2 -2
  50. package/dist/modules/customers/commands/shared.js +3 -3
  51. package/dist/modules/customers/commands/shared.js.map +2 -2
  52. package/dist/modules/customers/commands/tags.js +7 -7
  53. package/dist/modules/customers/commands/tags.js.map +2 -2
  54. package/dist/modules/customers/commands/todos.js +3 -3
  55. package/dist/modules/customers/commands/todos.js.map +2 -2
  56. package/dist/modules/customers/lib/personCompanies.js +4 -4
  57. package/dist/modules/customers/lib/personCompanies.js.map +2 -2
  58. package/dist/modules/perspectives/data/validators.js +4 -0
  59. package/dist/modules/perspectives/data/validators.js.map +2 -2
  60. package/dist/modules/sales/api/notes/route.js +2 -4
  61. package/dist/modules/sales/api/notes/route.js.map +2 -2
  62. package/dist/modules/sales/api/quotes/accept/route.js +2 -2
  63. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  64. package/dist/modules/sales/api/quotes/public/[token]/route.js +3 -7
  65. package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
  66. package/dist/modules/sales/api/quotes/send/route.js +2 -2
  67. package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
  68. package/dist/modules/sales/api/returns/[id]/route.js +2 -2
  69. package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
  70. package/dist/modules/sales/commands/configuration.js +11 -11
  71. package/dist/modules/sales/commands/configuration.js.map +2 -2
  72. package/dist/modules/sales/commands/documentAddresses.js +3 -3
  73. package/dist/modules/sales/commands/documentAddresses.js.map +2 -2
  74. package/dist/modules/sales/commands/documents.js +31 -39
  75. package/dist/modules/sales/commands/documents.js.map +2 -2
  76. package/dist/modules/sales/commands/notes.js +7 -7
  77. package/dist/modules/sales/commands/notes.js.map +2 -2
  78. package/dist/modules/sales/commands/payments.js +2 -2
  79. package/dist/modules/sales/commands/payments.js.map +2 -2
  80. package/dist/modules/sales/commands/returns.js +8 -8
  81. package/dist/modules/sales/commands/returns.js.map +2 -2
  82. package/dist/modules/sales/commands/shared.js +2 -2
  83. package/dist/modules/sales/commands/shared.js.map +2 -2
  84. package/dist/modules/sales/commands/shipments.js +5 -5
  85. package/dist/modules/sales/commands/shipments.js.map +2 -2
  86. package/dist/modules/sales/commands/statuses.js +2 -2
  87. package/dist/modules/sales/commands/statuses.js.map +2 -2
  88. package/dist/modules/sales/commands/tags.js +3 -3
  89. package/dist/modules/sales/commands/tags.js.map +2 -2
  90. package/dist/modules/sales/lib/calculations.js +6 -0
  91. package/dist/modules/sales/lib/calculations.js.map +2 -2
  92. package/package.json +7 -7
  93. package/src/modules/attachments/lib/reconcileOrganization.ts +16 -7
  94. package/src/modules/customer_accounts/i18n/de.json +12 -0
  95. package/src/modules/customer_accounts/i18n/en.json +12 -0
  96. package/src/modules/customer_accounts/i18n/es.json +34 -22
  97. package/src/modules/customer_accounts/i18n/pl.json +32 -20
  98. package/src/modules/customers/api/companies/[id]/people/route.ts +2 -2
  99. package/src/modules/customers/api/deals/[id]/companies/route.ts +2 -2
  100. package/src/modules/customers/api/deals/[id]/people/route.ts +2 -2
  101. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +4 -4
  102. package/src/modules/customers/api/entity-roles-factory.ts +3 -3
  103. package/src/modules/customers/api/labels/assign/route.ts +2 -2
  104. package/src/modules/customers/api/labels/unassign/route.ts +2 -2
  105. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +3 -7
  106. package/src/modules/customers/api/people/[id]/companies/context.ts +3 -3
  107. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +2 -2
  108. package/src/modules/customers/api/todos/route.ts +2 -2
  109. package/src/modules/customers/commands/addresses.ts +3 -3
  110. package/src/modules/customers/commands/comments.ts +3 -3
  111. package/src/modules/customers/commands/companies.ts +2 -2
  112. package/src/modules/customers/commands/deals.ts +3 -3
  113. package/src/modules/customers/commands/dictionaries.ts +3 -3
  114. package/src/modules/customers/commands/entity-roles.ts +3 -3
  115. package/src/modules/customers/commands/interactions.ts +6 -6
  116. package/src/modules/customers/commands/labels.ts +7 -7
  117. package/src/modules/customers/commands/people.ts +3 -3
  118. package/src/modules/customers/commands/personCompanyLinks.ts +6 -6
  119. package/src/modules/customers/commands/pipeline-stages.ts +3 -3
  120. package/src/modules/customers/commands/pipelines.ts +3 -3
  121. package/src/modules/customers/commands/shared.ts +3 -3
  122. package/src/modules/customers/commands/tags.ts +7 -7
  123. package/src/modules/customers/commands/todos.ts +3 -3
  124. package/src/modules/customers/lib/personCompanies.ts +4 -4
  125. package/src/modules/perspectives/data/validators.ts +4 -0
  126. package/src/modules/sales/api/notes/route.ts +2 -4
  127. package/src/modules/sales/api/quotes/accept/route.ts +2 -2
  128. package/src/modules/sales/api/quotes/public/[token]/route.ts +3 -7
  129. package/src/modules/sales/api/quotes/send/route.ts +2 -2
  130. package/src/modules/sales/api/returns/[id]/route.ts +2 -2
  131. package/src/modules/sales/commands/configuration.ts +11 -11
  132. package/src/modules/sales/commands/documentAddresses.ts +3 -3
  133. package/src/modules/sales/commands/documents.ts +23 -31
  134. package/src/modules/sales/commands/notes.ts +7 -7
  135. package/src/modules/sales/commands/payments.ts +2 -2
  136. package/src/modules/sales/commands/returns.ts +8 -8
  137. package/src/modules/sales/commands/shared.ts +2 -2
  138. package/src/modules/sales/commands/shipments.ts +5 -5
  139. package/src/modules/sales/commands/statuses.ts +2 -2
  140. package/src/modules/sales/commands/tags.ts +3 -3
  141. package/src/modules/sales/lib/calculations.ts +15 -0
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/personCompanyLinks.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } 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 { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../data/entities'\nimport {\n personCompanyLinkCreateSchema,\n personCompanyLinkDeleteSchema,\n personCompanyLinkUpdateSchema,\n type PersonCompanyLinkCreateInput,\n type PersonCompanyLinkDeleteInput,\n type PersonCompanyLinkUpdateInput,\n} from '../data/validators'\nimport {\n findDeletedPersonCompanyLink,\n loadPersonCompanyLinks,\n promoteFallbackPrimaryLink,\n} from '../lib/personCompanies'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n} from './shared'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\n\ntype PersonCompanyLinkSnapshot = {\n id: string\n personEntityId: string\n companyEntityId: string\n isPrimary: boolean\n tenantId: string\n organizationId: string\n deletedAt: string | null\n}\n\ntype PersonCompanyLinkUndoPayload = {\n before?: PersonCompanyLinkSnapshot | null\n after?: PersonCompanyLinkSnapshot | null\n}\n\nconst personCompanyLinkCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'person_company_link',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.entity && typeof ctx.entity === 'object' && 'person' in (ctx.entity as Record<string, unknown>)\n ? {\n personEntityId:\n typeof (ctx.entity as CustomerPersonCompanyLink).person === 'string'\n ? (ctx.entity as any).person\n : (ctx.entity as CustomerPersonCompanyLink).person?.id ?? null,\n companyEntityId:\n typeof (ctx.entity as CustomerPersonCompanyLink).company === 'string'\n ? (ctx.entity as any).company\n : (ctx.entity as CustomerPersonCompanyLink).company?.id ?? null,\n }\n : {}),\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }),\n}\n\nfunction getLinkIdentifiers(link: CustomerPersonCompanyLink) {\n return {\n id: link.id,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n }\n}\n\nasync function loadPersonCompanyLinkSnapshot(\n em: EntityManager,\n id: string,\n scope?: { tenantId?: string | null; organizationId?: string | null },\n): Promise<PersonCompanyLinkSnapshot | null> {\n const filter: Record<string, unknown> = { id }\n if (scope?.tenantId) filter.tenantId = scope.tenantId\n if (scope?.organizationId) filter.organizationId = scope.organizationId\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n filter,\n undefined,\n {\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n },\n )\n if (!link) return null\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n return {\n id: link.id,\n personEntityId: personId,\n companyEntityId: companyId,\n isPrimary: Boolean(link.isPrimary),\n tenantId: link.tenantId,\n organizationId: link.organizationId,\n deletedAt: link.deletedAt ? link.deletedAt.toISOString() : null,\n }\n}\n\nasync function requirePersonEntity(\n em: EntityManager,\n entityId: string,\n tenantId: string,\n organizationId: string,\n): Promise<CustomerEntity> {\n const person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: entityId, kind: 'person', tenantId, organizationId, deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n if (!person) {\n throw new CrudHttpError(404, { error: 'Person not found' })\n }\n return person\n}\n\nasync function requireCompanyEntity(\n em: EntityManager,\n entityId: string,\n tenantId: string,\n organizationId: string,\n): Promise<CustomerEntity> {\n const company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: entityId, kind: 'company', tenantId, organizationId, deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n if (!company) {\n throw new CrudHttpError(404, { error: 'Company not found' })\n }\n return company\n}\n\nasync function requirePersonProfile(\n em: EntityManager,\n person: CustomerEntity,\n): Promise<CustomerPersonProfile> {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) {\n throw new CrudHttpError(404, { error: 'Person profile not found' })\n }\n return profile\n}\n\nasync function clearPrimaryFlagsForPerson(em: EntityManager, person: CustomerEntity): Promise<void> {\n await em.nativeUpdate(\n CustomerPersonCompanyLink,\n { person, organizationId: person.organizationId, tenantId: person.tenantId, isPrimary: true },\n { isPrimary: false },\n )\n}\n\nconst createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInput, { linkId: string; created: boolean; undeleted: boolean }> = {\n id: 'customers.personCompanyLinks.create',\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkCreateSchema.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 person = await requirePersonEntity(em, parsed.personEntityId, parsed.tenantId, parsed.organizationId)\n const company = await requireCompanyEntity(em, parsed.companyEntityId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n\n const existingLinks = await loadPersonCompanyLinks(em, person)\n const makePrimary = Boolean(parsed.isPrimary) || existingLinks.length === 0\n const existingLive =\n existingLinks.find((link) => (typeof link.company === 'string' ? link.company : link.company.id) === company.id) ?? null\n\n if (existingLive) {\n if (makePrimary && !existingLive.isPrimary) {\n await withAtomicFlush(em, [\n () => clearPrimaryFlagsForPerson(em, person),\n () => {\n existingLive.isPrimary = true\n profile.company = company\n },\n ], { transaction: true })\n }\n return { linkId: existingLive.id, created: false, undeleted: false }\n }\n\n let link!: CustomerPersonCompanyLink\n let undeleted = false\n await withAtomicFlush(em, [\n async () => {\n const deletedLink = await findDeletedPersonCompanyLink(em, person, company)\n if (makePrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n }\n if (deletedLink) {\n deletedLink.deletedAt = null\n deletedLink.isPrimary = makePrimary\n em.persist(deletedLink)\n link = deletedLink\n undeleted = true\n } else {\n link = em.create(CustomerPersonCompanyLink, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n person,\n company,\n isPrimary: makePrimary,\n })\n em.persist(link)\n }\n },\n () => {\n if (makePrimary) {\n profile.company = company\n } else if (!profile.company && existingLinks.length === 0) {\n profile.company = company\n link.isPrimary = true\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: undeleted ? 'updated' : 'created',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id, created: !undeleted, undeleted }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = ctx.container.resolve('em') as EntityManager\n return loadPersonCompanyLinkSnapshot(em, result.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.create', 'Link company to person'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: after?.personEntityId ?? null,\n tenantId: after?.tenantId ?? null,\n organizationId: after?.organizationId ?? null,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n after: after ?? null,\n ...(result.undeleted ? { before: null } : {}),\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let remainingLinks: CustomerPersonCompanyLink[] = []\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: after.personEntityId, kind: 'person', tenantId: after.tenantId, organizationId: after.organizationId, deletedAt: null },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!person) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) return\n remainingLinks = (await loadPersonCompanyLinks(em, person)).filter((entry) => entry.id !== link.id)\n },\n async () => {\n link.isPrimary = false\n link.deletedAt = new Date()\n if (!person || !profile) return\n if (after.isPrimary) {\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, after.companyEntityId)\n } else if (profile.company && typeof profile.company !== 'string' && profile.company.id === after.companyEntityId) {\n profile.company = null\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'deleted',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<PersonCompanyLinkSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for person-company link create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const person = await requirePersonEntity(em, after.personEntityId, after.tenantId, after.organizationId)\n const company = await requireCompanyEntity(em, after.companyEntityId, after.tenantId, after.organizationId)\n const profile = await requirePersonProfile(em, person)\n\n let link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n\n await withAtomicFlush(em, [\n async () => {\n if (after.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n }\n if (!link) {\n link = em.create(CustomerPersonCompanyLink, {\n id: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n person,\n company,\n isPrimary: after.isPrimary,\n })\n em.persist(link)\n } else {\n link.deletedAt = null\n link.isPrimary = after.isPrimary\n em.persist(link)\n }\n },\n () => {\n if (after.isPrimary) {\n profile.company = company\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: link!,\n identifiers: getLinkIdentifiers(link!),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link!.id, created: true, undeleted: false }\n },\n}\n\nconst updatePersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkUpdateInput, { linkId: string }> = {\n id: 'customers.personCompanyLinks.update',\n async prepare(rawInput, ctx) {\n const parsed = personCompanyLinkUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadPersonCompanyLinkSnapshot(em, parsed.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkUpdateSchema.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 link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n {\n id: parsed.linkId,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n if (!link) {\n throw new CrudHttpError(404, { error: 'Company link not found' })\n }\n\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n const person = await requirePersonEntity(em, personId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n const linkedCompany = await requireCompanyEntity(em, companyId, parsed.tenantId, parsed.organizationId)\n\n const linkWasPrimary = link.isPrimary\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n profile.company = linkedCompany\n } else if (!parsed.isPrimary) {\n link.isPrimary = false\n if (!linkWasPrimary && profile.company && typeof profile.company !== 'string' && profile.company.id === companyId) {\n profile.company = null\n }\n }\n },\n async () => {\n if (!parsed.isPrimary && linkWasPrimary) {\n const remainingLinks = (await loadPersonCompanyLinks(em, person)).filter((entry) => entry.id !== link.id)\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, companyId)\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = ctx.container.resolve('em') as EntityManager\n return loadPersonCompanyLinkSnapshot(em, result.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as PersonCompanyLinkSnapshot | undefined\n const after = snapshots.after as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.update', 'Update company link'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: after?.personEntityId ?? before?.personEntityId ?? null,\n tenantId: after?.tenantId ?? before?.tenantId ?? null,\n organizationId: after?.organizationId ?? before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n before: before ?? null,\n after: after ?? null,\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: before.id },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let company: CustomerEntity | null = null\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.personEntityId, kind: 'person', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!person) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile || !before.isPrimary) return\n company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.companyEntityId, kind: 'company', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n },\n async () => {\n if (!person || !profile) return\n if (before.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n if (company) profile.company = company\n } else {\n link.isPrimary = false\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n}\n\nconst deletePersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkDeleteInput, { linkId: string }> = {\n id: 'customers.personCompanyLinks.delete',\n async prepare(rawInput, ctx) {\n const parsed = personCompanyLinkDeleteSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadPersonCompanyLinkSnapshot(em, parsed.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkDeleteSchema.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 link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n {\n id: parsed.linkId,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n if (!link) {\n throw new CrudHttpError(404, { error: 'Company link not found' })\n }\n\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n const person = await requirePersonEntity(em, personId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n const linkWasPrimary = link.isPrimary\n\n const existingLinks = await loadPersonCompanyLinks(em, person)\n const remainingLinks = existingLinks.filter((entry) => entry.id !== link.id)\n\n await withAtomicFlush(em, [\n () => {\n link.isPrimary = false\n link.deletedAt = new Date()\n },\n async () => {\n if (linkWasPrimary) {\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, companyId)\n } else if (profile.company && typeof profile.company !== 'string' && profile.company.id === companyId) {\n const primary = remainingLinks.find((entry) => entry.isPrimary) ?? null\n const primaryCompany = primary && typeof primary.company !== 'string' ? primary.company : null\n if (primaryCompany) {\n profile.company = primaryCompany\n }\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id }\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.delete', 'Remove company link'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: before?.personEntityId ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n payload: {\n undo: {\n before: before ?? null,\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: before.id },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let company: CustomerEntity | null = null\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.personEntityId, kind: 'person', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!person || !before.isPrimary) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) return\n company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.companyEntityId, kind: 'company', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n },\n async () => {\n link.deletedAt = null\n link.isPrimary = before.isPrimary\n if (person && before.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n if (profile && company) profile.company = company\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'created',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n}\n\nregisterCommand(createPersonCompanyLinkCommand)\nregisterCommand(updatePersonCompanyLinkCommand)\nregisterCommand(deletePersonCompanyLinkCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAGhC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,qBAAqB;AAC9B,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AAGtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAiBpC,MAAM,8BAAgD;AAAA,EACpD,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,SAAS;AAAA,IACtB,IAAI,IAAI,YAAY;AAAA,IACpB,gBAAgB,IAAI,YAAY;AAAA,IAChC,UAAU,IAAI,YAAY;AAAA,IAC1B,GAAI,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY,YAAa,IAAI,SACjE;AAAA,MACE,gBACE,OAAQ,IAAI,OAAqC,WAAW,WACvD,IAAI,OAAe,SACnB,IAAI,OAAqC,QAAQ,MAAM;AAAA,MAC9D,iBACE,OAAQ,IAAI,OAAqC,YAAY,WACxD,IAAI,OAAe,UACnB,IAAI,OAAqC,SAAS,MAAM;AAAA,IACjE,IACA,CAAC;AAAA,IACL,GAAI,IAAI,aAAa,EAAE,YAAY,IAAI,WAAW,IAAI,CAAC;AAAA,EACzD;AACF;AAEA,SAAS,mBAAmB,MAAiC;AAC3D,SAAO;AAAA,IACL,IAAI,KAAK;AAAA,IACT,gBAAgB,KAAK;AAAA,IACrB,UAAU,KAAK;AAAA,EACjB;AACF;AAEA,eAAe,8BACb,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C,QAAS;AACd,kBAAU,MAAM;AAAA,UACd;AAAA,UACA;AAAA,UACA,EAAE,IAAI,OAAO,iBAAiB,MAAM,WAAW,UAAU,OAAO,UAAU,gBAAgB,OAAO,gBAAgB,WAAW,KAAK;AAAA,UACjI;AAAA,UACA,EAAE,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,QACrE;AAAA,MACF;AAAA,MACA,YAAY;AACV,aAAK,YAAY;AACjB,aAAK,YAAY,OAAO;AACxB,YAAI,UAAU,OAAO,WAAW;AAC9B,gBAAM,2BAA2B,IAAI,MAAM;AAC3C,eAAK,YAAY;AACjB,cAAI,WAAW,QAAS,SAAQ,UAAU;AAAA,QAC5C;AAAA,MACF;AAAA,IACF,GAAG,EAAE,aAAa,KAAK,CAAC;AAExB,UAAM,aAAa,IAAI,UAAU,QAAQ,YAAY;AACrD,UAAM,wBAAwB;AAAA,MAC5B;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,aAAa,mBAAmB,IAAI;AAAA,MACpC,YAAY,IAAI;AAAA,MAChB,QAAQ;AAAA,MACR,SAAS,EAAE,YAAY,yCAAyC;AAAA,IAClE,CAAC;AAAA,EACH;AACF;AAEA,gBAAgB,8BAA8B;AAC9C,gBAAgB,8BAA8B;AAC9C,gBAAgB,8BAA8B;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects } 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 { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport {\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../data/entities'\nimport {\n personCompanyLinkCreateSchema,\n personCompanyLinkDeleteSchema,\n personCompanyLinkUpdateSchema,\n type PersonCompanyLinkCreateInput,\n type PersonCompanyLinkDeleteInput,\n type PersonCompanyLinkUpdateInput,\n} from '../data/validators'\nimport {\n findDeletedPersonCompanyLink,\n loadPersonCompanyLinks,\n promoteFallbackPrimaryLink,\n} from '../lib/personCompanies'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n extractUndoPayload,\n} from './shared'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\n\ntype PersonCompanyLinkSnapshot = {\n id: string\n personEntityId: string\n companyEntityId: string\n isPrimary: boolean\n tenantId: string\n organizationId: string\n deletedAt: string | null\n}\n\ntype PersonCompanyLinkUndoPayload = {\n before?: PersonCompanyLinkSnapshot | null\n after?: PersonCompanyLinkSnapshot | null\n}\n\nconst personCompanyLinkCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'person_company_link',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n ...(ctx.entity && typeof ctx.entity === 'object' && 'person' in (ctx.entity as Record<string, unknown>)\n ? {\n personEntityId:\n typeof (ctx.entity as CustomerPersonCompanyLink).person === 'string'\n ? (ctx.entity as any).person\n : (ctx.entity as CustomerPersonCompanyLink).person?.id ?? null,\n companyEntityId:\n typeof (ctx.entity as CustomerPersonCompanyLink).company === 'string'\n ? (ctx.entity as any).company\n : (ctx.entity as CustomerPersonCompanyLink).company?.id ?? null,\n }\n : {}),\n ...(ctx.syncOrigin ? { syncOrigin: ctx.syncOrigin } : {}),\n }),\n}\n\nfunction getLinkIdentifiers(link: CustomerPersonCompanyLink) {\n return {\n id: link.id,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n }\n}\n\nasync function loadPersonCompanyLinkSnapshot(\n em: EntityManager,\n id: string,\n scope?: { tenantId?: string | null; organizationId?: string | null },\n): Promise<PersonCompanyLinkSnapshot | null> {\n const filter: Record<string, unknown> = { id }\n if (scope?.tenantId) filter.tenantId = scope.tenantId\n if (scope?.organizationId) filter.organizationId = scope.organizationId\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n filter,\n undefined,\n {\n tenantId: scope?.tenantId ?? null,\n organizationId: scope?.organizationId ?? null,\n },\n )\n if (!link) return null\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n return {\n id: link.id,\n personEntityId: personId,\n companyEntityId: companyId,\n isPrimary: Boolean(link.isPrimary),\n tenantId: link.tenantId,\n organizationId: link.organizationId,\n deletedAt: link.deletedAt ? link.deletedAt.toISOString() : null,\n }\n}\n\nasync function requirePersonEntity(\n em: EntityManager,\n entityId: string,\n tenantId: string,\n organizationId: string,\n): Promise<CustomerEntity> {\n const person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: entityId, kind: 'person', tenantId, organizationId, deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n if (!person) {\n throw notFound('Person not found')\n }\n return person\n}\n\nasync function requireCompanyEntity(\n em: EntityManager,\n entityId: string,\n tenantId: string,\n organizationId: string,\n): Promise<CustomerEntity> {\n const company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: entityId, kind: 'company', tenantId, organizationId, deletedAt: null },\n undefined,\n { tenantId, organizationId },\n )\n if (!company) {\n throw notFound('Company not found')\n }\n return company\n}\n\nasync function requirePersonProfile(\n em: EntityManager,\n person: CustomerEntity,\n): Promise<CustomerPersonProfile> {\n const profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) {\n throw notFound('Person profile not found')\n }\n return profile\n}\n\nasync function clearPrimaryFlagsForPerson(em: EntityManager, person: CustomerEntity): Promise<void> {\n await em.nativeUpdate(\n CustomerPersonCompanyLink,\n { person, organizationId: person.organizationId, tenantId: person.tenantId, isPrimary: true },\n { isPrimary: false },\n )\n}\n\nconst createPersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkCreateInput, { linkId: string; created: boolean; undeleted: boolean }> = {\n id: 'customers.personCompanyLinks.create',\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkCreateSchema.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 person = await requirePersonEntity(em, parsed.personEntityId, parsed.tenantId, parsed.organizationId)\n const company = await requireCompanyEntity(em, parsed.companyEntityId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n\n const existingLinks = await loadPersonCompanyLinks(em, person)\n const makePrimary = Boolean(parsed.isPrimary) || existingLinks.length === 0\n const existingLive =\n existingLinks.find((link) => (typeof link.company === 'string' ? link.company : link.company.id) === company.id) ?? null\n\n if (existingLive) {\n if (makePrimary && !existingLive.isPrimary) {\n await withAtomicFlush(em, [\n () => clearPrimaryFlagsForPerson(em, person),\n () => {\n existingLive.isPrimary = true\n profile.company = company\n },\n ], { transaction: true })\n }\n return { linkId: existingLive.id, created: false, undeleted: false }\n }\n\n let link!: CustomerPersonCompanyLink\n let undeleted = false\n await withAtomicFlush(em, [\n async () => {\n const deletedLink = await findDeletedPersonCompanyLink(em, person, company)\n if (makePrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n }\n if (deletedLink) {\n deletedLink.deletedAt = null\n deletedLink.isPrimary = makePrimary\n em.persist(deletedLink)\n link = deletedLink\n undeleted = true\n } else {\n link = em.create(CustomerPersonCompanyLink, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n person,\n company,\n isPrimary: makePrimary,\n })\n em.persist(link)\n }\n },\n () => {\n if (makePrimary) {\n profile.company = company\n } else if (!profile.company && existingLinks.length === 0) {\n profile.company = company\n link.isPrimary = true\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: undeleted ? 'updated' : 'created',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id, created: !undeleted, undeleted }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = ctx.container.resolve('em') as EntityManager\n return loadPersonCompanyLinkSnapshot(em, result.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const after = snapshots.after as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.create', 'Link company to person'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: after?.personEntityId ?? null,\n tenantId: after?.tenantId ?? null,\n organizationId: after?.organizationId ?? null,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n after: after ?? null,\n ...(result.undeleted ? { before: null } : {}),\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const after = payload?.after\n if (!after) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let remainingLinks: CustomerPersonCompanyLink[] = []\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: after.personEntityId, kind: 'person', tenantId: after.tenantId, organizationId: after.organizationId, deletedAt: null },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!person) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) return\n remainingLinks = (await loadPersonCompanyLinks(em, person)).filter((entry) => entry.id !== link.id)\n },\n async () => {\n link.isPrimary = false\n link.deletedAt = new Date()\n if (!person || !profile) return\n if (after.isPrimary) {\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, after.companyEntityId)\n } else if (profile.company && typeof profile.company !== 'string' && profile.company.id === after.companyEntityId) {\n profile.company = null\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'deleted',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<PersonCompanyLinkSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for person-company link create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const person = await requirePersonEntity(em, after.personEntityId, after.tenantId, after.organizationId)\n const company = await requireCompanyEntity(em, after.companyEntityId, after.tenantId, after.organizationId)\n const profile = await requirePersonProfile(em, person)\n\n let link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n\n await withAtomicFlush(em, [\n async () => {\n if (after.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n }\n if (!link) {\n link = em.create(CustomerPersonCompanyLink, {\n id: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n person,\n company,\n isPrimary: after.isPrimary,\n })\n em.persist(link)\n } else {\n link.deletedAt = null\n link.isPrimary = after.isPrimary\n em.persist(link)\n }\n },\n () => {\n if (after.isPrimary) {\n profile.company = company\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'created',\n entity: link!,\n identifiers: getLinkIdentifiers(link!),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link!.id, created: true, undeleted: false }\n },\n}\n\nconst updatePersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkUpdateInput, { linkId: string }> = {\n id: 'customers.personCompanyLinks.update',\n async prepare(rawInput, ctx) {\n const parsed = personCompanyLinkUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadPersonCompanyLinkSnapshot(em, parsed.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkUpdateSchema.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 link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n {\n id: parsed.linkId,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n if (!link) {\n throw notFound('Company link not found')\n }\n\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n const person = await requirePersonEntity(em, personId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n const linkedCompany = await requireCompanyEntity(em, companyId, parsed.tenantId, parsed.organizationId)\n\n const linkWasPrimary = link.isPrimary\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n profile.company = linkedCompany\n } else if (!parsed.isPrimary) {\n link.isPrimary = false\n if (!linkWasPrimary && profile.company && typeof profile.company !== 'string' && profile.company.id === companyId) {\n profile.company = null\n }\n }\n },\n async () => {\n if (!parsed.isPrimary && linkWasPrimary) {\n const remainingLinks = (await loadPersonCompanyLinks(em, person)).filter((entry) => entry.id !== link.id)\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, companyId)\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'updated',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = ctx.container.resolve('em') as EntityManager\n return loadPersonCompanyLinkSnapshot(em, result.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as PersonCompanyLinkSnapshot | undefined\n const after = snapshots.after as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.update', 'Update company link'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: after?.personEntityId ?? before?.personEntityId ?? null,\n tenantId: after?.tenantId ?? before?.tenantId ?? null,\n organizationId: after?.organizationId ?? before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n snapshotAfter: after ?? null,\n payload: {\n undo: {\n before: before ?? null,\n after: after ?? null,\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: before.id },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let company: CustomerEntity | null = null\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.personEntityId, kind: 'person', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!person) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile || !before.isPrimary) return\n company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.companyEntityId, kind: 'company', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n },\n async () => {\n if (!person || !profile) return\n if (before.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n if (company) profile.company = company\n } else {\n link.isPrimary = false\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'updated',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n}\n\nconst deletePersonCompanyLinkCommand: CommandHandler<PersonCompanyLinkDeleteInput, { linkId: string }> = {\n id: 'customers.personCompanyLinks.delete',\n async prepare(rawInput, ctx) {\n const parsed = personCompanyLinkDeleteSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const snapshot = await loadPersonCompanyLinkSnapshot(em, parsed.linkId, {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n })\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = personCompanyLinkDeleteSchema.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 link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n {\n id: parsed.linkId,\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n deletedAt: null,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n if (!link) {\n throw notFound('Company link not found')\n }\n\n const personId = typeof link.person === 'string' ? link.person : link.person.id\n const companyId = typeof link.company === 'string' ? link.company : link.company.id\n const person = await requirePersonEntity(em, personId, parsed.tenantId, parsed.organizationId)\n const profile = await requirePersonProfile(em, person)\n const linkWasPrimary = link.isPrimary\n\n const existingLinks = await loadPersonCompanyLinks(em, person)\n const remainingLinks = existingLinks.filter((entry) => entry.id !== link.id)\n\n await withAtomicFlush(em, [\n () => {\n link.isPrimary = false\n link.deletedAt = new Date()\n },\n async () => {\n if (linkWasPrimary) {\n await promoteFallbackPrimaryLink(em, person, profile, remainingLinks, companyId)\n } else if (profile.company && typeof profile.company !== 'string' && profile.company.id === companyId) {\n const primary = remainingLinks.find((entry) => entry.isPrimary) ?? null\n const primaryCompany = primary && typeof primary.company !== 'string' ? primary.company : null\n if (primaryCompany) {\n profile.company = primaryCompany\n }\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudSideEffects({\n dataEngine,\n action: 'deleted',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n\n return { linkId: link.id }\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as PersonCompanyLinkSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.personCompanyLinks.delete', 'Remove company link'),\n resourceKind: 'customers.personCompanyLink',\n resourceId: result.linkId,\n parentResourceKind: 'customers.person',\n parentResourceId: before?.personEntityId ?? null,\n tenantId: before?.tenantId ?? null,\n organizationId: before?.organizationId ?? null,\n snapshotBefore: before ?? null,\n payload: {\n undo: {\n before: before ?? null,\n } satisfies PersonCompanyLinkUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<PersonCompanyLinkUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const link = await findOneWithDecryption(\n em,\n CustomerPersonCompanyLink,\n { id: before.id },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!link) return\n\n let person: CustomerEntity | null = null\n let profile: CustomerPersonProfile | null = null\n let company: CustomerEntity | null = null\n\n await withAtomicFlush(em, [\n async () => {\n person = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.personEntityId, kind: 'person', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n if (!person || !before.isPrimary) return\n profile = await findOneWithDecryption(\n em,\n CustomerPersonProfile,\n { entity: person },\n { populate: ['company'] },\n { tenantId: person.tenantId, organizationId: person.organizationId },\n )\n if (!profile) return\n company = await findOneWithDecryption(\n em,\n CustomerEntity,\n { id: before.companyEntityId, kind: 'company', tenantId: before.tenantId, organizationId: before.organizationId, deletedAt: null },\n undefined,\n { tenantId: before.tenantId, organizationId: before.organizationId },\n )\n },\n async () => {\n link.deletedAt = null\n link.isPrimary = before.isPrimary\n if (person && before.isPrimary) {\n await clearPrimaryFlagsForPerson(em, person)\n link.isPrimary = true\n if (profile && company) profile.company = company\n }\n },\n ], { transaction: true })\n\n const dataEngine = ctx.container.resolve('dataEngine') as DataEngine\n await emitCrudUndoSideEffects({\n dataEngine,\n action: 'created',\n entity: link,\n identifiers: getLinkIdentifiers(link),\n syncOrigin: ctx.syncOrigin,\n events: personCompanyLinkCrudEvents,\n indexer: { entityType: 'customers:customer_person_company_link' },\n })\n },\n}\n\nregisterCommand(createPersonCompanyLinkCommand)\nregisterCommand(updatePersonCompanyLinkCommand)\nregisterCommand(deletePersonCompanyLinkCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAGhC,SAAS,qBAAqB,+BAA+B;AAC7D,SAAS,eAAe,gBAAgB;AACxC,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AAGtC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AAiBpC,MAAM,8BAAgD;AAAA,EACpD,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,YAAY;AAAA,EACZ,cAAc,CAAC,SAAS;AAAA,IACtB,IAAI,IAAI,YAAY;AAAA,IACpB,gBAAgB,IAAI,YAAY;AAAA,IAChC,UAAU,IAAI,YAAY;AAAA,IAC1B,GAAI,IAAI,UAAU,OAAO,IAAI,WAAW,YAAY,YAAa,IAAI,SACjE;AAAA,MACE,gBACE,OAAQ,IAAI,OAAqC,WAAW,WACvD,IAAI,OAAe,SACnB,IAAI,OAAqC,QAAQ,MAAM;AAAA,MAC9D,iBACE,OAAQ,IAAI,OAAqC,YAAY,WACxD,IAAI,OAAe,UACnB,IAAI,OAAqC,SAAS,MAAM;AAAA,IACjE,IACA,CAAC;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,UACxB,EAAE,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,QACrE;AACA,YAAI,CAAC,QAAS;AACd,kBAAU,MAAM;AAAA,UACd;AAAA,UACA;AAAA,UACA,EAAE,IAAI,OAAO,iBAAiB,MAAM,WAAW,UAAU,OAAO,UAAU,gBAAgB,OAAO,gBAAgB,WAAW,KAAK;AAAA,UACjI;AAAA,UACA,EAAE,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,QACrE;AAAA,MACF;AAAA,MACA,YAAY;AACV,aAAK,YAAY;AACjB,aAAK,YAAY,OAAO;AACxB,YAAI,UAAU,OAAO,WAAW;AAC9B,gBAAM,2BAA2B,IAAI,MAAM;AAC3C,eAAK,YAAY;AACjB,cAAI,WAAW,QAAS,SAAQ,UAAU;AAAA,QAC5C;AAAA,MACF;AAAA,IACF,GAAG,EAAE,aAAa,KAAK,CAAC;AAExB,UAAM,aAAa,IAAI,UAAU,QAAQ,YAAY;AACrD,UAAM,wBAAwB;AAAA,MAC5B;AAAA,MACA,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,aAAa,mBAAmB,IAAI;AAAA,MACpC,YAAY,IAAI;AAAA,MAChB,QAAQ;AAAA,MACR,SAAS,EAAE,YAAY,yCAAyC;AAAA,IAClE,CAAC;AAAA,EACH;AACF;AAEA,gBAAgB,8BAA8B;AAC9C,gBAAgB,8BAA8B;AAC9C,gBAAgB,8BAA8B;",
6
6
  "names": ["link"]
7
7
  }
@@ -8,7 +8,7 @@ import {
8
8
  pipelineStageReorderSchema
9
9
  } from "../data/validators.js";
10
10
  import { ensureOrganizationScope, ensureTenantScope, ensureDictionaryEntry } from "./shared.js";
11
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
11
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
12
12
  import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
13
13
  import {
14
14
  enforceCommandOptimisticLockWithGuards,
@@ -83,7 +83,7 @@ const updatePipelineStageCommand = {
83
83
  });
84
84
  if (!stage) {
85
85
  enforceRecordGoneIsConflict({ resourceKind: "customers.pipelineStage", resourceId: parsed.id, request: ctx.request ?? null });
86
- throw new CrudHttpError(404, { error: "Pipeline stage not found" });
86
+ throw notFound("Pipeline stage not found");
87
87
  }
88
88
  ensureTenantScope(ctx, stage.tenantId);
89
89
  ensureOrganizationScope(ctx, stage.organizationId);
@@ -128,7 +128,7 @@ const deletePipelineStageCommand = {
128
128
  });
129
129
  if (!stage) {
130
130
  enforceRecordGoneIsConflict({ resourceKind: "customers.pipelineStage", resourceId: parsed.id, request: ctx.request ?? null });
131
- throw new CrudHttpError(404, { error: "Pipeline stage not found" });
131
+ throw notFound("Pipeline stage not found");
132
132
  }
133
133
  ensureTenantScope(ctx, stage.tenantId);
134
134
  ensureOrganizationScope(ctx, stage.organizationId);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/pipeline-stages.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerPipelineStage, CustomerDeal } from '../data/entities'\nimport {\n pipelineStageCreateSchema,\n pipelineStageUpdateSchema,\n pipelineStageDeleteSchema,\n pipelineStageReorderSchema,\n type PipelineStageCreateInput,\n type PipelineStageUpdateInput,\n type PipelineStageDeleteInput,\n type PipelineStageReorderInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, ensureDictionaryEntry } from './shared'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport {\n enforceCommandOptimisticLockWithGuards,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\n\nconst createPipelineStageCommand: CommandHandler<PipelineStageCreateInput, { stageId: string }> = {\n id: 'customers.pipeline-stages.create',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n // Load the full ordered list once. We need it both to know where \"end\" is and to\n // shift any stages that occupy positions at or after the chosen insert point.\n const existingStages = await findWithDecryption(\n em,\n CustomerPipelineStage,\n {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n pipelineId: parsed.pipelineId,\n },\n { orderBy: { order: 'ASC' } },\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n\n // Clamp the requested insert position into the legal range [0, length]. Anything\n // outside that range (negative, way past the end) collapses to \"append\" so we never\n // create stages that hop the visible board boundary.\n const requestedOrder = parsed.order\n const insertOrder =\n requestedOrder === undefined\n ? existingStages.length\n : Math.max(0, Math.min(requestedOrder, existingStages.length))\n\n const stage = em.create(CustomerPipelineStage, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n pipelineId: parsed.pipelineId,\n label: parsed.label,\n order: insertOrder,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n await withAtomicFlush(em, [\n () => {\n // Shift the order of every stage at or after the insert position. Skipping\n // this step would either duplicate `order` values (silently corrupting kanban\n // ordering) or push the new stage to the wrong spot when re-sorting.\n if (requestedOrder !== undefined) {\n for (const existing of existingStages) {\n if (existing.order >= insertOrder) {\n existing.order += 1\n existing.updatedAt = new Date()\n }\n }\n }\n em.persist(stage)\n },\n async () => {\n await ensureDictionaryEntry(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n color: parsed.color,\n icon: parsed.icon,\n })\n },\n ], { transaction: true })\n\n return { stageId: stage.id }\n },\n}\n\nconst updatePipelineStageCommand: CommandHandler<PipelineStageUpdateInput, void> = {\n id: 'customers.pipeline-stages.update',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageUpdateSchema.parse(rawInput)\n\n // Restrict the lookup to the caller's tenant/organization scope so a\n // wrong-tenant id returns 404 (same as a missing row), not 403 \u2014 avoids\n // leaking existence of stages outside the caller's scope.\n const callerTenantId = ctx.auth?.tenantId ?? null\n const callerOrganizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, {\n id: parsed.id,\n ...(callerTenantId ? { tenantId: callerTenantId } : {}),\n ...(callerOrganizationId ? { organizationId: callerOrganizationId } : {}),\n })\n if (!stage) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipelineStage', resourceId: parsed.id, request: ctx.request ?? null })\n throw new CrudHttpError(404, { error: 'Pipeline stage not found' })\n }\n\n ensureTenantScope(ctx, stage.tenantId)\n ensureOrganizationScope(ctx, stage.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipelineStage',\n resourceId: stage.id,\n current: stage.updatedAt,\n request: ctx.request ?? null,\n })\n\n await withAtomicFlush(em, [\n () => {\n if (parsed.label !== undefined) stage.label = parsed.label\n if (parsed.order !== undefined) stage.order = parsed.order\n stage.updatedAt = new Date()\n },\n async () => {\n if (parsed.label !== undefined || parsed.color !== undefined || parsed.icon !== undefined) {\n await ensureDictionaryEntry(em, {\n tenantId: stage.tenantId,\n organizationId: stage.organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n color: parsed.color,\n icon: parsed.icon,\n })\n }\n },\n ], { transaction: true })\n },\n}\n\nconst deletePipelineStageCommand: CommandHandler<PipelineStageDeleteInput, void> = {\n id: 'customers.pipeline-stages.delete',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageDeleteSchema.parse(rawInput)\n\n // See update command above \u2014 scope the lookup to the caller's tenant/org so a\n // cross-tenant id returns 404, not 403.\n const callerTenantId = ctx.auth?.tenantId ?? null\n const callerOrganizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, {\n id: parsed.id,\n ...(callerTenantId ? { tenantId: callerTenantId } : {}),\n ...(callerOrganizationId ? { organizationId: callerOrganizationId } : {}),\n })\n if (!stage) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipelineStage', resourceId: parsed.id, request: ctx.request ?? null })\n throw new CrudHttpError(404, { error: 'Pipeline stage not found' })\n }\n\n ensureTenantScope(ctx, stage.tenantId)\n ensureOrganizationScope(ctx, stage.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipelineStage',\n resourceId: stage.id,\n current: stage.updatedAt,\n request: ctx.request ?? null,\n })\n\n const activeDealsCount = await em.count(CustomerDeal, {\n pipelineStageId: parsed.id,\n deletedAt: null,\n })\n if (activeDealsCount > 0) {\n throw new CrudHttpError(409, { error: 'Cannot delete pipeline stage with active deals' })\n }\n\n em.remove(stage)\n await em.flush()\n },\n}\n\nconst reorderPipelineStagesCommand: CommandHandler<PipelineStageReorderInput, void> = {\n id: 'customers.pipeline-stages.reorder',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageReorderSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const ids = parsed.stages.map((s) => s.id)\n const stages = await findWithDecryption(\n em,\n CustomerPipelineStage,\n {\n id: { $in: ids },\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n\n const stageMap = new Map<string, CustomerPipelineStage>()\n stages.forEach((stage) => stageMap.set(stage.id, stage))\n\n for (const { id, order } of parsed.stages) {\n const stage = stageMap.get(id)\n if (!stage) continue\n stage.order = order\n stage.updatedAt = new Date()\n }\n\n await em.flush()\n },\n}\n\nregisterCommand(createPipelineStageCommand)\nregisterCommand(updatePipelineStageCommand)\nregisterCommand(deletePipelineStageCommand)\nregisterCommand(reorderPipelineStagesCommand)\n\nexport {\n createPipelineStageCommand,\n updatePipelineStageCommand,\n deletePipelineStageCommand,\n reorderPipelineStagesCommand,\n}\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAGhC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,uBAAuB,oBAAoB;AACpD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAKK;AACP,SAAS,yBAAyB,mBAAmB,6BAA6B;AAClF,SAAS,qBAAqB;AAC9B,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,MAAM,6BAA4F;AAAA,EAChG,IAAI;AAAA,EACJ,MAAM,QAAQ,UAAU,KAAK;AAC3B,UAAM,SAAS,0BAA0B,MAAM,QAAQ;AACvD,sBAAkB,KAAK,OAAO,QAAQ;AACtC,4BAAwB,KAAK,OAAO,cAAc;AAElD,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAI/D,UAAM,iBAAiB,MAAM;AAAA,MAC3B;AAAA,MACA;AAAA,MACA;AAAA,QACE,gBAAgB,OAAO;AAAA,QACvB,UAAU,OAAO;AAAA,QACjB,YAAY,OAAO;AAAA,MACrB;AAAA,MACA,EAAE,SAAS,EAAE,OAAO,MAAM,EAAE;AAAA,MAC5B,EAAE,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,IACrE;AAKA,UAAM,iBAAiB,OAAO;AAC9B,UAAM,cACJ,mBAAmB,SACf,eAAe,SACf,KAAK,IAAI,GAAG,KAAK,IAAI,gBAAgB,eAAe,MAAM,CAAC;AAEjE,UAAM,QAAQ,GAAG,OAAO,uBAAuB;AAAA,MAC7C,gBAAgB,OAAO;AAAA,MACvB,UAAU,OAAO;AAAA,MACj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,UAAU,OAAO,UAAU,gBAAgB,OAAO,eAAe;AAAA,IACrE;AAEA,UAAM,WAAW,oBAAI,IAAmC;AACxD,WAAO,QAAQ,CAAC,UAAU,SAAS,IAAI,MAAM,IAAI,KAAK,CAAC;AAEvD,eAAW,EAAE,IAAI,MAAM,KAAK,OAAO,QAAQ;AACzC,YAAM,QAAQ,SAAS,IAAI,EAAE;AAC7B,UAAI,CAAC,MAAO;AACZ,YAAM,QAAQ;AACd,YAAM,YAAY,oBAAI,KAAK;AAAA,IAC7B;AAEA,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAEA,gBAAgB,0BAA0B;AAC1C,gBAAgB,0BAA0B;AAC1C,gBAAgB,0BAA0B;AAC1C,gBAAgB,4BAA4B;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerPipelineStage, CustomerDeal } from '../data/entities'\nimport {\n pipelineStageCreateSchema,\n pipelineStageUpdateSchema,\n pipelineStageDeleteSchema,\n pipelineStageReorderSchema,\n type PipelineStageCreateInput,\n type PipelineStageUpdateInput,\n type PipelineStageDeleteInput,\n type PipelineStageReorderInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope, ensureDictionaryEntry } from './shared'\nimport { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport {\n enforceCommandOptimisticLockWithGuards,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\n\nconst createPipelineStageCommand: CommandHandler<PipelineStageCreateInput, { stageId: string }> = {\n id: 'customers.pipeline-stages.create',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n // Load the full ordered list once. We need it both to know where \"end\" is and to\n // shift any stages that occupy positions at or after the chosen insert point.\n const existingStages = await findWithDecryption(\n em,\n CustomerPipelineStage,\n {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n pipelineId: parsed.pipelineId,\n },\n { orderBy: { order: 'ASC' } },\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n\n // Clamp the requested insert position into the legal range [0, length]. Anything\n // outside that range (negative, way past the end) collapses to \"append\" so we never\n // create stages that hop the visible board boundary.\n const requestedOrder = parsed.order\n const insertOrder =\n requestedOrder === undefined\n ? existingStages.length\n : Math.max(0, Math.min(requestedOrder, existingStages.length))\n\n const stage = em.create(CustomerPipelineStage, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n pipelineId: parsed.pipelineId,\n label: parsed.label,\n order: insertOrder,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n await withAtomicFlush(em, [\n () => {\n // Shift the order of every stage at or after the insert position. Skipping\n // this step would either duplicate `order` values (silently corrupting kanban\n // ordering) or push the new stage to the wrong spot when re-sorting.\n if (requestedOrder !== undefined) {\n for (const existing of existingStages) {\n if (existing.order >= insertOrder) {\n existing.order += 1\n existing.updatedAt = new Date()\n }\n }\n }\n em.persist(stage)\n },\n async () => {\n await ensureDictionaryEntry(em, {\n tenantId: parsed.tenantId,\n organizationId: parsed.organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n color: parsed.color,\n icon: parsed.icon,\n })\n },\n ], { transaction: true })\n\n return { stageId: stage.id }\n },\n}\n\nconst updatePipelineStageCommand: CommandHandler<PipelineStageUpdateInput, void> = {\n id: 'customers.pipeline-stages.update',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageUpdateSchema.parse(rawInput)\n\n // Restrict the lookup to the caller's tenant/organization scope so a\n // wrong-tenant id returns 404 (same as a missing row), not 403 \u2014 avoids\n // leaking existence of stages outside the caller's scope.\n const callerTenantId = ctx.auth?.tenantId ?? null\n const callerOrganizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, {\n id: parsed.id,\n ...(callerTenantId ? { tenantId: callerTenantId } : {}),\n ...(callerOrganizationId ? { organizationId: callerOrganizationId } : {}),\n })\n if (!stage) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipelineStage', resourceId: parsed.id, request: ctx.request ?? null })\n throw notFound('Pipeline stage not found')\n }\n\n ensureTenantScope(ctx, stage.tenantId)\n ensureOrganizationScope(ctx, stage.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipelineStage',\n resourceId: stage.id,\n current: stage.updatedAt,\n request: ctx.request ?? null,\n })\n\n await withAtomicFlush(em, [\n () => {\n if (parsed.label !== undefined) stage.label = parsed.label\n if (parsed.order !== undefined) stage.order = parsed.order\n stage.updatedAt = new Date()\n },\n async () => {\n if (parsed.label !== undefined || parsed.color !== undefined || parsed.icon !== undefined) {\n await ensureDictionaryEntry(em, {\n tenantId: stage.tenantId,\n organizationId: stage.organizationId,\n kind: 'pipeline_stage',\n value: stage.label,\n color: parsed.color,\n icon: parsed.icon,\n })\n }\n },\n ], { transaction: true })\n },\n}\n\nconst deletePipelineStageCommand: CommandHandler<PipelineStageDeleteInput, void> = {\n id: 'customers.pipeline-stages.delete',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageDeleteSchema.parse(rawInput)\n\n // See update command above \u2014 scope the lookup to the caller's tenant/org so a\n // cross-tenant id returns 404, not 403.\n const callerTenantId = ctx.auth?.tenantId ?? null\n const callerOrganizationId = ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const stage = await findOneWithDecryption(em, CustomerPipelineStage, {\n id: parsed.id,\n ...(callerTenantId ? { tenantId: callerTenantId } : {}),\n ...(callerOrganizationId ? { organizationId: callerOrganizationId } : {}),\n })\n if (!stage) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipelineStage', resourceId: parsed.id, request: ctx.request ?? null })\n throw notFound('Pipeline stage not found')\n }\n\n ensureTenantScope(ctx, stage.tenantId)\n ensureOrganizationScope(ctx, stage.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipelineStage',\n resourceId: stage.id,\n current: stage.updatedAt,\n request: ctx.request ?? null,\n })\n\n const activeDealsCount = await em.count(CustomerDeal, {\n pipelineStageId: parsed.id,\n deletedAt: null,\n })\n if (activeDealsCount > 0) {\n throw new CrudHttpError(409, { error: 'Cannot delete pipeline stage with active deals' })\n }\n\n em.remove(stage)\n await em.flush()\n },\n}\n\nconst reorderPipelineStagesCommand: CommandHandler<PipelineStageReorderInput, void> = {\n id: 'customers.pipeline-stages.reorder',\n async execute(rawInput, ctx) {\n const parsed = pipelineStageReorderSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const ids = parsed.stages.map((s) => s.id)\n const stages = await findWithDecryption(\n em,\n CustomerPipelineStage,\n {\n id: { $in: ids },\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n },\n undefined,\n { tenantId: parsed.tenantId, organizationId: parsed.organizationId },\n )\n\n const stageMap = new Map<string, CustomerPipelineStage>()\n stages.forEach((stage) => stageMap.set(stage.id, stage))\n\n for (const { id, order } of parsed.stages) {\n const stage = stageMap.get(id)\n if (!stage) continue\n stage.order = order\n stage.updatedAt = new Date()\n }\n\n await em.flush()\n },\n}\n\nregisterCommand(createPipelineStageCommand)\nregisterCommand(updatePipelineStageCommand)\nregisterCommand(deletePipelineStageCommand)\nregisterCommand(reorderPipelineStagesCommand)\n\nexport {\n createPipelineStageCommand,\n updatePipelineStageCommand,\n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;AAC7B,UAAI,CAAC,MAAO;AACZ,YAAM,QAAQ;AACd,YAAM,YAAY,oBAAI,KAAK;AAAA,IAC7B;AAEA,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAEA,gBAAgB,0BAA0B;AAC1C,gBAAgB,0BAA0B;AAC1C,gBAAgB,0BAA0B;AAC1C,gBAAgB,4BAA4B;",
6
6
  "names": []
7
7
  }
@@ -6,7 +6,7 @@ import {
6
6
  pipelineDeleteSchema
7
7
  } from "../data/validators.js";
8
8
  import { ensureOrganizationScope, ensureTenantScope } from "./shared.js";
9
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
9
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
10
10
  import {
11
11
  enforceCommandOptimisticLockWithGuards,
12
12
  enforceRecordGoneIsConflict
@@ -50,7 +50,7 @@ const updatePipelineCommand = {
50
50
  const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id });
51
51
  if (!pipeline) {
52
52
  enforceRecordGoneIsConflict({ resourceKind: "customers.pipeline", resourceId: parsed.id, request: ctx.request ?? null });
53
- throw new CrudHttpError(404, { error: "Pipeline not found" });
53
+ throw notFound("Pipeline not found");
54
54
  }
55
55
  ensureTenantScope(ctx, pipeline.tenantId);
56
56
  ensureOrganizationScope(ctx, pipeline.organizationId);
@@ -84,7 +84,7 @@ const deletePipelineCommand = {
84
84
  const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id });
85
85
  if (!pipeline) {
86
86
  enforceRecordGoneIsConflict({ resourceKind: "customers.pipeline", resourceId: parsed.id, request: ctx.request ?? null });
87
- throw new CrudHttpError(404, { error: "Pipeline not found" });
87
+ throw notFound("Pipeline not found");
88
88
  }
89
89
  ensureTenantScope(ctx, pipeline.tenantId);
90
90
  ensureOrganizationScope(ctx, pipeline.organizationId);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/pipelines.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerPipeline, CustomerDeal } from '../data/entities'\nimport {\n pipelineCreateSchema,\n pipelineUpdateSchema,\n pipelineDeleteSchema,\n type PipelineCreateInput,\n type PipelineUpdateInput,\n type PipelineDeleteInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope } from './shared'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n enforceCommandOptimisticLockWithGuards,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\n\nconst createPipelineCommand: CommandHandler<PipelineCreateInput, { pipelineId: string }> = {\n id: 'customers.pipelines.create',\n async execute(rawInput, ctx) {\n const parsed = pipelineCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const pipeline = em.create(CustomerPipeline, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n isDefault: parsed.isDefault ?? false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isDefault) {\n await em.nativeUpdate(\n CustomerPipeline,\n { organizationId: parsed.organizationId, tenantId: parsed.tenantId, isDefault: true },\n { isDefault: false }\n )\n }\n em.persist(pipeline)\n },\n ], { transaction: true })\n\n return { pipelineId: pipeline.id }\n },\n}\n\nconst updatePipelineCommand: CommandHandler<PipelineUpdateInput, void> = {\n id: 'customers.pipelines.update',\n async execute(rawInput, ctx) {\n const parsed = pipelineUpdateSchema.parse(rawInput)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id })\n if (!pipeline) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipeline', resourceId: parsed.id, request: ctx.request ?? null })\n throw new CrudHttpError(404, { error: 'Pipeline not found' })\n }\n\n ensureTenantScope(ctx, pipeline.tenantId)\n ensureOrganizationScope(ctx, pipeline.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipeline',\n resourceId: pipeline.id,\n current: pipeline.updatedAt,\n request: ctx.request ?? null,\n })\n\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isDefault && !pipeline.isDefault) {\n await em.nativeUpdate(\n CustomerPipeline,\n { organizationId: pipeline.organizationId, tenantId: pipeline.tenantId, isDefault: true },\n { isDefault: false }\n )\n }\n\n if (parsed.name !== undefined) pipeline.name = parsed.name\n if (parsed.isDefault !== undefined) pipeline.isDefault = parsed.isDefault\n pipeline.updatedAt = new Date()\n },\n ], { transaction: true })\n },\n}\n\nconst deletePipelineCommand: CommandHandler<PipelineDeleteInput, void> = {\n id: 'customers.pipelines.delete',\n async execute(rawInput, ctx) {\n const parsed = pipelineDeleteSchema.parse(rawInput)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id })\n if (!pipeline) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipeline', resourceId: parsed.id, request: ctx.request ?? null })\n throw new CrudHttpError(404, { error: 'Pipeline not found' })\n }\n\n ensureTenantScope(ctx, pipeline.tenantId)\n ensureOrganizationScope(ctx, pipeline.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipeline',\n resourceId: pipeline.id,\n current: pipeline.updatedAt,\n request: ctx.request ?? null,\n })\n\n const activeDealsCount = await em.count(CustomerDeal, {\n pipelineId: parsed.id,\n deletedAt: null,\n })\n if (activeDealsCount > 0) {\n throw new CrudHttpError(409, { error: 'Cannot delete pipeline with active deals' })\n }\n\n em.remove(pipeline)\n await em.flush()\n },\n}\n\nregisterCommand(createPipelineCommand)\nregisterCommand(updatePipelineCommand)\nregisterCommand(deletePipelineCommand)\n\nexport { createPipelineCommand, updatePipelineCommand, deletePipelineCommand }\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAGhC,SAAS,kBAAkB,oBAAoB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,yBAAyB,yBAAyB;AAC3D,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAEhC,MAAM,wBAAqF;AAAA,EACzF,IAAI;AAAA,EACJ,MAAM,QAAQ,UAAU,KAAK;AAC3B,UAAM,SAAS,qBAAqB,MAAM,QAAQ;AAClD,sBAAkB,KAAK,OAAO,QAAQ;AACtC,4BAAwB,KAAK,OAAO,cAAc;AAElD,UAAM,KAAM,IAAI,UAAU,QAAQ,IAAI,EAAoB,KAAK;AAE/D,UAAM,WAAW,GAAG,OAAO,kBAAkB;AAAA,MAC3C,gBAAgB,OAAO;AAAA,MACvB,UAAU,OAAO;AAAA,MACjB,MAAM,OAAO;AAAA,MACb,WAAW,OAAO,aAAa;AAAA,MAC/B,WAAW,oBAAI,KAAK;AAAA,MACpB,WAAW,oBAAI,KAAK;AAAA,IACtB,CAAC;AAED,UAAM,gBAAgB,IAAI;AAAA,MACxB,YAAY;AACV,YAAI,OAAO,WAAW;AACpB,gBAAM,GAAG;AAAA,YACP;AAAA,YACA,EAAE,gBAAgB,OAAO,gBAAgB,UAAU,OAAO,UAAU,WAAW,KAAK;AAAA,YACpF,EAAE,WAAW,MAAM;AAAA,UACrB;AAAA,QACF;AACA,WAAG,QAAQ,QAAQ;AAAA,MACrB;AAAA,IACF,GAAG,EAAE,aAAa,KAAK,CAAC;AAExB,WAAO,EAAE,YAAY,SAAS,GAAG;AAAA,EACnC;AACF;AAEA,MAAM,wBAAmE;AAAA,EACvE,IAAI;AAAA,EACJ,MAAM,QAAQ,UAAU,KAAK;AAC3B,UAAM,SAAS,q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;AACrE,QAAI,CAAC,UAAU;AACb,kCAA4B,EAAE,cAAc,sBAAsB,YAAY,OAAO,IAAI,SAAS,IAAI,WAAW,KAAK,CAAC;AACvH,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,qBAAqB,CAAC;AAAA,IAC9D;AAEA,sBAAkB,KAAK,SAAS,QAAQ;AACxC,4BAAwB,KAAK,SAAS,cAAc;AAEpD,UAAM,uCAAuC,IAAI,WAAW;AAAA,MAC1D,cAAc;AAAA,MACd,YAAY,SAAS;AAAA,MACrB,SAAS,SAAS;AAAA,MAClB,SAAS,IAAI,WAAW;AAAA,IAC1B,CAAC;AAED,UAAM,mBAAmB,MAAM,GAAG,MAAM,cAAc;AAAA,MACpD,YAAY,OAAO;AAAA,MACnB,WAAW;AAAA,IACb,CAAC;AACD,QAAI,mBAAmB,GAAG;AACxB,YAAM,IAAI,cAAc,KAAK,EAAE,OAAO,2CAA2C,CAAC;AAAA,IACpF;AAEA,OAAG,OAAO,QAAQ;AAClB,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAEA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerPipeline, CustomerDeal } from '../data/entities'\nimport {\n pipelineCreateSchema,\n pipelineUpdateSchema,\n pipelineDeleteSchema,\n type PipelineCreateInput,\n type PipelineUpdateInput,\n type PipelineDeleteInput,\n} from '../data/validators'\nimport { ensureOrganizationScope, ensureTenantScope } from './shared'\nimport { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport {\n enforceCommandOptimisticLockWithGuards,\n enforceRecordGoneIsConflict,\n} from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\n\nconst createPipelineCommand: CommandHandler<PipelineCreateInput, { pipelineId: string }> = {\n id: 'customers.pipelines.create',\n async execute(rawInput, ctx) {\n const parsed = pipelineCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n\n const pipeline = em.create(CustomerPipeline, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n name: parsed.name,\n isDefault: parsed.isDefault ?? false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isDefault) {\n await em.nativeUpdate(\n CustomerPipeline,\n { organizationId: parsed.organizationId, tenantId: parsed.tenantId, isDefault: true },\n { isDefault: false }\n )\n }\n em.persist(pipeline)\n },\n ], { transaction: true })\n\n return { pipelineId: pipeline.id }\n },\n}\n\nconst updatePipelineCommand: CommandHandler<PipelineUpdateInput, void> = {\n id: 'customers.pipelines.update',\n async execute(rawInput, ctx) {\n const parsed = pipelineUpdateSchema.parse(rawInput)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id })\n if (!pipeline) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipeline', resourceId: parsed.id, request: ctx.request ?? null })\n throw notFound('Pipeline not found')\n }\n\n ensureTenantScope(ctx, pipeline.tenantId)\n ensureOrganizationScope(ctx, pipeline.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipeline',\n resourceId: pipeline.id,\n current: pipeline.updatedAt,\n request: ctx.request ?? null,\n })\n\n await withAtomicFlush(em, [\n async () => {\n if (parsed.isDefault && !pipeline.isDefault) {\n await em.nativeUpdate(\n CustomerPipeline,\n { organizationId: pipeline.organizationId, tenantId: pipeline.tenantId, isDefault: true },\n { isDefault: false }\n )\n }\n\n if (parsed.name !== undefined) pipeline.name = parsed.name\n if (parsed.isDefault !== undefined) pipeline.isDefault = parsed.isDefault\n pipeline.updatedAt = new Date()\n },\n ], { transaction: true })\n },\n}\n\nconst deletePipelineCommand: CommandHandler<PipelineDeleteInput, void> = {\n id: 'customers.pipelines.delete',\n async execute(rawInput, ctx) {\n const parsed = pipelineDeleteSchema.parse(rawInput)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const pipeline = await em.findOne(CustomerPipeline, { id: parsed.id })\n if (!pipeline) {\n enforceRecordGoneIsConflict({ resourceKind: 'customers.pipeline', resourceId: parsed.id, request: ctx.request ?? null })\n throw notFound('Pipeline not found')\n }\n\n ensureTenantScope(ctx, pipeline.tenantId)\n ensureOrganizationScope(ctx, pipeline.organizationId)\n\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'customers.pipeline',\n resourceId: pipeline.id,\n current: pipeline.updatedAt,\n request: ctx.request ?? null,\n })\n\n const activeDealsCount = await em.count(CustomerDeal, {\n pipelineId: parsed.id,\n deletedAt: null,\n })\n if (activeDealsCount > 0) {\n throw new CrudHttpError(409, { error: 'Cannot delete pipeline with active deals' })\n }\n\n em.remove(pipeline)\n await em.flush()\n },\n}\n\nregisterCommand(createPipelineCommand)\nregisterCommand(updatePipelineCommand)\nregisterCommand(deletePipelineCommand)\n\nexport { createPipelineCommand, updatePipelineCommand, deletePipelineCommand }\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAGhC,SAAS,kBAAkB,oBAAoB;AAC/C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,yBAAyB,yBAAyB;AAC3D,SAAS,eAAe,gBAAgB;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP,SAAS,uBAAuB;AAEhC,MAAM,wBAAqF;AAAA,EACzF,IAAI;AAAA,EACJ,MAAM,QAAQ,UAAU,KAAK;AAC3B,UAAM,SAAS,qBAAqB,MAAM,QAAQ;AAClD,sBAAkB,KAAK,OAAO,QAAQ;AACtC,4BAAwB,KAAK,OAAO,cAAc;AAEl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,CAAC;AAAA,IACpF;AAEA,OAAG,OAAO,QAAQ;AAClB,UAAM,GAAG,MAAM;AAAA,EACjB;AACF;AAEA,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;AACrC,gBAAgB,qBAAqB;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,5 @@
1
1
  import { CustomerDeal, CustomerEntity, CustomerTag, CustomerTagAssignment, CustomerDictionaryEntry } from "../data/entities.js";
2
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
2
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
3
3
  import { ensureSameScope } from "@open-mercato/shared/lib/commands/scope";
4
4
  import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
5
5
  import { createLogger } from "@open-mercato/shared/lib/logger";
@@ -28,7 +28,7 @@ async function requireCustomerEntity(em, id, scope, kind, message = "Customer en
28
28
  tenantId: scope.tenantId,
29
29
  organizationId: scope.organizationId
30
30
  });
31
- if (!entity) throw new CrudHttpError(404, { error: message });
31
+ if (!entity) throw notFound(message);
32
32
  if (kind && entity.kind !== kind) {
33
33
  throw new CrudHttpError(400, { error: "Invalid entity type" });
34
34
  }
@@ -56,7 +56,7 @@ async function requireTimelineParentEntity(em, id, scope) {
56
56
  if (deal) {
57
57
  throw new CrudHttpError(422, { error: "entityId must reference a person or company, not a deal" });
58
58
  }
59
- throw new CrudHttpError(404, { error: "Customer not found" });
59
+ throw notFound("Customer not found");
60
60
  }
61
61
  async function syncEntityTags(em, entity, tags) {
62
62
  if (tags === void 0) return;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/shared.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerDeal, CustomerEntity, CustomerTag, CustomerTagAssignment, CustomerDictionaryEntry, type CustomerEntityKind } from '../data/entities'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope, ensureSameScope } from '@open-mercato/shared/lib/commands/scope'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EventBus } from '@open-mercato/events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\nexport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nexport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\n\nexport function normalizeDictionaryColor(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n const hexMatch = /^#([0-9a-fA-F]{6})$/.exec(trimmed)\n if (!hexMatch) return null\n return `#${hexMatch[1].toLowerCase()}`\n}\n\nexport function normalizeDictionaryIcon(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n return trimmed.slice(0, 48)\n}\n\nexport { assertFound } from '@open-mercato/shared/lib/crud/errors'\n\nexport type CustomerEntityScope = {\n tenantId: string\n organizationId: string\n}\n\nexport async function requireCustomerEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n kind?: CustomerEntityKind,\n message = 'Customer entity not found'\n): Promise<CustomerEntity> {\n const entity = await em.findOne(CustomerEntity, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (!entity) throw new CrudHttpError(404, { error: message })\n if (kind && entity.kind !== kind) {\n throw new CrudHttpError(400, { error: 'Invalid entity type' })\n }\n return entity\n}\n\nexport async function requireTimelineParentEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n): Promise<CustomerEntity> {\n const entity = await em.findOne(CustomerEntity, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (entity) {\n if (entity.kind !== 'person' && entity.kind !== 'company') {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company' })\n }\n return entity\n }\n const deal = await em.findOne(CustomerDeal, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (deal) {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company, not a deal' })\n }\n throw new CrudHttpError(404, { error: 'Customer not found' })\n}\n\nexport async function syncEntityTags(\n em: EntityManager,\n entity: CustomerEntity,\n tags: string[] | undefined | null\n): Promise<void> {\n if (tags === undefined) return\n const desired = Array.from(new Set((tags ?? []).filter((id) => typeof id === 'string')))\n const existing = await loadEntityTagIds(em, entity)\n const toRemove = existing.filter((id) => !desired.includes(id))\n if (toRemove.length) {\n await em.nativeDelete(CustomerTagAssignment, { entity, tag: { $in: toRemove } })\n }\n const toAdd = desired.filter((id) => !existing.includes(id))\n if (!toAdd.length) return\n const tagsInScope = await em.find(CustomerTag, {\n id: { $in: toAdd },\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n })\n if (tagsInScope.length !== toAdd.length) {\n throw new CrudHttpError(400, { error: 'One or more tags not found for this scope' })\n }\n for (const tag of toAdd) {\n const assignment = em.create(CustomerTagAssignment, {\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n tag: em.getReference(CustomerTag, tag),\n entity,\n })\n em.persist(assignment)\n }\n}\n\nexport async function loadEntityTagIds(em: EntityManager, entity: CustomerEntity): Promise<string[]> {\n const assignments = await findWithDecryption(\n em,\n CustomerTagAssignment,\n { entity },\n { populate: ['tag'] },\n { tenantId: entity.tenantId, organizationId: entity.organizationId },\n )\n return assignments.map((assignment) =>\n typeof assignment.tag === 'string' ? assignment.tag : assignment.tag.id\n )\n}\n\nexport async function requireDealInScope(\n em: EntityManager,\n dealId: string | null | undefined,\n tenantId: string,\n organizationId: string\n): Promise<CustomerDeal | null> {\n if (!dealId) return null\n const deal = await em.findOne(CustomerDeal, { id: dealId, deletedAt: null, tenantId, organizationId })\n if (!deal) throw new CrudHttpError(400, { error: 'Deal not found' })\n ensureSameScope(deal, organizationId, tenantId)\n return deal\n}\n\nconst DICTIONARY_KINDS = new Set([\n 'status',\n 'source',\n 'lifecycle_stage',\n 'address_type',\n 'activity_type',\n 'deal_status',\n 'pipeline_stage',\n 'job_title',\n 'industry',\n 'temperature',\n 'renewal_quarter',\n 'person_company_role',\n 'interaction_status',\n])\n\nconst CUSTOM_DICTIONARY_KIND_PATTERN = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport async function ensureDictionaryEntry(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n kind: string\n value: string\n label?: string | null\n color?: string | null | undefined\n icon?: string | null | undefined\n }\n): Promise<CustomerDictionaryEntry | null> {\n const trimmed = params.value?.trim()\n if (!trimmed) return null\n if (!DICTIONARY_KINDS.has(params.kind) && !CUSTOM_DICTIONARY_KIND_PATTERN.test(params.kind)) {\n throw new CrudHttpError(400, { error: 'Unsupported dictionary kind' })\n }\n const normalized = trimmed.toLowerCase()\n const color = params.color === undefined ? undefined : normalizeDictionaryColor(params.color)\n const icon = params.icon === undefined ? undefined : normalizeDictionaryIcon(params.icon)\n const existing = await em.findOne(CustomerDictionaryEntry, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n normalizedValue: normalized,\n })\n if (existing) {\n let changed = false\n if (color !== undefined) {\n if (existing.color !== color) {\n existing.color = color ?? null\n changed = true\n }\n }\n if (icon !== undefined) {\n if (existing.icon !== icon) {\n existing.icon = icon ?? null\n changed = true\n }\n }\n if (changed) {\n existing.updatedAt = new Date()\n em.persist(existing)\n }\n return existing\n }\n const entry = em.create(CustomerDictionaryEntry, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n value: trimmed,\n label: params.label?.trim() || trimmed,\n normalizedValue: normalized,\n color: color ?? null,\n icon: icon ?? null,\n })\n em.persist(entry)\n return entry\n}\n\nexport function resolveParentResourceKind(entityKind: CustomerEntityKind | string | null | undefined): string | null {\n if (entityKind === 'company') return 'customers.company'\n if (entityKind === 'person') return 'customers.person'\n return null\n}\n\nexport type QueryIndexEventEntry = {\n entityType: string\n recordId: string\n tenantId: string | null\n organizationId: string | null\n}\n\ntype QueryIndexEventKind = 'delete' | 'upsert'\n\nfunction normalizeEventEntries(entries: readonly QueryIndexEventEntry[]): QueryIndexEventEntry[] {\n const map = new Map<string, QueryIndexEventEntry>()\n for (const entry of entries) {\n if (!entry || typeof entry !== 'object') continue\n const entityType = String(entry.entityType ?? '')\n const recordId = String(entry.recordId ?? '')\n if (!entityType || !recordId) continue\n const key = [\n entityType,\n recordId,\n entry.organizationId ?? '__org__',\n entry.tenantId ?? '__tenant__',\n ].join('|')\n if (!map.has(key)) {\n map.set(key, {\n entityType,\n recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n })\n }\n }\n return Array.from(map.values())\n}\n\nasync function emitQueryIndexEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n kind: QueryIndexEventKind,\n): Promise<void> {\n const normalized = normalizeEventEntries(entries)\n if (!normalized.length) return\n\n let bus: EventBus | null = null\n try {\n bus = ctx.container.resolve<EventBus>('eventBus')\n } catch (err) {\n logger.warn('eventBus resolve failed; skipping query index events', { component: 'commands.shared', err })\n bus = null\n }\n if (!bus) return\n\n const eventName = kind === 'delete' ? 'query_index.delete_one' : 'query_index.upsert_one'\n const crudAction = kind === 'delete' ? 'deleted' : 'updated'\n\n await Promise.all(\n normalized.map((entry) =>\n bus!\n .emitEvent(\n eventName,\n {\n entityType: entry.entityType,\n recordId: entry.recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n crudAction,\n },\n {\n tenantId: entry.tenantId ?? null,\n organizationId: entry.organizationId ?? null,\n },\n )\n .catch((err) => {\n logger.warn('Query index emitEvent failed', { component: 'commands.shared', entry, err })\n return undefined\n }),\n ),\n )\n}\n\nexport async function emitQueryIndexDeleteEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'delete')\n}\n\nexport async function emitQueryIndexUpsertEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'upsert')\n}\n"],
5
- "mappings": "AACA,SAAS,cAAc,gBAAgB,aAAa,uBAAuB,+BAAwD;AACnI,SAAS,qBAAqB;AAE9B,SAAkC,uBAAuB;AACzD,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AACvC,SAAS,2BAAAA,0BAAyB,mBAAAC,kBAAiB,yBAAyB;AAC5E,SAAS,0BAA0B;AAE5B,SAAS,yBAAyB,OAA+B;AACtE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,WAAW,sBAAsB,KAAK,OAAO;AACnD,MAAI,CAAC,SAAU,QAAO;AACtB,SAAO,IAAI,SAAS,CAAC,EAAE,YAAY,CAAC;AACtC;AAEO,SAAS,wBAAwB,OAA+B;AACrE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,SAAO,QAAQ,MAAM,GAAG,EAAE;AAC5B;AAEA,SAAS,mBAAmB;AAO5B,eAAsB,sBACpB,IACA,IACA,OACA,MACA,UAAU,6BACe;AACzB,QAAM,SAAS,MAAM,GAAG,QAAQ,gBAAgB;AAAA,IAC9C;AAAA,IACA,WAAW;AAAA,IACX,UAAU,MAAM;AAAA,IAChB,gBAAgB,MAAM;AAAA,EACxB,CAAC;AACD,MAAI,CAAC,OAAQ,OAAM,IAAI,cAAc,KAAK,EAAE,OAAO,QAAQ,CAAC;AAC5D,MAAI,QAAQ,OAAO,SAAS,MAAM;AAChC,UAAM,IAAI,cAAc,KAAK,EAAE,OAAO,sBAAsB,CAAC;AAAA,EAC/D;AACA,SAAO;AACT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M,kBAAkB;AAAA,UACxC,UAAU,MAAM,YAAY;AAAA,UAC5B;AAAA,QACF;AAAA,QACA;AAAA,UACE,UAAU,MAAM,YAAY;AAAA,UAC5B,gBAAgB,MAAM,kBAAkB;AAAA,QAC1C;AAAA,MACF,EACC,MAAM,CAAC,QAAQ;AACd,eAAO,KAAK,gCAAgC,EAAE,WAAW,mBAAmB,OAAO,IAAI,CAAC;AACxF,eAAO;AAAA,MACT,CAAC;AAAA,IACL;AAAA,EACF;AACF;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerDeal, CustomerEntity, CustomerTag, CustomerTagAssignment, CustomerDictionaryEntry, type CustomerEntityKind } from '../data/entities'\nimport { CrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport type { CommandRuntimeContext } from '@open-mercato/shared/lib/commands'\nimport { ensureOrganizationScope, ensureSameScope } from '@open-mercato/shared/lib/commands/scope'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport type { EventBus } from '@open-mercato/events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\nexport { ensureOrganizationScope, ensureSameScope, ensureTenantScope } from '@open-mercato/shared/lib/commands/scope'\nexport { extractUndoPayload } from '@open-mercato/shared/lib/commands/undo'\n\nexport function normalizeDictionaryColor(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n const hexMatch = /^#([0-9a-fA-F]{6})$/.exec(trimmed)\n if (!hexMatch) return null\n return `#${hexMatch[1].toLowerCase()}`\n}\n\nexport function normalizeDictionaryIcon(input: unknown): string | null {\n if (typeof input !== 'string') return null\n const trimmed = input.trim()\n if (!trimmed) return null\n return trimmed.slice(0, 48)\n}\n\nexport { assertFound } from '@open-mercato/shared/lib/crud/errors'\n\nexport type CustomerEntityScope = {\n tenantId: string\n organizationId: string\n}\n\nexport async function requireCustomerEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n kind?: CustomerEntityKind,\n message = 'Customer entity not found'\n): Promise<CustomerEntity> {\n const entity = await em.findOne(CustomerEntity, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (!entity) throw notFound(message)\n if (kind && entity.kind !== kind) {\n throw new CrudHttpError(400, { error: 'Invalid entity type' })\n }\n return entity\n}\n\nexport async function requireTimelineParentEntity(\n em: EntityManager,\n id: string,\n scope: CustomerEntityScope,\n): Promise<CustomerEntity> {\n const entity = await em.findOne(CustomerEntity, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (entity) {\n if (entity.kind !== 'person' && entity.kind !== 'company') {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company' })\n }\n return entity\n }\n const deal = await em.findOne(CustomerDeal, {\n id,\n deletedAt: null,\n tenantId: scope.tenantId,\n organizationId: scope.organizationId,\n })\n if (deal) {\n throw new CrudHttpError(422, { error: 'entityId must reference a person or company, not a deal' })\n }\n throw notFound('Customer not found')\n}\n\nexport async function syncEntityTags(\n em: EntityManager,\n entity: CustomerEntity,\n tags: string[] | undefined | null\n): Promise<void> {\n if (tags === undefined) return\n const desired = Array.from(new Set((tags ?? []).filter((id) => typeof id === 'string')))\n const existing = await loadEntityTagIds(em, entity)\n const toRemove = existing.filter((id) => !desired.includes(id))\n if (toRemove.length) {\n await em.nativeDelete(CustomerTagAssignment, { entity, tag: { $in: toRemove } })\n }\n const toAdd = desired.filter((id) => !existing.includes(id))\n if (!toAdd.length) return\n const tagsInScope = await em.find(CustomerTag, {\n id: { $in: toAdd },\n organizationId: entity.organizationId,\n tenantId: entity.tenantId,\n })\n if (tagsInScope.length !== toAdd.length) {\n throw new CrudHttpError(400, { error: 'One or more tags not found for this scope' })\n }\n for (const tag of toAdd) {\n const assignment = em.create(CustomerTagAssignment, {\n tenantId: entity.tenantId,\n organizationId: entity.organizationId,\n tag: em.getReference(CustomerTag, tag),\n entity,\n })\n em.persist(assignment)\n }\n}\n\nexport async function loadEntityTagIds(em: EntityManager, entity: CustomerEntity): Promise<string[]> {\n const assignments = await findWithDecryption(\n em,\n CustomerTagAssignment,\n { entity },\n { populate: ['tag'] },\n { tenantId: entity.tenantId, organizationId: entity.organizationId },\n )\n return assignments.map((assignment) =>\n typeof assignment.tag === 'string' ? assignment.tag : assignment.tag.id\n )\n}\n\nexport async function requireDealInScope(\n em: EntityManager,\n dealId: string | null | undefined,\n tenantId: string,\n organizationId: string\n): Promise<CustomerDeal | null> {\n if (!dealId) return null\n const deal = await em.findOne(CustomerDeal, { id: dealId, deletedAt: null, tenantId, organizationId })\n if (!deal) throw new CrudHttpError(400, { error: 'Deal not found' })\n ensureSameScope(deal, organizationId, tenantId)\n return deal\n}\n\nconst DICTIONARY_KINDS = new Set([\n 'status',\n 'source',\n 'lifecycle_stage',\n 'address_type',\n 'activity_type',\n 'deal_status',\n 'pipeline_stage',\n 'job_title',\n 'industry',\n 'temperature',\n 'renewal_quarter',\n 'person_company_role',\n 'interaction_status',\n])\n\nconst CUSTOM_DICTIONARY_KIND_PATTERN = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/\n\nexport async function ensureDictionaryEntry(\n em: EntityManager,\n params: {\n tenantId: string\n organizationId: string\n kind: string\n value: string\n label?: string | null\n color?: string | null | undefined\n icon?: string | null | undefined\n }\n): Promise<CustomerDictionaryEntry | null> {\n const trimmed = params.value?.trim()\n if (!trimmed) return null\n if (!DICTIONARY_KINDS.has(params.kind) && !CUSTOM_DICTIONARY_KIND_PATTERN.test(params.kind)) {\n throw new CrudHttpError(400, { error: 'Unsupported dictionary kind' })\n }\n const normalized = trimmed.toLowerCase()\n const color = params.color === undefined ? undefined : normalizeDictionaryColor(params.color)\n const icon = params.icon === undefined ? undefined : normalizeDictionaryIcon(params.icon)\n const existing = await em.findOne(CustomerDictionaryEntry, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n normalizedValue: normalized,\n })\n if (existing) {\n let changed = false\n if (color !== undefined) {\n if (existing.color !== color) {\n existing.color = color ?? null\n changed = true\n }\n }\n if (icon !== undefined) {\n if (existing.icon !== icon) {\n existing.icon = icon ?? null\n changed = true\n }\n }\n if (changed) {\n existing.updatedAt = new Date()\n em.persist(existing)\n }\n return existing\n }\n const entry = em.create(CustomerDictionaryEntry, {\n tenantId: params.tenantId,\n organizationId: params.organizationId,\n kind: params.kind,\n value: trimmed,\n label: params.label?.trim() || trimmed,\n normalizedValue: normalized,\n color: color ?? null,\n icon: icon ?? null,\n })\n em.persist(entry)\n return entry\n}\n\nexport function resolveParentResourceKind(entityKind: CustomerEntityKind | string | null | undefined): string | null {\n if (entityKind === 'company') return 'customers.company'\n if (entityKind === 'person') return 'customers.person'\n return null\n}\n\nexport type QueryIndexEventEntry = {\n entityType: string\n recordId: string\n tenantId: string | null\n organizationId: string | null\n}\n\ntype QueryIndexEventKind = 'delete' | 'upsert'\n\nfunction normalizeEventEntries(entries: readonly QueryIndexEventEntry[]): QueryIndexEventEntry[] {\n const map = new Map<string, QueryIndexEventEntry>()\n for (const entry of entries) {\n if (!entry || typeof entry !== 'object') continue\n const entityType = String(entry.entityType ?? '')\n const recordId = String(entry.recordId ?? '')\n if (!entityType || !recordId) continue\n const key = [\n entityType,\n recordId,\n entry.organizationId ?? '__org__',\n entry.tenantId ?? '__tenant__',\n ].join('|')\n if (!map.has(key)) {\n map.set(key, {\n entityType,\n recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n })\n }\n }\n return Array.from(map.values())\n}\n\nasync function emitQueryIndexEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n kind: QueryIndexEventKind,\n): Promise<void> {\n const normalized = normalizeEventEntries(entries)\n if (!normalized.length) return\n\n let bus: EventBus | null = null\n try {\n bus = ctx.container.resolve<EventBus>('eventBus')\n } catch (err) {\n logger.warn('eventBus resolve failed; skipping query index events', { component: 'commands.shared', err })\n bus = null\n }\n if (!bus) return\n\n const eventName = kind === 'delete' ? 'query_index.delete_one' : 'query_index.upsert_one'\n const crudAction = kind === 'delete' ? 'deleted' : 'updated'\n\n await Promise.all(\n normalized.map((entry) =>\n bus!\n .emitEvent(\n eventName,\n {\n entityType: entry.entityType,\n recordId: entry.recordId,\n organizationId: entry.organizationId ?? null,\n tenantId: entry.tenantId ?? null,\n crudAction,\n },\n {\n tenantId: entry.tenantId ?? null,\n organizationId: entry.organizationId ?? null,\n },\n )\n .catch((err) => {\n logger.warn('Query index emitEvent failed', { component: 'commands.shared', entry, err })\n return undefined\n }),\n ),\n )\n}\n\nexport async function emitQueryIndexDeleteEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'delete')\n}\n\nexport async function emitQueryIndexUpsertEvents(\n ctx: CommandRuntimeContext,\n entries: readonly QueryIndexEventEntry[],\n): Promise<void> {\n await emitQueryIndexEvents(ctx, entries, 'upsert')\n}\n"],
5
+ "mappings": "AACA,SAAS,cAAc,gBAAgB,aAAa,uBAAuB,+BAAwD;AACnI,SAAS,eAAe,gBAAgB;AAExC,SAAkC,uBAAuB;AACzD,SAAS,0BAA0B;AAEnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AACvC,SAAS,2BAAAA,0BAAyB,mBAAAC,kBAAiB,yBAAyB;AAC5E,SAAS,0BAA0B;AAE5B,SAAS,yBAAyB,OAA+B;AACtE,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,QAAM,UAAU,MAAM,KAAK;AAC3B,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,WAAW,sBAAsB,KAAK,OAAO;AACnD,MAAI,CAAC,SAAU,QAAO;AACt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,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC;AAChC;AAEA,eAAe,qBACb,KACA,SACA,MACe;AACf,QAAM,aAAa,sBAAsB,OAAO;AAChD,MAAI,CAAC,WAAW,OAAQ;AAExB,MAAI,MAAuB;AAC3B,MAAI;AACF,UAAM,IAAI,UAAU,QAAkB,UAAU;AAAA,EAClD,SAAS,KAAK;AACZ,WAAO,KAAK,wDAAwD,EAAE,WAAW,mBAAmB,IAAI,CAAC;AACzG,UAAM;AAAA,EACR;AACA,MAAI,CAAC,IAAK;AAEV,QAAM,YAAY,SAAS,WAAW,2BAA2B;AACjE,QAAM,aAAa,SAAS,WAAW,YAAY;AAEnD,QAAM,QAAQ;AAAA,IACZ,WAAW;AAAA,MAAI,CAAC,UACd,IACG;AAAA,QACC;AAAA,QACA;AAAA,UACE,YAAY,MAAM;AAAA,UAClB,UAAU,MAAM;AAAA,UAChB,gBAAgB,MAAM,kBAAkB;AAAA,UACxC,UAAU,MAAM,YAAY;AAAA,UAC5B;AAAA,QACF;AAAA,QACA;AAAA,UACE,UAAU,MAAM,YAAY;AAAA,UAC5B,gBAAgB,MAAM,kBAAkB;AAAA,QAC1C;AAAA,MACF,EACC,MAAM,CAAC,QAAQ;AACd,eAAO,KAAK,gCAAgC,EAAE,WAAW,mBAAmB,OAAO,IAAI,CAAC;AACxF,eAAO;AAAA,MACT,CAAC;AAAA,IACL;AAAA,EACF;AACF;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;AAEA,eAAsB,2BACpB,KACA,SACe;AACf,QAAM,qBAAqB,KAAK,SAAS,QAAQ;AACnD;",
6
6
  "names": ["ensureOrganizationScope", "ensureSameScope"]
7
7
  }
@@ -15,7 +15,7 @@ import {
15
15
  loadEntityTagIds
16
16
  } from "./shared.js";
17
17
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
18
- import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
18
+ import { CrudHttpError, notFound } from "@open-mercato/shared/lib/crud/errors";
19
19
  import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
20
20
  import { emitCustomersEvent } from "../events.js";
21
21
  import { withAtomicFlush } from "@open-mercato/shared/lib/commands/flush";
@@ -131,7 +131,7 @@ const updateTagCommand = {
131
131
  const parsed = tagUpdateSchema.parse(rawInput);
132
132
  const em = ctx.container.resolve("em").fork();
133
133
  const tag = await em.findOne(CustomerTag, { id: parsed.id });
134
- if (!tag) throw new CrudHttpError(404, { error: "Tag not found" });
134
+ if (!tag) throw notFound("Tag not found");
135
135
  ensureTenantScope(ctx, tag.tenantId);
136
136
  ensureOrganizationScope(ctx, tag.organizationId);
137
137
  if (parsed.slug !== void 0 && parsed.slug !== tag.slug) {
@@ -240,7 +240,7 @@ const deleteTagCommand = {
240
240
  const id = requireId(input, "Tag id required");
241
241
  const em = ctx.container.resolve("em").fork();
242
242
  const tag = await em.findOne(CustomerTag, { id });
243
- if (!tag) throw new CrudHttpError(404, { error: "Tag not found" });
243
+ if (!tag) throw notFound("Tag not found");
244
244
  ensureTenantScope(ctx, tag.tenantId);
245
245
  ensureOrganizationScope(ctx, tag.organizationId);
246
246
  await withAtomicFlush(em, [
@@ -332,7 +332,7 @@ const assignTagCommand = {
332
332
  ensureOrganizationScope(ctx, parsed.organizationId);
333
333
  const em = ctx.container.resolve("em").fork();
334
334
  const tag = await em.findOne(CustomerTag, { id: parsed.tagId, tenantId: parsed.tenantId, organizationId: parsed.organizationId });
335
- if (!tag) throw new CrudHttpError(404, { error: "Tag not found" });
335
+ if (!tag) throw notFound("Tag not found");
336
336
  const entity = await requireCustomerEntity(em, parsed.entityId, { tenantId: parsed.tenantId, organizationId: parsed.organizationId }, void 0, "Customer not found");
337
337
  ensureSameScope(entity, parsed.organizationId, parsed.tenantId);
338
338
  const tagIds = await loadEntityTagIds(em, entity);
@@ -419,7 +419,7 @@ const assignTagCommand = {
419
419
  const assignmentId = logEntry?.resourceId ?? null;
420
420
  const em = ctx.container.resolve("em").fork();
421
421
  const tag = await em.findOne(CustomerTag, { id: before.tagId });
422
- if (!tag) throw new CrudHttpError(404, { error: "Tag not found" });
422
+ if (!tag) throw notFound("Tag not found");
423
423
  const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, void 0, "Customer not found");
424
424
  ensureSameScope(entity, before.organizationId, before.tenantId);
425
425
  let assignment = await em.findOne(CustomerTagAssignment, {
@@ -473,7 +473,7 @@ const unassignTagCommand = {
473
473
  tenantId: parsed.tenantId,
474
474
  organizationId: parsed.organizationId
475
475
  });
476
- if (!existing) throw new CrudHttpError(404, { error: "Tag assignment not found" });
476
+ if (!existing) throw notFound("Tag assignment not found");
477
477
  await em.remove(existing).flush();
478
478
  const de = ctx.container.resolve("dataEngine");
479
479
  await emitCrudSideEffects({
@@ -524,7 +524,7 @@ const unassignTagCommand = {
524
524
  const tag = await em.findOne(CustomerTag, { id: before.tagId });
525
525
  const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, void 0, "Customer not found");
526
526
  ensureSameScope(entity, before.organizationId, before.tenantId);
527
- if (!tag) throw new CrudHttpError(404, { error: "Tag not found" });
527
+ if (!tag) throw notFound("Tag not found");
528
528
  const existing = await em.findOne(CustomerTagAssignment, {
529
529
  tag,
530
530
  entity,