@open-mercato/core 0.6.5-develop.5337.1.534b781eac → 0.6.5-develop.5382.1.f542de69af

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 (119) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/AGENTS.md +1 -1
  3. package/dist/modules/attachments/api/library/route.js +2 -2
  4. package/dist/modules/attachments/api/library/route.js.map +2 -2
  5. package/dist/modules/attachments/components/AttachmentContentPreview.js +9 -5
  6. package/dist/modules/attachments/components/AttachmentContentPreview.js.map +2 -2
  7. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js +3 -2
  8. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js.map +2 -2
  9. package/dist/modules/auth/commands/users.js +20 -14
  10. package/dist/modules/auth/commands/users.js.map +2 -2
  11. package/dist/modules/auth/data/entities.js +1 -1
  12. package/dist/modules/auth/data/entities.js.map +2 -2
  13. package/dist/modules/auth/migrations/Migration20260610120000.js +30 -0
  14. package/dist/modules/auth/migrations/Migration20260610120000.js.map +7 -0
  15. package/dist/modules/catalog/ai-tools/configuration-pack.js.map +1 -1
  16. package/dist/modules/catalog/ai-tools/prices-offers-pack.js.map +1 -1
  17. package/dist/modules/catalog/ai-tools/products-pack.js.map +1 -1
  18. package/dist/modules/catalog/ai-tools/variants-pack.js.map +1 -1
  19. package/dist/modules/communication_channels/data/entities.js.map +1 -1
  20. package/dist/modules/communication_channels/encryption.js.map +1 -1
  21. package/dist/modules/communication_channels/lib/thread-matcher.js.map +1 -1
  22. package/dist/modules/communication_channels/lib/thread-token.js.map +1 -1
  23. package/dist/modules/currencies/api/currencies/route.js +4 -3
  24. package/dist/modules/currencies/api/currencies/route.js.map +2 -2
  25. package/dist/modules/customer_accounts/api/admin/roles.js +2 -1
  26. package/dist/modules/customer_accounts/api/admin/roles.js.map +2 -2
  27. package/dist/modules/customer_accounts/events.js +1 -1
  28. package/dist/modules/customer_accounts/events.js.map +1 -1
  29. package/dist/modules/customer_accounts/lib/resolveTenantContext.js.map +1 -1
  30. package/dist/modules/customers/acl.js +1 -1
  31. package/dist/modules/customers/acl.js.map +1 -1
  32. package/dist/modules/customers/ai-tools/companies-pack.js.map +1 -1
  33. package/dist/modules/customers/ai-tools/deals-pack.js.map +1 -1
  34. package/dist/modules/customers/ai-tools/people-pack.js.map +1 -1
  35. package/dist/modules/customers/api/companies/route.js +4 -4
  36. package/dist/modules/customers/api/companies/route.js.map +2 -2
  37. package/dist/modules/customers/api/people/route.js +4 -4
  38. package/dist/modules/customers/api/people/route.js.map +2 -2
  39. package/dist/modules/customers/commands/addresses.js +5 -5
  40. package/dist/modules/customers/commands/addresses.js.map +2 -2
  41. package/dist/modules/customers/commands/comments.js +5 -5
  42. package/dist/modules/customers/commands/comments.js.map +2 -2
  43. package/dist/modules/customers/commands/deals.js +2 -2
  44. package/dist/modules/customers/commands/deals.js.map +2 -2
  45. package/dist/modules/customers/commands/entity-roles.js +2 -1
  46. package/dist/modules/customers/commands/entity-roles.js.map +2 -2
  47. package/dist/modules/customers/commands/interactions.js +8 -5
  48. package/dist/modules/customers/commands/interactions.js.map +2 -2
  49. package/dist/modules/customers/commands/shared.js +21 -6
  50. package/dist/modules/customers/commands/shared.js.map +2 -2
  51. package/dist/modules/customers/commands/tags.js +3 -3
  52. package/dist/modules/customers/commands/tags.js.map +2 -2
  53. package/dist/modules/customers/components/detail/assignableStaff.js +21 -8
  54. package/dist/modules/customers/components/detail/assignableStaff.js.map +2 -2
  55. package/dist/modules/customers/migrations/Migration20260519120000_pipeline_stage_color_tones.js.map +1 -1
  56. package/dist/modules/data_sync/api/run.js +1 -1
  57. package/dist/modules/data_sync/api/run.js.map +2 -2
  58. package/dist/modules/payment_gateways/api/transactions/route.js +2 -4
  59. package/dist/modules/payment_gateways/api/transactions/route.js.map +2 -2
  60. package/dist/modules/progress/api/jobs/[id]/route.js +7 -2
  61. package/dist/modules/progress/api/jobs/[id]/route.js.map +2 -2
  62. package/dist/modules/progress/api/jobs/route.js +1 -1
  63. package/dist/modules/progress/api/jobs/route.js.map +2 -2
  64. package/dist/modules/progress/lib/progressServiceImpl.js +8 -2
  65. package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
  66. package/dist/modules/resources/api/resources.js +2 -3
  67. package/dist/modules/resources/api/resources.js.map +2 -2
  68. package/dist/modules/sales/api/documents/factory.js +2 -2
  69. package/dist/modules/sales/api/documents/factory.js.map +2 -2
  70. package/dist/modules/sync_excel/api/import/route.js +1 -1
  71. package/dist/modules/sync_excel/api/import/route.js.map +2 -2
  72. package/dist/modules/workflows/api/definitions/route.js +3 -2
  73. package/dist/modules/workflows/api/definitions/route.js.map +2 -2
  74. package/package.json +7 -7
  75. package/src/modules/attachments/api/library/route.ts +2 -2
  76. package/src/modules/attachments/components/AttachmentContentPreview.tsx +6 -6
  77. package/src/modules/audit_logs/api/audit-logs/actions/redo/route.ts +14 -2
  78. package/src/modules/auth/commands/users.ts +32 -15
  79. package/src/modules/auth/data/entities.ts +11 -1
  80. package/src/modules/auth/migrations/.snapshot-open-mercato.json +0 -10
  81. package/src/modules/auth/migrations/Migration20260610120000.ts +53 -0
  82. package/src/modules/catalog/ai-tools/configuration-pack.ts +1 -1
  83. package/src/modules/catalog/ai-tools/prices-offers-pack.ts +1 -1
  84. package/src/modules/catalog/ai-tools/products-pack.ts +1 -1
  85. package/src/modules/catalog/ai-tools/variants-pack.ts +1 -1
  86. package/src/modules/communication_channels/data/entities.ts +2 -2
  87. package/src/modules/communication_channels/encryption.ts +1 -1
  88. package/src/modules/communication_channels/lib/adapter.ts +1 -1
  89. package/src/modules/communication_channels/lib/thread-matcher.ts +1 -1
  90. package/src/modules/communication_channels/lib/thread-token.ts +1 -1
  91. package/src/modules/currencies/api/currencies/route.ts +4 -3
  92. package/src/modules/customer_accounts/api/admin/roles.ts +2 -1
  93. package/src/modules/customer_accounts/events.ts +1 -1
  94. package/src/modules/customer_accounts/lib/resolveTenantContext.ts +2 -2
  95. package/src/modules/customers/acl.ts +1 -1
  96. package/src/modules/customers/ai-tools/companies-pack.ts +1 -1
  97. package/src/modules/customers/ai-tools/deals-pack.ts +1 -1
  98. package/src/modules/customers/ai-tools/people-pack.ts +1 -1
  99. package/src/modules/customers/api/companies/route.ts +4 -4
  100. package/src/modules/customers/api/people/route.ts +4 -4
  101. package/src/modules/customers/commands/addresses.ts +5 -5
  102. package/src/modules/customers/commands/comments.ts +5 -5
  103. package/src/modules/customers/commands/deals.ts +2 -2
  104. package/src/modules/customers/commands/entity-roles.ts +2 -1
  105. package/src/modules/customers/commands/interactions.ts +8 -5
  106. package/src/modules/customers/commands/shared.ts +26 -4
  107. package/src/modules/customers/commands/tags.ts +3 -3
  108. package/src/modules/customers/components/detail/assignableStaff.ts +32 -8
  109. package/src/modules/customers/migrations/Migration20260519120000_pipeline_stage_color_tones.ts +1 -1
  110. package/src/modules/data_sync/api/run.ts +1 -1
  111. package/src/modules/payment_gateways/api/transactions/route.ts +2 -5
  112. package/src/modules/progress/api/jobs/[id]/route.ts +6 -1
  113. package/src/modules/progress/api/jobs/route.ts +1 -1
  114. package/src/modules/progress/lib/progressServiceImpl.ts +7 -1
  115. package/src/modules/resources/api/resources.ts +2 -3
  116. package/src/modules/sales/api/documents/factory.ts +2 -2
  117. package/src/modules/staff/AGENTS.md +1 -1
  118. package/src/modules/sync_excel/api/import/route.ts +1 -1
  119. package/src/modules/workflows/api/definitions/route.ts +3 -2
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/api/people/route.ts"],
4
- "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n CustomerDealPersonLink,\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../../data/entities'\nimport { E } from '#generated/entities.ids.generated'\nimport { personCreateSchema, personUpdateSchema } from '../../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n applyEntityIdExclusion,\n applyEntityIdRestriction,\n findMatchingEntityIdsWithQueryEngine,\n findMatchingEntityIdsBySearchTokensAcrossSources,\n withScopedPayload,\n} from '../utils'\nimport { buildCustomFieldFiltersFromQuery, extractAllCustomFieldEntries, splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { escapeLikePattern } from '@open-mercato/shared/lib/db/escapeLikePattern'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { consumeAdvancedFilterState, mergeAdvancedFilterTree } from '@open-mercato/shared/lib/crud/advanced-filter-integration'\nimport {\n createCustomersCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi'\nimport {\n filterActivePersonCompanyLinks,\n withActiveCustomerPersonCompanyLinkFilter,\n withCustomerPersonCompanyLinkScope,\n withScopedCustomerDealLinkWhere,\n} from '../../lib/personCompanyLinkTable'\nimport { normalizeProfilePayload } from './payload'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst listSchema = z\n .object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n email: z.string().optional(),\n emailStartsWith: z.string().optional(),\n emailContains: z.string().optional(),\n status: z.string().optional(),\n lifecycleStage: z.string().optional(),\n source: z.string().optional(),\n hasEmail: z.string().optional(),\n hasPhone: z.string().optional(),\n hasNextInteraction: z.string().optional(),\n createdFrom: z.string().optional(),\n createdTo: z.string().optional(),\n sortField: z.string().optional(),\n sortDir: z.enum(['asc', 'desc']).optional(),\n id: z.string().uuid().optional(),\n tagIds: z.string().optional(),\n tagIdsEmpty: z.string().optional(),\n excludeIds: z.string().optional(),\n excludeLinkedCompanyId: z.string().uuid().optional(),\n excludeLinkedDealId: z.string().uuid().optional(),\n })\n .passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: CustomerEntity,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n enrichers: { entityId: 'customers.person' },\n indexer: { entityType: E.customers.customer_entity },\n list: {\n schema: listSchema,\n entityId: E.customers.customer_entity,\n fields: [\n 'id',\n 'display_name',\n 'description',\n 'owner_user_id',\n 'primary_email',\n 'primary_phone',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'next_interaction_at',\n 'next_interaction_name',\n 'next_interaction_ref_id',\n 'next_interaction_icon',\n 'next_interaction_color',\n 'organization_id',\n 'tenant_id',\n 'kind',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'display_name',\n email: 'primary_email',\n primaryEmail: 'primary_email',\n status: 'status',\n lifecycleStage: 'lifecycle_stage',\n source: 'source',\n nextInteractionAt: 'next_interaction_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n buildFilters: async (query, ctx) => {\n const advancedFilterTree = consumeAdvancedFilterState(query)\n const filters: Record<string, unknown> = { kind: { $eq: 'person' } }\n if (query.id) filters.id = { $eq: query.id }\n if (query.search) {\n const matchingIds = ctx\n ? await findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query: query.search,\n sources: [\n {\n entityType: E.customers.customer_entity,\n fields: [\n 'display_name',\n 'primary_email',\n 'primary_phone',\n 'description',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'next_interaction_name',\n ],\n },\n {\n entityType: E.customers.customer_person_profile,\n fields: [\n 'display_name',\n 'primary_email',\n 'primary_phone',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'first_name',\n 'last_name',\n 'preferred_name',\n 'job_title',\n 'department',\n 'seniority',\n 'timezone',\n 'linked_in_url',\n 'twitter_url',\n ],\n mapToEntityIds: {\n table: 'customer_people',\n targetColumn: 'entity_id',\n },\n },\n ],\n })\n : null\n if (matchingIds !== null && matchingIds.length > 0) {\n applyEntityIdRestriction(filters, matchingIds)\n } else {\n const searchPattern = `%${escapeLikePattern(query.search)}%`\n filters.$or = [\n { display_name: { $ilike: searchPattern } },\n { primary_email: { $ilike: searchPattern } },\n { primary_phone: { $ilike: searchPattern } },\n { description: { $ilike: searchPattern } },\n { next_interaction_name: { $ilike: searchPattern } },\n ]\n }\n }\n const email = typeof query.email === 'string' ? query.email.trim().toLowerCase() : ''\n const emailStartsWith = typeof query.emailStartsWith === 'string' ? query.emailStartsWith.trim().toLowerCase() : ''\n const emailContains = typeof query.emailContains === 'string' ? query.emailContains.trim().toLowerCase() : ''\n if (email) {\n filters.primary_email = { $eq: email }\n } else if (emailStartsWith) {\n filters.primary_email = { $ilike: `${escapeLikePattern(emailStartsWith)}%` }\n } else if (emailContains) {\n filters.primary_email = { $ilike: `%${escapeLikePattern(emailContains)}%` }\n }\n if (query.status) {\n filters.status = { $eq: query.status }\n }\n if (query.lifecycleStage) {\n filters.lifecycle_stage = { $eq: query.lifecycleStage }\n }\n if (query.source) {\n filters.source = { $eq: query.source }\n }\n const tagIdsRaw = typeof query.tagIds === 'string' ? query.tagIds : ''\n const tagIds = tagIdsRaw\n .split(',')\n .map((value: string) => value.trim())\n .filter((value: string) => value.length > 0)\n const tagIdsEmpty = parseBooleanToken(query.tagIdsEmpty) === true\n if (tagIdsEmpty) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n } else if (tagIds.length > 0) {\n filters['tag_assignments.tag_id'] = { $in: tagIds }\n }\n const excludedIds = new Set<string>()\n const excludeIdsRaw = typeof query.excludeIds === 'string' ? query.excludeIds : ''\n excludeIdsRaw\n .split(',')\n .map((value: string) => value.trim())\n .filter((value: string) => value.length > 0)\n .forEach((value: string) => excludedIds.add(value))\n if (ctx && query.excludeLinkedCompanyId) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(\n em,\n withCustomerPersonCompanyLinkScope({ company: query.excludeLinkedCompanyId }, decryptionScope),\n 'customers.people.GET',\n )\n const links = filterActivePersonCompanyLinks(\n await findWithDecryption(\n em,\n CustomerPersonCompanyLink,\n linkWhere,\n { populate: ['person'] },\n decryptionScope,\n ),\n )\n links.forEach((link) => {\n const personId = link.person?.id\n if (typeof personId === 'string' && personId.length > 0) excludedIds.add(personId)\n })\n } catch (err) {\n console.warn('[customers.people.list] exclusion lookup failed; falling back to base result set', err)\n }\n }\n if (ctx && query.excludeLinkedDealId) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n withScopedCustomerDealLinkWhere(query.excludeLinkedDealId, decryptionScope),\n { populate: ['person'] },\n decryptionScope,\n )\n links.forEach((link) => {\n const personId = link.person?.id\n if (typeof personId === 'string' && personId.length > 0) excludedIds.add(personId)\n })\n } catch (err) {\n console.warn('[customers.people.list] exclusion lookup failed; falling back to base result set', err)\n }\n }\n applyEntityIdExclusion(filters, Array.from(excludedIds))\n const hasEmail = parseBooleanToken(query.hasEmail)\n if (!email && !emailStartsWith && !emailContains && hasEmail !== null) {\n filters.primary_email = { $exists: hasEmail }\n }\n const hasPhone = parseBooleanToken(query.hasPhone)\n if (hasPhone !== null) {\n filters.primary_phone = { $exists: hasPhone }\n }\n const hasNextInteraction = parseBooleanToken(query.hasNextInteraction)\n if (hasNextInteraction !== null) {\n filters.next_interaction_at = { $exists: hasNextInteraction }\n }\n const createdRange: Record<string, Date> = {}\n if (query.createdFrom) {\n const from = new Date(query.createdFrom)\n if (!Number.isNaN(from.getTime())) createdRange.$gte = from\n }\n if (query.createdTo) {\n const to = new Date(query.createdTo)\n if (!Number.isNaN(to.getTime())) createdRange.$lte = to\n }\n if (Object.keys(createdRange).length) {\n filters.created_at = createdRange\n }\n if (ctx) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const cfFilters = await buildCustomFieldFiltersFromQuery({\n entityIds: [E.customers.customer_entity, E.customers.customer_person_profile],\n query,\n em,\n tenantId: ctx.auth?.tenantId ?? null,\n })\n Object.assign(filters, cfFilters)\n } catch (err) {\n console.warn('[customers.people.list] custom field filter resolution failed; falling back to base filters', err)\n }\n }\n if (ctx && advancedFilterTree) {\n const advancedFilters = mergeAdvancedFilterTree({ ...filters }, advancedFilterTree)\n const matchedIds = await findMatchingEntityIdsWithQueryEngine({\n ctx,\n entityId: E.customers.customer_entity,\n filters: advancedFilters,\n customFieldSources: [\n {\n entityId: E.customers.customer_person_profile,\n table: 'customer_people',\n alias: 'person_profile',\n recordIdColumn: 'id',\n join: { fromField: 'id', toField: 'entity_id' },\n },\n ],\n joins: [\n {\n alias: 'tag_assignments',\n table: 'customer_tag_assignments',\n from: { field: 'id' },\n to: { field: 'entity_id' },\n type: 'left',\n },\n ],\n })\n applyEntityIdRestriction(filters, matchedIds)\n }\n return filters\n },\n customFieldSources: [\n {\n entityId: E.customers.customer_person_profile,\n table: 'customer_people',\n alias: 'person_profile',\n recordIdColumn: 'id',\n join: { fromField: 'id', toField: 'entity_id' },\n },\n ],\n joins: [\n {\n alias: 'tag_assignments',\n table: 'customer_tag_assignments',\n from: { field: 'id' },\n to: { field: 'entity_id' },\n type: 'left',\n },\n ],\n transformItem: (item) => {\n if (!item || typeof item !== 'object') return item\n const record = item as Record<string, unknown>\n const normalized: Record<string, unknown> = { ...record }\n delete normalized.kind\n const cfEntries = extractAllCustomFieldEntries(record)\n for (const key of Object.keys(normalized)) {\n if (key.startsWith('cf:')) {\n delete normalized[key]\n }\n }\n return { ...normalized, ...cfEntries }\n },\n },\n actions: {\n create: {\n commandId: 'customers.people.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n const { base, custom } = splitCustomFieldPayload(scoped)\n const parsed = personCreateSchema.parse(base)\n return Object.keys(custom).length ? { ...parsed, customFields: custom } : parsed\n },\n response: ({ result }) => ({\n id: result?.entityId ?? result?.id ?? null,\n personId: result?.personId ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: 'customers.people.update',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n const normalized = normalizeProfilePayload(scoped, translate)\n const { base, custom } = splitCustomFieldPayload(normalized)\n const parsed = personUpdateSchema.parse(base)\n return Object.keys(custom).length ? { ...parsed, customFields: custom } : parsed\n },\n // Return the freshly-bumped updatedAt so inline-edit detail pages can refresh\n // their optimistic-lock token between sequential saves (#2055).\n response: (arg: { result?: unknown; updatedAt?: Date | string | null }) => {\n const raw = arg?.updatedAt\n ?? (arg?.result as { updatedAt?: Date | string | null } | null | undefined)?.updatedAt\n ?? null\n return {\n ok: true,\n updatedAt: raw instanceof Date ? raw.toISOString() : (typeof raw === 'string' ? raw : null),\n }\n },\n },\n delete: {\n commandId: 'customers.people.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id =\n parsed?.body?.id ??\n parsed?.id ??\n parsed?.query?.id ??\n (ctx.request ? new URL(ctx.request.url).searchParams.get('id') : null)\n if (!id) throw new CrudHttpError(400, { error: translate('customers.errors.person_required', 'Person id is required') })\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n hooks: {\n afterList: async (payload, ctx) => {\n const items = Array.isArray(payload?.items) ? payload.items : []\n const ids = items\n .map((item: unknown) => (\n item && typeof item === 'object' && typeof (item as Record<string, unknown>).id === 'string'\n ? (item as Record<string, unknown>).id as string\n : null\n ))\n .filter((id: string | null): id is string => typeof id === 'string' && id.length > 0)\n if (!ids.length) return\n\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const profileWhere: Record<string, unknown> = {\n entity: { $in: ids },\n tenantId: ctx.auth?.tenantId ?? null,\n }\n if (ctx.selectedOrganizationId) {\n profileWhere.organizationId = ctx.selectedOrganizationId\n }\n\n const [entities, profiles] = await Promise.all([\n findWithDecryption(\n em,\n CustomerEntity,\n {\n id: { $in: ids },\n deletedAt: null,\n kind: 'person',\n } as FilterQuery<CustomerEntity>,\n undefined,\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerPersonProfile,\n profileWhere as FilterQuery<CustomerPersonProfile>,\n { populate: ['entity', 'company'] },\n decryptionScope,\n ),\n ])\n\n const entitiesById = new Map<string, CustomerEntity>()\n for (const entity of entities) {\n entitiesById.set(entity.id, entity)\n }\n\n const profilesByEntityId = new Map<string, CustomerPersonProfile>()\n for (const profile of profiles) {\n const profileEntity = (profile as { entity?: { id?: unknown } }).entity\n const entityId = typeof profileEntity?.id === 'string' ? profileEntity.id : null\n if (entityId) profilesByEntityId.set(entityId, profile)\n }\n\n payload.items = items.map((item: unknown) => {\n if (!item || typeof item !== 'object') return item\n const record = item as Record<string, unknown>\n const entity = typeof record.id === 'string' ? entitiesById.get(record.id) : undefined\n const profile = typeof record.id === 'string' ? profilesByEntityId.get(record.id) : undefined\n if (!entity && !profile) return item\n return {\n ...record,\n display_name: entity?.displayName ?? record.display_name ?? null,\n description: entity?.description ?? record.description ?? null,\n owner_user_id: entity?.ownerUserId ?? record.owner_user_id ?? null,\n primary_email: entity?.primaryEmail ?? record.primary_email ?? null,\n primary_phone: entity?.primaryPhone ?? record.primary_phone ?? null,\n status: entity?.status ?? record.status ?? null,\n lifecycle_stage: entity?.lifecycleStage ?? record.lifecycle_stage ?? null,\n source: entity?.source ?? record.source ?? null,\n next_interaction_at: entity?.nextInteractionAt ? entity.nextInteractionAt.toISOString() : record.next_interaction_at ?? null,\n next_interaction_name: entity?.nextInteractionName ?? record.next_interaction_name ?? null,\n next_interaction_ref_id: entity?.nextInteractionRefId ?? record.next_interaction_ref_id ?? null,\n next_interaction_icon: entity?.nextInteractionIcon ?? record.next_interaction_icon ?? null,\n next_interaction_color: entity?.nextInteractionColor ?? record.next_interaction_color ?? null,\n first_name: profile?.firstName ?? null,\n last_name: profile?.lastName ?? null,\n preferred_name: profile?.preferredName ?? null,\n job_title: profile?.jobTitle ?? null,\n department: profile?.department ?? null,\n seniority: profile?.seniority ?? null,\n timezone: profile?.timezone ?? null,\n linked_in_url: profile?.linkedInUrl ?? null,\n twitter_url: profile?.twitterUrl ?? null,\n company_entity_id:\n profile?.company && typeof profile.company === 'object'\n ? profile.company.id\n : profile?.company ?? null,\n }\n })\n },\n },\n})\n\nconst { POST, PUT, DELETE } = crud\n\nexport { POST, PUT, DELETE }\nexport const GET = crud.GET\n\nconst personListItemSchema = z.object({\n id: z.string().uuid(),\n display_name: z.string().optional(),\n description: z.string().nullable().optional(),\n owner_user_id: z.string().uuid().nullable().optional(),\n primary_email: z.string().nullable().optional(),\n primary_phone: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n lifecycle_stage: z.string().nullable().optional(),\n source: z.string().nullable().optional(),\n next_interaction_at: z.string().nullable().optional(),\n next_interaction_name: z.string().nullable().optional(),\n next_interaction_ref_id: z.string().nullable().optional(),\n next_interaction_icon: z.string().nullable().optional(),\n next_interaction_color: z.string().nullable().optional(),\n organization_id: z.string().uuid().nullable().optional(),\n tenant_id: z.string().uuid().nullable().optional(),\n created_at: z.string().nullable().optional(),\n})\n\nconst personCreateResponseSchema = z.object({\n id: z.string().uuid().nullable(),\n personId: z.string().uuid().nullable(),\n})\n\nexport const openApi = createCustomersCrudOpenApi({\n resourceName: 'Person',\n pluralName: 'People',\n querySchema: listSchema,\n listResponseSchema: createPagedListResponseSchema(personListItemSchema),\n create: {\n schema: personCreateSchema,\n responseSchema: personCreateResponseSchema,\n description: 'Creates a person contact using scoped organization and tenant identifiers.',\n },\n update: {\n schema: personUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Updates contact details or custom fields for a person.',\n },\n del: {\n schema: z.object({ id: z.string().uuid() }),\n responseSchema: defaultOkResponseSchema,\n description: 'Deletes a person by id. Request body or query may provide the identifier.',\n errors: [\n {\n status: 422,\n description: 'Person has dependent records (e.g. linked deals); unlink or reassign before delete.',\n schema: z.object({\n error: z.string(),\n code: z.literal('PERSON_HAS_DEPENDENTS'),\n }),\n },\n ],\n },\n})\n"],
5
- "mappings": "AACA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAClB,SAAS,oBAAoB,0BAA0B;AACvD,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kCAAkC,8BAA8B,+BAA+B;AACxG,SAAS,yBAAyB;AAClC,SAAS,yBAAyB;AAClC,SAAS,0BAA0B;AACnC,SAAS,4BAA4B,+BAA+B;AACpE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,+BAA+B;AAExC,MAAM,gBAAgB,EAAE,OAAO,CAAC,CAAC,EAAE,YAAY;AAE/C,MAAM,aAAa,EAChB,OAAO;AAAA,EACN,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACxC,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,EAAE,OAAO;AAAA,UAChB,MAAM,EAAE,QAAQ,uBAAuB;AAAA,QACzC,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF,CAAC;",
4
+ "sourcesContent": ["import type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { makeCrudRoute } from '@open-mercato/shared/lib/crud/factory'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n CustomerDealPersonLink,\n CustomerEntity,\n CustomerPersonCompanyLink,\n CustomerPersonProfile,\n} from '../../data/entities'\nimport { E } from '#generated/entities.ids.generated'\nimport { personCreateSchema, personUpdateSchema } from '../../data/validators'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport {\n applyEntityIdExclusion,\n applyEntityIdRestriction,\n findMatchingEntityIdsWithQueryEngine,\n findMatchingEntityIdsBySearchTokensAcrossSources,\n withScopedPayload,\n} from '../utils'\nimport { buildCustomFieldFiltersFromQuery, extractAllCustomFieldEntries, splitCustomFieldPayload } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { buildIlikeTerm } from '@open-mercato/shared/lib/db/buildIlikeTerm'\nimport { parseBooleanToken } from '@open-mercato/shared/lib/boolean'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { consumeAdvancedFilterState, mergeAdvancedFilterTree } from '@open-mercato/shared/lib/crud/advanced-filter-integration'\nimport {\n createCustomersCrudOpenApi,\n createPagedListResponseSchema,\n defaultOkResponseSchema,\n} from '../openapi'\nimport {\n filterActivePersonCompanyLinks,\n withActiveCustomerPersonCompanyLinkFilter,\n withCustomerPersonCompanyLinkScope,\n withScopedCustomerDealLinkWhere,\n} from '../../lib/personCompanyLinkTable'\nimport { normalizeProfilePayload } from './payload'\n\nconst rawBodySchema = z.object({}).passthrough()\n\nconst listSchema = z\n .object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(50),\n search: z.string().optional(),\n email: z.string().optional(),\n emailStartsWith: z.string().optional(),\n emailContains: z.string().optional(),\n status: z.string().optional(),\n lifecycleStage: z.string().optional(),\n source: z.string().optional(),\n hasEmail: z.string().optional(),\n hasPhone: z.string().optional(),\n hasNextInteraction: z.string().optional(),\n createdFrom: z.string().optional(),\n createdTo: z.string().optional(),\n sortField: z.string().optional(),\n sortDir: z.enum(['asc', 'desc']).optional(),\n id: z.string().uuid().optional(),\n tagIds: z.string().optional(),\n tagIdsEmpty: z.string().optional(),\n excludeIds: z.string().optional(),\n excludeLinkedCompanyId: z.string().uuid().optional(),\n excludeLinkedDealId: z.string().uuid().optional(),\n })\n .passthrough()\n\nconst routeMetadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n PUT: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n DELETE: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n}\n\nexport const metadata = routeMetadata\n\nconst crud = makeCrudRoute({\n metadata: routeMetadata,\n orm: {\n entity: CustomerEntity,\n idField: 'id',\n orgField: 'organizationId',\n tenantField: 'tenantId',\n softDeleteField: 'deletedAt',\n },\n enrichers: { entityId: 'customers.person' },\n indexer: { entityType: E.customers.customer_entity },\n list: {\n schema: listSchema,\n entityId: E.customers.customer_entity,\n fields: [\n 'id',\n 'display_name',\n 'description',\n 'owner_user_id',\n 'primary_email',\n 'primary_phone',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'next_interaction_at',\n 'next_interaction_name',\n 'next_interaction_ref_id',\n 'next_interaction_icon',\n 'next_interaction_color',\n 'organization_id',\n 'tenant_id',\n 'kind',\n 'created_at',\n 'updated_at',\n ],\n sortFieldMap: {\n name: 'display_name',\n email: 'primary_email',\n primaryEmail: 'primary_email',\n status: 'status',\n lifecycleStage: 'lifecycle_stage',\n source: 'source',\n nextInteractionAt: 'next_interaction_at',\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n },\n buildFilters: async (query, ctx) => {\n const advancedFilterTree = consumeAdvancedFilterState(query)\n const filters: Record<string, unknown> = { kind: { $eq: 'person' } }\n if (query.id) filters.id = { $eq: query.id }\n if (query.search) {\n const matchingIds = ctx\n ? await findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query: query.search,\n sources: [\n {\n entityType: E.customers.customer_entity,\n fields: [\n 'display_name',\n 'primary_email',\n 'primary_phone',\n 'description',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'next_interaction_name',\n ],\n },\n {\n entityType: E.customers.customer_person_profile,\n fields: [\n 'display_name',\n 'primary_email',\n 'primary_phone',\n 'status',\n 'lifecycle_stage',\n 'source',\n 'first_name',\n 'last_name',\n 'preferred_name',\n 'job_title',\n 'department',\n 'seniority',\n 'timezone',\n 'linked_in_url',\n 'twitter_url',\n ],\n mapToEntityIds: {\n table: 'customer_people',\n targetColumn: 'entity_id',\n },\n },\n ],\n })\n : null\n if (matchingIds !== null && matchingIds.length > 0) {\n applyEntityIdRestriction(filters, matchingIds)\n } else {\n const searchPattern = buildIlikeTerm(query.search)\n filters.$or = [\n { display_name: { $ilike: searchPattern } },\n { primary_email: { $ilike: searchPattern } },\n { primary_phone: { $ilike: searchPattern } },\n { description: { $ilike: searchPattern } },\n { next_interaction_name: { $ilike: searchPattern } },\n ]\n }\n }\n const email = typeof query.email === 'string' ? query.email.trim().toLowerCase() : ''\n const emailStartsWith = typeof query.emailStartsWith === 'string' ? query.emailStartsWith.trim().toLowerCase() : ''\n const emailContains = typeof query.emailContains === 'string' ? query.emailContains.trim().toLowerCase() : ''\n if (email) {\n filters.primary_email = { $eq: email }\n } else if (emailStartsWith) {\n filters.primary_email = { $ilike: buildIlikeTerm(emailStartsWith, 'startsWith') }\n } else if (emailContains) {\n filters.primary_email = { $ilike: buildIlikeTerm(emailContains) }\n }\n if (query.status) {\n filters.status = { $eq: query.status }\n }\n if (query.lifecycleStage) {\n filters.lifecycle_stage = { $eq: query.lifecycleStage }\n }\n if (query.source) {\n filters.source = { $eq: query.source }\n }\n const tagIdsRaw = typeof query.tagIds === 'string' ? query.tagIds : ''\n const tagIds = tagIdsRaw\n .split(',')\n .map((value: string) => value.trim())\n .filter((value: string) => value.length > 0)\n const tagIdsEmpty = parseBooleanToken(query.tagIdsEmpty) === true\n if (tagIdsEmpty) {\n filters.id = { $eq: '00000000-0000-0000-0000-000000000000' }\n } else if (tagIds.length > 0) {\n filters['tag_assignments.tag_id'] = { $in: tagIds }\n }\n const excludedIds = new Set<string>()\n const excludeIdsRaw = typeof query.excludeIds === 'string' ? query.excludeIds : ''\n excludeIdsRaw\n .split(',')\n .map((value: string) => value.trim())\n .filter((value: string) => value.length > 0)\n .forEach((value: string) => excludedIds.add(value))\n if (ctx && query.excludeLinkedCompanyId) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(\n em,\n withCustomerPersonCompanyLinkScope({ company: query.excludeLinkedCompanyId }, decryptionScope),\n 'customers.people.GET',\n )\n const links = filterActivePersonCompanyLinks(\n await findWithDecryption(\n em,\n CustomerPersonCompanyLink,\n linkWhere,\n { populate: ['person'] },\n decryptionScope,\n ),\n )\n links.forEach((link) => {\n const personId = link.person?.id\n if (typeof personId === 'string' && personId.length > 0) excludedIds.add(personId)\n })\n } catch (err) {\n console.warn('[customers.people.list] exclusion lookup failed; falling back to base result set', err)\n }\n }\n if (ctx && query.excludeLinkedDealId) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n withScopedCustomerDealLinkWhere(query.excludeLinkedDealId, decryptionScope),\n { populate: ['person'] },\n decryptionScope,\n )\n links.forEach((link) => {\n const personId = link.person?.id\n if (typeof personId === 'string' && personId.length > 0) excludedIds.add(personId)\n })\n } catch (err) {\n console.warn('[customers.people.list] exclusion lookup failed; falling back to base result set', err)\n }\n }\n applyEntityIdExclusion(filters, Array.from(excludedIds))\n const hasEmail = parseBooleanToken(query.hasEmail)\n if (!email && !emailStartsWith && !emailContains && hasEmail !== null) {\n filters.primary_email = { $exists: hasEmail }\n }\n const hasPhone = parseBooleanToken(query.hasPhone)\n if (hasPhone !== null) {\n filters.primary_phone = { $exists: hasPhone }\n }\n const hasNextInteraction = parseBooleanToken(query.hasNextInteraction)\n if (hasNextInteraction !== null) {\n filters.next_interaction_at = { $exists: hasNextInteraction }\n }\n const createdRange: Record<string, Date> = {}\n if (query.createdFrom) {\n const from = new Date(query.createdFrom)\n if (!Number.isNaN(from.getTime())) createdRange.$gte = from\n }\n if (query.createdTo) {\n const to = new Date(query.createdTo)\n if (!Number.isNaN(to.getTime())) createdRange.$lte = to\n }\n if (Object.keys(createdRange).length) {\n filters.created_at = createdRange\n }\n if (ctx) {\n try {\n const em = ctx.container.resolve('em') as EntityManager\n const cfFilters = await buildCustomFieldFiltersFromQuery({\n entityIds: [E.customers.customer_entity, E.customers.customer_person_profile],\n query,\n em,\n tenantId: ctx.auth?.tenantId ?? null,\n })\n Object.assign(filters, cfFilters)\n } catch (err) {\n console.warn('[customers.people.list] custom field filter resolution failed; falling back to base filters', err)\n }\n }\n if (ctx && advancedFilterTree) {\n const advancedFilters = mergeAdvancedFilterTree({ ...filters }, advancedFilterTree)\n const matchedIds = await findMatchingEntityIdsWithQueryEngine({\n ctx,\n entityId: E.customers.customer_entity,\n filters: advancedFilters,\n customFieldSources: [\n {\n entityId: E.customers.customer_person_profile,\n table: 'customer_people',\n alias: 'person_profile',\n recordIdColumn: 'id',\n join: { fromField: 'id', toField: 'entity_id' },\n },\n ],\n joins: [\n {\n alias: 'tag_assignments',\n table: 'customer_tag_assignments',\n from: { field: 'id' },\n to: { field: 'entity_id' },\n type: 'left',\n },\n ],\n })\n applyEntityIdRestriction(filters, matchedIds)\n }\n return filters\n },\n customFieldSources: [\n {\n entityId: E.customers.customer_person_profile,\n table: 'customer_people',\n alias: 'person_profile',\n recordIdColumn: 'id',\n join: { fromField: 'id', toField: 'entity_id' },\n },\n ],\n joins: [\n {\n alias: 'tag_assignments',\n table: 'customer_tag_assignments',\n from: { field: 'id' },\n to: { field: 'entity_id' },\n type: 'left',\n },\n ],\n transformItem: (item) => {\n if (!item || typeof item !== 'object') return item\n const record = item as Record<string, unknown>\n const normalized: Record<string, unknown> = { ...record }\n delete normalized.kind\n const cfEntries = extractAllCustomFieldEntries(record)\n for (const key of Object.keys(normalized)) {\n if (key.startsWith('cf:')) {\n delete normalized[key]\n }\n }\n return { ...normalized, ...cfEntries }\n },\n },\n actions: {\n create: {\n commandId: 'customers.people.create',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n const { base, custom } = splitCustomFieldPayload(scoped)\n const parsed = personCreateSchema.parse(base)\n return Object.keys(custom).length ? { ...parsed, customFields: custom } : parsed\n },\n response: ({ result }) => ({\n id: result?.entityId ?? result?.id ?? null,\n personId: result?.personId ?? null,\n }),\n status: 201,\n },\n update: {\n commandId: 'customers.people.update',\n schema: rawBodySchema,\n mapInput: async ({ raw, ctx }) => {\n const { translate } = await resolveTranslations()\n const scoped = withScopedPayload(raw ?? {}, ctx, translate)\n const normalized = normalizeProfilePayload(scoped, translate)\n const { base, custom } = splitCustomFieldPayload(normalized)\n const parsed = personUpdateSchema.parse(base)\n return Object.keys(custom).length ? { ...parsed, customFields: custom } : parsed\n },\n // Return the freshly-bumped updatedAt so inline-edit detail pages can refresh\n // their optimistic-lock token between sequential saves (#2055).\n response: (arg: { result?: unknown; updatedAt?: Date | string | null }) => {\n const raw = arg?.updatedAt\n ?? (arg?.result as { updatedAt?: Date | string | null } | null | undefined)?.updatedAt\n ?? null\n return {\n ok: true,\n updatedAt: raw instanceof Date ? raw.toISOString() : (typeof raw === 'string' ? raw : null),\n }\n },\n },\n delete: {\n commandId: 'customers.people.delete',\n schema: rawBodySchema,\n mapInput: async ({ parsed, ctx }) => {\n const { translate } = await resolveTranslations()\n const id =\n parsed?.body?.id ??\n parsed?.id ??\n parsed?.query?.id ??\n (ctx.request ? new URL(ctx.request.url).searchParams.get('id') : null)\n if (!id) throw new CrudHttpError(400, { error: translate('customers.errors.person_required', 'Person id is required') })\n return { id }\n },\n response: () => ({ ok: true }),\n },\n },\n hooks: {\n afterList: async (payload, ctx) => {\n const items = Array.isArray(payload?.items) ? payload.items : []\n const ids = items\n .map((item: unknown) => (\n item && typeof item === 'object' && typeof (item as Record<string, unknown>).id === 'string'\n ? (item as Record<string, unknown>).id as string\n : null\n ))\n .filter((id: string | null): id is string => typeof id === 'string' && id.length > 0)\n if (!ids.length) return\n\n const em = ctx.container.resolve('em') as EntityManager\n const decryptionScope = {\n tenantId: ctx.auth?.tenantId ?? null,\n organizationId: ctx.selectedOrganizationId ?? ctx.auth?.orgId ?? null,\n }\n const profileWhere: Record<string, unknown> = {\n entity: { $in: ids },\n tenantId: ctx.auth?.tenantId ?? null,\n }\n if (ctx.selectedOrganizationId) {\n profileWhere.organizationId = ctx.selectedOrganizationId\n }\n\n const [entities, profiles] = await Promise.all([\n findWithDecryption(\n em,\n CustomerEntity,\n {\n id: { $in: ids },\n deletedAt: null,\n kind: 'person',\n } as FilterQuery<CustomerEntity>,\n undefined,\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerPersonProfile,\n profileWhere as FilterQuery<CustomerPersonProfile>,\n { populate: ['entity', 'company'] },\n decryptionScope,\n ),\n ])\n\n const entitiesById = new Map<string, CustomerEntity>()\n for (const entity of entities) {\n entitiesById.set(entity.id, entity)\n }\n\n const profilesByEntityId = new Map<string, CustomerPersonProfile>()\n for (const profile of profiles) {\n const profileEntity = (profile as { entity?: { id?: unknown } }).entity\n const entityId = typeof profileEntity?.id === 'string' ? profileEntity.id : null\n if (entityId) profilesByEntityId.set(entityId, profile)\n }\n\n payload.items = items.map((item: unknown) => {\n if (!item || typeof item !== 'object') return item\n const record = item as Record<string, unknown>\n const entity = typeof record.id === 'string' ? entitiesById.get(record.id) : undefined\n const profile = typeof record.id === 'string' ? profilesByEntityId.get(record.id) : undefined\n if (!entity && !profile) return item\n return {\n ...record,\n display_name: entity?.displayName ?? record.display_name ?? null,\n description: entity?.description ?? record.description ?? null,\n owner_user_id: entity?.ownerUserId ?? record.owner_user_id ?? null,\n primary_email: entity?.primaryEmail ?? record.primary_email ?? null,\n primary_phone: entity?.primaryPhone ?? record.primary_phone ?? null,\n status: entity?.status ?? record.status ?? null,\n lifecycle_stage: entity?.lifecycleStage ?? record.lifecycle_stage ?? null,\n source: entity?.source ?? record.source ?? null,\n next_interaction_at: entity?.nextInteractionAt ? entity.nextInteractionAt.toISOString() : record.next_interaction_at ?? null,\n next_interaction_name: entity?.nextInteractionName ?? record.next_interaction_name ?? null,\n next_interaction_ref_id: entity?.nextInteractionRefId ?? record.next_interaction_ref_id ?? null,\n next_interaction_icon: entity?.nextInteractionIcon ?? record.next_interaction_icon ?? null,\n next_interaction_color: entity?.nextInteractionColor ?? record.next_interaction_color ?? null,\n first_name: profile?.firstName ?? null,\n last_name: profile?.lastName ?? null,\n preferred_name: profile?.preferredName ?? null,\n job_title: profile?.jobTitle ?? null,\n department: profile?.department ?? null,\n seniority: profile?.seniority ?? null,\n timezone: profile?.timezone ?? null,\n linked_in_url: profile?.linkedInUrl ?? null,\n twitter_url: profile?.twitterUrl ?? null,\n company_entity_id:\n profile?.company && typeof profile.company === 'object'\n ? profile.company.id\n : profile?.company ?? null,\n }\n })\n },\n },\n})\n\nconst { POST, PUT, DELETE } = crud\n\nexport { POST, PUT, DELETE }\nexport const GET = crud.GET\n\nconst personListItemSchema = z.object({\n id: z.string().uuid(),\n display_name: z.string().optional(),\n description: z.string().nullable().optional(),\n owner_user_id: z.string().uuid().nullable().optional(),\n primary_email: z.string().nullable().optional(),\n primary_phone: z.string().nullable().optional(),\n status: z.string().nullable().optional(),\n lifecycle_stage: z.string().nullable().optional(),\n source: z.string().nullable().optional(),\n next_interaction_at: z.string().nullable().optional(),\n next_interaction_name: z.string().nullable().optional(),\n next_interaction_ref_id: z.string().nullable().optional(),\n next_interaction_icon: z.string().nullable().optional(),\n next_interaction_color: z.string().nullable().optional(),\n organization_id: z.string().uuid().nullable().optional(),\n tenant_id: z.string().uuid().nullable().optional(),\n created_at: z.string().nullable().optional(),\n})\n\nconst personCreateResponseSchema = z.object({\n id: z.string().uuid().nullable(),\n personId: z.string().uuid().nullable(),\n})\n\nexport const openApi = createCustomersCrudOpenApi({\n resourceName: 'Person',\n pluralName: 'People',\n querySchema: listSchema,\n listResponseSchema: createPagedListResponseSchema(personListItemSchema),\n create: {\n schema: personCreateSchema,\n responseSchema: personCreateResponseSchema,\n description: 'Creates a person contact using scoped organization and tenant identifiers.',\n },\n update: {\n schema: personUpdateSchema,\n responseSchema: defaultOkResponseSchema,\n description: 'Updates contact details or custom fields for a person.',\n },\n del: {\n schema: z.object({ id: z.string().uuid() }),\n responseSchema: defaultOkResponseSchema,\n description: 'Deletes a person by id. Request body or query may provide the identifier.',\n errors: [\n {\n status: 422,\n description: 'Person has dependent records (e.g. linked deals); unlink or reassign before delete.',\n schema: z.object({\n error: z.string(),\n code: z.literal('PERSON_HAS_DEPENDENTS'),\n }),\n },\n ],\n },\n})\n"],
5
+ "mappings": "AACA,SAAS,SAAS;AAClB,SAAS,qBAAqB;AAC9B,SAAS,qBAAqB;AAC9B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS;AAClB,SAAS,oBAAoB,0BAA0B;AACvD,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kCAAkC,8BAA8B,+BAA+B;AACxG,SAAS,sBAAsB;AAC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;AAAA,EACA,QAAQ;AAAA,IACN,QAAQ;AAAA,IACR,gBAAgB;AAAA,IAChB,aAAa;AAAA,EACf;AAAA,EACA,KAAK;AAAA,IACH,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC;AAAA,IAC1C,gBAAgB;AAAA,IAChB,aAAa;AAAA,IACb,QAAQ;AAAA,MACN;AAAA,QACE,QAAQ;AAAA,QACR,aAAa;AAAA,QACb,QAAQ,EAAE,OAAO;AAAA,UACf,OAAO,EAAE,OAAO;AAAA,UAChB,MAAM,EAAE,QAAQ,uBAAuB;AAAA,QACzC,CAAC;AAAA,MACH;AAAA,IACF;AAAA,EACF;AACF,CAAC;",
6
6
  "names": []
7
7
  }
@@ -70,7 +70,7 @@ const createAddressCommand = {
70
70
  ensureTenantScope(ctx, parsed.tenantId);
71
71
  ensureOrganizationScope(ctx, parsed.organizationId);
72
72
  const em = ctx.container.resolve("em").fork();
73
- const entity = await requireCustomerEntity(em, parsed.entityId, void 0, "Customer not found");
73
+ const entity = await requireCustomerEntity(em, parsed.entityId, { tenantId: parsed.tenantId, organizationId: parsed.organizationId }, void 0, "Customer not found");
74
74
  ensureSameScope(entity, parsed.organizationId, parsed.tenantId);
75
75
  const address = em.create(CustomerAddress, {
76
76
  organizationId: parsed.organizationId,
@@ -156,7 +156,7 @@ const createAddressCommand = {
156
156
  throw new CrudHttpError(400, { error: "[internal] redo snapshot unavailable for address create" });
157
157
  }
158
158
  const em = ctx.container.resolve("em").fork();
159
- const entity = await requireCustomerEntity(em, after.entityId, void 0, "Customer not found");
159
+ const entity = await requireCustomerEntity(em, after.entityId, { tenantId: after.tenantId, organizationId: after.organizationId }, void 0, "Customer not found");
160
160
  let address = await findOneWithDecryption(
161
161
  em,
162
162
  CustomerAddress,
@@ -247,7 +247,7 @@ const updateAddressCommand = {
247
247
  ensureTenantScope(ctx, address.tenantId);
248
248
  ensureOrganizationScope(ctx, address.organizationId);
249
249
  if (parsed.entityId !== void 0) {
250
- const entity = await requireCustomerEntity(em, parsed.entityId, void 0, "Customer not found");
250
+ const entity = await requireCustomerEntity(em, parsed.entityId, { tenantId: address.tenantId, organizationId: address.organizationId }, void 0, "Customer not found");
251
251
  ensureSameScope(entity, address.organizationId, address.tenantId);
252
252
  address.entity = entity;
253
253
  }
@@ -344,7 +344,7 @@ const updateAddressCommand = {
344
344
  if (!before) return;
345
345
  const em = ctx.container.resolve("em").fork();
346
346
  let address = await em.findOne(CustomerAddress, { id: before.id });
347
- const entity = await requireCustomerEntity(em, before.entityId, void 0, "Customer not found");
347
+ const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, void 0, "Customer not found");
348
348
  if (!address) {
349
349
  address = em.create(CustomerAddress, {
350
350
  id: before.id,
@@ -467,7 +467,7 @@ const deleteAddressCommand = {
467
467
  const before = payload?.before;
468
468
  if (!before) return;
469
469
  const em = ctx.container.resolve("em").fork();
470
- const entity = await requireCustomerEntity(em, before.entityId, void 0, "Customer not found");
470
+ const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, void 0, "Customer not found");
471
471
  let address = await em.findOne(CustomerAddress, { id: before.id });
472
472
  if (!address) {
473
473
  address = em.create(CustomerAddress, {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/addresses.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects, buildChanges, requireId } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerAddress } from '../data/entities'\nimport { addressCreateSchema, addressUpdateSchema, type AddressCreateInput, type AddressUpdateInput } from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireCustomerEntity,\n ensureSameScope,\n extractUndoPayload,\n resolveParentResourceKind,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst addressCrudIndexer: CrudIndexerConfig<CustomerAddress> = {\n entityType: E.customers.customer_address,\n}\n\nconst addressCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'address',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype AddressSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n entityId: string\n entityKind: string | null\n name: string | null\n purpose: string | null\n companyName: string | null\n addressLine1: string\n addressLine2: string | null\n buildingNumber: string | null\n flatNumber: string | null\n city: string | null\n region: string | null\n postalCode: string | null\n country: string | null\n latitude: number | null\n longitude: number | null\n isPrimary: boolean\n}\n\ntype AddressUndoPayload = {\n before?: AddressSnapshot | null\n after?: AddressSnapshot | null\n}\n\nasync function loadAddressSnapshot(em: EntityManager, id: string): Promise<AddressSnapshot | null> {\n const address = await em.findOne(CustomerAddress, { id }, { populate: ['entity'] })\n if (!address) return null\n const entityRef = address.entity\n const entityKind = (typeof entityRef === 'object' && entityRef !== null && 'kind' in entityRef)\n ? (entityRef as { kind: string }).kind\n : null\n return {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n entityId: typeof entityRef === 'string' ? entityRef : entityRef.id,\n entityKind,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n }\n}\n\nasync function enforcePrimaryAddress(em: EntityManager, entityId: string, addressId: string): Promise<void> {\n await em.nativeUpdate(\n CustomerAddress,\n { entity: entityId, id: { $ne: addressId }, isPrimary: true },\n { isPrimary: false }\n )\n}\n\nconst createAddressCommand: CommandHandler<AddressCreateInput, { addressId: string }> = {\n id: 'customers.addresses.create',\n async execute(rawInput, ctx) {\n const parsed = addressCreateSchema.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 entity = await requireCustomerEntity(em, parsed.entityId, undefined, 'Customer not found')\n ensureSameScope(entity, parsed.organizationId, parsed.tenantId)\n\n const address = em.create(CustomerAddress, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n entity,\n name: parsed.name ?? null,\n purpose: parsed.purpose ?? null,\n companyName: parsed.companyName ?? null,\n addressLine1: parsed.addressLine1,\n addressLine2: parsed.addressLine2 ?? null,\n buildingNumber: parsed.buildingNumber ?? null,\n flatNumber: parsed.flatNumber ?? null,\n city: parsed.city ?? null,\n region: parsed.region ?? null,\n postalCode: parsed.postalCode ?? null,\n country: parsed.country ?? null,\n latitude: parsed.latitude ?? null,\n longitude: parsed.longitude ?? null,\n isPrimary: parsed.isPrimary ?? false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (address.isPrimary) {\n await enforcePrimaryAddress(em, entity.id, address.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: address.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadAddressSnapshot(em, result.addressId)\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const snapshot = snapshots.after as AddressSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.addresses.create', 'Create address'),\n resourceKind: 'customers.address',\n resourceId: result.addressId,\n parentResourceKind: resolveParentResourceKind(snapshot?.entityKind),\n parentResourceId: snapshot?.entityId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n organizationId: snapshot?.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n payload: {\n undo: {\n after: snapshot ?? null,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const addressId = logEntry?.resourceId ?? null\n if (!addressId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id: addressId })\n if (address) {\n em.remove(address)\n await em.flush()\n }\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<AddressSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for address create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireCustomerEntity(em, after.entityId, undefined, 'Customer not found')\n let address = await findOneWithDecryption(\n em,\n CustomerAddress,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!address) {\n address = em.create(CustomerAddress, {\n id: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n entity,\n name: after.name,\n purpose: after.purpose,\n companyName: after.companyName,\n addressLine1: after.addressLine1,\n addressLine2: after.addressLine2,\n buildingNumber: after.buildingNumber,\n flatNumber: after.flatNumber,\n city: after.city,\n region: after.region,\n postalCode: after.postalCode,\n country: after.country,\n latitude: after.latitude,\n longitude: after.longitude,\n isPrimary: after.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = after.name\n address.purpose = after.purpose\n address.companyName = after.companyName\n address.addressLine1 = after.addressLine1\n address.addressLine2 = after.addressLine2\n address.buildingNumber = after.buildingNumber\n address.flatNumber = after.flatNumber\n address.city = after.city\n address.region = after.region\n address.postalCode = after.postalCode\n address.country = after.country\n address.latitude = after.latitude\n address.longitude = after.longitude\n address.isPrimary = after.isPrimary\n }\n const restoredAddress = address\n await withAtomicFlush(em, [\n async () => {\n em.persist(restoredAddress)\n await em.flush()\n if (after.isPrimary) {\n await enforcePrimaryAddress(em, after.entityId, after.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: restoredAddress,\n identifiers: {\n id: restoredAddress.id,\n organizationId: restoredAddress.organizationId,\n tenantId: restoredAddress.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: restoredAddress.id }\n },\n}\n\nconst updateAddressCommand: CommandHandler<AddressUpdateInput, { addressId: string }> = {\n id: 'customers.addresses.update',\n async prepare(rawInput, ctx) {\n const parsed = addressUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadAddressSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = addressUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id: parsed.id })\n if (!address) throw new CrudHttpError(404, { error: 'Address not found' })\n ensureTenantScope(ctx, address.tenantId)\n ensureOrganizationScope(ctx, address.organizationId)\n\n if (parsed.entityId !== undefined) {\n const entity = await requireCustomerEntity(em, parsed.entityId, undefined, 'Customer not found')\n ensureSameScope(entity, address.organizationId, address.tenantId)\n address.entity = entity\n }\n\n await withAtomicFlush(em, [\n () => {\n if (parsed.name !== undefined) address.name = parsed.name ?? null\n if (parsed.purpose !== undefined) address.purpose = parsed.purpose ?? null\n if (parsed.companyName !== undefined) address.companyName = parsed.companyName ?? null\n if (parsed.addressLine1 !== undefined) address.addressLine1 = parsed.addressLine1\n if (parsed.addressLine2 !== undefined) address.addressLine2 = parsed.addressLine2 ?? null\n if (parsed.buildingNumber !== undefined) address.buildingNumber = parsed.buildingNumber ?? null\n if (parsed.flatNumber !== undefined) address.flatNumber = parsed.flatNumber ?? null\n if (parsed.city !== undefined) address.city = parsed.city ?? null\n if (parsed.region !== undefined) address.region = parsed.region ?? null\n if (parsed.postalCode !== undefined) address.postalCode = parsed.postalCode ?? null\n if (parsed.country !== undefined) address.country = parsed.country ?? null\n if (parsed.latitude !== undefined) address.latitude = parsed.latitude ?? null\n if (parsed.longitude !== undefined) address.longitude = parsed.longitude ?? null\n if (parsed.isPrimary !== undefined) address.isPrimary = parsed.isPrimary\n },\n async () => {\n if (address.isPrimary) {\n await enforcePrimaryAddress(em, typeof address.entity === 'string' ? address.entity : address.entity.id, address.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: address.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadAddressSnapshot(em, result.addressId)\n },\n buildLog: async ({ snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as AddressSnapshot | undefined\n if (!before) return null\n const afterSnapshot = snapshots.after as AddressSnapshot | undefined\n const changes =\n afterSnapshot && before\n ? buildChanges(\n before as unknown as Record<string, unknown>,\n afterSnapshot as unknown as Record<string, unknown>,\n [\n 'entityId',\n 'name',\n 'purpose',\n 'companyName',\n 'addressLine1',\n 'addressLine2',\n 'buildingNumber',\n 'flatNumber',\n 'city',\n 'region',\n 'postalCode',\n 'country',\n 'latitude',\n 'longitude',\n 'isPrimary',\n ]\n )\n : {}\n return {\n actionLabel: translate('customers.audit.addresses.update', 'Update address'),\n resourceKind: 'customers.address',\n resourceId: before.id,\n parentResourceKind: resolveParentResourceKind(before.entityKind),\n parentResourceId: before.entityId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n changes,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<AddressUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let address = await em.findOne(CustomerAddress, { id: before.id })\n const entity = await requireCustomerEntity(em, before.entityId, undefined, 'Customer not found')\n if (!address) {\n address = em.create(CustomerAddress, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n name: before.name,\n purpose: before.purpose,\n companyName: before.companyName,\n addressLine1: before.addressLine1,\n addressLine2: before.addressLine2,\n buildingNumber: before.buildingNumber,\n flatNumber: before.flatNumber,\n city: before.city,\n region: before.region,\n postalCode: before.postalCode,\n country: before.country,\n latitude: before.latitude,\n longitude: before.longitude,\n isPrimary: before.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = before.name\n address.purpose = before.purpose\n address.companyName = before.companyName\n address.addressLine1 = before.addressLine1\n address.addressLine2 = before.addressLine2\n address.buildingNumber = before.buildingNumber\n address.flatNumber = before.flatNumber\n address.city = before.city\n address.region = before.region\n address.postalCode = before.postalCode\n address.country = before.country\n address.latitude = before.latitude\n address.longitude = before.longitude\n address.isPrimary = before.isPrimary\n }\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (before.isPrimary) {\n await enforcePrimaryAddress(em, before.entityId, before.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n },\n}\n\nconst deleteAddressCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { addressId: string }> =\n {\n id: 'customers.addresses.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Address id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadAddressSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Address id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id })\n if (!address) throw new CrudHttpError(404, { error: 'Address not found' })\n ensureTenantScope(ctx, address.tenantId)\n ensureOrganizationScope(ctx, address.organizationId)\n em.remove(address)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n return { addressId: address.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as AddressSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.addresses.delete', 'Delete address'),\n resourceKind: 'customers.address',\n resourceId: before.id,\n parentResourceKind: resolveParentResourceKind(before.entityKind),\n parentResourceId: before.entityId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<AddressUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireCustomerEntity(em, before.entityId, undefined, 'Customer not found')\n let address = await em.findOne(CustomerAddress, { id: before.id })\n if (!address) {\n address = em.create(CustomerAddress, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n name: before.name,\n purpose: before.purpose,\n companyName: before.companyName,\n addressLine1: before.addressLine1,\n addressLine2: before.addressLine2,\n buildingNumber: before.buildingNumber,\n flatNumber: before.flatNumber,\n city: before.city,\n region: before.region,\n postalCode: before.postalCode,\n country: before.country,\n latitude: before.latitude,\n longitude: before.longitude,\n isPrimary: before.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = before.name\n address.purpose = before.purpose\n address.addressLine1 = before.addressLine1\n address.addressLine2 = before.addressLine2\n address.buildingNumber = before.buildingNumber\n address.flatNumber = before.flatNumber\n address.city = before.city\n address.region = before.region\n address.postalCode = before.postalCode\n address.country = before.country\n address.latitude = before.latitude\n address.longitude = before.longitude\n address.isPrimary = before.isPrimary\n }\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (before.isPrimary) {\n await enforcePrimaryAddress(em, before.entityId, before.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n },\n }\n\nregisterCommand(createAddressCommand)\nregisterCommand(updateAddressCommand)\nregisterCommand(deleteAddressCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAA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AA,IACpB,OAAO;AACL,cAAQ,SAAS;AACjB,cAAQ,OAAO,OAAO;AACtB,cAAQ,UAAU,OAAO;AACzB,cAAQ,eAAe,OAAO;AAC9B,cAAQ,eAAe,OAAO;AAC9B,cAAQ,iBAAiB,OAAO;AAChC,cAAQ,aAAa,OAAO;AAC5B,cAAQ,OAAO,OAAO;AACtB,cAAQ,SAAS,OAAO;AACxB,cAAQ,aAAa,OAAO;AAC5B,cAAQ,UAAU,OAAO;AACzB,cAAQ,WAAW,OAAO;AAC1B,cAAQ,YAAY,OAAO;AAC3B,cAAQ,YAAY,OAAO;AAAA,IAC7B;AACA,UAAM,gBAAgB,IAAI;AAAA,MACxB,YAAY;AACV,WAAG,QAAQ,OAAO;AAClB,cAAM,GAAG,MAAM;AACf,YAAI,OAAO,WAAW;AACpB,gBAAM,sBAAsB,IAAI,OAAO,UAAU,OAAO,EAAE;AAAA,QAC5D;AAAA,MACF;AAAA,IACF,GAAG,EAAE,aAAa,KAAK,CAAC;AAExB,UAAM,KAAM,IAAI,UAAU,QAAQ,YAAY;AAC9C,UAAM,wBAAwB;AAAA,MAC5B,YAAY;AAAA,MACZ,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,aAAa;AAAA,QACX,IAAI,QAAQ;AAAA,QACZ,gBAAgB,QAAQ;AAAA,QACxB,UAAU,QAAQ;AAAA,MACpB;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AACF;AAEF,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects, buildChanges, requireId } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerAddress } from '../data/entities'\nimport { addressCreateSchema, addressUpdateSchema, type AddressCreateInput, type AddressUpdateInput } from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireCustomerEntity,\n ensureSameScope,\n extractUndoPayload,\n resolveParentResourceKind,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { withAtomicFlush } from '@open-mercato/shared/lib/commands/flush'\nimport { resolveRedoSnapshot } from '@open-mercato/shared/lib/commands/redo'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst addressCrudIndexer: CrudIndexerConfig<CustomerAddress> = {\n entityType: E.customers.customer_address,\n}\n\nconst addressCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'address',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype AddressSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n entityId: string\n entityKind: string | null\n name: string | null\n purpose: string | null\n companyName: string | null\n addressLine1: string\n addressLine2: string | null\n buildingNumber: string | null\n flatNumber: string | null\n city: string | null\n region: string | null\n postalCode: string | null\n country: string | null\n latitude: number | null\n longitude: number | null\n isPrimary: boolean\n}\n\ntype AddressUndoPayload = {\n before?: AddressSnapshot | null\n after?: AddressSnapshot | null\n}\n\nasync function loadAddressSnapshot(em: EntityManager, id: string): Promise<AddressSnapshot | null> {\n const address = await em.findOne(CustomerAddress, { id }, { populate: ['entity'] })\n if (!address) return null\n const entityRef = address.entity\n const entityKind = (typeof entityRef === 'object' && entityRef !== null && 'kind' in entityRef)\n ? (entityRef as { kind: string }).kind\n : null\n return {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n entityId: typeof entityRef === 'string' ? entityRef : entityRef.id,\n entityKind,\n name: address.name ?? null,\n purpose: address.purpose ?? null,\n companyName: address.companyName ?? null,\n addressLine1: address.addressLine1,\n addressLine2: address.addressLine2 ?? null,\n buildingNumber: address.buildingNumber ?? null,\n flatNumber: address.flatNumber ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n postalCode: address.postalCode ?? null,\n country: address.country ?? null,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n isPrimary: address.isPrimary,\n }\n}\n\nasync function enforcePrimaryAddress(em: EntityManager, entityId: string, addressId: string): Promise<void> {\n await em.nativeUpdate(\n CustomerAddress,\n { entity: entityId, id: { $ne: addressId }, isPrimary: true },\n { isPrimary: false }\n )\n}\n\nconst createAddressCommand: CommandHandler<AddressCreateInput, { addressId: string }> = {\n id: 'customers.addresses.create',\n async execute(rawInput, ctx) {\n const parsed = addressCreateSchema.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 entity = await requireCustomerEntity(em, parsed.entityId, { tenantId: parsed.tenantId, organizationId: parsed.organizationId }, undefined, 'Customer not found')\n ensureSameScope(entity, parsed.organizationId, parsed.tenantId)\n\n const address = em.create(CustomerAddress, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n entity,\n name: parsed.name ?? null,\n purpose: parsed.purpose ?? null,\n companyName: parsed.companyName ?? null,\n addressLine1: parsed.addressLine1,\n addressLine2: parsed.addressLine2 ?? null,\n buildingNumber: parsed.buildingNumber ?? null,\n flatNumber: parsed.flatNumber ?? null,\n city: parsed.city ?? null,\n region: parsed.region ?? null,\n postalCode: parsed.postalCode ?? null,\n country: parsed.country ?? null,\n latitude: parsed.latitude ?? null,\n longitude: parsed.longitude ?? null,\n isPrimary: parsed.isPrimary ?? false,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (address.isPrimary) {\n await enforcePrimaryAddress(em, entity.id, address.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: address.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadAddressSnapshot(em, result.addressId)\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const snapshot = snapshots.after as AddressSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.addresses.create', 'Create address'),\n resourceKind: 'customers.address',\n resourceId: result.addressId,\n parentResourceKind: resolveParentResourceKind(snapshot?.entityKind),\n parentResourceId: snapshot?.entityId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n organizationId: snapshot?.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n payload: {\n undo: {\n after: snapshot ?? null,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const addressId = logEntry?.resourceId ?? null\n if (!addressId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id: addressId })\n if (address) {\n em.remove(address)\n await em.flush()\n }\n },\n redo: async ({ logEntry, ctx }) => {\n const after = resolveRedoSnapshot<AddressSnapshot>(logEntry)\n if (!after) {\n throw new CrudHttpError(400, { error: '[internal] redo snapshot unavailable for address create' })\n }\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireCustomerEntity(em, after.entityId, { tenantId: after.tenantId, organizationId: after.organizationId }, undefined, 'Customer not found')\n let address = await findOneWithDecryption(\n em,\n CustomerAddress,\n { id: after.id },\n undefined,\n { tenantId: after.tenantId, organizationId: after.organizationId },\n )\n if (!address) {\n address = em.create(CustomerAddress, {\n id: after.id,\n organizationId: after.organizationId,\n tenantId: after.tenantId,\n entity,\n name: after.name,\n purpose: after.purpose,\n companyName: after.companyName,\n addressLine1: after.addressLine1,\n addressLine2: after.addressLine2,\n buildingNumber: after.buildingNumber,\n flatNumber: after.flatNumber,\n city: after.city,\n region: after.region,\n postalCode: after.postalCode,\n country: after.country,\n latitude: after.latitude,\n longitude: after.longitude,\n isPrimary: after.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = after.name\n address.purpose = after.purpose\n address.companyName = after.companyName\n address.addressLine1 = after.addressLine1\n address.addressLine2 = after.addressLine2\n address.buildingNumber = after.buildingNumber\n address.flatNumber = after.flatNumber\n address.city = after.city\n address.region = after.region\n address.postalCode = after.postalCode\n address.country = after.country\n address.latitude = after.latitude\n address.longitude = after.longitude\n address.isPrimary = after.isPrimary\n }\n const restoredAddress = address\n await withAtomicFlush(em, [\n async () => {\n em.persist(restoredAddress)\n await em.flush()\n if (after.isPrimary) {\n await enforcePrimaryAddress(em, after.entityId, after.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: restoredAddress,\n identifiers: {\n id: restoredAddress.id,\n organizationId: restoredAddress.organizationId,\n tenantId: restoredAddress.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: restoredAddress.id }\n },\n}\n\nconst updateAddressCommand: CommandHandler<AddressUpdateInput, { addressId: string }> = {\n id: 'customers.addresses.update',\n async prepare(rawInput, ctx) {\n const parsed = addressUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadAddressSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = addressUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id: parsed.id })\n if (!address) throw new CrudHttpError(404, { error: 'Address not found' })\n ensureTenantScope(ctx, address.tenantId)\n ensureOrganizationScope(ctx, address.organizationId)\n\n if (parsed.entityId !== undefined) {\n const entity = await requireCustomerEntity(em, parsed.entityId, { tenantId: address.tenantId, organizationId: address.organizationId }, undefined, 'Customer not found')\n ensureSameScope(entity, address.organizationId, address.tenantId)\n address.entity = entity\n }\n\n await withAtomicFlush(em, [\n () => {\n if (parsed.name !== undefined) address.name = parsed.name ?? null\n if (parsed.purpose !== undefined) address.purpose = parsed.purpose ?? null\n if (parsed.companyName !== undefined) address.companyName = parsed.companyName ?? null\n if (parsed.addressLine1 !== undefined) address.addressLine1 = parsed.addressLine1\n if (parsed.addressLine2 !== undefined) address.addressLine2 = parsed.addressLine2 ?? null\n if (parsed.buildingNumber !== undefined) address.buildingNumber = parsed.buildingNumber ?? null\n if (parsed.flatNumber !== undefined) address.flatNumber = parsed.flatNumber ?? null\n if (parsed.city !== undefined) address.city = parsed.city ?? null\n if (parsed.region !== undefined) address.region = parsed.region ?? null\n if (parsed.postalCode !== undefined) address.postalCode = parsed.postalCode ?? null\n if (parsed.country !== undefined) address.country = parsed.country ?? null\n if (parsed.latitude !== undefined) address.latitude = parsed.latitude ?? null\n if (parsed.longitude !== undefined) address.longitude = parsed.longitude ?? null\n if (parsed.isPrimary !== undefined) address.isPrimary = parsed.isPrimary\n },\n async () => {\n if (address.isPrimary) {\n await enforcePrimaryAddress(em, typeof address.entity === 'string' ? address.entity : address.entity.id, address.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n\n return { addressId: address.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadAddressSnapshot(em, result.addressId)\n },\n buildLog: async ({ snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as AddressSnapshot | undefined\n if (!before) return null\n const afterSnapshot = snapshots.after as AddressSnapshot | undefined\n const changes =\n afterSnapshot && before\n ? buildChanges(\n before as unknown as Record<string, unknown>,\n afterSnapshot as unknown as Record<string, unknown>,\n [\n 'entityId',\n 'name',\n 'purpose',\n 'companyName',\n 'addressLine1',\n 'addressLine2',\n 'buildingNumber',\n 'flatNumber',\n 'city',\n 'region',\n 'postalCode',\n 'country',\n 'latitude',\n 'longitude',\n 'isPrimary',\n ]\n )\n : {}\n return {\n actionLabel: translate('customers.audit.addresses.update', 'Update address'),\n resourceKind: 'customers.address',\n resourceId: before.id,\n parentResourceKind: resolveParentResourceKind(before.entityKind),\n parentResourceId: before.entityId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n changes,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<AddressUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let address = await em.findOne(CustomerAddress, { id: before.id })\n const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, undefined, 'Customer not found')\n if (!address) {\n address = em.create(CustomerAddress, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n name: before.name,\n purpose: before.purpose,\n companyName: before.companyName,\n addressLine1: before.addressLine1,\n addressLine2: before.addressLine2,\n buildingNumber: before.buildingNumber,\n flatNumber: before.flatNumber,\n city: before.city,\n region: before.region,\n postalCode: before.postalCode,\n country: before.country,\n latitude: before.latitude,\n longitude: before.longitude,\n isPrimary: before.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = before.name\n address.purpose = before.purpose\n address.companyName = before.companyName\n address.addressLine1 = before.addressLine1\n address.addressLine2 = before.addressLine2\n address.buildingNumber = before.buildingNumber\n address.flatNumber = before.flatNumber\n address.city = before.city\n address.region = before.region\n address.postalCode = before.postalCode\n address.country = before.country\n address.latitude = before.latitude\n address.longitude = before.longitude\n address.isPrimary = before.isPrimary\n }\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (before.isPrimary) {\n await enforcePrimaryAddress(em, before.entityId, before.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n },\n}\n\nconst deleteAddressCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { addressId: string }> =\n {\n id: 'customers.addresses.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Address id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadAddressSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Address id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const address = await em.findOne(CustomerAddress, { id })\n if (!address) throw new CrudHttpError(404, { error: 'Address not found' })\n ensureTenantScope(ctx, address.tenantId)\n ensureOrganizationScope(ctx, address.organizationId)\n em.remove(address)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n return { addressId: address.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as AddressSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.addresses.delete', 'Delete address'),\n resourceKind: 'customers.address',\n resourceId: before.id,\n parentResourceKind: resolveParentResourceKind(before.entityKind),\n parentResourceId: before.entityId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n payload: {\n undo: {\n before,\n } satisfies AddressUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<AddressUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireCustomerEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId }, undefined, 'Customer not found')\n let address = await em.findOne(CustomerAddress, { id: before.id })\n if (!address) {\n address = em.create(CustomerAddress, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n name: before.name,\n purpose: before.purpose,\n companyName: before.companyName,\n addressLine1: before.addressLine1,\n addressLine2: before.addressLine2,\n buildingNumber: before.buildingNumber,\n flatNumber: before.flatNumber,\n city: before.city,\n region: before.region,\n postalCode: before.postalCode,\n country: before.country,\n latitude: before.latitude,\n longitude: before.longitude,\n isPrimary: before.isPrimary,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(address)\n } else {\n address.entity = entity\n address.name = before.name\n address.purpose = before.purpose\n address.addressLine1 = before.addressLine1\n address.addressLine2 = before.addressLine2\n address.buildingNumber = before.buildingNumber\n address.flatNumber = before.flatNumber\n address.city = before.city\n address.region = before.region\n address.postalCode = before.postalCode\n address.country = before.country\n address.latitude = before.latitude\n address.longitude = before.longitude\n address.isPrimary = before.isPrimary\n }\n await withAtomicFlush(em, [\n async () => {\n em.persist(address)\n await em.flush()\n if (before.isPrimary) {\n await enforcePrimaryAddress(em, before.entityId, before.id)\n }\n },\n ], { transaction: true })\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: address,\n identifiers: {\n id: address.id,\n organizationId: address.organizationId,\n tenantId: address.tenantId,\n },\n indexer: addressCrudIndexer,\n events: addressCrudEvents,\n })\n },\n }\n\nregisterCommand(createAddressCommand)\nregisterCommand(updateAddressCommand)\nregisterCommand(deleteAddressCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB,yBAAyB,cAAc,iBAAiB;AAGtF,SAAS,uBAAuB;AAChC,SAAS,qBAAqB,2BAA6E;AAC3G;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAE9B,SAAS,SAAS;AAClB,SAAS,uBAAuB;AAChC,SAAS,2BAA2B;AACpC,SAAS,6BAA6B;AAEtC,MAAM,qBAAyD;AAAA,EAC7D,YAAY,EAAE,UAAU;AAC1B;AAEA,MAAM,oBAAsC;AAAA,EAC1C,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,EAC5B;AACF;AA6BA,eAAe,oBAAoB,IAAmB,IAA6C;AACjG,QAAM,UAAU,MAAM,GAAG,QAAQ,iBAAiB,EAAE,GAAG,GAAG,EAAE,UAAU,CAAC,QAAQ,EAAE,CAAC;AAClF,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,YAAY,QAAQ;AAC1B,QAAM,aAAc,OAAO,cAAc,YAAY,cAAc,QAAQ,UAAU,YAChF,UAA+B,OAChC;AACJ,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,gBAAgB,QAAQ;AAAA,IACxB,UAAU,QAAQ;AAAA,IAClB,UAAU,OAAO,cAAc,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;AAAA,MACR,QAAQ;AAAA,MACR,aAAa;AAAA,QACX,IAAI,QAAQ;AAAA,QACZ,gBAAgB,QAAQ;AAAA,QACxB,UAAU,QAAQ;AAAA,MACpB;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AACF;AAEF,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;",
6
6
  "names": []
7
7
  }
@@ -55,7 +55,7 @@ const createCommentCommand = {
55
55
  ensureOrganizationScope(ctx, parsed.organizationId);
56
56
  const normalizedAuthor = normalizeAuthorUserId(parsed.authorUserId, ctx.auth);
57
57
  const em = ctx.container.resolve("em").fork();
58
- const entity = await requireTimelineParentEntity(em, parsed.entityId);
58
+ const entity = await requireTimelineParentEntity(em, parsed.entityId, { tenantId: parsed.tenantId, organizationId: parsed.organizationId });
59
59
  ensureSameScope(entity, parsed.organizationId, parsed.tenantId);
60
60
  const deal = await requireDealInScope(em, parsed.dealId, parsed.tenantId, parsed.organizationId);
61
61
  const comment = em.create(CustomerComment, {
@@ -143,7 +143,7 @@ const createCommentCommand = {
143
143
  appearanceColor: snapshot.appearanceColor
144
144
  }),
145
145
  beforeRestore: async ({ em, snapshot }) => {
146
- const entity = await requireTimelineParentEntity(em, snapshot.entityId);
146
+ const entity = await requireTimelineParentEntity(em, snapshot.entityId, { tenantId: snapshot.tenantId, organizationId: snapshot.organizationId });
147
147
  const deal = await requireDealInScope(em, snapshot.dealId, snapshot.tenantId, snapshot.organizationId);
148
148
  return { entity, deal };
149
149
  },
@@ -166,7 +166,7 @@ const updateCommentCommand = {
166
166
  ensureTenantScope(ctx, comment.tenantId);
167
167
  ensureOrganizationScope(ctx, comment.organizationId);
168
168
  if (parsed.entityId !== void 0) {
169
- const entity = await requireTimelineParentEntity(em, parsed.entityId);
169
+ const entity = await requireTimelineParentEntity(em, parsed.entityId, { tenantId: comment.tenantId, organizationId: comment.organizationId });
170
170
  ensureSameScope(entity, comment.organizationId, comment.tenantId);
171
171
  comment.entity = entity;
172
172
  }
@@ -234,7 +234,7 @@ const updateCommentCommand = {
234
234
  if (!before) return;
235
235
  const em = ctx.container.resolve("em").fork();
236
236
  let comment = await em.findOne(CustomerComment, { id: before.id });
237
- const entity = await requireTimelineParentEntity(em, before.entityId);
237
+ const entity = await requireTimelineParentEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId });
238
238
  const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId);
239
239
  if (!comment) {
240
240
  comment = em.create(CustomerComment, {
@@ -334,7 +334,7 @@ const deleteCommentCommand = {
334
334
  const before = payload?.before;
335
335
  if (!before) return;
336
336
  const em = ctx.container.resolve("em").fork();
337
- const entity = await requireTimelineParentEntity(em, before.entityId);
337
+ const entity = await requireTimelineParentEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId });
338
338
  const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId);
339
339
  let comment = await em.findOne(CustomerComment, { id: before.id });
340
340
  if (!comment) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/commands/comments.ts"],
4
- "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects, buildChanges, requireId, normalizeAuthorUserId } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerComment } from '../data/entities'\nimport { commentCreateSchema, commentUpdateSchema, type CommentCreateInput, type CommentUpdateInput } from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireTimelineParentEntity,\n ensureSameScope,\n extractUndoPayload,\n requireDealInScope,\n resolveParentResourceKind,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst commentCrudIndexer: CrudIndexerConfig<CustomerComment> = {\n entityType: E.customers.customer_comment,\n}\n\nconst commentCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'comment',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CommentSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n entityId: string\n entityKind: string | null\n dealId: string | null\n body: string\n authorUserId: string | null\n appearanceIcon: string | null\n appearanceColor: string | null\n}\n\ntype CommentUndoPayload = {\n before?: CommentSnapshot | null\n after?: CommentSnapshot | null\n}\n\nasync function loadCommentSnapshot(em: EntityManager, id: string): Promise<CommentSnapshot | null> {\n const comment = await em.findOne(CustomerComment, { id }, { populate: ['entity'] })\n if (!comment) return null\n const entityRef = comment.entity\n const entityKind = (typeof entityRef === 'object' && entityRef !== null && 'kind' in entityRef)\n ? (entityRef as { kind: string }).kind\n : null\n return {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n entityId: typeof entityRef === 'string' ? entityRef : entityRef.id,\n entityKind,\n dealId: comment.deal ? (typeof comment.deal === 'string' ? comment.deal : comment.deal.id) : null,\n body: comment.body,\n authorUserId: comment.authorUserId ?? null,\n appearanceIcon: comment.appearanceIcon ?? null,\n appearanceColor: comment.appearanceColor ?? null,\n }\n}\n\nconst createCommentCommand: CommandHandler<CommentCreateInput, { commentId: string; authorUserId: string | null }> = {\n id: 'customers.comments.create',\n async execute(rawInput, ctx) {\n const parsed = commentCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const normalizedAuthor = normalizeAuthorUserId(parsed.authorUserId, ctx.auth)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireTimelineParentEntity(em, parsed.entityId)\n ensureSameScope(entity, parsed.organizationId, parsed.tenantId)\n const deal = await requireDealInScope(em, parsed.dealId, parsed.tenantId, parsed.organizationId)\n\n const comment = em.create(CustomerComment, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n entity,\n deal,\n body: parsed.body,\n authorUserId: normalizedAuthor,\n appearanceIcon: parsed.appearanceIcon ?? null,\n appearanceColor: parsed.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n\n return { commentId: comment.id, authorUserId: comment.authorUserId ?? null }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadCommentSnapshot(em, result.commentId)\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const snapshot = snapshots.after as CommentSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.comments.create', 'Create note'),\n resourceKind: 'customers.comment',\n resourceId: result.commentId,\n parentResourceKind: snapshot?.entityId ? resolveParentResourceKind(snapshot.entityKind) : (snapshot?.dealId ? 'customers.deal' : null),\n parentResourceId: snapshot?.entityId ?? snapshot?.dealId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n organizationId: snapshot?.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n relatedResourceKind: snapshot?.dealId ? 'customers.deal' : null,\n relatedResourceId: snapshot?.dealId ?? null,\n payload: {\n undo: {\n after: snapshot ?? null,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const commentId = logEntry?.resourceId ?? null\n if (!commentId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const existing = await em.findOne(CustomerComment, { id: commentId })\n if (existing) {\n em.remove(existing)\n await em.flush()\n }\n },\n redo: makeCreateRedo<CustomerComment, CommentSnapshot, CommentCreateInput, { commentId: string; authorUserId: string | null }>({\n entityClass: CustomerComment,\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n findRow: ({ em, id, snapshot }) =>\n findOneWithDecryption(\n em,\n CustomerComment,\n { id },\n undefined,\n { tenantId: snapshot.tenantId, organizationId: snapshot.organizationId },\n ),\n seedFromSnapshot: (snapshot) => ({\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n body: snapshot.body,\n authorUserId: snapshot.authorUserId,\n appearanceIcon: snapshot.appearanceIcon,\n appearanceColor: snapshot.appearanceColor,\n }),\n beforeRestore: async ({ em, snapshot }) => {\n const entity = await requireTimelineParentEntity(em, snapshot.entityId)\n const deal = await requireDealInScope(em, snapshot.dealId, snapshot.tenantId, snapshot.organizationId)\n return { entity, deal }\n },\n buildResult: (entity) => ({ commentId: entity.id, authorUserId: entity.authorUserId ?? null }),\n }),\n}\n\nconst updateCommentCommand: CommandHandler<CommentUpdateInput, { commentId: string }> = {\n id: 'customers.comments.update',\n async prepare(rawInput, ctx) {\n const parsed = commentUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadCommentSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = commentUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const comment = await em.findOne(CustomerComment, { id: parsed.id })\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n ensureTenantScope(ctx, comment.tenantId)\n ensureOrganizationScope(ctx, comment.organizationId)\n\n if (parsed.entityId !== undefined) {\n const entity = await requireTimelineParentEntity(em, parsed.entityId)\n ensureSameScope(entity, comment.organizationId, comment.tenantId)\n comment.entity = entity\n }\n if (parsed.dealId !== undefined) {\n comment.deal = await requireDealInScope(em, parsed.dealId, comment.tenantId, comment.organizationId)\n }\n if (parsed.body !== undefined) comment.body = parsed.body\n if (parsed.authorUserId !== undefined) comment.authorUserId = parsed.authorUserId ?? null\n if (parsed.appearanceIcon !== undefined) comment.appearanceIcon = parsed.appearanceIcon ?? null\n if (parsed.appearanceColor !== undefined) comment.appearanceColor = parsed.appearanceColor ?? null\n\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n\n return { commentId: comment.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadCommentSnapshot(em, result.commentId)\n },\n buildLog: async ({ snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as CommentSnapshot | undefined\n if (!before) return null\n const afterSnapshot = snapshots.after as CommentSnapshot | undefined\n const changes =\n afterSnapshot && before\n ? buildChanges(\n before as unknown as Record<string, unknown>,\n afterSnapshot as unknown as Record<string, unknown>,\n ['entityId', 'dealId', 'body', 'authorUserId', 'appearanceIcon', 'appearanceColor']\n )\n : {}\n return {\n actionLabel: translate('customers.audit.comments.update', 'Update note'),\n resourceKind: 'customers.comment',\n resourceId: before.id,\n parentResourceKind: before.entityId ? resolveParentResourceKind(before.entityKind) : (before.dealId ? 'customers.deal' : null),\n parentResourceId: before.entityId ?? before.dealId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n relatedResourceKind: (afterSnapshot?.dealId ?? before.dealId) ? 'customers.deal' : null,\n relatedResourceId: afterSnapshot?.dealId ?? before.dealId ?? null,\n changes,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CommentUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let comment = await em.findOne(CustomerComment, { id: before.id })\n const entity = await requireTimelineParentEntity(em, before.entityId)\n const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId)\n\n if (!comment) {\n comment = em.create(CustomerComment, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n deal,\n body: before.body,\n authorUserId: before.authorUserId,\n appearanceIcon: before.appearanceIcon,\n appearanceColor: before.appearanceColor,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n } else {\n comment.entity = entity\n comment.deal = deal\n comment.body = before.body\n comment.authorUserId = before.authorUserId\n comment.appearanceIcon = before.appearanceIcon\n comment.appearanceColor = before.appearanceColor\n }\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n },\n}\n\nconst deleteCommentCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { commentId: string }> =\n {\n id: 'customers.comments.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Comment id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadCommentSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Comment id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const comment = await em.findOne(CustomerComment, { id })\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n ensureTenantScope(ctx, comment.tenantId)\n ensureOrganizationScope(ctx, comment.organizationId)\n em.remove(comment)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n return { commentId: comment.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CommentSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.comments.delete', 'Delete note'),\n resourceKind: 'customers.comment',\n resourceId: before.id,\n parentResourceKind: before.entityId ? resolveParentResourceKind(before.entityKind) : (before.dealId ? 'customers.deal' : null),\n parentResourceId: before.entityId ?? before.dealId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n relatedResourceKind: before.dealId ? 'customers.deal' : null,\n relatedResourceId: before.dealId ?? null,\n payload: {\n undo: {\n before,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CommentUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireTimelineParentEntity(em, before.entityId)\n const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId)\n let comment = await em.findOne(CustomerComment, { id: before.id })\n if (!comment) {\n comment = em.create(CustomerComment, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n deal,\n body: before.body,\n authorUserId: before.authorUserId,\n appearanceIcon: before.appearanceIcon,\n appearanceColor: before.appearanceColor,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n } else {\n comment.entity = entity\n comment.deal = deal\n comment.body = before.body\n comment.authorUserId = before.authorUserId\n comment.appearanceIcon = before.appearanceIcon\n comment.appearanceColor = before.appearanceColor\n }\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n },\n }\n\nregisterCommand(createCommentCommand)\nregisterCommand(updateCommentCommand)\nregisterCommand(deleteCommentCommand)\n"],
5
- "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB,yBAAyB,cAAc,WAAW,6BAA6B;AAG7G,SAAS,uBAAuB;AAChC,SAAS,qBAAqB,2BAA6E;AAC3G;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,2BAA2B;AACpC,SAAS,qBAAqB;AAE9B,SAAS,SAAS;AAClB,SAAS,sBAAsB;AAC/B,SAAS,6BAA6B;AAEtC,MAAM,qBAAyD;AAAA,EAC7D,YAAY,EAAE,UAAU;AAC1B;AAEA,MAAM,oBAAsC;AAAA,EAC1C,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,EAC5B;AACF;AAoBA,eAAe,oBAAoB,IAAmB,IAA6C;AACjG,QAAM,UAAU,MAAM,GAAG,QAAQ,iBAAiB,EAAE,GAAG,GAAG,EAAE,UAAU,CAAC,QAAQ,EAAE,CAAC;AAClF,MAAI,CAAC,QAAS,QAAO;AACrB,QAAM,YAAY,QAAQ;AAC1B,QAAM,aAAc,OAAO,cAAc,YAAY,cAAc,QAAQ,UAAU,YAChF,UAA+B,OAChC;AACJ,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IAC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B,UAAU,QAAQ;AAAA,MACpB;AAAA,MACA,SAAS;AAAA,MACT,QAAQ;AAAA,IACV,CAAC;AAAA,EACH;AACF;AAEF,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;AACpC,gBAAgB,oBAAoB;",
4
+ "sourcesContent": ["import { registerCommand } from '@open-mercato/shared/lib/commands'\nimport type { CommandHandler } from '@open-mercato/shared/lib/commands'\nimport { emitCrudSideEffects, emitCrudUndoSideEffects, buildChanges, requireId, normalizeAuthorUserId } from '@open-mercato/shared/lib/commands/helpers'\nimport type { DataEngine } from '@open-mercato/shared/lib/data/engine'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CustomerComment } from '../data/entities'\nimport { commentCreateSchema, commentUpdateSchema, type CommentCreateInput, type CommentUpdateInput } from '../data/validators'\nimport {\n ensureOrganizationScope,\n ensureTenantScope,\n requireTimelineParentEntity,\n ensureSameScope,\n extractUndoPayload,\n requireDealInScope,\n resolveParentResourceKind,\n} from './shared'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { CrudIndexerConfig, CrudEventsConfig } from '@open-mercato/shared/lib/crud/types'\nimport { E } from '#generated/entities.ids.generated'\nimport { makeCreateRedo } from '@open-mercato/shared/lib/commands/redo'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\nconst commentCrudIndexer: CrudIndexerConfig<CustomerComment> = {\n entityType: E.customers.customer_comment,\n}\n\nconst commentCrudEvents: CrudEventsConfig = {\n module: 'customers',\n entity: 'comment',\n persistent: true,\n buildPayload: (ctx) => ({\n id: ctx.identifiers.id,\n organizationId: ctx.identifiers.organizationId,\n tenantId: ctx.identifiers.tenantId,\n }),\n}\n\ntype CommentSnapshot = {\n id: string\n organizationId: string\n tenantId: string\n entityId: string\n entityKind: string | null\n dealId: string | null\n body: string\n authorUserId: string | null\n appearanceIcon: string | null\n appearanceColor: string | null\n}\n\ntype CommentUndoPayload = {\n before?: CommentSnapshot | null\n after?: CommentSnapshot | null\n}\n\nasync function loadCommentSnapshot(em: EntityManager, id: string): Promise<CommentSnapshot | null> {\n const comment = await em.findOne(CustomerComment, { id }, { populate: ['entity'] })\n if (!comment) return null\n const entityRef = comment.entity\n const entityKind = (typeof entityRef === 'object' && entityRef !== null && 'kind' in entityRef)\n ? (entityRef as { kind: string }).kind\n : null\n return {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n entityId: typeof entityRef === 'string' ? entityRef : entityRef.id,\n entityKind,\n dealId: comment.deal ? (typeof comment.deal === 'string' ? comment.deal : comment.deal.id) : null,\n body: comment.body,\n authorUserId: comment.authorUserId ?? null,\n appearanceIcon: comment.appearanceIcon ?? null,\n appearanceColor: comment.appearanceColor ?? null,\n }\n}\n\nconst createCommentCommand: CommandHandler<CommentCreateInput, { commentId: string; authorUserId: string | null }> = {\n id: 'customers.comments.create',\n async execute(rawInput, ctx) {\n const parsed = commentCreateSchema.parse(rawInput)\n ensureTenantScope(ctx, parsed.tenantId)\n ensureOrganizationScope(ctx, parsed.organizationId)\n const normalizedAuthor = normalizeAuthorUserId(parsed.authorUserId, ctx.auth)\n\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireTimelineParentEntity(em, parsed.entityId, { tenantId: parsed.tenantId, organizationId: parsed.organizationId })\n ensureSameScope(entity, parsed.organizationId, parsed.tenantId)\n const deal = await requireDealInScope(em, parsed.dealId, parsed.tenantId, parsed.organizationId)\n\n const comment = em.create(CustomerComment, {\n organizationId: parsed.organizationId,\n tenantId: parsed.tenantId,\n entity,\n deal,\n body: parsed.body,\n authorUserId: normalizedAuthor,\n appearanceIcon: parsed.appearanceIcon ?? null,\n appearanceColor: parsed.appearanceColor ?? null,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'created',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n\n return { commentId: comment.id, authorUserId: comment.authorUserId ?? null }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadCommentSnapshot(em, result.commentId)\n },\n buildLog: async ({ result, snapshots }) => {\n const { translate } = await resolveTranslations()\n const snapshot = snapshots.after as CommentSnapshot | undefined\n return {\n actionLabel: translate('customers.audit.comments.create', 'Create note'),\n resourceKind: 'customers.comment',\n resourceId: result.commentId,\n parentResourceKind: snapshot?.entityId ? resolveParentResourceKind(snapshot.entityKind) : (snapshot?.dealId ? 'customers.deal' : null),\n parentResourceId: snapshot?.entityId ?? snapshot?.dealId ?? null,\n tenantId: snapshot?.tenantId ?? null,\n organizationId: snapshot?.organizationId ?? null,\n snapshotAfter: snapshot ?? null,\n relatedResourceKind: snapshot?.dealId ? 'customers.deal' : null,\n relatedResourceId: snapshot?.dealId ?? null,\n payload: {\n undo: {\n after: snapshot ?? null,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const commentId = logEntry?.resourceId ?? null\n if (!commentId) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const existing = await em.findOne(CustomerComment, { id: commentId })\n if (existing) {\n em.remove(existing)\n await em.flush()\n }\n },\n redo: makeCreateRedo<CustomerComment, CommentSnapshot, CommentCreateInput, { commentId: string; authorUserId: string | null }>({\n entityClass: CustomerComment,\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n findRow: ({ em, id, snapshot }) =>\n findOneWithDecryption(\n em,\n CustomerComment,\n { id },\n undefined,\n { tenantId: snapshot.tenantId, organizationId: snapshot.organizationId },\n ),\n seedFromSnapshot: (snapshot) => ({\n id: snapshot.id,\n organizationId: snapshot.organizationId,\n tenantId: snapshot.tenantId,\n body: snapshot.body,\n authorUserId: snapshot.authorUserId,\n appearanceIcon: snapshot.appearanceIcon,\n appearanceColor: snapshot.appearanceColor,\n }),\n beforeRestore: async ({ em, snapshot }) => {\n const entity = await requireTimelineParentEntity(em, snapshot.entityId, { tenantId: snapshot.tenantId, organizationId: snapshot.organizationId })\n const deal = await requireDealInScope(em, snapshot.dealId, snapshot.tenantId, snapshot.organizationId)\n return { entity, deal }\n },\n buildResult: (entity) => ({ commentId: entity.id, authorUserId: entity.authorUserId ?? null }),\n }),\n}\n\nconst updateCommentCommand: CommandHandler<CommentUpdateInput, { commentId: string }> = {\n id: 'customers.comments.update',\n async prepare(rawInput, ctx) {\n const parsed = commentUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadCommentSnapshot(em, parsed.id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(rawInput, ctx) {\n const parsed = commentUpdateSchema.parse(rawInput)\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const comment = await em.findOne(CustomerComment, { id: parsed.id })\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n ensureTenantScope(ctx, comment.tenantId)\n ensureOrganizationScope(ctx, comment.organizationId)\n\n if (parsed.entityId !== undefined) {\n const entity = await requireTimelineParentEntity(em, parsed.entityId, { tenantId: comment.tenantId, organizationId: comment.organizationId })\n ensureSameScope(entity, comment.organizationId, comment.tenantId)\n comment.entity = entity\n }\n if (parsed.dealId !== undefined) {\n comment.deal = await requireDealInScope(em, parsed.dealId, comment.tenantId, comment.organizationId)\n }\n if (parsed.body !== undefined) comment.body = parsed.body\n if (parsed.authorUserId !== undefined) comment.authorUserId = parsed.authorUserId ?? null\n if (parsed.appearanceIcon !== undefined) comment.appearanceIcon = parsed.appearanceIcon ?? null\n if (parsed.appearanceColor !== undefined) comment.appearanceColor = parsed.appearanceColor ?? null\n\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n\n return { commentId: comment.id }\n },\n captureAfter: async (_input, result, ctx) => {\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n return await loadCommentSnapshot(em, result.commentId)\n },\n buildLog: async ({ snapshots }) => {\n const { translate } = await resolveTranslations()\n const before = snapshots.before as CommentSnapshot | undefined\n if (!before) return null\n const afterSnapshot = snapshots.after as CommentSnapshot | undefined\n const changes =\n afterSnapshot && before\n ? buildChanges(\n before as unknown as Record<string, unknown>,\n afterSnapshot as unknown as Record<string, unknown>,\n ['entityId', 'dealId', 'body', 'authorUserId', 'appearanceIcon', 'appearanceColor']\n )\n : {}\n return {\n actionLabel: translate('customers.audit.comments.update', 'Update note'),\n resourceKind: 'customers.comment',\n resourceId: before.id,\n parentResourceKind: before.entityId ? resolveParentResourceKind(before.entityKind) : (before.dealId ? 'customers.deal' : null),\n parentResourceId: before.entityId ?? before.dealId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n snapshotAfter: afterSnapshot ?? null,\n relatedResourceKind: (afterSnapshot?.dealId ?? before.dealId) ? 'customers.deal' : null,\n relatedResourceId: afterSnapshot?.dealId ?? before.dealId ?? null,\n changes,\n payload: {\n undo: {\n before,\n after: afterSnapshot ?? null,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CommentUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n let comment = await em.findOne(CustomerComment, { id: before.id })\n const entity = await requireTimelineParentEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId })\n const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId)\n\n if (!comment) {\n comment = em.create(CustomerComment, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n deal,\n body: before.body,\n authorUserId: before.authorUserId,\n appearanceIcon: before.appearanceIcon,\n appearanceColor: before.appearanceColor,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n } else {\n comment.entity = entity\n comment.deal = deal\n comment.body = before.body\n comment.authorUserId = before.authorUserId\n comment.appearanceIcon = before.appearanceIcon\n comment.appearanceColor = before.appearanceColor\n }\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'updated',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n },\n}\n\nconst deleteCommentCommand: CommandHandler<{ body?: Record<string, unknown>; query?: Record<string, unknown> }, { commentId: string }> =\n {\n id: 'customers.comments.delete',\n async prepare(input, ctx) {\n const id = requireId(input, 'Comment id required')\n const em = (ctx.container.resolve('em') as EntityManager)\n const snapshot = await loadCommentSnapshot(em, id)\n return snapshot ? { before: snapshot } : {}\n },\n async execute(input, ctx) {\n const id = requireId(input, 'Comment id required')\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const comment = await em.findOne(CustomerComment, { id })\n if (!comment) throw new CrudHttpError(404, { error: 'Comment not found' })\n ensureTenantScope(ctx, comment.tenantId)\n ensureOrganizationScope(ctx, comment.organizationId)\n em.remove(comment)\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudSideEffects({\n dataEngine: de,\n action: 'deleted',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n return { commentId: comment.id }\n },\n buildLog: async ({ snapshots }) => {\n const before = snapshots.before as CommentSnapshot | undefined\n if (!before) return null\n const { translate } = await resolveTranslations()\n return {\n actionLabel: translate('customers.audit.comments.delete', 'Delete note'),\n resourceKind: 'customers.comment',\n resourceId: before.id,\n parentResourceKind: before.entityId ? resolveParentResourceKind(before.entityKind) : (before.dealId ? 'customers.deal' : null),\n parentResourceId: before.entityId ?? before.dealId ?? null,\n tenantId: before.tenantId,\n organizationId: before.organizationId,\n snapshotBefore: before,\n relatedResourceKind: before.dealId ? 'customers.deal' : null,\n relatedResourceId: before.dealId ?? null,\n payload: {\n undo: {\n before,\n } satisfies CommentUndoPayload,\n },\n }\n },\n undo: async ({ logEntry, ctx }) => {\n const payload = extractUndoPayload<CommentUndoPayload>(logEntry)\n const before = payload?.before\n if (!before) return\n const em = (ctx.container.resolve('em') as EntityManager).fork()\n const entity = await requireTimelineParentEntity(em, before.entityId, { tenantId: before.tenantId, organizationId: before.organizationId })\n const deal = await requireDealInScope(em, before.dealId, before.tenantId, before.organizationId)\n let comment = await em.findOne(CustomerComment, { id: before.id })\n if (!comment) {\n comment = em.create(CustomerComment, {\n id: before.id,\n organizationId: before.organizationId,\n tenantId: before.tenantId,\n entity,\n deal,\n body: before.body,\n authorUserId: before.authorUserId,\n appearanceIcon: before.appearanceIcon,\n appearanceColor: before.appearanceColor,\n createdAt: new Date(),\n updatedAt: new Date(),\n })\n em.persist(comment)\n } else {\n comment.entity = entity\n comment.deal = deal\n comment.body = before.body\n comment.authorUserId = before.authorUserId\n comment.appearanceIcon = before.appearanceIcon\n comment.appearanceColor = before.appearanceColor\n }\n await em.flush()\n\n const de = (ctx.container.resolve('dataEngine') as DataEngine)\n await emitCrudUndoSideEffects({\n dataEngine: de,\n action: 'created',\n entity: comment,\n identifiers: {\n id: comment.id,\n organizationId: comment.organizationId,\n tenantId: comment.tenantId,\n },\n indexer: commentCrudIndexer,\n events: commentCrudEvents,\n })\n },\n }\n\nregisterCommand(createCommentCommand)\nregisterCommand(updateCommentCommand)\nregisterCommand(deleteCommentCommand)\n"],
5
+ "mappings": "AAAA,SAAS,uBAAuB;AAEhC,SAAS,qBAAqB,yBAAyB,cAAc,WAAW,6BAA6B;AAG7G,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