@open-mercato/core 0.6.7-develop.6725.1.07a748cfc2 → 0.6.7-develop.6744.1.0483b18565

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 (153) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/resources_resource/index.js +2 -0
  3. package/dist/generated/entities/resources_resource/index.js.map +2 -2
  4. package/dist/generated/entity-fields-registry.js +1 -0
  5. package/dist/generated/entity-fields-registry.js.map +2 -2
  6. package/dist/helpers/integration/salesFixtures.js +31 -2
  7. package/dist/helpers/integration/salesFixtures.js.map +2 -2
  8. package/dist/helpers/integration/salesUi.js +5 -0
  9. package/dist/helpers/integration/salesUi.js.map +2 -2
  10. package/dist/modules/communication_channels/data/enrichers.js +4 -4
  11. package/dist/modules/communication_channels/data/enrichers.js.map +2 -2
  12. package/dist/modules/customers/analytics.js +1 -0
  13. package/dist/modules/customers/analytics.js.map +2 -2
  14. package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js +17 -3
  15. package/dist/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.js.map +2 -2
  16. package/dist/modules/customers/backend/customers/deals/pipeline/page.js +7 -1
  17. package/dist/modules/customers/backend/customers/deals/pipeline/page.js.map +2 -2
  18. package/dist/modules/customers/components/detail/DealForm.js +2 -1
  19. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  20. package/dist/modules/customers/components/detail/DealsSection.js +1 -1
  21. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  22. package/dist/modules/customers/data/validators.js +3 -1
  23. package/dist/modules/customers/data/validators.js.map +2 -2
  24. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/config.js +52 -2
  25. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/config.js.map +2 -2
  26. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js +42 -26
  27. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js.map +2 -2
  28. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.js +2 -2
  29. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.js.map +2 -2
  30. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +34 -12
  31. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  32. package/dist/modules/dictionaries/api/openapi.js +15 -2
  33. package/dist/modules/dictionaries/api/openapi.js.map +2 -2
  34. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js +30 -29
  35. package/dist/modules/dictionaries/components/hooks/useDictionaryEntries.js.map +2 -2
  36. package/dist/modules/dictionaries/data/validators.js +7 -0
  37. package/dist/modules/dictionaries/data/validators.js.map +2 -2
  38. package/dist/modules/dictionaries/lib/clientEntries.js +4 -3
  39. package/dist/modules/dictionaries/lib/clientEntries.js.map +2 -2
  40. package/dist/modules/dictionaries/lib/fetchAllEntries.js +43 -0
  41. package/dist/modules/dictionaries/lib/fetchAllEntries.js.map +7 -0
  42. package/dist/modules/entities/api/definitions.js +51 -3
  43. package/dist/modules/entities/api/definitions.js.map +2 -2
  44. package/dist/modules/entities/api/entities.js +21 -2
  45. package/dist/modules/entities/api/entities.js.map +2 -2
  46. package/dist/modules/entities/api/records.js +3 -24
  47. package/dist/modules/entities/api/records.js.map +2 -2
  48. package/dist/modules/entities/api/sidebar-entities.js +34 -12
  49. package/dist/modules/entities/api/sidebar-entities.js.map +2 -2
  50. package/dist/modules/entities/lib/entityAcl.js +46 -0
  51. package/dist/modules/entities/lib/entityAcl.js.map +2 -2
  52. package/dist/modules/messages/api/route.js +2 -5
  53. package/dist/modules/messages/api/route.js.map +2 -2
  54. package/dist/modules/messages/lib/participantScope.js +15 -0
  55. package/dist/modules/messages/lib/participantScope.js.map +7 -0
  56. package/dist/modules/planner/components/unavailabilityReasons.js +3 -3
  57. package/dist/modules/planner/components/unavailabilityReasons.js.map +2 -2
  58. package/dist/modules/progress/lib/progressService.js +2 -0
  59. package/dist/modules/progress/lib/progressService.js.map +2 -2
  60. package/dist/modules/progress/lib/progressServiceImpl.js +322 -104
  61. package/dist/modules/progress/lib/progressServiceImpl.js.map +2 -2
  62. package/dist/modules/resources/api/resources.js +2 -0
  63. package/dist/modules/resources/api/resources.js.map +2 -2
  64. package/dist/modules/resources/backend/resources/resources/[id]/page.js +3 -2
  65. package/dist/modules/resources/backend/resources/resources/[id]/page.js.map +2 -2
  66. package/dist/modules/resources/commands/resources.js +9 -0
  67. package/dist/modules/resources/commands/resources.js.map +2 -2
  68. package/dist/modules/resources/components/detail/dictionaries.js +3 -3
  69. package/dist/modules/resources/components/detail/dictionaries.js.map +2 -2
  70. package/dist/modules/resources/data/entities.js +3 -0
  71. package/dist/modules/resources/data/entities.js.map +2 -2
  72. package/dist/modules/resources/data/validators.js +6 -2
  73. package/dist/modules/resources/data/validators.js.map +2 -2
  74. package/dist/modules/resources/lib/seeds.js +16 -9
  75. package/dist/modules/resources/lib/seeds.js.map +2 -2
  76. package/dist/modules/resources/migrations/Migration20260608231000.js +13 -0
  77. package/dist/modules/resources/migrations/Migration20260608231000.js.map +7 -0
  78. package/dist/modules/sales/backend/sales/documents/create/page.js +11 -14
  79. package/dist/modules/sales/backend/sales/documents/create/page.js.map +2 -2
  80. package/dist/modules/sales/commands/documents.js +8 -0
  81. package/dist/modules/sales/commands/documents.js.map +2 -2
  82. package/dist/modules/sales/components/documents/ItemsSection.js +18 -9
  83. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  84. package/dist/modules/sales/components/documents/LineItemDialog.js +12 -5
  85. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  86. package/dist/modules/sales/components/documents/SalesDocumentForm.js +48 -2
  87. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  88. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js +167 -0
  89. package/dist/modules/sales/components/documents/SalesOrderDraftLines.js.map +7 -0
  90. package/dist/modules/sales/data/validators.js +5 -1
  91. package/dist/modules/sales/data/validators.js.map +2 -2
  92. package/dist/modules/staff/components/detail/dictionaries.js +3 -3
  93. package/dist/modules/staff/components/detail/dictionaries.js.map +2 -2
  94. package/dist/modules/workflows/widgets/injection/order-approval/widget.client.js +11 -4
  95. package/dist/modules/workflows/widgets/injection/order-approval/widget.client.js.map +2 -2
  96. package/generated/entities/resources_resource/index.ts +1 -0
  97. package/generated/entity-fields-registry.ts +1 -0
  98. package/package.json +7 -7
  99. package/src/helpers/integration/salesFixtures.ts +34 -2
  100. package/src/helpers/integration/salesUi.ts +8 -0
  101. package/src/modules/communication_channels/data/enrichers.ts +6 -26
  102. package/src/modules/customers/analytics.ts +1 -0
  103. package/src/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.tsx +35 -3
  104. package/src/modules/customers/backend/customers/deals/pipeline/page.tsx +10 -1
  105. package/src/modules/customers/components/detail/DealForm.tsx +5 -1
  106. package/src/modules/customers/components/detail/DealsSection.tsx +1 -1
  107. package/src/modules/customers/data/validators.ts +5 -1
  108. package/src/modules/dashboards/i18n/de.json +3 -0
  109. package/src/modules/dashboards/i18n/en.json +3 -0
  110. package/src/modules/dashboards/i18n/es.json +3 -0
  111. package/src/modules/dashboards/i18n/pl.json +3 -0
  112. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/config.ts +86 -0
  113. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.tsx +33 -18
  114. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/widget.ts +2 -2
  115. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +39 -11
  116. package/src/modules/dictionaries/api/openapi.ts +19 -0
  117. package/src/modules/dictionaries/components/hooks/useDictionaryEntries.ts +35 -36
  118. package/src/modules/dictionaries/data/validators.ts +14 -0
  119. package/src/modules/dictionaries/lib/clientEntries.ts +4 -3
  120. package/src/modules/dictionaries/lib/fetchAllEntries.ts +72 -0
  121. package/src/modules/entities/api/definitions.ts +51 -3
  122. package/src/modules/entities/api/entities.ts +30 -2
  123. package/src/modules/entities/api/records.ts +3 -27
  124. package/src/modules/entities/api/sidebar-entities.ts +43 -14
  125. package/src/modules/entities/lib/entityAcl.ts +58 -0
  126. package/src/modules/messages/api/route.ts +4 -5
  127. package/src/modules/messages/lib/participantScope.ts +64 -0
  128. package/src/modules/planner/components/unavailabilityReasons.ts +3 -3
  129. package/src/modules/progress/AGENTS.md +11 -1
  130. package/src/modules/progress/lib/progressService.ts +1 -0
  131. package/src/modules/progress/lib/progressServiceImpl.ts +385 -117
  132. package/src/modules/resources/api/resources.ts +2 -0
  133. package/src/modules/resources/backend/resources/resources/[id]/page.tsx +9 -3
  134. package/src/modules/resources/commands/resources.ts +10 -0
  135. package/src/modules/resources/components/detail/dictionaries.ts +3 -3
  136. package/src/modules/resources/data/entities.ts +3 -0
  137. package/src/modules/resources/data/validators.ts +5 -0
  138. package/src/modules/resources/lib/seeds.ts +16 -9
  139. package/src/modules/resources/migrations/.snapshot-open-mercato.json +17 -1
  140. package/src/modules/resources/migrations/Migration20260608231000.ts +13 -0
  141. package/src/modules/sales/backend/sales/documents/create/page.tsx +2 -4
  142. package/src/modules/sales/commands/documents.ts +8 -0
  143. package/src/modules/sales/components/documents/ItemsSection.tsx +19 -10
  144. package/src/modules/sales/components/documents/LineItemDialog.tsx +13 -5
  145. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +48 -6
  146. package/src/modules/sales/components/documents/SalesOrderDraftLines.tsx +198 -0
  147. package/src/modules/sales/data/validators.ts +7 -1
  148. package/src/modules/sales/i18n/de.json +2 -0
  149. package/src/modules/sales/i18n/en.json +2 -0
  150. package/src/modules/sales/i18n/es.json +2 -0
  151. package/src/modules/sales/i18n/pl.json +2 -0
  152. package/src/modules/staff/components/detail/dictionaries.ts +3 -3
  153. package/src/modules/workflows/widgets/injection/order-approval/widget.client.tsx +12 -5
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/data/enrichers.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EnricherContext, ResponseEnricher } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { sanitizeChannelHtml } from '../lib/sanitize-channel-html'\nimport {\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n MessageReaction,\n} from './entities'\n\n/**\n * Response enrichers for the messages.message entity.\n *\n * The hub declares 2 enrichers; downstream hosts (Messages module's `/api/messages`\n * CRUD route + future provider routes) opt in via `makeCrudRoute({ enrichers: { entityId: 'messages.message' } })`.\n *\n * - `messageChannelEnricher` \u2192 `_channel`, `_channelPayload`, `_channelContact`\n * - `messageReactionsEnricher` \u2192 `_reactions`\n *\n * The channel/payload/contact enrichments were three separate enrichers, each\n * independently issuing its own `MessageChannelLink` `$in` query (and two of them\n * an `ExternalConversation` query) for the same message page. Because the shared\n * enricher runner executes active enrichers sequentially with no per-pass shared\n * context, those lookups were repeated for every page (#3183). They are merged\n * into one batched enricher so the link batch (and the conversation batch) is\n * loaded once per pass, while preserving the public enriched field names:\n *\n * - `_channel` \u2192 channel metadata + capabilities snapshot\n * - `_channelPayload` \u2192 channel-native payload (Block Kit / interactive / email MIME / \u2026)\n * - `_channelContact` \u2192 CRM person preview (email + display name)\n * - `_reactions` \u2192 grouped emoji counts + users + reactedByMe\n *\n * Per `packages/shared/lib/crud/response-enricher` rules:\n * - `enrichMany` is implemented for every enricher (N+1 prevention).\n * - Enriched fields are namespaced with `_channel*` / `_reactions` prefixes.\n * - Enrichers are read-only; no writes via the EntityManager.\n * - Each enricher is feature-gated by `communication_channels.view`.\n */\n\ntype MessageRecord = Record<string, unknown> & {\n id: string\n threadId?: string | null\n}\n\ntype MessageParticipantDatabase = {\n messages: {\n id: string\n tenant_id: string\n organization_id: string | null\n sender_user_id: string\n deleted_at: Date | null\n }\n message_recipients: {\n message_id: string\n recipient_user_id: string\n deleted_at: Date | null\n }\n}\n\ntype ResolvedCtx = EnricherContext & {\n em: EntityManager\n}\n\nfunction ctxEm(ctx: EnricherContext): EntityManager {\n return ctx.em as EntityManager\n}\n\nexport type ChannelEnrichment = {\n providerKey: string\n channelType: string\n direction: 'inbound' | 'outbound' | string\n deliveryStatus: string | null\n capabilities: Record<string, unknown> | null\n}\n\nexport type ChannelPayloadEnrichment = {\n channelContentType: string | null\n channelPayload: Record<string, unknown> | null\n interactiveState: Record<string, unknown> | null\n channelMetadata: Record<string, unknown> | null\n /**\n * Server-sanitized email HTML, safe for `dangerouslySetInnerHTML`. Populated\n * for `email/*` payloads that carry an html body, `null` otherwise. Sanitizing\n * here keeps `sanitize-html` off the client render path.\n */\n sanitizedHtml: string | null\n}\n\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\n}\n\n/**\n * Sanitize channel-supplied email HTML on the server so the client widget never\n * has to pull `sanitize-html` into the browser bundle or run sanitization on the\n * render path. Returns the sanitized HTML for `email/*` payloads that carry an\n * html body, and `null` otherwise. The raw `channelPayload` is left untouched so\n * provider-package widget overrides keep their existing data contract.\n */\nfunction sanitizeEmailPayloadHtml(\n contentType: string | null | undefined,\n payload: Record<string, unknown> | null | undefined,\n): string | null {\n if (!contentType || !contentType.startsWith('email/')) return null\n const html = payload?.html\n if (typeof html !== 'string' || html.length === 0) return null\n return sanitizeChannelHtml(html)\n}\n\n// \u2500\u2500 _channel + _channelPayload + _channelContact \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageChannelEnricher: ResponseEnricher<\n MessageRecord,\n {\n _channel?: ChannelEnrichment | null\n _channelPayload?: ChannelPayloadEnrichment | null\n _channelContact?: ChannelContactEnrichment | null\n }\n> = {\n id: 'communication_channels.message-channel',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 30,\n timeout: 2000,\n fallback: { _channel: null, _channelPayload: null, _channelContact: null },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const tenantId = ctx.tenantId as string\n const organizationId = ctx.organizationId ?? null\n const dscope = { tenantId, organizationId }\n\n const userId = typeof ctx.userId === 'string' ? ctx.userId : null\n if (!userId) {\n return records.map((record) => ({\n ...record,\n _channel: null,\n _channelPayload: null,\n _channelContact: null,\n }))\n }\n\n const db = em.getKysely<MessageParticipantDatabase>()\n let participantQuery = db\n .selectFrom('messages as m')\n .leftJoin('message_recipients as r', (join) => join\n .onRef('m.id', '=', 'r.message_id')\n .on('r.recipient_user_id', '=', userId)\n .on('r.deleted_at', 'is', null))\n .select('m.id')\n .distinct()\n .where('m.id', 'in', messageIds)\n .where('m.tenant_id', '=', tenantId)\n .where('m.deleted_at', 'is', null)\n .where((eb) => eb.or([\n eb('m.sender_user_id', '=', userId),\n eb('r.message_id', 'is not', null),\n ]))\n\n participantQuery = organizationId !== null\n ? participantQuery.where('m.organization_id', '=', organizationId)\n : participantQuery.where('m.organization_id', 'is', null)\n\n const participantRows = await participantQuery.execute()\n const participantMessageIds = participantRows.map((row) => row.id)\n const participantMessageIdSet = new Set(participantMessageIds)\n\n // 1) MessageChannelLink \u2014 one bounded `$in` query for the whole page, shared by\n // all three enrichments (channel metadata, channel payload, conversation\n // contact). The result set is already bounded by the `messageId $in messageIds`\n // filter (the host list endpoint caps the page at 100), so no separate row\n // limit is needed.\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: participantMessageIds },\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n // 2) ExternalConversation \u2014 one query, shared by the channel-capabilities hop and\n // the conversation-contact enrichment.\n const conversationIds = Array.from(\n new Set(\n links\n .map((l) => l.externalConversationId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const conversationsById = new Map<string, ExternalConversation>()\n if (conversationIds.length > 0) {\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { id: { $in: conversationIds }, tenantId, organizationId },\n undefined,\n dscope,\n )\n for (const conversation of conversations) {\n conversationsById.set(conversation.id, conversation)\n }\n }\n\n // 3) CommunicationChannel \u2014 capabilities snapshot. Resolve by `id` (not\n // `providerKey`): multi-user channels share the same `providerKey` (e.g. two\n // users with Gmail), so a providerKey-keyed map collapses them and returns the\n // wrong owner's capabilities. The hop is `link \u2192 ExternalConversation \u2192 CommunicationChannel`.\n const channelIds = Array.from(\n new Set(\n Array.from(conversationsById.values())\n .map((conversation) => conversation.channelId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const channelsById = new Map<string, CommunicationChannel>()\n if (channelIds.length > 0) {\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n for (const channel of channels) channelsById.set(channel.id, channel)\n }\n\n const channelByMessageId = new Map<string, CommunicationChannel>()\n for (const link of links) {\n if (!link.externalConversationId) continue\n const conversation = conversationsById.get(link.externalConversationId)\n if (!conversation) continue\n const channel = conversation.channelId ? channelsById.get(conversation.channelId) : undefined\n if (channel) channelByMessageId.set(link.messageId, channel)\n }\n\n return records.map((r) => {\n if (!participantMessageIdSet.has(r.id)) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const link = linksByMessage.get(r.id)\n if (!link) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const channel = channelByMessageId.get(r.id)\n const channelEnrichment: ChannelEnrichment = {\n providerKey: link.providerKey,\n channelType: link.channelType,\n direction: link.direction,\n deliveryStatus: link.deliveryStatus ?? null,\n capabilities: (channel?.capabilities as Record<string, unknown> | null) ?? null,\n }\n\n const payloadEnrichment: ChannelPayloadEnrichment = {\n channelContentType: link.channelContentType ?? null,\n channelPayload: link.channelPayload ?? null,\n interactiveState: link.interactiveState ?? null,\n channelMetadata: link.channelMetadata ?? null,\n sanitizedHtml: sanitizeEmailPayloadHtml(link.channelContentType, link.channelPayload),\n }\n\n const conversation = link.externalConversationId\n ? conversationsById.get(link.externalConversationId)\n : undefined\n const contactEnrichment: ChannelContactEnrichment | null = conversation\n ? {\n contactPersonId: conversation.contactPersonId ?? null,\n assignedUserId: conversation.assignedUserId ?? null,\n subject: conversation.subject ?? null,\n }\n : null\n\n return {\n ...r,\n _channel: channelEnrichment,\n _channelPayload: payloadEnrichment,\n _channelContact: contactEnrichment,\n }\n })\n },\n}\n\n// \u2500\u2500 _reactions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageReactionsEnricher: ResponseEnricher<\n MessageRecord,\n { _reactions?: ReactionGroup[] }\n> = {\n id: 'communication_channels.message-reactions',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 25,\n timeout: 1500,\n fallback: { _reactions: [] },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const reactions = await findWithDecryption(\n em,\n MessageReaction,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n\n const byMessage = new Map<string, MessageReaction[]>()\n for (const reaction of reactions) {\n const existing = byMessage.get(reaction.messageId) ?? []\n existing.push(reaction)\n byMessage.set(reaction.messageId, existing)\n }\n\n return records.map((r) => {\n const rows = byMessage.get(r.id) ?? []\n const grouped = groupReactions(rows, ctx.userId)\n return { ...r, _reactions: grouped }\n })\n },\n}\n\nexport type ReactionGroup = {\n emoji: string\n count: number\n users: Array<{\n userId?: string | null\n externalId?: string | null\n displayName?: string | null\n providerKey?: string | null\n }>\n reactedByMe: boolean\n /**\n * MessageReaction.id of the current user's reaction row, if any. Exposed so\n * the reaction-bar UI can issue\n * `DELETE /api/communication_channels/messages/{messageId}/reactions/{myReactionId}`\n * when the user toggles their own reaction off. Null when `reactedByMe` is\n * false or the row was added by an external participant (provider-side).\n */\n myReactionId: string | null\n}\n\nfunction groupReactions(rows: MessageReaction[], currentUserId: string): ReactionGroup[] {\n const map = new Map<string, ReactionGroup>()\n for (const row of rows) {\n const key = row.emoji\n if (!map.has(key)) {\n map.set(key, { emoji: key, count: 0, users: [], reactedByMe: false, myReactionId: null })\n }\n const group = map.get(key)!\n group.count += 1\n group.users.push({\n userId: row.reactedByUserId ?? null,\n externalId: row.reactedByExternalId ?? null,\n displayName: row.reactedByDisplayName ?? null,\n providerKey: row.providerKey ?? null,\n })\n if (row.reactedByUserId && row.reactedByUserId === currentUserId) {\n group.reactedByMe = true\n if (!group.myReactionId) group.myReactionId = row.id ?? null\n }\n }\n return Array.from(map.values()).sort((a, b) => b.count - a.count)\n}\n\n// \u2500\u2500 Export \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const enrichers: ResponseEnricher[] = [\n messageChannelEnricher as unknown as ResponseEnricher,\n messageReactionsEnricher as unknown as ResponseEnricher,\n]\n\nexport default enrichers\n"],
5
- "mappings": "AAEA,SAAS,0BAA0B;AACnC,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAuDP,SAAS,MAAM,KAAqC;AAClD,SAAO,IAAI;AACb;AAoCA,SAAS,yBACP,aACA,SACe;AACf,MAAI,CAAC,eAAe,CAAC,YAAY,WAAW,QAAQ,EAAG,QAAO;AAC9D,QAAM,OAAO,SAAS;AACtB,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,EAAG,QAAO;AAC1D,SAAO,oBAAoB,IAAI;AACjC;AAIA,MAAM,yBAOF;AAAA,EACF,IAAI;AAAA,EACJ,cAAc;AAAA,EACd,UAAU,CAAC,6BAA6B;AAAA,EACxC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU,EAAE,UAAU,MAAM,iBAAiB,MAAM,iBAAiB,KAAK;AAAA,EACzE,UAAU;AAAA,EAEV,MAAM,UAAU,QAAQ,KAAK;AAC3B,UAAM,CAAC,GAAG,IAAI,MAAM,KAAK,WAAY,CAAC,MAAM,GAAG,GAAG;AAClD,WAAO;AAAA,EACT;AAAA,EAEA,MAAM,WAAW,SAAS,KAAK;AAC7B,QAAI,QAAQ,WAAW,EAAG,QAAO;AACjC,UAAM,aAAa,QAAQ,IAAI,CAAC,MAAM,EAAE,EAAE;AAC1C,UAAM,KAAK,MAAM,GAAG;AACpB,UAAM,WAAW,IAAI;AACrB,UAAM,iBAAiB,IAAI,kBAAkB;AAC7C,UAAM,SAAS,EAAE,UAAU,eAAe;AAE1C,UAAM,SAAS,OAAO,IAAI,WAAW,WAAW,IAAI,SAAS;AAC7D,QAAI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AAQ,IAAI,IAAI,GAAG;AACzB,UAAM,SAAS;AACf,UAAM,MAAM,KAAK;AAAA,MACf,QAAQ,IAAI,mBAAmB;AAAA,MAC/B,YAAY,IAAI,uBAAuB;AAAA,MACvC,aAAa,IAAI,wBAAwB;AAAA,MACzC,aAAa,IAAI,eAAe;AAAA,IAClC,CAAC;AACD,QAAI,IAAI,mBAAmB,IAAI,oBAAoB,eAAe;AAChE,YAAM,cAAc;AACpB,UAAI,CAAC,MAAM,aAAc,OAAM,eAAe,IAAI,MAAM;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAClE;AAIO,MAAM,YAAgC;AAAA,EAC3C;AAAA,EACA;AACF;AAEA,IAAO,oBAAQ;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EnricherContext, ResponseEnricher } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n applyMessageParticipantScope,\n type MessagesParticipantScopeDatabase,\n} from '../../messages/lib/participantScope'\nimport { sanitizeChannelHtml } from '../lib/sanitize-channel-html'\nimport {\n CommunicationChannel,\n ExternalConversation,\n MessageChannelLink,\n MessageReaction,\n} from './entities'\n\n/**\n * Response enrichers for the messages.message entity.\n *\n * The hub declares 2 enrichers; downstream hosts (Messages module's `/api/messages`\n * CRUD route + future provider routes) opt in via `makeCrudRoute({ enrichers: { entityId: 'messages.message' } })`.\n *\n * - `messageChannelEnricher` \u2192 `_channel`, `_channelPayload`, `_channelContact`\n * - `messageReactionsEnricher` \u2192 `_reactions`\n *\n * The channel/payload/contact enrichments were three separate enrichers, each\n * independently issuing its own `MessageChannelLink` `$in` query (and two of them\n * an `ExternalConversation` query) for the same message page. Because the shared\n * enricher runner executes active enrichers sequentially with no per-pass shared\n * context, those lookups were repeated for every page (#3183). They are merged\n * into one batched enricher so the link batch (and the conversation batch) is\n * loaded once per pass, while preserving the public enriched field names:\n *\n * - `_channel` \u2192 channel metadata + capabilities snapshot\n * - `_channelPayload` \u2192 channel-native payload (Block Kit / interactive / email MIME / \u2026)\n * - `_channelContact` \u2192 CRM person preview (email + display name)\n * - `_reactions` \u2192 grouped emoji counts + users + reactedByMe\n *\n * Per `packages/shared/lib/crud/response-enricher` rules:\n * - `enrichMany` is implemented for every enricher (N+1 prevention).\n * - Enriched fields are namespaced with `_channel*` / `_reactions` prefixes.\n * - Enrichers are read-only; no writes via the EntityManager.\n * - Each enricher is feature-gated by `communication_channels.view`.\n */\n\ntype MessageRecord = Record<string, unknown> & {\n id: string\n threadId?: string | null\n}\n\ntype ResolvedCtx = EnricherContext & {\n em: EntityManager\n}\n\nfunction ctxEm(ctx: EnricherContext): EntityManager {\n return ctx.em as EntityManager\n}\n\nexport type ChannelEnrichment = {\n providerKey: string\n channelType: string\n direction: 'inbound' | 'outbound' | string\n deliveryStatus: string | null\n capabilities: Record<string, unknown> | null\n}\n\nexport type ChannelPayloadEnrichment = {\n channelContentType: string | null\n channelPayload: Record<string, unknown> | null\n interactiveState: Record<string, unknown> | null\n channelMetadata: Record<string, unknown> | null\n /**\n * Server-sanitized email HTML, safe for `dangerouslySetInnerHTML`. Populated\n * for `email/*` payloads that carry an html body, `null` otherwise. Sanitizing\n * here keeps `sanitize-html` off the client render path.\n */\n sanitizedHtml: string | null\n}\n\nexport type ChannelContactEnrichment = {\n contactPersonId: string | null\n assignedUserId: string | null\n subject: string | null\n}\n\n/**\n * Sanitize channel-supplied email HTML on the server so the client widget never\n * has to pull `sanitize-html` into the browser bundle or run sanitization on the\n * render path. Returns the sanitized HTML for `email/*` payloads that carry an\n * html body, and `null` otherwise. The raw `channelPayload` is left untouched so\n * provider-package widget overrides keep their existing data contract.\n */\nfunction sanitizeEmailPayloadHtml(\n contentType: string | null | undefined,\n payload: Record<string, unknown> | null | undefined,\n): string | null {\n if (!contentType || !contentType.startsWith('email/')) return null\n const html = payload?.html\n if (typeof html !== 'string' || html.length === 0) return null\n return sanitizeChannelHtml(html)\n}\n\n// \u2500\u2500 _channel + _channelPayload + _channelContact \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageChannelEnricher: ResponseEnricher<\n MessageRecord,\n {\n _channel?: ChannelEnrichment | null\n _channelPayload?: ChannelPayloadEnrichment | null\n _channelContact?: ChannelContactEnrichment | null\n }\n> = {\n id: 'communication_channels.message-channel',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 30,\n timeout: 2000,\n fallback: { _channel: null, _channelPayload: null, _channelContact: null },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const tenantId = ctx.tenantId as string\n const organizationId = ctx.organizationId ?? null\n const dscope = { tenantId, organizationId }\n\n const userId = typeof ctx.userId === 'string' ? ctx.userId : null\n if (!userId) {\n return records.map((record) => ({\n ...record,\n _channel: null,\n _channelPayload: null,\n _channelContact: null,\n }))\n }\n\n const db = em.getKysely<MessagesParticipantScopeDatabase>()\n let participantQuery = applyMessageParticipantScope(db.selectFrom('messages as m'), userId)\n .select('m.id')\n .distinct()\n .where('m.id', 'in', messageIds)\n .where('m.tenant_id', '=', tenantId)\n .where('m.deleted_at', 'is', null)\n\n participantQuery = organizationId !== null\n ? participantQuery.where('m.organization_id', '=', organizationId)\n : participantQuery.where('m.organization_id', 'is', null)\n\n const participantRows = await participantQuery.execute()\n const participantMessageIds = participantRows.map((row) => row.id)\n const participantMessageIdSet = new Set(participantMessageIds)\n\n // 1) MessageChannelLink \u2014 one bounded `$in` query for the whole page, shared by\n // all three enrichments (channel metadata, channel payload, conversation\n // contact). The result set is already bounded by the `messageId $in messageIds`\n // filter (the host list endpoint caps the page at 100), so no separate row\n // limit is needed.\n const links = await findWithDecryption(\n em,\n MessageChannelLink,\n {\n messageId: { $in: participantMessageIds },\n tenantId,\n organizationId,\n },\n undefined,\n dscope,\n )\n const linksByMessage = new Map<string, MessageChannelLink>()\n for (const link of links) linksByMessage.set(link.messageId, link)\n\n // 2) ExternalConversation \u2014 one query, shared by the channel-capabilities hop and\n // the conversation-contact enrichment.\n const conversationIds = Array.from(\n new Set(\n links\n .map((l) => l.externalConversationId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const conversationsById = new Map<string, ExternalConversation>()\n if (conversationIds.length > 0) {\n const conversations = await findWithDecryption(\n em,\n ExternalConversation,\n { id: { $in: conversationIds }, tenantId, organizationId },\n undefined,\n dscope,\n )\n for (const conversation of conversations) {\n conversationsById.set(conversation.id, conversation)\n }\n }\n\n // 3) CommunicationChannel \u2014 capabilities snapshot. Resolve by `id` (not\n // `providerKey`): multi-user channels share the same `providerKey` (e.g. two\n // users with Gmail), so a providerKey-keyed map collapses them and returns the\n // wrong owner's capabilities. The hop is `link \u2192 ExternalConversation \u2192 CommunicationChannel`.\n const channelIds = Array.from(\n new Set(\n Array.from(conversationsById.values())\n .map((conversation) => conversation.channelId)\n .filter((id): id is string => typeof id === 'string' && id.length > 0),\n ),\n )\n const channelsById = new Map<string, CommunicationChannel>()\n if (channelIds.length > 0) {\n const channels = await findWithDecryption(\n em,\n CommunicationChannel,\n { id: { $in: channelIds }, tenantId, organizationId, deletedAt: null },\n undefined,\n dscope,\n )\n for (const channel of channels) channelsById.set(channel.id, channel)\n }\n\n const channelByMessageId = new Map<string, CommunicationChannel>()\n for (const link of links) {\n if (!link.externalConversationId) continue\n const conversation = conversationsById.get(link.externalConversationId)\n if (!conversation) continue\n const channel = conversation.channelId ? channelsById.get(conversation.channelId) : undefined\n if (channel) channelByMessageId.set(link.messageId, channel)\n }\n\n return records.map((r) => {\n if (!participantMessageIdSet.has(r.id)) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const link = linksByMessage.get(r.id)\n if (!link) {\n return { ...r, _channel: null, _channelPayload: null, _channelContact: null }\n }\n\n const channel = channelByMessageId.get(r.id)\n const channelEnrichment: ChannelEnrichment = {\n providerKey: link.providerKey,\n channelType: link.channelType,\n direction: link.direction,\n deliveryStatus: link.deliveryStatus ?? null,\n capabilities: (channel?.capabilities as Record<string, unknown> | null) ?? null,\n }\n\n const payloadEnrichment: ChannelPayloadEnrichment = {\n channelContentType: link.channelContentType ?? null,\n channelPayload: link.channelPayload ?? null,\n interactiveState: link.interactiveState ?? null,\n channelMetadata: link.channelMetadata ?? null,\n sanitizedHtml: sanitizeEmailPayloadHtml(link.channelContentType, link.channelPayload),\n }\n\n const conversation = link.externalConversationId\n ? conversationsById.get(link.externalConversationId)\n : undefined\n const contactEnrichment: ChannelContactEnrichment | null = conversation\n ? {\n contactPersonId: conversation.contactPersonId ?? null,\n assignedUserId: conversation.assignedUserId ?? null,\n subject: conversation.subject ?? null,\n }\n : null\n\n return {\n ...r,\n _channel: channelEnrichment,\n _channelPayload: payloadEnrichment,\n _channelContact: contactEnrichment,\n }\n })\n },\n}\n\n// \u2500\u2500 _reactions \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst messageReactionsEnricher: ResponseEnricher<\n MessageRecord,\n { _reactions?: ReactionGroup[] }\n> = {\n id: 'communication_channels.message-reactions',\n targetEntity: 'messages.message',\n features: ['communication_channels.view'],\n priority: 25,\n timeout: 1500,\n fallback: { _reactions: [] },\n critical: false,\n\n async enrichOne(record, ctx) {\n const [out] = await this.enrichMany!([record], ctx)\n return out\n },\n\n async enrichMany(records, ctx) {\n if (records.length === 0) return records\n const messageIds = records.map((r) => r.id)\n const em = ctxEm(ctx)\n const dscope = { tenantId: ctx.tenantId, organizationId: ctx.organizationId ?? null }\n const reactions = await findWithDecryption(\n em,\n MessageReaction,\n {\n messageId: { $in: messageIds },\n tenantId: ctx.tenantId,\n organizationId: ctx.organizationId ?? null,\n },\n undefined,\n dscope,\n )\n\n const byMessage = new Map<string, MessageReaction[]>()\n for (const reaction of reactions) {\n const existing = byMessage.get(reaction.messageId) ?? []\n existing.push(reaction)\n byMessage.set(reaction.messageId, existing)\n }\n\n return records.map((r) => {\n const rows = byMessage.get(r.id) ?? []\n const grouped = groupReactions(rows, ctx.userId)\n return { ...r, _reactions: grouped }\n })\n },\n}\n\nexport type ReactionGroup = {\n emoji: string\n count: number\n users: Array<{\n userId?: string | null\n externalId?: string | null\n displayName?: string | null\n providerKey?: string | null\n }>\n reactedByMe: boolean\n /**\n * MessageReaction.id of the current user's reaction row, if any. Exposed so\n * the reaction-bar UI can issue\n * `DELETE /api/communication_channels/messages/{messageId}/reactions/{myReactionId}`\n * when the user toggles their own reaction off. Null when `reactedByMe` is\n * false or the row was added by an external participant (provider-side).\n */\n myReactionId: string | null\n}\n\nfunction groupReactions(rows: MessageReaction[], currentUserId: string): ReactionGroup[] {\n const map = new Map<string, ReactionGroup>()\n for (const row of rows) {\n const key = row.emoji\n if (!map.has(key)) {\n map.set(key, { emoji: key, count: 0, users: [], reactedByMe: false, myReactionId: null })\n }\n const group = map.get(key)!\n group.count += 1\n group.users.push({\n userId: row.reactedByUserId ?? null,\n externalId: row.reactedByExternalId ?? null,\n displayName: row.reactedByDisplayName ?? null,\n providerKey: row.providerKey ?? null,\n })\n if (row.reactedByUserId && row.reactedByUserId === currentUserId) {\n group.reactedByMe = true\n if (!group.myReactionId) group.myReactionId = row.id ?? null\n }\n }\n return Array.from(map.values()).sort((a, b) => b.count - a.count)\n}\n\n// \u2500\u2500 Export \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport const enrichers: ResponseEnricher[] = [\n messageChannelEnricher as unknown as ResponseEnricher,\n messageReactionsEnricher as unknown as ResponseEnricher,\n]\n\nexport default enrichers\n"],
5
+ "mappings": "AAEA,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,OAEK;AACP,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAwCP,SAAS,MAAM,KAAqC;AAClD,SAAO,IAAI;AACb;AAoCA,SAAS,yBACP,aACA,SACe;AACf,MAAI,CAAC,eAAe,CAAC,YAAY,WAAW,QAAQ,EAAG,QAAO;AAC9D,QAAM,OAAO,SAAS;AACtB,MAAI,OAAO,SAAS,YAAY,KAAK,WAAW,EAAG,QAAO;AAC1D,SAAO,oBAAoB,IAAI;AACjC;AAIA,MAAM,yBAOF;AAAA,EACF,IAAI;AAAA,EACJ,cAAc;AAAA,EACd,UAAU,CAAC,6BAA6B;AAAA,EACxC,UAAU;AAAA,EACV,SAAS;AAAA,EACT,UAAU,EAAE,UAAU,MAAM,iBAAiB,MAAM,iBAAiB,KAAK;AAAA,EACzE,UAAU;AAAA,EAEV,MAAM,UAAU,QAAQ,KAAK;AAC3B,UAAM,CAAC,GAAG,IAAI,MAAM,KAAK,WAAY,CAAC,MAAM,GAAG,GAAG;AAClD,WAAO;AAAA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AAG,OAAO,CAAC,GAAG,aAAa,OAAO,cAAc,KAAK,CAAC;AAAA,IAC1F;AACA,UAAM,QAAQ,IAAI,IAAI,GAAG;AACzB,UAAM,SAAS;AACf,UAAM,MAAM,KAAK;AAAA,MACf,QAAQ,IAAI,mBAAmB;AAAA,MAC/B,YAAY,IAAI,uBAAuB;AAAA,MACvC,aAAa,IAAI,wBAAwB;AAAA,MACzC,aAAa,IAAI,eAAe;AAAA,IAClC,CAAC;AACD,QAAI,IAAI,mBAAmB,IAAI,oBAAoB,eAAe;AAChE,YAAM,cAAc;AACpB,UAAI,CAAC,MAAM,aAAc,OAAM,eAAe,IAAI,MAAM;AAAA,IAC1D;AAAA,EACF;AACA,SAAO,MAAM,KAAK,IAAI,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;AAClE;AAIO,MAAM,YAAgC;AAAA,EAC3C;AAAA,EACA;AACF;AAEA,IAAO,oBAAQ;",
6
6
  "names": []
7
7
  }
@@ -29,6 +29,7 @@ const analyticsConfig = {
29
29
  id: { dbColumn: "id", type: "uuid" },
30
30
  valueAmount: { dbColumn: "value_amount", type: "numeric" },
31
31
  status: { dbColumn: "status", type: "text" },
32
+ closureOutcome: { dbColumn: "closure_outcome", type: "text" },
32
33
  pipelineStage: { dbColumn: "pipeline_stage", type: "text" },
33
34
  probability: { dbColumn: "probability", type: "numeric" },
34
35
  createdAt: { dbColumn: "created_at", type: "timestamp" },
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../src/modules/customers/analytics.ts"],
4
- "sourcesContent": ["import type { AnalyticsModuleConfig } from '@open-mercato/shared/modules/analytics'\n\nexport const analyticsConfig: AnalyticsModuleConfig = {\n entities: [\n {\n entityId: 'customers:entities',\n requiredFeatures: ['customers.view'],\n entityConfig: {\n tableName: 'customer_entities',\n dateField: 'created_at',\n defaultScopeFields: ['tenant_id', 'organization_id'],\n },\n fieldMappings: {\n id: { dbColumn: 'id', type: 'uuid' },\n kind: { dbColumn: 'kind', type: 'text' },\n status: { dbColumn: 'status', type: 'text' },\n lifecycleStage: { dbColumn: 'lifecycle_stage', type: 'text' },\n createdAt: { dbColumn: 'created_at', type: 'timestamp' },\n displayName: { dbColumn: 'display_name', type: 'text' },\n },\n },\n {\n entityId: 'customers:deals',\n requiredFeatures: ['customers.deals.view'],\n entityConfig: {\n tableName: 'customer_deals',\n dateField: 'created_at',\n defaultScopeFields: ['tenant_id', 'organization_id'],\n },\n fieldMappings: {\n id: { dbColumn: 'id', type: 'uuid' },\n valueAmount: { dbColumn: 'value_amount', type: 'numeric' },\n status: { dbColumn: 'status', type: 'text' },\n pipelineStage: { dbColumn: 'pipeline_stage', type: 'text' },\n probability: { dbColumn: 'probability', type: 'numeric' },\n createdAt: { dbColumn: 'created_at', type: 'timestamp' },\n expectedCloseAt: { dbColumn: 'expected_close_at', type: 'timestamp' },\n },\n labelResolvers: {\n customerEntityId: { table: 'customer_entities', idColumn: 'id', labelColumn: 'display_name' },\n },\n },\n ],\n}\n\nexport default analyticsConfig\nexport const config = analyticsConfig\n"],
5
- "mappings": "AAEO,MAAM,kBAAyC;AAAA,EACpD,UAAU;AAAA,IACR;AAAA,MACE,UAAU;AAAA,MACV,kBAAkB,CAAC,gBAAgB;AAAA,MACnC,cAAc;AAAA,QACZ,WAAW;AAAA,QACX,WAAW;AAAA,QACX,oBAAoB,CAAC,aAAa,iBAAiB;AAAA,MACrD;AAAA,MACA,eAAe;AAAA,QACb,IAAI,EAAE,UAAU,MAAM,MAAM,OAAO;AAAA,QACnC,MAAM,EAAE,UAAU,QAAQ,MAAM,OAAO;AAAA,QACvC,QAAQ,EAAE,UAAU,UAAU,MAAM,OAAO;AAAA,QAC3C,gBAAgB,EAAE,UAAU,mBAAmB,MAAM,OAAO;AAAA,QAC5D,WAAW,EAAE,UAAU,cAAc,MAAM,YAAY;AAAA,QACvD,aAAa,EAAE,UAAU,gBAAgB,MAAM,OAAO;AAAA,MACxD;AAAA,IACF;AAAA,IACA;AAAA,MACE,UAAU;AAAA,MACV,kBAAkB,CAAC,sBAAsB;AAAA,MACzC,cAAc;AAAA,QACZ,WAAW;AAAA,QACX,WAAW;AAAA,QACX,oBAAoB,CAAC,aAAa,iBAAiB;AAAA,MACrD;AAAA,MACA,eAAe;AAAA,QACb,IAAI,EAAE,UAAU,MAAM,MAAM,OAAO;AAAA,QACnC,aAAa,EAAE,UAAU,gBAAgB,MAAM,UAAU;AAAA,QACzD,QAAQ,EAAE,UAAU,UAAU,MAAM,OAAO;AAAA,QAC3C,eAAe,EAAE,UAAU,kBAAkB,MAAM,OAAO;AAAA,QAC1D,aAAa,EAAE,UAAU,eAAe,MAAM,UAAU;AAAA,QACxD,WAAW,EAAE,UAAU,cAAc,MAAM,YAAY;AAAA,QACvD,iBAAiB,EAAE,UAAU,qBAAqB,MAAM,YAAY;AAAA,MACtE;AAAA,MACA,gBAAgB;AAAA,QACd,kBAAkB,EAAE,OAAO,qBAAqB,UAAU,MAAM,aAAa,eAAe;AAAA,MAC9F;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,oBAAQ;AACR,MAAM,SAAS;",
4
+ "sourcesContent": ["import type { AnalyticsModuleConfig } from '@open-mercato/shared/modules/analytics'\n\nexport const analyticsConfig: AnalyticsModuleConfig = {\n entities: [\n {\n entityId: 'customers:entities',\n requiredFeatures: ['customers.view'],\n entityConfig: {\n tableName: 'customer_entities',\n dateField: 'created_at',\n defaultScopeFields: ['tenant_id', 'organization_id'],\n },\n fieldMappings: {\n id: { dbColumn: 'id', type: 'uuid' },\n kind: { dbColumn: 'kind', type: 'text' },\n status: { dbColumn: 'status', type: 'text' },\n lifecycleStage: { dbColumn: 'lifecycle_stage', type: 'text' },\n createdAt: { dbColumn: 'created_at', type: 'timestamp' },\n displayName: { dbColumn: 'display_name', type: 'text' },\n },\n },\n {\n entityId: 'customers:deals',\n requiredFeatures: ['customers.deals.view'],\n entityConfig: {\n tableName: 'customer_deals',\n dateField: 'created_at',\n defaultScopeFields: ['tenant_id', 'organization_id'],\n },\n fieldMappings: {\n id: { dbColumn: 'id', type: 'uuid' },\n valueAmount: { dbColumn: 'value_amount', type: 'numeric' },\n status: { dbColumn: 'status', type: 'text' },\n closureOutcome: { dbColumn: 'closure_outcome', type: 'text' },\n pipelineStage: { dbColumn: 'pipeline_stage', type: 'text' },\n probability: { dbColumn: 'probability', type: 'numeric' },\n createdAt: { dbColumn: 'created_at', type: 'timestamp' },\n expectedCloseAt: { dbColumn: 'expected_close_at', type: 'timestamp' },\n },\n labelResolvers: {\n customerEntityId: { table: 'customer_entities', idColumn: 'id', labelColumn: 'display_name' },\n },\n },\n ],\n}\n\nexport default analyticsConfig\nexport const config = analyticsConfig\n"],
5
+ "mappings": "AAEO,MAAM,kBAAyC;AAAA,EACpD,UAAU;AAAA,IACR;AAAA,MACE,UAAU;AAAA,MACV,kBAAkB,CAAC,gBAAgB;AAAA,MACnC,cAAc;AAAA,QACZ,WAAW;AAAA,QACX,WAAW;AAAA,QACX,oBAAoB,CAAC,aAAa,iBAAiB;AAAA,MACrD;AAAA,MACA,eAAe;AAAA,QACb,IAAI,EAAE,UAAU,MAAM,MAAM,OAAO;AAAA,QACnC,MAAM,EAAE,UAAU,QAAQ,MAAM,OAAO;AAAA,QACvC,QAAQ,EAAE,UAAU,UAAU,MAAM,OAAO;AAAA,QAC3C,gBAAgB,EAAE,UAAU,mBAAmB,MAAM,OAAO;AAAA,QAC5D,WAAW,EAAE,UAAU,cAAc,MAAM,YAAY;AAAA,QACvD,aAAa,EAAE,UAAU,gBAAgB,MAAM,OAAO;AAAA,MACxD;AAAA,IACF;AAAA,IACA;AAAA,MACE,UAAU;AAAA,MACV,kBAAkB,CAAC,sBAAsB;AAAA,MACzC,cAAc;AAAA,QACZ,WAAW;AAAA,QACX,WAAW;AAAA,QACX,oBAAoB,CAAC,aAAa,iBAAiB;AAAA,MACrD;AAAA,MACA,eAAe;AAAA,QACb,IAAI,EAAE,UAAU,MAAM,MAAM,OAAO;AAAA,QACnC,aAAa,EAAE,UAAU,gBAAgB,MAAM,UAAU;AAAA,QACzD,QAAQ,EAAE,UAAU,UAAU,MAAM,OAAO;AAAA,QAC3C,gBAAgB,EAAE,UAAU,mBAAmB,MAAM,OAAO;AAAA,QAC5D,eAAe,EAAE,UAAU,kBAAkB,MAAM,OAAO;AAAA,QAC1D,aAAa,EAAE,UAAU,eAAe,MAAM,UAAU;AAAA,QACxD,WAAW,EAAE,UAAU,cAAc,MAAM,YAAY;AAAA,QACvD,iBAAiB,EAAE,UAAU,qBAAqB,MAAM,YAAY;AAAA,MACtE;AAAA,MACA,gBAAgB;AAAA,QACd,kBAAkB,EAAE,OAAO,qBAAqB,UAAU,MAAM,aAAa,eAAe;AAAA,MAC9F;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAO,oBAAQ;AACR,MAAM,SAAS;",
6
6
  "names": []
7
7
  }
@@ -18,6 +18,7 @@ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuarde
18
18
  import { flash } from "@open-mercato/ui/backend/FlashMessages";
19
19
  import { useT } from "@open-mercato/shared/lib/i18n/context";
20
20
  import { translateWithFallback } from "@open-mercato/shared/lib/i18n/translate";
21
+ import { registerComponent } from "@open-mercato/shared/modules/widgets/component-registry";
21
22
  const STATUS_OPTIONS = ["open", "in_progress", "win", "loose"];
22
23
  const FALLBACK_CURRENCIES = [
23
24
  { code: "USD", isBase: true },
@@ -25,6 +26,8 @@ const FALLBACK_CURRENCIES = [
25
26
  { code: "GBP" },
26
27
  { code: "PLN" }
27
28
  ];
29
+ const QUICK_DEAL_DIALOG_COMPONENT_ID = "dialog:customers.deals.quickDeal";
30
+ const DEFAULT_QUICK_DEAL_PROBABILITY = 25;
28
31
  const QUICK_DEAL_CONTEXT_ID = "customers-deals-kanban:quick-deal";
29
32
  function QuickDealDialog({
30
33
  open,
@@ -34,7 +37,8 @@ function QuickDealDialog({
34
37
  currentUserId,
35
38
  currentUserLabel,
36
39
  companies = [],
37
- currencies
40
+ currencies,
41
+ defaultProbability = DEFAULT_QUICK_DEAL_PROBABILITY
38
42
  }) {
39
43
  const t = useT();
40
44
  const [formInstanceKey, setFormInstanceKey] = React.useState(0);
@@ -82,11 +86,11 @@ function QuickDealDialog({
82
86
  valueCurrency: defaultCurrencyCode,
83
87
  companyId: "",
84
88
  status: "open",
85
- probability: 25,
89
+ probability: defaultProbability,
86
90
  expectedCloseAt: "",
87
91
  description: ""
88
92
  }),
89
- [defaultCurrencyCode]
93
+ [defaultCurrencyCode, defaultProbability]
90
94
  );
91
95
  const fields = React.useMemo(
92
96
  () => {
@@ -310,8 +314,18 @@ function QuickDealDialog({
310
314
  }
311
315
  );
312
316
  }
317
+ registerComponent({
318
+ id: QUICK_DEAL_DIALOG_COMPONENT_ID,
319
+ component: QuickDealDialog,
320
+ metadata: {
321
+ module: "customers",
322
+ description: 'Kanban quick-add deal dialog (pipeline board "+ deal").'
323
+ }
324
+ });
313
325
  var QuickDealDialog_default = QuickDealDialog;
314
326
  export {
327
+ DEFAULT_QUICK_DEAL_PROBABILITY,
328
+ QUICK_DEAL_DIALOG_COMPONENT_ID,
315
329
  QuickDealDialog,
316
330
  QuickDealDialog_default as default
317
331
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../../src/modules/customers/backend/customers/deals/pipeline/components/QuickDealDialog.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { z } from 'zod'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Avatar } from '@open-mercato/ui/primitives/avatar'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { createCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\n\n// Deal status values written by the kanban flow. These intentionally do NOT include 'closed'\n// because the rest of the app only persists 'loose' for lost deals (see StatusFilterPopover\n// notes). 'in_progress' is kept for backwards compatibility with quick-deals created from\n// the previous version of this dialog. The labels are looked up via i18n at render time so\n// the historic typo 'loose' doesn't leak to operators \u2014 the storage value stays unchanged.\nconst STATUS_OPTIONS = ['open', 'in_progress', 'win', 'loose'] as const\n\n/**\n * Tenant currency option. The page resolves these from the currencies module (see\n * `useCurrencyDictionary`) and passes them in; we no longer hardcode the 4-currency\n * list that previously locked tenants on CZK/SEK/HUF/etc. out of quick-add.\n */\nexport type QuickDealCurrencyOption = {\n code: string\n label?: string\n isBase?: boolean\n}\n\nconst FALLBACK_CURRENCIES: QuickDealCurrencyOption[] = [\n { code: 'USD', isBase: true },\n { code: 'EUR' },\n { code: 'GBP' },\n { code: 'PLN' },\n]\n\nexport type QuickDealContext = {\n pipelineId: string\n pipelineName: string\n pipelineStageId: string\n pipelineStageLabel: string\n}\n\nexport type QuickDealCompanyOption = {\n id: string\n label: string\n}\n\ntype QuickDealDialogProps = {\n open: boolean\n context: QuickDealContext | null\n onClose: () => void\n onCreated: () => void\n currentUserId?: string\n currentUserLabel?: string\n companies?: QuickDealCompanyOption[]\n /**\n * Tenant currency list. When omitted (e.g. dictionary not yet loaded), we render a\n * conservative fallback so the dialog still works end-to-end. The default selection is\n * always the entry with `isBase: true`, falling back to the first item.\n */\n currencies?: QuickDealCurrencyOption[]\n}\n\ntype QuickDealFormValues = {\n title: string\n valueAmount: number | null\n valueCurrency: string\n companyId: string\n status: (typeof STATUS_OPTIONS)[number]\n probability: number | null\n expectedCloseAt: string\n description: string\n}\n\nconst QUICK_DEAL_CONTEXT_ID = 'customers-deals-kanban:quick-deal'\n\nexport function QuickDealDialog({\n open,\n context,\n onClose,\n onCreated,\n currentUserId,\n currentUserLabel,\n companies = [],\n currencies,\n}: QuickDealDialogProps): React.ReactElement | null {\n const t = useT()\n // Re-mount CrudForm whenever the dialog opens so cleared state is consistently fresh.\n // We also key on `context?.pipelineStageId` so reopening from a different stage doesn't\n // reuse stale field values (the page passes a fresh stage in `context` each time).\n const [formInstanceKey, setFormInstanceKey] = React.useState(0)\n React.useEffect(() => {\n if (open) setFormInstanceKey((current) => current + 1)\n }, [open])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({\n contextId: QUICK_DEAL_CONTEXT_ID,\n blockedMessage: translateWithFallback(t, 'ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n const titleRequiredMessage = translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.required',\n 'Title is required.',\n )\n\n // Default currency selection: tenant base currency, else first available, else 'USD' as\n // a last-resort literal that satisfies the form validator (which now accepts any 3-char\n // code rather than a hardcoded enum).\n const resolvedCurrencies = React.useMemo(\n () => (currencies && currencies.length > 0 ? currencies : FALLBACK_CURRENCIES),\n [currencies],\n )\n const defaultCurrencyCode = React.useMemo(() => {\n const base = resolvedCurrencies.find((currency) => currency.isBase)\n return base?.code ?? resolvedCurrencies[0]?.code ?? 'USD'\n }, [resolvedCurrencies])\n\n const formSchema = React.useMemo(\n () =>\n z.object({\n title: z.string().trim().min(1, titleRequiredMessage),\n valueAmount: z.number().min(0).nullable().optional(),\n // The set of valid currencies is tenant-defined and resolved at runtime; we accept\n // any non-empty string here and let the server (which knows the canonical list)\n // reject anything bogus.\n valueCurrency: z.string().min(1),\n companyId: z.string().optional(),\n status: z.enum(STATUS_OPTIONS),\n probability: z.number().min(0).max(100).nullable().optional(),\n expectedCloseAt: z.string().optional(),\n description: z.string().optional(),\n }),\n // Cast widens to QuickDealFormValues so CrudForm's TValues generic stays exact.\n [titleRequiredMessage],\n ) as unknown as z.ZodType<QuickDealFormValues>\n\n const initialValues = React.useMemo<Partial<QuickDealFormValues>>(\n () => ({\n title: '',\n valueAmount: null,\n valueCurrency: defaultCurrencyCode,\n companyId: '',\n status: 'open',\n probability: 25,\n expectedCloseAt: '',\n description: '',\n }),\n [defaultCurrencyCode],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => {\n const list: CrudField[] = [\n {\n // CrudForm auto-focuses the first field of the first group on mount; we don't\n // need (and CrudField doesn't accept) an explicit `autoFocus` prop here.\n id: 'title',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.title.label', 'Deal title'),\n type: 'text',\n required: true,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.placeholder',\n 'e.g. Q3 Expansion \u2014 Lighting Package',\n ),\n },\n {\n id: 'valueAmount',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.value', 'Value'),\n type: 'number',\n layout: 'half',\n placeholder: '0',\n },\n {\n id: 'valueCurrency',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.currency', 'Currency'),\n type: 'select',\n layout: 'half',\n options: resolvedCurrencies.map((currency) => ({\n value: currency.code,\n label: currency.label && currency.label !== currency.code\n ? `${currency.code} \u2014 ${currency.label}`\n : currency.code,\n })),\n },\n {\n // Company is a typeahead (ComboboxInput) rather than a plain <select>: tenants\n // with hundreds of companies get an unusable dropdown otherwise. The `seedOptions`\n // carry the most-recent companies the page already loaded; an async loader could\n // be added later to hit the companies search endpoint for full coverage.\n id: 'companyId',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.company', 'Company'),\n type: 'custom',\n component: ({ value, setValue }) => (\n <ComboboxInput\n value={typeof value === 'string' ? value : ''}\n onChange={(next) => setValue(next)}\n seedOptions={companies.map((company) => ({ value: company.id, label: company.label }))}\n placeholder={translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.companyPh',\n 'Pick a company or add new\u2026',\n )}\n allowCustomValues={false}\n />\n ),\n },\n ]\n // Owner is read-only display of the current user (mirrors original UX). Hidden when\n // we don't know the user \u2014 avoids confusing empty avatar cell.\n if (currentUserLabel) {\n list.push({\n id: 'owner',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.owner', 'Owner'),\n type: 'custom',\n readOnly: true,\n component: () => (\n <div className=\"flex h-9 items-center gap-2 rounded-md border border-input bg-card px-3 text-sm\">\n <Avatar label={currentUserLabel} size=\"sm\" />\n <span>{currentUserLabel}</span>\n </div>\n ),\n })\n }\n // Progressive disclosure: status + probability + close date + description live in\n // a separate \"More details\" group with `defaultExpanded: false` (configured via\n // collapsibleGroups on the host CrudForm).\n list.push(\n {\n id: 'status',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.status', 'Status'),\n type: 'select',\n // Storage value is preserved (`loose` etc.) \u2014 only the displayed label is\n // translated, so we never write a localised string back to the DB.\n options: STATUS_OPTIONS.map((statusValue) => ({\n value: statusValue,\n label: translateWithFallback(\n t,\n `customers.deals.kanban.quickDeal.status.${statusValue}`,\n statusValue,\n ),\n })),\n },\n {\n id: 'probability',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.probability', 'Probability'),\n type: 'number',\n layout: 'half',\n placeholder: '25',\n },\n {\n id: 'expectedCloseAt',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.expectedClose', 'Expected close'),\n type: 'date',\n layout: 'half',\n },\n {\n id: 'description',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.description', 'Description'),\n type: 'textarea',\n rows: 3,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.description.placeholder',\n 'Short context, decision makers or next steps. Markdown supported.',\n ),\n },\n )\n return list\n },\n [companies, currentUserLabel, resolvedCurrencies, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'basic',\n // No title \u2014 keep the basic section flush with the dialog header.\n fields: ['title', 'valueAmount', 'valueCurrency', 'companyId', ...(currentUserLabel ? ['owner'] : [])],\n },\n {\n id: 'more',\n title: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.more',\n 'More details (probability, close date, description)',\n ),\n fields: ['status', 'probability', 'expectedCloseAt', 'description'],\n },\n ],\n [currentUserLabel, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: QuickDealFormValues) => {\n if (!context) return\n const trimmedTitle = values.title.trim()\n if (!trimmedTitle.length) {\n throw createCrudFormError(titleRequiredMessage, { title: titleRequiredMessage })\n }\n const payload: Record<string, unknown> = {\n title: trimmedTitle,\n pipelineId: context.pipelineId,\n pipelineStageId: context.pipelineStageId,\n valueCurrency: values.valueCurrency,\n }\n if (typeof values.valueAmount === 'number' && Number.isFinite(values.valueAmount)) {\n payload.valueAmount = values.valueAmount\n }\n if (currentUserId) payload.ownerUserId = currentUserId\n if (values.companyId) payload.companyIds = [values.companyId]\n if (values.status) payload.status = values.status\n if (typeof values.probability === 'number' && Number.isFinite(values.probability)) {\n payload.probability = values.probability\n }\n if (values.expectedCloseAt && values.expectedCloseAt.trim().length) {\n payload.expectedCloseAt = values.expectedCloseAt\n }\n if (values.description && values.description.trim().length) {\n payload.description = values.description\n }\n const operation = () =>\n createCrud('customers/deals', payload, {\n errorMessage: translateWithFallback(t, 'customers.deals.create.error', 'Failed to create deal.'),\n })\n await runMutation({\n operation,\n context: {\n formId: QUICK_DEAL_CONTEXT_ID,\n resourceKind: 'customers.deal',\n retryLastMutation,\n },\n })\n flash(\n translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.success',\n 'Deal added to {stage}.',\n { stage: context.pipelineStageLabel },\n ),\n 'success',\n )\n onCreated()\n onClose()\n },\n [context, currentUserId, onClose, onCreated, retryLastMutation, runMutation, t, titleRequiredMessage],\n )\n\n if (!context) return null\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) onClose()\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {translateWithFallback(t, 'customers.deals.kanban.quickDeal.title', 'Quick deal')}\n </DialogTitle>\n <DialogDescription>\n {translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.context',\n 'Pipeline: {pipeline} \u00B7 Stage: {stage}',\n { pipeline: context.pipelineName, stage: context.pipelineStageLabel },\n )}\n </DialogDescription>\n </DialogHeader>\n\n <CrudForm<QuickDealFormValues>\n key={`${context.pipelineStageId}:${formInstanceKey}`}\n embedded\n fields={fields}\n groups={groups}\n // The \"More details\" group starts collapsed; users can expand to set\n // status / probability / close date / description. Mirrors the previous\n // \"+ More details\" toggle.\n collapsibleGroups={{ pageType: 'customers.deals.kanban.quickDeal' }}\n initialValues={initialValues}\n schema={formSchema}\n submitLabel={translateWithFallback(t, 'customers.deals.kanban.quickDeal.submit', 'Add deal')}\n onSubmit={handleSubmit}\n />\n </DialogContent>\n </Dialog>\n )\n}\n\nexport default QuickDealDialog\n"],
5
- "mappings": ";AAkNY,cAuBA,YAvBA;AAhNZ,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,gBAAoD;AAC7D,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AAOtC,MAAM,iBAAiB,CAAC,QAAQ,eAAe,OAAO,OAAO;AAa7D,MAAM,sBAAiD;AAAA,EACrD,EAAE,MAAM,OAAO,QAAQ,KAAK;AAAA,EAC5B,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAChB;AAyCA,MAAM,wBAAwB;AAEvB,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,YAAY,CAAC;AAAA,EACb;AACF,GAAo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;AAAA,UAXL,GAAG,QAAQ,eAAe,IAAI,eAAe;AAAA,QAYpD;AAAA,SACF;AAAA;AAAA,EACF;AAEJ;AAEA,IAAO,0BAAQ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { z } from 'zod'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogHeader,\n DialogTitle,\n} from '@open-mercato/ui/primitives/dialog'\nimport { Avatar } from '@open-mercato/ui/primitives/avatar'\nimport { CrudForm, type CrudField, type CrudFormGroup } from '@open-mercato/ui/backend/CrudForm'\nimport { ComboboxInput } from '@open-mercato/ui/backend/inputs/ComboboxInput'\nimport { createCrud } from '@open-mercato/ui/backend/utils/crud'\nimport { createCrudFormError } from '@open-mercato/ui/backend/utils/serverErrors'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { translateWithFallback } from '@open-mercato/shared/lib/i18n/translate'\nimport { registerComponent } from '@open-mercato/shared/modules/widgets/component-registry'\n\n// Deal status values written by the kanban flow. These intentionally do NOT include 'closed'\n// because the rest of the app only persists 'loose' for lost deals (see StatusFilterPopover\n// notes). 'in_progress' is kept for backwards compatibility with quick-deals created from\n// the previous version of this dialog. The labels are looked up via i18n at render time so\n// the historic typo 'loose' doesn't leak to operators \u2014 the storage value stays unchanged.\nconst STATUS_OPTIONS = ['open', 'in_progress', 'win', 'loose'] as const\n\n/**\n * Tenant currency option. The page resolves these from the currencies module (see\n * `useCurrencyDictionary`) and passes them in; we no longer hardcode the 4-currency\n * list that previously locked tenants on CZK/SEK/HUF/etc. out of quick-add.\n */\nexport type QuickDealCurrencyOption = {\n code: string\n label?: string\n isBase?: boolean\n}\n\nconst FALLBACK_CURRENCIES: QuickDealCurrencyOption[] = [\n { code: 'USD', isBase: true },\n { code: 'EUR' },\n { code: 'GBP' },\n { code: 'PLN' },\n]\n\nexport type QuickDealContext = {\n pipelineId: string\n pipelineName: string\n pipelineStageId: string\n pipelineStageLabel: string\n}\n\nexport type QuickDealCompanyOption = {\n id: string\n label: string\n}\n\n/**\n * Registered component id for the kanban quick-add dialog. Downstream apps can\n * target it from `widgets/components.ts` to replace/wrap the dialog or to\n * transform its props \u2014 e.g. `defaultProbability: null` so quick-create stops\n * seeding a probability that overrides pipeline automation (#4329).\n */\nexport const QUICK_DEAL_DIALOG_COMPONENT_ID = 'dialog:customers.deals.quickDeal'\n\n/** Probability seeded into the quick-add form when the host passes no override. */\nexport const DEFAULT_QUICK_DEAL_PROBABILITY = 25\n\nexport type QuickDealDialogProps = {\n open: boolean\n context: QuickDealContext | null\n onClose: () => void\n onCreated: () => void\n currentUserId?: string\n currentUserLabel?: string\n companies?: QuickDealCompanyOption[]\n /**\n * Probability pre-filled in the collapsed \"More details\" group. `null` leaves\n * the field empty, so quick-create sends no `probability` at all and whatever\n * the pipeline/automation derives for the target stage stands. Defaults to\n * `DEFAULT_QUICK_DEAL_PROBABILITY` to preserve the historic behavior.\n */\n defaultProbability?: number | null\n /**\n * Tenant currency list. When omitted (e.g. dictionary not yet loaded), we render a\n * conservative fallback so the dialog still works end-to-end. The default selection is\n * always the entry with `isBase: true`, falling back to the first item.\n */\n currencies?: QuickDealCurrencyOption[]\n}\n\ntype QuickDealFormValues = {\n title: string\n valueAmount: number | null\n valueCurrency: string\n companyId: string\n status: (typeof STATUS_OPTIONS)[number]\n probability: number | null\n expectedCloseAt: string\n description: string\n}\n\nconst QUICK_DEAL_CONTEXT_ID = 'customers-deals-kanban:quick-deal'\n\nexport function QuickDealDialog({\n open,\n context,\n onClose,\n onCreated,\n currentUserId,\n currentUserLabel,\n companies = [],\n currencies,\n defaultProbability = DEFAULT_QUICK_DEAL_PROBABILITY,\n}: QuickDealDialogProps): React.ReactElement | null {\n const t = useT()\n // Re-mount CrudForm whenever the dialog opens so cleared state is consistently fresh.\n // We also key on `context?.pipelineStageId` so reopening from a different stage doesn't\n // reuse stale field values (the page passes a fresh stage in `context` each time).\n const [formInstanceKey, setFormInstanceKey] = React.useState(0)\n React.useEffect(() => {\n if (open) setFormInstanceKey((current) => current + 1)\n }, [open])\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n }>({\n contextId: QUICK_DEAL_CONTEXT_ID,\n blockedMessage: translateWithFallback(t, 'ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n const titleRequiredMessage = translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.required',\n 'Title is required.',\n )\n\n // Default currency selection: tenant base currency, else first available, else 'USD' as\n // a last-resort literal that satisfies the form validator (which now accepts any 3-char\n // code rather than a hardcoded enum).\n const resolvedCurrencies = React.useMemo(\n () => (currencies && currencies.length > 0 ? currencies : FALLBACK_CURRENCIES),\n [currencies],\n )\n const defaultCurrencyCode = React.useMemo(() => {\n const base = resolvedCurrencies.find((currency) => currency.isBase)\n return base?.code ?? resolvedCurrencies[0]?.code ?? 'USD'\n }, [resolvedCurrencies])\n\n const formSchema = React.useMemo(\n () =>\n z.object({\n title: z.string().trim().min(1, titleRequiredMessage),\n valueAmount: z.number().min(0).nullable().optional(),\n // The set of valid currencies is tenant-defined and resolved at runtime; we accept\n // any non-empty string here and let the server (which knows the canonical list)\n // reject anything bogus.\n valueCurrency: z.string().min(1),\n companyId: z.string().optional(),\n status: z.enum(STATUS_OPTIONS),\n probability: z.number().min(0).max(100).nullable().optional(),\n expectedCloseAt: z.string().optional(),\n description: z.string().optional(),\n }),\n // Cast widens to QuickDealFormValues so CrudForm's TValues generic stays exact.\n [titleRequiredMessage],\n ) as unknown as z.ZodType<QuickDealFormValues>\n\n const initialValues = React.useMemo<Partial<QuickDealFormValues>>(\n () => ({\n title: '',\n valueAmount: null,\n valueCurrency: defaultCurrencyCode,\n companyId: '',\n status: 'open',\n probability: defaultProbability,\n expectedCloseAt: '',\n description: '',\n }),\n [defaultCurrencyCode, defaultProbability],\n )\n\n const fields = React.useMemo<CrudField[]>(\n () => {\n const list: CrudField[] = [\n {\n // CrudForm auto-focuses the first field of the first group on mount; we don't\n // need (and CrudField doesn't accept) an explicit `autoFocus` prop here.\n id: 'title',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.title.label', 'Deal title'),\n type: 'text',\n required: true,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.title.placeholder',\n 'e.g. Q3 Expansion \u2014 Lighting Package',\n ),\n },\n {\n id: 'valueAmount',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.value', 'Value'),\n type: 'number',\n layout: 'half',\n placeholder: '0',\n },\n {\n id: 'valueCurrency',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.currency', 'Currency'),\n type: 'select',\n layout: 'half',\n options: resolvedCurrencies.map((currency) => ({\n value: currency.code,\n label: currency.label && currency.label !== currency.code\n ? `${currency.code} \u2014 ${currency.label}`\n : currency.code,\n })),\n },\n {\n // Company is a typeahead (ComboboxInput) rather than a plain <select>: tenants\n // with hundreds of companies get an unusable dropdown otherwise. The `seedOptions`\n // carry the most-recent companies the page already loaded; an async loader could\n // be added later to hit the companies search endpoint for full coverage.\n id: 'companyId',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.company', 'Company'),\n type: 'custom',\n component: ({ value, setValue }) => (\n <ComboboxInput\n value={typeof value === 'string' ? value : ''}\n onChange={(next) => setValue(next)}\n seedOptions={companies.map((company) => ({ value: company.id, label: company.label }))}\n placeholder={translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.companyPh',\n 'Pick a company or add new\u2026',\n )}\n allowCustomValues={false}\n />\n ),\n },\n ]\n // Owner is read-only display of the current user (mirrors original UX). Hidden when\n // we don't know the user \u2014 avoids confusing empty avatar cell.\n if (currentUserLabel) {\n list.push({\n id: 'owner',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.owner', 'Owner'),\n type: 'custom',\n readOnly: true,\n component: () => (\n <div className=\"flex h-9 items-center gap-2 rounded-md border border-input bg-card px-3 text-sm\">\n <Avatar label={currentUserLabel} size=\"sm\" />\n <span>{currentUserLabel}</span>\n </div>\n ),\n })\n }\n // Progressive disclosure: status + probability + close date + description live in\n // a separate \"More details\" group with `defaultExpanded: false` (configured via\n // collapsibleGroups on the host CrudForm).\n list.push(\n {\n id: 'status',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.status', 'Status'),\n type: 'select',\n // Storage value is preserved (`loose` etc.) \u2014 only the displayed label is\n // translated, so we never write a localised string back to the DB.\n options: STATUS_OPTIONS.map((statusValue) => ({\n value: statusValue,\n label: translateWithFallback(\n t,\n `customers.deals.kanban.quickDeal.status.${statusValue}`,\n statusValue,\n ),\n })),\n },\n {\n id: 'probability',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.probability', 'Probability'),\n type: 'number',\n layout: 'half',\n placeholder: '25',\n },\n {\n id: 'expectedCloseAt',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.expectedClose', 'Expected close'),\n type: 'date',\n layout: 'half',\n },\n {\n id: 'description',\n label: translateWithFallback(t, 'customers.deals.kanban.quickDeal.description', 'Description'),\n type: 'textarea',\n rows: 3,\n placeholder: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.description.placeholder',\n 'Short context, decision makers or next steps. Markdown supported.',\n ),\n },\n )\n return list\n },\n [companies, currentUserLabel, resolvedCurrencies, t],\n )\n\n const groups = React.useMemo<CrudFormGroup[]>(\n () => [\n {\n id: 'basic',\n // No title \u2014 keep the basic section flush with the dialog header.\n fields: ['title', 'valueAmount', 'valueCurrency', 'companyId', ...(currentUserLabel ? ['owner'] : [])],\n },\n {\n id: 'more',\n title: translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.more',\n 'More details (probability, close date, description)',\n ),\n fields: ['status', 'probability', 'expectedCloseAt', 'description'],\n },\n ],\n [currentUserLabel, t],\n )\n\n const handleSubmit = React.useCallback(\n async (values: QuickDealFormValues) => {\n if (!context) return\n const trimmedTitle = values.title.trim()\n if (!trimmedTitle.length) {\n throw createCrudFormError(titleRequiredMessage, { title: titleRequiredMessage })\n }\n const payload: Record<string, unknown> = {\n title: trimmedTitle,\n pipelineId: context.pipelineId,\n pipelineStageId: context.pipelineStageId,\n valueCurrency: values.valueCurrency,\n }\n if (typeof values.valueAmount === 'number' && Number.isFinite(values.valueAmount)) {\n payload.valueAmount = values.valueAmount\n }\n if (currentUserId) payload.ownerUserId = currentUserId\n if (values.companyId) payload.companyIds = [values.companyId]\n if (values.status) payload.status = values.status\n if (typeof values.probability === 'number' && Number.isFinite(values.probability)) {\n payload.probability = values.probability\n }\n if (values.expectedCloseAt && values.expectedCloseAt.trim().length) {\n payload.expectedCloseAt = values.expectedCloseAt\n }\n if (values.description && values.description.trim().length) {\n payload.description = values.description\n }\n const operation = () =>\n createCrud('customers/deals', payload, {\n errorMessage: translateWithFallback(t, 'customers.deals.create.error', 'Failed to create deal.'),\n })\n await runMutation({\n operation,\n context: {\n formId: QUICK_DEAL_CONTEXT_ID,\n resourceKind: 'customers.deal',\n retryLastMutation,\n },\n })\n flash(\n translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.success',\n 'Deal added to {stage}.',\n { stage: context.pipelineStageLabel },\n ),\n 'success',\n )\n onCreated()\n onClose()\n },\n [context, currentUserId, onClose, onCreated, retryLastMutation, runMutation, t, titleRequiredMessage],\n )\n\n if (!context) return null\n\n return (\n <Dialog\n open={open}\n onOpenChange={(next) => {\n if (!next) onClose()\n }}\n >\n <DialogContent>\n <DialogHeader>\n <DialogTitle>\n {translateWithFallback(t, 'customers.deals.kanban.quickDeal.title', 'Quick deal')}\n </DialogTitle>\n <DialogDescription>\n {translateWithFallback(\n t,\n 'customers.deals.kanban.quickDeal.context',\n 'Pipeline: {pipeline} \u00B7 Stage: {stage}',\n { pipeline: context.pipelineName, stage: context.pipelineStageLabel },\n )}\n </DialogDescription>\n </DialogHeader>\n\n <CrudForm<QuickDealFormValues>\n key={`${context.pipelineStageId}:${formInstanceKey}`}\n embedded\n fields={fields}\n groups={groups}\n // The \"More details\" group starts collapsed; users can expand to set\n // status / probability / close date / description. Mirrors the previous\n // \"+ More details\" toggle.\n collapsibleGroups={{ pageType: 'customers.deals.kanban.quickDeal' }}\n initialValues={initialValues}\n schema={formSchema}\n submitLabel={translateWithFallback(t, 'customers.deals.kanban.quickDeal.submit', 'Add deal')}\n onSubmit={handleSubmit}\n />\n </DialogContent>\n </Dialog>\n )\n}\n\n// Register so downstream apps can reach the dialog from `widgets/components.ts`\n// (replace / wrap / propsTransform) instead of forking the whole kanban page\n// just to change a default (#4329).\nregisterComponent<QuickDealDialogProps>({\n id: QUICK_DEAL_DIALOG_COMPONENT_ID,\n component: QuickDealDialog,\n metadata: {\n module: 'customers',\n description: 'Kanban quick-add deal dialog (pipeline board \"+ deal\").',\n },\n})\n\nexport default QuickDealDialog\n"],
5
+ "mappings": ";AAsOY,cAuBA,YAvBA;AApOZ,YAAY,WAAW;AACvB,SAAS,SAAS;AAClB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,cAAc;AACvB,SAAS,gBAAoD;AAC7D,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,0BAA0B;AACnC,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB,SAAS,6BAA6B;AACtC,SAAS,yBAAyB;AAOlC,MAAM,iBAAiB,CAAC,QAAQ,eAAe,OAAO,OAAO;AAa7D,MAAM,sBAAiD;AAAA,EACrD,EAAE,MAAM,OAAO,QAAQ,KAAK;AAAA,EAC5B,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAAA,EACd,EAAE,MAAM,MAAM;AAChB;AAoBO,MAAM,iCAAiC;AAGvC,MAAM,iCAAiC;AAoC9C,MAAM,wBAAwB;AAEvB,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EAC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AAE,UAAU,mCAAmC;AAAA,YAClE;AAAA,YACA,QAAQ;AAAA,YACR,aAAa,sBAAsB,GAAG,2CAA2C,UAAU;AAAA,YAC3F,UAAU;AAAA;AAAA,UAXL,GAAG,QAAQ,eAAe,IAAI,eAAe;AAAA,QAYpD;AAAA,SACF;AAAA;AAAA,EACF;AAEJ;AAKA,kBAAwC;AAAA,EACtC,IAAI;AAAA,EACJ,WAAW;AAAA,EACX,UAAU;AAAA,IACR,QAAQ;AAAA,IACR,aAAa;AAAA,EACf;AACF,CAAC;AAED,IAAO,0BAAQ;",
6
6
  "names": []
7
7
  }
@@ -58,7 +58,8 @@ import { LaneCurrencyBreakdown } from "./components/LaneCurrencyBreakdown.js";
58
58
  import { CurrencyFilterPopover } from "./components/CurrencyFilterPopover.js";
59
59
  import { AddStageLane } from "./components/AddStageLane.js";
60
60
  import {
61
- QuickDealDialog
61
+ QuickDealDialog as DefaultQuickDealDialog,
62
+ QUICK_DEAL_DIALOG_COMPONENT_ID
62
63
  } from "./components/QuickDealDialog.js";
63
64
  import { AddStageDialog } from "./components/AddStageDialog.js";
64
65
  import { StatusFilterPopover } from "./components/StatusFilterPopover.js";
@@ -71,6 +72,7 @@ import {
71
72
  ActivityComposerDialog
72
73
  } from "./components/ActivityComposerDialog.js";
73
74
  import { BulkActionsBar } from "./components/BulkActionsBar.js";
75
+ import { useRegisteredComponent } from "@open-mercato/ui/backend/injection/useRegisteredComponent";
74
76
  import { ChangeStageDialog } from "./components/ChangeStageDialog.js";
75
77
  import { ChangeOwnerDialog } from "./components/ChangeOwnerDialog.js";
76
78
  import { buildCrudExportUrl, deleteCrud } from "@open-mercato/ui/backend/utils/crud";
@@ -278,6 +280,10 @@ function sortDeals(deals, option) {
278
280
  }
279
281
  function DealsKanbanPage() {
280
282
  const t = useT();
283
+ const QuickDealDialog = useRegisteredComponent(
284
+ QUICK_DEAL_DIALOG_COMPONENT_ID,
285
+ DefaultQuickDealDialog
286
+ );
281
287
  const router = useRouter();
282
288
  const scopeVersion = useOrganizationScopeVersion();
283
289
  const queryClient = useQueryClient();