@open-mercato/core 0.6.5-develop.4384.1.ce2ec6eaaa → 0.6.5-develop.4393.1.de282b5dfd

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 (533) hide show
  1. package/.turbo/turbo-build.log +2 -2
  2. package/dist/generated/entities/channel_ingest_dead_letter/index.js +25 -0
  3. package/dist/generated/entities/channel_ingest_dead_letter/index.js.map +7 -0
  4. package/dist/generated/entities/channel_thread_mapping/index.js +25 -0
  5. package/dist/generated/entities/channel_thread_mapping/index.js.map +7 -0
  6. package/dist/generated/entities/channel_thread_token/index.js +17 -0
  7. package/dist/generated/entities/channel_thread_token/index.js.map +7 -0
  8. package/dist/generated/entities/communication_channel/index.js +43 -0
  9. package/dist/generated/entities/communication_channel/index.js.map +7 -0
  10. package/dist/generated/entities/customer_interaction/index.js +4 -0
  11. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  12. package/dist/generated/entities/external_conversation/index.js +25 -0
  13. package/dist/generated/entities/external_conversation/index.js.map +7 -0
  14. package/dist/generated/entities/external_message/index.js +25 -0
  15. package/dist/generated/entities/external_message/index.js.map +7 -0
  16. package/dist/generated/entities/integration_credentials/index.js +3 -1
  17. package/dist/generated/entities/integration_credentials/index.js.map +2 -2
  18. package/dist/generated/entities/message/index.js +2 -0
  19. package/dist/generated/entities/message/index.js.map +2 -2
  20. package/dist/generated/entities/message_channel_link/index.js +33 -0
  21. package/dist/generated/entities/message_channel_link/index.js.map +7 -0
  22. package/dist/generated/entities/message_reaction/index.js +25 -0
  23. package/dist/generated/entities/message_reaction/index.js.map +7 -0
  24. package/dist/generated/entities.ids.generated.js +11 -0
  25. package/dist/generated/entities.ids.generated.js.map +2 -2
  26. package/dist/generated/entity-fields-registry.js +117 -0
  27. package/dist/generated/entity-fields-registry.js.map +2 -2
  28. package/dist/helpers/integration/authFixtures.js +2 -1
  29. package/dist/helpers/integration/authFixtures.js.map +2 -2
  30. package/dist/helpers/integration/communicationChannelsFixtures.js +58 -0
  31. package/dist/helpers/integration/communicationChannelsFixtures.js.map +7 -0
  32. package/dist/modules/communication_channels/acl.js +47 -0
  33. package/dist/modules/communication_channels/acl.js.map +7 -0
  34. package/dist/modules/communication_channels/api/delete/channels/[id]/route.js +133 -0
  35. package/dist/modules/communication_channels/api/delete/channels/[id]/route.js.map +7 -0
  36. package/dist/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.js +113 -0
  37. package/dist/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.js.map +7 -0
  38. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js +138 -0
  39. package/dist/modules/communication_channels/api/get/channels/[id]/health/route.js.map +7 -0
  40. package/dist/modules/communication_channels/api/get/channels/[id]/route.js +93 -0
  41. package/dist/modules/communication_channels/api/get/channels/[id]/route.js.map +7 -0
  42. package/dist/modules/communication_channels/api/get/channels/route.js +96 -0
  43. package/dist/modules/communication_channels/api/get/channels/route.js.map +7 -0
  44. package/dist/modules/communication_channels/api/get/me/channels/route.js +82 -0
  45. package/dist/modules/communication_channels/api/get/me/channels/route.js.map +7 -0
  46. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +274 -0
  47. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +7 -0
  48. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js +168 -0
  49. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js.map +7 -0
  50. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js +143 -0
  51. package/dist/modules/communication_channels/api/post/channels/[id]/poll-now/route.js.map +7 -0
  52. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js +127 -0
  53. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js.map +7 -0
  54. package/dist/modules/communication_channels/api/post/channels/[id]/set-primary/route.js +99 -0
  55. package/dist/modules/communication_channels/api/post/channels/[id]/set-primary/route.js.map +7 -0
  56. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js +197 -0
  57. package/dist/modules/communication_channels/api/post/channels/[id]/test-send/route.js.map +7 -0
  58. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +124 -0
  59. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +7 -0
  60. package/dist/modules/communication_channels/api/post/messages/[messageId]/reactions/route.js +120 -0
  61. package/dist/modules/communication_channels/api/post/messages/[messageId]/reactions/route.js.map +7 -0
  62. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +157 -0
  63. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +7 -0
  64. package/dist/modules/communication_channels/api/post/send-as-user/route.js +115 -0
  65. package/dist/modules/communication_channels/api/post/send-as-user/route.js.map +7 -0
  66. package/dist/modules/communication_channels/api/post/test-seed/route.js +217 -0
  67. package/dist/modules/communication_channels/api/post/test-seed/route.js.map +7 -0
  68. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js +175 -0
  69. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js.map +7 -0
  70. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js +123 -0
  71. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js.map +7 -0
  72. package/dist/modules/communication_channels/api/put/threads/[threadId]/assign/route.js +117 -0
  73. package/dist/modules/communication_channels/api/put/threads/[threadId]/assign/route.js.map +7 -0
  74. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.js +180 -0
  75. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.js.map +7 -0
  76. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.js +36 -0
  77. package/dist/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.js.map +7 -0
  78. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js +107 -0
  79. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js.map +7 -0
  80. package/dist/modules/communication_channels/backend/communication_channels/channels/page.meta.js +38 -0
  81. package/dist/modules/communication_channels/backend/communication_channels/channels/page.meta.js.map +7 -0
  82. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js +727 -0
  83. package/dist/modules/communication_channels/backend/profile/communication-channels/page.js.map +7 -0
  84. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js +38 -0
  85. package/dist/modules/communication_channels/backend/profile/communication-channels/page.meta.js.map +7 -0
  86. package/dist/modules/communication_channels/commands/connect-credential-channel.js +154 -0
  87. package/dist/modules/communication_channels/commands/connect-credential-channel.js.map +7 -0
  88. package/dist/modules/communication_channels/commands/delete-channel.js +137 -0
  89. package/dist/modules/communication_channels/commands/delete-channel.js.map +7 -0
  90. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +400 -0
  91. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +7 -0
  92. package/dist/modules/communication_channels/commands/disconnect-channel.js +163 -0
  93. package/dist/modules/communication_channels/commands/disconnect-channel.js.map +7 -0
  94. package/dist/modules/communication_channels/commands/ingest-inbound-message.js +413 -0
  95. package/dist/modules/communication_channels/commands/ingest-inbound-message.js.map +7 -0
  96. package/dist/modules/communication_channels/commands/interceptors.js +68 -0
  97. package/dist/modules/communication_channels/commands/interceptors.js.map +7 -0
  98. package/dist/modules/communication_channels/commands/process-inbound-reaction.js +198 -0
  99. package/dist/modules/communication_channels/commands/process-inbound-reaction.js.map +7 -0
  100. package/dist/modules/communication_channels/commands/push-register.js +146 -0
  101. package/dist/modules/communication_channels/commands/push-register.js.map +7 -0
  102. package/dist/modules/communication_channels/commands/push-renew.js +23 -0
  103. package/dist/modules/communication_channels/commands/push-renew.js.map +7 -0
  104. package/dist/modules/communication_channels/commands/push-unregister.js +108 -0
  105. package/dist/modules/communication_channels/commands/push-unregister.js.map +7 -0
  106. package/dist/modules/communication_channels/commands/queue-import-history.js +113 -0
  107. package/dist/modules/communication_channels/commands/queue-import-history.js.map +7 -0
  108. package/dist/modules/communication_channels/commands/reassign-conversation.js +193 -0
  109. package/dist/modules/communication_channels/commands/reassign-conversation.js.map +7 -0
  110. package/dist/modules/communication_channels/commands/set-primary-channel.js +114 -0
  111. package/dist/modules/communication_channels/commands/set-primary-channel.js.map +7 -0
  112. package/dist/modules/communication_channels/commands/toggle-outbound-reaction.js +260 -0
  113. package/dist/modules/communication_channels/commands/toggle-outbound-reaction.js.map +7 -0
  114. package/dist/modules/communication_channels/data/enrichers.js +286 -0
  115. package/dist/modules/communication_channels/data/enrichers.js.map +7 -0
  116. package/dist/modules/communication_channels/data/entities.js +447 -0
  117. package/dist/modules/communication_channels/data/entities.js.map +7 -0
  118. package/dist/modules/communication_channels/data/extensions.js +67 -0
  119. package/dist/modules/communication_channels/data/extensions.js.map +7 -0
  120. package/dist/modules/communication_channels/data/validators.js +123 -0
  121. package/dist/modules/communication_channels/data/validators.js.map +7 -0
  122. package/dist/modules/communication_channels/di.js +35 -0
  123. package/dist/modules/communication_channels/di.js.map +7 -0
  124. package/dist/modules/communication_channels/encryption.js +12 -0
  125. package/dist/modules/communication_channels/encryption.js.map +7 -0
  126. package/dist/modules/communication_channels/events.js +124 -0
  127. package/dist/modules/communication_channels/events.js.map +7 -0
  128. package/dist/modules/communication_channels/index.js +20 -0
  129. package/dist/modules/communication_channels/index.js.map +7 -0
  130. package/dist/modules/communication_channels/lib/access-control.js +43 -0
  131. package/dist/modules/communication_channels/lib/access-control.js.map +7 -0
  132. package/dist/modules/communication_channels/lib/adapter-compat.js +36 -0
  133. package/dist/modules/communication_channels/lib/adapter-compat.js.map +7 -0
  134. package/dist/modules/communication_channels/lib/adapter-registry-singleton.js +22 -0
  135. package/dist/modules/communication_channels/lib/adapter-registry-singleton.js.map +7 -0
  136. package/dist/modules/communication_channels/lib/adapter.js +1 -0
  137. package/dist/modules/communication_channels/lib/adapter.js.map +7 -0
  138. package/dist/modules/communication_channels/lib/connect-channel.js +95 -0
  139. package/dist/modules/communication_channels/lib/connect-channel.js.map +7 -0
  140. package/dist/modules/communication_channels/lib/contact-resolver.js +79 -0
  141. package/dist/modules/communication_channels/lib/contact-resolver.js.map +7 -0
  142. package/dist/modules/communication_channels/lib/credential-refresh.js +97 -0
  143. package/dist/modules/communication_channels/lib/credential-refresh.js.map +7 -0
  144. package/dist/modules/communication_channels/lib/dead-letter.js +62 -0
  145. package/dist/modules/communication_channels/lib/dead-letter.js.map +7 -0
  146. package/dist/modules/communication_channels/lib/email-capabilities.js +47 -0
  147. package/dist/modules/communication_channels/lib/email-capabilities.js.map +7 -0
  148. package/dist/modules/communication_channels/lib/email-contact.js +14 -0
  149. package/dist/modules/communication_channels/lib/email-contact.js.map +7 -0
  150. package/dist/modules/communication_channels/lib/email-mime.js +259 -0
  151. package/dist/modules/communication_channels/lib/email-mime.js.map +7 -0
  152. package/dist/modules/communication_channels/lib/error-classification.js +101 -0
  153. package/dist/modules/communication_channels/lib/error-classification.js.map +7 -0
  154. package/dist/modules/communication_channels/lib/gmail-pubsub-jwt.js +185 -0
  155. package/dist/modules/communication_channels/lib/gmail-pubsub-jwt.js.map +7 -0
  156. package/dist/modules/communication_channels/lib/mutation-guards.js +114 -0
  157. package/dist/modules/communication_channels/lib/mutation-guards.js.map +7 -0
  158. package/dist/modules/communication_channels/lib/oauth-client-config.js +32 -0
  159. package/dist/modules/communication_channels/lib/oauth-client-config.js.map +7 -0
  160. package/dist/modules/communication_channels/lib/oauth-state.js +128 -0
  161. package/dist/modules/communication_channels/lib/oauth-state.js.map +7 -0
  162. package/dist/modules/communication_channels/lib/oauth-token.js +45 -0
  163. package/dist/modules/communication_channels/lib/oauth-token.js.map +7 -0
  164. package/dist/modules/communication_channels/lib/pg-errors.js +11 -0
  165. package/dist/modules/communication_channels/lib/pg-errors.js.map +7 -0
  166. package/dist/modules/communication_channels/lib/provider-health.js +24 -0
  167. package/dist/modules/communication_channels/lib/provider-health.js.map +7 -0
  168. package/dist/modules/communication_channels/lib/push-state.js +19 -0
  169. package/dist/modules/communication_channels/lib/push-state.js.map +7 -0
  170. package/dist/modules/communication_channels/lib/queue.js +54 -0
  171. package/dist/modules/communication_channels/lib/queue.js.map +7 -0
  172. package/dist/modules/communication_channels/lib/reaction-processor-types.js +5 -0
  173. package/dist/modules/communication_channels/lib/reaction-processor-types.js.map +7 -0
  174. package/dist/modules/communication_channels/lib/reaction-semantics.js +11 -0
  175. package/dist/modules/communication_channels/lib/reaction-semantics.js.map +7 -0
  176. package/dist/modules/communication_channels/lib/registry.js +67 -0
  177. package/dist/modules/communication_channels/lib/registry.js.map +7 -0
  178. package/dist/modules/communication_channels/lib/route-mutation-guard.js +43 -0
  179. package/dist/modules/communication_channels/lib/route-mutation-guard.js.map +7 -0
  180. package/dist/modules/communication_channels/lib/sanitize-channel-html.js +96 -0
  181. package/dist/modules/communication_channels/lib/sanitize-channel-html.js.map +7 -0
  182. package/dist/modules/communication_channels/lib/send-as-user.js +194 -0
  183. package/dist/modules/communication_channels/lib/send-as-user.js.map +7 -0
  184. package/dist/modules/communication_channels/lib/system-user.js +22 -0
  185. package/dist/modules/communication_channels/lib/system-user.js.map +7 -0
  186. package/dist/modules/communication_channels/lib/test-seed.js +68 -0
  187. package/dist/modules/communication_channels/lib/test-seed.js.map +7 -0
  188. package/dist/modules/communication_channels/lib/thread-matcher.js +263 -0
  189. package/dist/modules/communication_channels/lib/thread-matcher.js.map +7 -0
  190. package/dist/modules/communication_channels/lib/thread-token.js +219 -0
  191. package/dist/modules/communication_channels/lib/thread-token.js.map +7 -0
  192. package/dist/modules/communication_channels/lib/use-connect-channel.js +61 -0
  193. package/dist/modules/communication_channels/lib/use-connect-channel.js.map +7 -0
  194. package/dist/modules/communication_channels/migrations/Migration20260526134719_communication_channels.js +50 -0
  195. package/dist/modules/communication_channels/migrations/Migration20260526134719_communication_channels.js.map +7 -0
  196. package/dist/modules/communication_channels/migrations/Migration20260527195446_communication_channels.js +19 -0
  197. package/dist/modules/communication_channels/migrations/Migration20260527195446_communication_channels.js.map +7 -0
  198. package/dist/modules/communication_channels/migrations/Migration20260529231848_communication_channels.js +13 -0
  199. package/dist/modules/communication_channels/migrations/Migration20260529231848_communication_channels.js.map +7 -0
  200. package/dist/modules/communication_channels/migrations/Migration20260531120000_communication_channels.js +17 -0
  201. package/dist/modules/communication_channels/migrations/Migration20260531120000_communication_channels.js.map +7 -0
  202. package/dist/modules/communication_channels/notifications.client.js +51 -0
  203. package/dist/modules/communication_channels/notifications.client.js.map +7 -0
  204. package/dist/modules/communication_channels/notifications.handlers.js +53 -0
  205. package/dist/modules/communication_channels/notifications.handlers.js.map +7 -0
  206. package/dist/modules/communication_channels/notifications.js +56 -0
  207. package/dist/modules/communication_channels/notifications.js.map +7 -0
  208. package/dist/modules/communication_channels/setup.js +105 -0
  209. package/dist/modules/communication_channels/setup.js.map +7 -0
  210. package/dist/modules/communication_channels/subscribers/channel-requires-reauth-notification.js +71 -0
  211. package/dist/modules/communication_channels/subscribers/channel-requires-reauth-notification.js.map +7 -0
  212. package/dist/modules/communication_channels/subscribers/outbound-bridge.js +103 -0
  213. package/dist/modules/communication_channels/subscribers/outbound-bridge.js.map +7 -0
  214. package/dist/modules/communication_channels/subscribers/user-deleted-cascade.js +51 -0
  215. package/dist/modules/communication_channels/subscribers/user-deleted-cascade.js.map +7 -0
  216. package/dist/modules/communication_channels/widgets/components.js +7 -0
  217. package/dist/modules/communication_channels/widgets/components.js.map +7 -0
  218. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.client.js +18 -0
  219. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.client.js.map +7 -0
  220. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.js +30 -0
  221. package/dist/modules/communication_channels/widgets/injection/channel-badge/widget.js.map +7 -0
  222. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.js +185 -0
  223. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.js.map +7 -0
  224. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.js +17 -0
  225. package/dist/modules/communication_channels/widgets/injection/channel-info-panel/widget.js.map +7 -0
  226. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js +44 -0
  227. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.js.map +7 -0
  228. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.js +17 -0
  229. package/dist/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.js.map +7 -0
  230. package/dist/modules/communication_channels/widgets/injection/profile-channels-menu/widget.js +23 -0
  231. package/dist/modules/communication_channels/widgets/injection/profile-channels-menu/widget.js.map +7 -0
  232. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.client.js +141 -0
  233. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.client.js.map +7 -0
  234. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.js +17 -0
  235. package/dist/modules/communication_channels/widgets/injection/reaction-bar/widget.js.map +7 -0
  236. package/dist/modules/communication_channels/widgets/injection-table.js +38 -0
  237. package/dist/modules/communication_channels/widgets/injection-table.js.map +7 -0
  238. package/dist/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.js +25 -0
  239. package/dist/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.js.map +7 -0
  240. package/dist/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.js +19 -0
  241. package/dist/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.js.map +7 -0
  242. package/dist/modules/communication_channels/widgets/notifications/index.js +7 -0
  243. package/dist/modules/communication_channels/widgets/notifications/index.js.map +7 -0
  244. package/dist/modules/communication_channels/workers/channel-import-history.js +185 -0
  245. package/dist/modules/communication_channels/workers/channel-import-history.js.map +7 -0
  246. package/dist/modules/communication_channels/workers/gmail-history-sync.js +154 -0
  247. package/dist/modules/communication_channels/workers/gmail-history-sync.js.map +7 -0
  248. package/dist/modules/communication_channels/workers/gmail-renew-watch.js +95 -0
  249. package/dist/modules/communication_channels/workers/gmail-renew-watch.js.map +7 -0
  250. package/dist/modules/communication_channels/workers/inbound-processor.js +56 -0
  251. package/dist/modules/communication_channels/workers/inbound-processor.js.map +7 -0
  252. package/dist/modules/communication_channels/workers/outbound-delivery.js +85 -0
  253. package/dist/modules/communication_channels/workers/outbound-delivery.js.map +7 -0
  254. package/dist/modules/communication_channels/workers/poll-channel.js +240 -0
  255. package/dist/modules/communication_channels/workers/poll-channel.js.map +7 -0
  256. package/dist/modules/communication_channels/workers/poll-tick.js +132 -0
  257. package/dist/modules/communication_channels/workers/poll-tick.js.map +7 -0
  258. package/dist/modules/communication_channels/workers/reaction-processor.js +192 -0
  259. package/dist/modules/communication_channels/workers/reaction-processor.js.map +7 -0
  260. package/dist/modules/customers/acl.js +18 -0
  261. package/dist/modules/customers/acl.js.map +2 -2
  262. package/dist/modules/customers/api/activities/route.js +9 -0
  263. package/dist/modules/customers/api/activities/route.js.map +2 -2
  264. package/dist/modules/customers/api/companies/[id]/route.js +18 -7
  265. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  266. package/dist/modules/customers/api/interactions/[id]/visibility/route.js +151 -0
  267. package/dist/modules/customers/api/interactions/[id]/visibility/route.js.map +7 -0
  268. package/dist/modules/customers/api/interactions/counts/route.js +6 -0
  269. package/dist/modules/customers/api/interactions/counts/route.js.map +2 -2
  270. package/dist/modules/customers/api/interactions/route.js +26 -7
  271. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  272. package/dist/modules/customers/api/people/[id]/email-threads/route.js +82 -0
  273. package/dist/modules/customers/api/people/[id]/email-threads/route.js.map +7 -0
  274. package/dist/modules/customers/api/people/[id]/emails/route.js +157 -0
  275. package/dist/modules/customers/api/people/[id]/emails/route.js.map +7 -0
  276. package/dist/modules/customers/api/people/[id]/route.js +12 -4
  277. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  278. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js +10 -0
  279. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js.map +2 -2
  280. package/dist/modules/customers/commands/deals.js +46 -5
  281. package/dist/modules/customers/commands/deals.js.map +2 -2
  282. package/dist/modules/customers/commands/interactions.js +16 -0
  283. package/dist/modules/customers/commands/interactions.js.map +2 -2
  284. package/dist/modules/customers/components/detail/ActivityCard.js +32 -0
  285. package/dist/modules/customers/components/detail/ActivityCard.js.map +2 -2
  286. package/dist/modules/customers/components/detail/ComposeEmailDialog.js +242 -0
  287. package/dist/modules/customers/components/detail/ComposeEmailDialog.js.map +7 -0
  288. package/dist/modules/customers/components/detail/DealForm.js +2 -1
  289. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  290. package/dist/modules/customers/components/detail/DealsSection.js +10 -0
  291. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  292. package/dist/modules/customers/components/detail/EmailCardActions.js +179 -0
  293. package/dist/modules/customers/components/detail/EmailCardActions.js.map +7 -0
  294. package/dist/modules/customers/components/detail/EmailReplyForwardActions.js +52 -0
  295. package/dist/modules/customers/components/detail/EmailReplyForwardActions.js.map +7 -0
  296. package/dist/modules/customers/components/detail/PersonDetailTabs.js +7 -1
  297. package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +2 -2
  298. package/dist/modules/customers/components/detail/PersonEmailThreadsTab.js +366 -0
  299. package/dist/modules/customers/components/detail/PersonEmailThreadsTab.js.map +7 -0
  300. package/dist/modules/customers/data/enrichers.js +133 -2
  301. package/dist/modules/customers/data/enrichers.js.map +2 -2
  302. package/dist/modules/customers/data/entities.js +18 -0
  303. package/dist/modules/customers/data/entities.js.map +2 -2
  304. package/dist/modules/customers/data/extensions.js +16 -0
  305. package/dist/modules/customers/data/extensions.js.map +7 -0
  306. package/dist/modules/customers/encryption.js +11 -0
  307. package/dist/modules/customers/encryption.js.map +2 -2
  308. package/dist/modules/customers/events.js +4 -1
  309. package/dist/modules/customers/events.js.map +2 -2
  310. package/dist/modules/customers/lib/findPeopleByAddresses.js +64 -0
  311. package/dist/modules/customers/lib/findPeopleByAddresses.js.map +7 -0
  312. package/dist/modules/customers/lib/kysely.js.map +2 -2
  313. package/dist/modules/customers/lib/link-channel-message-handler.js +303 -0
  314. package/dist/modules/customers/lib/link-channel-message-handler.js.map +7 -0
  315. package/dist/modules/customers/lib/personEmailThreads.js +205 -0
  316. package/dist/modules/customers/lib/personEmailThreads.js.map +7 -0
  317. package/dist/modules/customers/lib/visibilityFilter.js +51 -0
  318. package/dist/modules/customers/lib/visibilityFilter.js.map +7 -0
  319. package/dist/modules/customers/migrations/Migration20260527012240_customers.js +20 -0
  320. package/dist/modules/customers/migrations/Migration20260527012240_customers.js.map +7 -0
  321. package/dist/modules/customers/setup.js +2 -1
  322. package/dist/modules/customers/setup.js.map +2 -2
  323. package/dist/modules/customers/subscribers/link-channel-message-received.js +12 -0
  324. package/dist/modules/customers/subscribers/link-channel-message-received.js.map +7 -0
  325. package/dist/modules/customers/subscribers/link-channel-message-sent.js +12 -0
  326. package/dist/modules/customers/subscribers/link-channel-message-sent.js.map +7 -0
  327. package/dist/modules/integrations/data/entities.js +8 -1
  328. package/dist/modules/integrations/data/entities.js.map +2 -2
  329. package/dist/modules/integrations/lib/credentials-service.js +29 -14
  330. package/dist/modules/integrations/lib/credentials-service.js.map +2 -2
  331. package/dist/modules/integrations/migrations/Migration20260526154136_integrations.js +15 -0
  332. package/dist/modules/integrations/migrations/Migration20260526154136_integrations.js.map +7 -0
  333. package/dist/modules/messages/commands/messages.js +70 -8
  334. package/dist/modules/messages/commands/messages.js.map +2 -2
  335. package/dist/modules/messages/components/ComposeMessagePageClient.js +24 -13
  336. package/dist/modules/messages/components/ComposeMessagePageClient.js.map +2 -2
  337. package/dist/modules/messages/components/MessageDetailPageClient.js +39 -2
  338. package/dist/modules/messages/components/MessageDetailPageClient.js.map +2 -2
  339. package/dist/modules/messages/components/MessagesInboxPageClient.js +1 -0
  340. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  341. package/dist/modules/messages/data/entities.js +8 -1
  342. package/dist/modules/messages/data/entities.js.map +2 -2
  343. package/dist/modules/messages/migrations/Migration20260531130000.js +15 -0
  344. package/dist/modules/messages/migrations/Migration20260531130000.js.map +7 -0
  345. package/dist/modules/messages/widgets/injection-table.js +7 -0
  346. package/dist/modules/messages/widgets/injection-table.js.map +7 -0
  347. package/generated/entities/channel_ingest_dead_letter/index.ts +11 -0
  348. package/generated/entities/channel_thread_mapping/index.ts +11 -0
  349. package/generated/entities/channel_thread_token/index.ts +7 -0
  350. package/generated/entities/communication_channel/index.ts +20 -0
  351. package/generated/entities/customer_interaction/index.ts +2 -0
  352. package/generated/entities/external_conversation/index.ts +11 -0
  353. package/generated/entities/external_message/index.ts +11 -0
  354. package/generated/entities/integration_credentials/index.ts +1 -0
  355. package/generated/entities/message/index.ts +1 -0
  356. package/generated/entities/message_channel_link/index.ts +15 -0
  357. package/generated/entities/message_reaction/index.ts +11 -0
  358. package/generated/entities.ids.generated.ts +11 -0
  359. package/generated/entity-fields-registry.ts +117 -0
  360. package/package.json +9 -7
  361. package/src/helpers/integration/authFixtures.ts +4 -1
  362. package/src/helpers/integration/communicationChannelsFixtures.ts +124 -0
  363. package/src/modules/communication_channels/acl.ts +43 -0
  364. package/src/modules/communication_channels/api/delete/channels/[id]/route.ts +163 -0
  365. package/src/modules/communication_channels/api/delete/messages/[messageId]/reactions/[reactionId]/route.ts +143 -0
  366. package/src/modules/communication_channels/api/get/channels/[id]/health/route.ts +173 -0
  367. package/src/modules/communication_channels/api/get/channels/[id]/route.ts +111 -0
  368. package/src/modules/communication_channels/api/get/channels/route.ts +109 -0
  369. package/src/modules/communication_channels/api/get/me/channels/route.ts +100 -0
  370. package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +355 -0
  371. package/src/modules/communication_channels/api/post/channels/[id]/import-history/route.ts +206 -0
  372. package/src/modules/communication_channels/api/post/channels/[id]/poll-now/route.ts +174 -0
  373. package/src/modules/communication_channels/api/post/channels/[id]/push/register/route.ts +158 -0
  374. package/src/modules/communication_channels/api/post/channels/[id]/set-primary/route.ts +114 -0
  375. package/src/modules/communication_channels/api/post/channels/[id]/test-send/route.ts +241 -0
  376. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +134 -0
  377. package/src/modules/communication_channels/api/post/messages/[messageId]/reactions/route.ts +143 -0
  378. package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +192 -0
  379. package/src/modules/communication_channels/api/post/send-as-user/route.ts +125 -0
  380. package/src/modules/communication_channels/api/post/test-seed/route.ts +267 -0
  381. package/src/modules/communication_channels/api/post/webhook/[provider]/route.ts +227 -0
  382. package/src/modules/communication_channels/api/post/webhooks/gmail/route.ts +161 -0
  383. package/src/modules/communication_channels/api/put/threads/[threadId]/assign/route.ts +132 -0
  384. package/src/modules/communication_channels/backend/communication_channels/channels/[id]/page.meta.ts +34 -0
  385. package/src/modules/communication_channels/backend/communication_channels/channels/[id]/page.tsx +250 -0
  386. package/src/modules/communication_channels/backend/communication_channels/channels/page.meta.ts +36 -0
  387. package/src/modules/communication_channels/backend/communication_channels/channels/page.tsx +137 -0
  388. package/src/modules/communication_channels/backend/profile/communication-channels/page.meta.ts +36 -0
  389. package/src/modules/communication_channels/backend/profile/communication-channels/page.tsx +907 -0
  390. package/src/modules/communication_channels/commands/connect-credential-channel.ts +243 -0
  391. package/src/modules/communication_channels/commands/delete-channel.ts +193 -0
  392. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +579 -0
  393. package/src/modules/communication_channels/commands/disconnect-channel.ts +241 -0
  394. package/src/modules/communication_channels/commands/ingest-inbound-message.ts +602 -0
  395. package/src/modules/communication_channels/commands/interceptors.ts +104 -0
  396. package/src/modules/communication_channels/commands/process-inbound-reaction.ts +265 -0
  397. package/src/modules/communication_channels/commands/push-register.ts +203 -0
  398. package/src/modules/communication_channels/commands/push-renew.ts +49 -0
  399. package/src/modules/communication_channels/commands/push-unregister.ts +168 -0
  400. package/src/modules/communication_channels/commands/queue-import-history.ts +180 -0
  401. package/src/modules/communication_channels/commands/reassign-conversation.ts +273 -0
  402. package/src/modules/communication_channels/commands/set-primary-channel.ts +154 -0
  403. package/src/modules/communication_channels/commands/toggle-outbound-reaction.ts +347 -0
  404. package/src/modules/communication_channels/data/enrichers.ts +413 -0
  405. package/src/modules/communication_channels/data/entities.ts +546 -0
  406. package/src/modules/communication_channels/data/extensions.ts +76 -0
  407. package/src/modules/communication_channels/data/validators.ts +138 -0
  408. package/src/modules/communication_channels/di.ts +40 -0
  409. package/src/modules/communication_channels/encryption.ts +44 -0
  410. package/src/modules/communication_channels/events.ts +122 -0
  411. package/src/modules/communication_channels/i18n/de.json +138 -0
  412. package/src/modules/communication_channels/i18n/en.json +138 -0
  413. package/src/modules/communication_channels/i18n/es.json +138 -0
  414. package/src/modules/communication_channels/i18n/pl.json +138 -0
  415. package/src/modules/communication_channels/index.ts +19 -0
  416. package/src/modules/communication_channels/lib/access-control.ts +110 -0
  417. package/src/modules/communication_channels/lib/adapter-compat.ts +57 -0
  418. package/src/modules/communication_channels/lib/adapter-registry-singleton.ts +35 -0
  419. package/src/modules/communication_channels/lib/adapter.ts +605 -0
  420. package/src/modules/communication_channels/lib/connect-channel.ts +163 -0
  421. package/src/modules/communication_channels/lib/contact-resolver.ts +162 -0
  422. package/src/modules/communication_channels/lib/credential-refresh.ts +197 -0
  423. package/src/modules/communication_channels/lib/dead-letter.ts +87 -0
  424. package/src/modules/communication_channels/lib/email-capabilities.ts +60 -0
  425. package/src/modules/communication_channels/lib/email-contact.ts +17 -0
  426. package/src/modules/communication_channels/lib/email-mime.ts +425 -0
  427. package/src/modules/communication_channels/lib/error-classification.ts +144 -0
  428. package/src/modules/communication_channels/lib/gmail-pubsub-jwt.ts +278 -0
  429. package/src/modules/communication_channels/lib/mutation-guards.ts +215 -0
  430. package/src/modules/communication_channels/lib/oauth-client-config.ts +79 -0
  431. package/src/modules/communication_channels/lib/oauth-state.ts +228 -0
  432. package/src/modules/communication_channels/lib/oauth-token.ts +81 -0
  433. package/src/modules/communication_channels/lib/pg-errors.ts +12 -0
  434. package/src/modules/communication_channels/lib/provider-health.ts +47 -0
  435. package/src/modules/communication_channels/lib/push-state.ts +38 -0
  436. package/src/modules/communication_channels/lib/queue.ts +66 -0
  437. package/src/modules/communication_channels/lib/reaction-processor-types.ts +51 -0
  438. package/src/modules/communication_channels/lib/reaction-semantics.ts +48 -0
  439. package/src/modules/communication_channels/lib/registry.ts +99 -0
  440. package/src/modules/communication_channels/lib/route-mutation-guard.ts +68 -0
  441. package/src/modules/communication_channels/lib/sanitize-channel-html.ts +129 -0
  442. package/src/modules/communication_channels/lib/send-as-user.ts +284 -0
  443. package/src/modules/communication_channels/lib/system-user.ts +74 -0
  444. package/src/modules/communication_channels/lib/test-seed.ts +140 -0
  445. package/src/modules/communication_channels/lib/thread-matcher.ts +430 -0
  446. package/src/modules/communication_channels/lib/thread-token.ts +355 -0
  447. package/src/modules/communication_channels/lib/use-connect-channel.ts +73 -0
  448. package/src/modules/communication_channels/migrations/.snapshot-open-mercato.json +2142 -0
  449. package/src/modules/communication_channels/migrations/Migration20260526134719_communication_channels.ts +55 -0
  450. package/src/modules/communication_channels/migrations/Migration20260527195446_communication_channels.ts +20 -0
  451. package/src/modules/communication_channels/migrations/Migration20260529231848_communication_channels.ts +13 -0
  452. package/src/modules/communication_channels/migrations/Migration20260531120000_communication_channels.ts +24 -0
  453. package/src/modules/communication_channels/notifications.client.ts +50 -0
  454. package/src/modules/communication_channels/notifications.handlers.ts +86 -0
  455. package/src/modules/communication_channels/notifications.ts +52 -0
  456. package/src/modules/communication_channels/setup.ts +158 -0
  457. package/src/modules/communication_channels/subscribers/channel-requires-reauth-notification.ts +118 -0
  458. package/src/modules/communication_channels/subscribers/outbound-bridge.ts +175 -0
  459. package/src/modules/communication_channels/subscribers/user-deleted-cascade.ts +100 -0
  460. package/src/modules/communication_channels/widgets/components.ts +36 -0
  461. package/src/modules/communication_channels/widgets/injection/channel-badge/widget.client.tsx +38 -0
  462. package/src/modules/communication_channels/widgets/injection/channel-badge/widget.ts +51 -0
  463. package/src/modules/communication_channels/widgets/injection/channel-info-panel/widget.client.tsx +278 -0
  464. package/src/modules/communication_channels/widgets/injection/channel-info-panel/widget.ts +24 -0
  465. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.client.tsx +63 -0
  466. package/src/modules/communication_channels/widgets/injection/channel-payload-renderer/widget.ts +29 -0
  467. package/src/modules/communication_channels/widgets/injection/profile-channels-menu/widget.ts +34 -0
  468. package/src/modules/communication_channels/widgets/injection/reaction-bar/widget.client.tsx +177 -0
  469. package/src/modules/communication_channels/widgets/injection/reaction-bar/widget.ts +26 -0
  470. package/src/modules/communication_channels/widgets/injection-table.ts +47 -0
  471. package/src/modules/communication_channels/widgets/notifications/ChannelRequiresReauthRenderer.tsx +48 -0
  472. package/src/modules/communication_channels/widgets/notifications/MessageReceivedRenderer.tsx +45 -0
  473. package/src/modules/communication_channels/widgets/notifications/index.ts +2 -0
  474. package/src/modules/communication_channels/workers/channel-import-history.ts +252 -0
  475. package/src/modules/communication_channels/workers/gmail-history-sync.ts +223 -0
  476. package/src/modules/communication_channels/workers/gmail-renew-watch.ts +141 -0
  477. package/src/modules/communication_channels/workers/inbound-processor.ts +114 -0
  478. package/src/modules/communication_channels/workers/outbound-delivery.ts +155 -0
  479. package/src/modules/communication_channels/workers/poll-channel.ts +391 -0
  480. package/src/modules/communication_channels/workers/poll-tick.ts +210 -0
  481. package/src/modules/communication_channels/workers/reaction-processor.ts +264 -0
  482. package/src/modules/customers/acl.ts +18 -0
  483. package/src/modules/customers/api/activities/route.ts +13 -0
  484. package/src/modules/customers/api/companies/[id]/route.ts +21 -1
  485. package/src/modules/customers/api/interactions/[id]/visibility/route.ts +179 -0
  486. package/src/modules/customers/api/interactions/counts/route.ts +10 -0
  487. package/src/modules/customers/api/interactions/route.ts +51 -5
  488. package/src/modules/customers/api/people/[id]/email-threads/route.ts +92 -0
  489. package/src/modules/customers/api/people/[id]/emails/route.ts +184 -0
  490. package/src/modules/customers/api/people/[id]/route.ts +17 -2
  491. package/src/modules/customers/backend/customers/people-v2/[id]/page.tsx +11 -1
  492. package/src/modules/customers/commands/deals.ts +65 -6
  493. package/src/modules/customers/commands/interactions.ts +30 -0
  494. package/src/modules/customers/components/detail/ActivityCard.tsx +48 -0
  495. package/src/modules/customers/components/detail/ComposeEmailDialog.tsx +329 -0
  496. package/src/modules/customers/components/detail/DealForm.tsx +2 -1
  497. package/src/modules/customers/components/detail/DealsSection.tsx +26 -0
  498. package/src/modules/customers/components/detail/EmailCardActions.tsx +258 -0
  499. package/src/modules/customers/components/detail/EmailReplyForwardActions.tsx +53 -0
  500. package/src/modules/customers/components/detail/PersonDetailTabs.tsx +8 -1
  501. package/src/modules/customers/components/detail/PersonEmailThreadsTab.tsx +448 -0
  502. package/src/modules/customers/data/enrichers.ts +252 -1
  503. package/src/modules/customers/data/entities.ts +46 -1
  504. package/src/modules/customers/data/extensions.ts +26 -0
  505. package/src/modules/customers/encryption.ts +11 -0
  506. package/src/modules/customers/events.ts +4 -0
  507. package/src/modules/customers/i18n/de.json +41 -0
  508. package/src/modules/customers/i18n/en.json +41 -0
  509. package/src/modules/customers/i18n/es.json +41 -0
  510. package/src/modules/customers/i18n/pl.json +41 -0
  511. package/src/modules/customers/lib/findPeopleByAddresses.ts +107 -0
  512. package/src/modules/customers/lib/kysely.ts +16 -0
  513. package/src/modules/customers/lib/link-channel-message-handler.ts +571 -0
  514. package/src/modules/customers/lib/personEmailThreads.ts +325 -0
  515. package/src/modules/customers/lib/visibilityFilter.ts +152 -0
  516. package/src/modules/customers/migrations/.snapshot-open-mercato.json +61 -0
  517. package/src/modules/customers/migrations/Migration20260527012240_customers.ts +23 -0
  518. package/src/modules/customers/setup.ts +1 -0
  519. package/src/modules/customers/subscribers/link-channel-message-received.ts +21 -0
  520. package/src/modules/customers/subscribers/link-channel-message-sent.ts +21 -0
  521. package/src/modules/integrations/AGENTS.md +9 -0
  522. package/src/modules/integrations/data/entities.ts +21 -1
  523. package/src/modules/integrations/lib/credentials-service.ts +49 -13
  524. package/src/modules/integrations/migrations/.snapshot-open-mercato.json +26 -1
  525. package/src/modules/integrations/migrations/Migration20260526154136_integrations.ts +15 -0
  526. package/src/modules/messages/commands/messages.ts +101 -8
  527. package/src/modules/messages/components/ComposeMessagePageClient.tsx +17 -0
  528. package/src/modules/messages/components/MessageDetailPageClient.tsx +43 -0
  529. package/src/modules/messages/components/MessagesInboxPageClient.tsx +4 -0
  530. package/src/modules/messages/data/entities.ts +11 -0
  531. package/src/modules/messages/migrations/.snapshot-open-mercato.json +18 -0
  532. package/src/modules/messages/migrations/Migration20260531130000.ts +15 -0
  533. package/src/modules/messages/widgets/injection-table.ts +29 -0
@@ -6,6 +6,7 @@ import { useT } from "@open-mercato/shared/lib/i18n/context";
6
6
  import { Button } from "@open-mercato/ui/primitives/button";
7
7
  import {
8
8
  SquareCheckBig,
9
+ Mail,
9
10
  Briefcase,
10
11
  Building2,
11
12
  Check,
@@ -13,7 +14,7 @@ import {
13
14
  Paperclip,
14
15
  Plus
15
16
  } from "lucide-react";
16
- const SUPPORTED_TAB_IDS = /* @__PURE__ */ new Set(["activities", "deals", "companies", "tasks", "changelog", "files"]);
17
+ const SUPPORTED_TAB_IDS = /* @__PURE__ */ new Set(["activities", "emails", "deals", "companies", "tasks", "changelog", "files"]);
17
18
  function resolveLegacyTab(tab) {
18
19
  if (!tab) return "activities";
19
20
  return SUPPORTED_TAB_IDS.has(tab) ? tab : "activities";
@@ -46,6 +47,11 @@ function PersonDetailTabs({
46
47
  icon: /* @__PURE__ */ jsx(SquareCheckBig, { className: "size-4" }),
47
48
  badge: /* @__PURE__ */ jsx(CountBadge, { count: activitiesCount })
48
49
  },
50
+ {
51
+ id: "emails",
52
+ label: t("customers.people.detail.tabs.emails", "Emails"),
53
+ icon: /* @__PURE__ */ jsx(Mail, { className: "size-4" })
54
+ },
49
55
  {
50
56
  id: "deals",
51
57
  label: t("customers.people.detail.tabs.deals", "Deals"),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/components/detail/PersonDetailTabs.tsx"],
4
- "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport {\n SquareCheckBig,\n Briefcase,\n Building2,\n Check,\n History,\n Paperclip,\n Plus,\n} from 'lucide-react'\nimport type { SectionAction } from '@open-mercato/ui/backend/detail'\n\nexport type PersonTabId =\n | 'activities'\n | 'deals'\n | 'companies'\n | 'tasks'\n | 'changelog'\n | 'files'\n | string\n\ntype TabDef = {\n id: PersonTabId\n label: string\n icon?: React.ReactNode\n badge?: React.ReactNode\n}\n\ntype PersonDetailTabsProps = {\n activeTab: PersonTabId\n onTabChange: (tab: PersonTabId) => void\n injectedTabs?: Array<{ id: string; label: string }>\n activitiesCount?: number\n dealsCount?: number\n companiesCount?: number\n tasksCount?: number\n filesCount?: number\n sectionAction?: SectionAction | null\n children: React.ReactNode\n}\n\nconst SUPPORTED_TAB_IDS = new Set<PersonTabId>(['activities', 'deals', 'companies', 'tasks', 'changelog', 'files'])\n\nexport function resolveLegacyTab(tab: string | null | undefined): PersonTabId {\n if (!tab) return 'activities'\n return SUPPORTED_TAB_IDS.has(tab as PersonTabId) ? (tab as PersonTabId) : 'activities'\n}\n\nfunction CountBadge({ count }: { count: number }) {\n if (count <= 0) return null\n return (\n <span className=\"ml-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-medium leading-none text-muted-foreground\">\n {count > 999 ? '999+' : count}\n </span>\n )\n}\n\nfunction NewBadge() {\n return (\n <span className=\"ml-1.5 rounded bg-foreground px-1.5 py-0.5 text-overline font-semibold leading-none text-background\">\n NEW\n </span>\n )\n}\n\nexport function PersonDetailTabs({\n activeTab,\n onTabChange,\n injectedTabs = [],\n activitiesCount = 0,\n dealsCount = 0,\n companiesCount = 0,\n tasksCount = 0,\n filesCount = 0,\n sectionAction = null,\n children,\n}: PersonDetailTabsProps) {\n const t = useT()\n\n const builtInTabs: TabDef[] = React.useMemo(\n () => [\n {\n id: 'activities',\n label: t('customers.people.detail.tabs.activities', 'Activities'),\n icon: <SquareCheckBig className=\"size-4\" />,\n badge: <CountBadge count={activitiesCount} />,\n },\n {\n id: 'deals',\n label: t('customers.people.detail.tabs.deals', 'Deals'),\n icon: <Briefcase className=\"size-4\" />,\n badge: <CountBadge count={dealsCount} />,\n },\n {\n id: 'companies',\n label: t('customers.people.detail.tabs.companies', 'Companies'),\n icon: <Building2 className=\"size-4\" />,\n badge: <CountBadge count={companiesCount} />,\n },\n {\n id: 'tasks',\n label: t('customers.people.detail.tabs.tasks', 'Tasks'),\n icon: <Check className=\"size-4\" />,\n badge: <CountBadge count={tasksCount} />,\n },\n {\n id: 'changelog',\n label: t('customers.people.detail.tabs.changelog', 'Change log'),\n icon: <History className=\"size-4\" />,\n badge: <NewBadge />,\n },\n {\n id: 'files',\n label: t('customers.people.detail.tabs.files', 'Files'),\n icon: <Paperclip className=\"size-4\" />,\n badge: <CountBadge count={filesCount} />,\n },\n ],\n [t, activitiesCount, dealsCount, companiesCount, tasksCount, filesCount],\n )\n\n const allTabs: TabDef[] = React.useMemo(\n () => [\n ...builtInTabs,\n ...injectedTabs.map((tab) => ({\n id: tab.id as PersonTabId,\n label: tab.label,\n })),\n ],\n [builtInTabs, injectedTabs],\n )\n\n return (\n <div>\n {/* Tab navigation \u2014 full width above both zones */}\n <div className=\"flex items-end justify-between gap-2 border-b\" role=\"tablist\" aria-label={t('customers.people.detail.tabs.label', 'Person detail sections')}>\n <nav className=\"-mb-px flex flex-1 gap-1 overflow-x-auto px-1\">\n {allTabs.map((tab) => {\n const isActive = activeTab === tab.id\n return (\n <Button\n key={tab.id}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n role=\"tab\"\n aria-selected={isActive}\n onClick={() => onTabChange(tab.id)}\n className={cn(\n 'h-auto shrink-0 rounded-none border-b-2 px-3 py-2.5 hover:bg-transparent',\n isActive\n ? 'border-foreground text-foreground font-semibold'\n : 'border-transparent text-muted-foreground hover:text-foreground',\n )}\n >\n {tab.icon && <span className=\"mr-1.5\">{tab.icon}</span>}\n {tab.label}\n {tab.badge}\n </Button>\n )\n })}\n </nav>\n {sectionAction ? (\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={sectionAction.onClick}\n disabled={sectionAction.disabled}\n className=\"mb-1.5 mr-1 shrink-0\"\n >\n <Plus className=\"mr-1.5 h-4 w-4\" />\n {sectionAction.label}\n </Button>\n ) : null}\n </div>\n\n {/* Two-column content below tabs */}\n <div className=\"pt-6\">\n {children}\n </div>\n </div>\n )\n}\n"],
5
- "mappings": ";AAwDI,cAyFU,YAzFV;AAtDJ,YAAY,WAAW;AACvB,SAAS,UAAU;AACnB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAgCP,MAAM,oBAAoB,oBAAI,IAAiB,CAAC,cAAc,SAAS,aAAa,SAAS,aAAa,OAAO,CAAC;AAE3G,SAAS,iBAAiB,KAA6C;AAC5E,MAAI,CAAC,IAAK,QAAO;AACjB,SAAO,kBAAkB,IAAI,GAAkB,IAAK,MAAsB;AAC5E;AAEA,SAAS,WAAW,EAAE,MAAM,GAAsB;AAChD,MAAI,SAAS,EAAG,QAAO;AACvB,SACE,oBAAC,UAAK,WAAU,mGACb,kBAAQ,MAAM,SAAS,OAC1B;AAEJ;AAEA,SAAS,WAAW;AAClB,SACE,oBAAC,UAAK,WAAU,uGAAsG,iBAEtH;AAEJ;AAEO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA,eAAe,CAAC;AAAA,EAChB,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB;AACF,GAA0B;AACxB,QAAM,IAAI,KAAK;AAEf,QAAM,cA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A,QACR,OAAO,IAAI;AAAA,MACb,EAAE;AAAA,IACJ;AAAA,IACA,CAAC,aAAa,YAAY;AAAA,EAC5B;AAEA,SACE,qBAAC,SAEC;AAAA,yBAAC,SAAI,WAAU,iDAAgD,MAAK,WAAU,cAAY,EAAE,sCAAsC,wBAAwB,GACxJ;AAAA,0BAAC,SAAI,WAAU,iDACZ,kBAAQ,IAAI,CAAC,QAAQ;AACpB,cAAM,WAAW,cAAc,IAAI;AACnC,eACE;AAAA,UAAC;AAAA;AAAA,YAEC,MAAK;AAAA,YACL,SAAQ;AAAA,YACR,MAAK;AAAA,YACL,MAAK;AAAA,YACL,iBAAe;AAAA,YACf,SAAS,MAAM,YAAY,IAAI,EAAE;AAAA,YACjC,WAAW;AAAA,cACT;AAAA,cACA,WACI,oDACA;AAAA,YACN;AAAA,YAEC;AAAA,kBAAI,QAAQ,oBAAC,UAAK,WAAU,UAAU,cAAI,MAAK;AAAA,cAC/C,IAAI;AAAA,cACJ,IAAI;AAAA;AAAA;AAAA,UAhBA,IAAI;AAAA,QAiBX;AAAA,MAEJ,CAAC,GACH;AAAA,MACC,gBACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,MAAK;AAAA,UACL,SAAS,cAAc;AAAA,UACvB,UAAU,cAAc;AAAA,UACxB,WAAU;AAAA,UAEV;AAAA,gCAAC,QAAK,WAAU,kBAAiB;AAAA,YAChC,cAAc;AAAA;AAAA;AAAA,MACjB,IACE;AAAA,OACN;AAAA,IAGA,oBAAC,SAAI,WAAU,QACZ,UACH;AAAA,KACF;AAEJ;",
4
+ "sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport {\n SquareCheckBig,\n Mail,\n Briefcase,\n Building2,\n Check,\n History,\n Paperclip,\n Plus,\n} from 'lucide-react'\nimport type { SectionAction } from '@open-mercato/ui/backend/detail'\n\nexport type PersonTabId =\n | 'activities'\n | 'emails'\n | 'deals'\n | 'companies'\n | 'tasks'\n | 'changelog'\n | 'files'\n | string\n\ntype TabDef = {\n id: PersonTabId\n label: string\n icon?: React.ReactNode\n badge?: React.ReactNode\n}\n\ntype PersonDetailTabsProps = {\n activeTab: PersonTabId\n onTabChange: (tab: PersonTabId) => void\n injectedTabs?: Array<{ id: string; label: string }>\n activitiesCount?: number\n dealsCount?: number\n companiesCount?: number\n tasksCount?: number\n filesCount?: number\n sectionAction?: SectionAction | null\n children: React.ReactNode\n}\n\nconst SUPPORTED_TAB_IDS = new Set<PersonTabId>(['activities', 'emails', 'deals', 'companies', 'tasks', 'changelog', 'files'])\n\nexport function resolveLegacyTab(tab: string | null | undefined): PersonTabId {\n if (!tab) return 'activities'\n return SUPPORTED_TAB_IDS.has(tab as PersonTabId) ? (tab as PersonTabId) : 'activities'\n}\n\nfunction CountBadge({ count }: { count: number }) {\n if (count <= 0) return null\n return (\n <span className=\"ml-1 rounded-full bg-muted px-1.5 py-0.5 text-xs font-medium leading-none text-muted-foreground\">\n {count > 999 ? '999+' : count}\n </span>\n )\n}\n\nfunction NewBadge() {\n return (\n <span className=\"ml-1.5 rounded bg-foreground px-1.5 py-0.5 text-overline font-semibold leading-none text-background\">\n NEW\n </span>\n )\n}\n\nexport function PersonDetailTabs({\n activeTab,\n onTabChange,\n injectedTabs = [],\n activitiesCount = 0,\n dealsCount = 0,\n companiesCount = 0,\n tasksCount = 0,\n filesCount = 0,\n sectionAction = null,\n children,\n}: PersonDetailTabsProps) {\n const t = useT()\n\n const builtInTabs: TabDef[] = React.useMemo(\n () => [\n {\n id: 'activities',\n label: t('customers.people.detail.tabs.activities', 'Activities'),\n icon: <SquareCheckBig className=\"size-4\" />,\n badge: <CountBadge count={activitiesCount} />,\n },\n {\n id: 'emails',\n label: t('customers.people.detail.tabs.emails', 'Emails'),\n icon: <Mail className=\"size-4\" />,\n },\n {\n id: 'deals',\n label: t('customers.people.detail.tabs.deals', 'Deals'),\n icon: <Briefcase className=\"size-4\" />,\n badge: <CountBadge count={dealsCount} />,\n },\n {\n id: 'companies',\n label: t('customers.people.detail.tabs.companies', 'Companies'),\n icon: <Building2 className=\"size-4\" />,\n badge: <CountBadge count={companiesCount} />,\n },\n {\n id: 'tasks',\n label: t('customers.people.detail.tabs.tasks', 'Tasks'),\n icon: <Check className=\"size-4\" />,\n badge: <CountBadge count={tasksCount} />,\n },\n {\n id: 'changelog',\n label: t('customers.people.detail.tabs.changelog', 'Change log'),\n icon: <History className=\"size-4\" />,\n badge: <NewBadge />,\n },\n {\n id: 'files',\n label: t('customers.people.detail.tabs.files', 'Files'),\n icon: <Paperclip className=\"size-4\" />,\n badge: <CountBadge count={filesCount} />,\n },\n ],\n [t, activitiesCount, dealsCount, companiesCount, tasksCount, filesCount],\n )\n\n const allTabs: TabDef[] = React.useMemo(\n () => [\n ...builtInTabs,\n ...injectedTabs.map((tab) => ({\n id: tab.id as PersonTabId,\n label: tab.label,\n })),\n ],\n [builtInTabs, injectedTabs],\n )\n\n return (\n <div>\n {/* Tab navigation \u2014 full width above both zones */}\n <div className=\"flex items-end justify-between gap-2 border-b\" role=\"tablist\" aria-label={t('customers.people.detail.tabs.label', 'Person detail sections')}>\n <nav className=\"-mb-px flex flex-1 gap-1 overflow-x-auto px-1\">\n {allTabs.map((tab) => {\n const isActive = activeTab === tab.id\n return (\n <Button\n key={tab.id}\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n role=\"tab\"\n aria-selected={isActive}\n onClick={() => onTabChange(tab.id)}\n className={cn(\n 'h-auto shrink-0 rounded-none border-b-2 px-3 py-2.5 hover:bg-transparent',\n isActive\n ? 'border-foreground text-foreground font-semibold'\n : 'border-transparent text-muted-foreground hover:text-foreground',\n )}\n >\n {tab.icon && <span className=\"mr-1.5\">{tab.icon}</span>}\n {tab.label}\n {tab.badge}\n </Button>\n )\n })}\n </nav>\n {sectionAction ? (\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={sectionAction.onClick}\n disabled={sectionAction.disabled}\n className=\"mb-1.5 mr-1 shrink-0\"\n >\n <Plus className=\"mr-1.5 h-4 w-4\" />\n {sectionAction.label}\n </Button>\n ) : null}\n </div>\n\n {/* Two-column content below tabs */}\n <div className=\"pt-6\">\n {children}\n </div>\n </div>\n )\n}\n"],
5
+ "mappings": ";AA0DI,cA8FU,YA9FV;AAxDJ,YAAY,WAAW;AACvB,SAAS,UAAU;AACnB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAiCP,MAAM,oBAAoB,oBAAI,IAAiB,CAAC,cAAc,UAAU,SAAS,aAAa,SAAS,aAAa,OAAO,CAAC;AAErH,SAAS,iBAAiB,KAA6C;AAC5E,MAAI,CAAC,IAAK,QAAO;AACjB,SAAO,kBAAkB,IAAI,GAAkB,IAAK,MAAsB;AAC5E;AAEA,SAAS,WAAW,EAAE,MAAM,GAAsB;AAChD,MAAI,SAAS,EAAG,QAAO;AACvB,SACE,oBAAC,UAAK,WAAU,mGACb,kBAAQ,MAAM,SAAS,OAC1B;AAEJ;AAEA,SAAS,WAAW;AAClB,SACE,oBAAC,UAAK,WAAU,uGAAsG,iBAEtH;AAEJ;AAEO,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA,eAAe,CAAC;AAAA,EAChB,kBAAkB;AAAA,EAClB,aAAa;AAAA,EACb,iBAAiB;AAAA,EACjB,aAAa;AAAA,EACb,aAAa;AAAA,EACb,gBAAgB;AAAA,EAChB;AACF,GAA0B;AACxB,QAAM,IAAI,KAAK;AAEf,QAAM,cAAwB,MAAM;AAAA,IAClC,MAAM;AAAA,MACJ;AAAA,QACE,IAAI;AAAA,QACJ,OAAO,EAAE,2CAA2C,YAAY;AAAA,QAChE,MAAM,oBAAC,kBAAe,WAAU,UAAS;AAAA,QAC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ACb,EAAE;AAAA,IACJ;AAAA,IACA,CAAC,aAAa,YAAY;AAAA,EAC5B;AAEA,SACE,qBAAC,SAEC;AAAA,yBAAC,SAAI,WAAU,iDAAgD,MAAK,WAAU,cAAY,EAAE,sCAAsC,wBAAwB,GACxJ;AAAA,0BAAC,SAAI,WAAU,iDACZ,kBAAQ,IAAI,CAAC,QAAQ;AACpB,cAAM,WAAW,cAAc,IAAI;AACnC,eACE;AAAA,UAAC;AAAA;AAAA,YAEC,MAAK;AAAA,YACL,SAAQ;AAAA,YACR,MAAK;AAAA,YACL,MAAK;AAAA,YACL,iBAAe;AAAA,YACf,SAAS,MAAM,YAAY,IAAI,EAAE;AAAA,YACjC,WAAW;AAAA,cACT;AAAA,cACA,WACI,oDACA;AAAA,YACN;AAAA,YAEC;AAAA,kBAAI,QAAQ,oBAAC,UAAK,WAAU,UAAU,cAAI,MAAK;AAAA,cAC/C,IAAI;AAAA,cACJ,IAAI;AAAA;AAAA;AAAA,UAhBA,IAAI;AAAA,QAiBX;AAAA,MAEJ,CAAC,GACH;AAAA,MACC,gBACC;AAAA,QAAC;AAAA;AAAA,UACC,MAAK;AAAA,UACL,MAAK;AAAA,UACL,SAAS,cAAc;AAAA,UACvB,UAAU,cAAc;AAAA,UACxB,WAAU;AAAA,UAEV;AAAA,gCAAC,QAAK,WAAU,kBAAiB;AAAA,YAChC,cAAc;AAAA;AAAA;AAAA,MACjB,IACE;AAAA,OACN;AAAA,IAGA,oBAAC,SAAI,WAAU,QACZ,UACH;AAAA,KACF;AAEJ;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,366 @@
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import * as React from "react";
4
+ import Link from "next/link";
5
+ import { Mail } from "lucide-react";
6
+ import { Button } from "@open-mercato/ui/primitives/button";
7
+ import {
8
+ EmailThreadsPanel,
9
+ mergeOptimisticEmailThreads
10
+ } from "@open-mercato/ui/backend/messages";
11
+ import { apiCall } from "@open-mercato/ui/backend/utils/apiCall";
12
+ import { useGuardedMutation } from "@open-mercato/ui/backend/injection/useGuardedMutation";
13
+ import { useAppEvent } from "@open-mercato/ui/backend/injection/useAppEvent";
14
+ import { flash } from "@open-mercato/ui/backend/FlashMessages";
15
+ import { useT } from "@open-mercato/shared/lib/i18n/context";
16
+ import {
17
+ ComposeEmailDialog
18
+ } from "./ComposeEmailDialog.js";
19
+ const CONTEXT_ID = "customers-person-email-threads";
20
+ const MAX_REFERENCES = 40;
21
+ const BACKGROUND_POLL_MS = 2e4;
22
+ const BURST_INTERVAL_MS = 3e3;
23
+ const BURST_DURATION_MS = 36e3;
24
+ function resolveReplyRecipient(thread, fallback) {
25
+ for (let i = thread.messages.length - 1; i >= 0; i -= 1) {
26
+ const message = thread.messages[i];
27
+ if (message.direction === "inbound" && message.fromEmail) return message.fromEmail;
28
+ }
29
+ return thread.participants[0] ?? fallback;
30
+ }
31
+ function buildReplyState(thread, fallbackRecipient) {
32
+ const last = thread.messages[thread.messages.length - 1];
33
+ if (!last) return null;
34
+ const recipient = resolveReplyRecipient(thread, fallbackRecipient);
35
+ const references = Array.from(
36
+ /* @__PURE__ */ new Set([...last.references ?? [], ...last.rfcMessageId ? [last.rfcMessageId] : []])
37
+ ).slice(-MAX_REFERENCES);
38
+ const baseSubject = thread.subject ?? "";
39
+ const subject = /^re:/i.test(baseSubject) ? baseSubject : `Re: ${baseSubject}`.trim();
40
+ return {
41
+ inReplyTo: last.rfcMessageId ?? void 0,
42
+ references: references.length > 0 ? references : void 0,
43
+ to: recipient ? [recipient] : [],
44
+ subject,
45
+ parentMessageId: last.messageId ?? void 0
46
+ };
47
+ }
48
+ function readEventMessageId(event) {
49
+ const payload = event?.payload;
50
+ const messageId = payload?.messageId;
51
+ return typeof messageId === "string" ? messageId : null;
52
+ }
53
+ function PersonEmailThreadsTab({ personId, defaultRecipient }) {
54
+ const t = useT();
55
+ const [threads, setThreads] = React.useState([]);
56
+ const [optimistic, setOptimistic] = React.useState([]);
57
+ const [channels, setChannels] = React.useState([]);
58
+ const [loading, setLoading] = React.useState(true);
59
+ const [error, setError] = React.useState(null);
60
+ const [dialogOpen, setDialogOpen] = React.useState(false);
61
+ const [replyTo, setReplyTo] = React.useState(null);
62
+ const burstTimer = React.useRef(null);
63
+ const channelsRef = React.useRef([]);
64
+ channelsRef.current = channels;
65
+ const optimisticRef = React.useRef([]);
66
+ optimisticRef.current = optimistic;
67
+ const { runMutation, retryLastMutation } = useGuardedMutation({
68
+ contextId: CONTEXT_ID,
69
+ blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
70
+ });
71
+ const loadThreads = React.useCallback(
72
+ async (opts) => {
73
+ if (opts?.showLoading) setLoading(true);
74
+ try {
75
+ const response = await apiCall(
76
+ `/api/customers/people/${encodeURIComponent(personId)}/email-threads`,
77
+ // Background poll: degrade silently on an expired session instead of
78
+ // hijacking the whole page with a login redirect.
79
+ { method: "GET", headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" } }
80
+ );
81
+ if (!response.ok) {
82
+ const err = response.result;
83
+ throw new Error(err?.error ?? t("customers.email.threads.loadFailed", "Failed to load emails"));
84
+ }
85
+ setThreads(Array.isArray(response.result?.threads) ? response.result.threads : []);
86
+ setError(null);
87
+ } catch (err) {
88
+ setError(err instanceof Error ? err.message : t("customers.email.threads.loadFailed", "Failed to load emails"));
89
+ } finally {
90
+ if (opts?.showLoading) setLoading(false);
91
+ }
92
+ },
93
+ [personId, t]
94
+ );
95
+ const loadChannels = React.useCallback(async () => {
96
+ try {
97
+ const response = await apiCall(
98
+ "/api/communication_channels/me/channels",
99
+ { method: "GET", headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" } }
100
+ );
101
+ const items = Array.isArray(response.result?.items) ? response.result.items : [];
102
+ const connected = items.filter(
103
+ (item) => item !== null && typeof item === "object" && item.status === "connected"
104
+ );
105
+ setChannels(connected);
106
+ } catch {
107
+ setChannels([]);
108
+ }
109
+ }, []);
110
+ const triggerSync = React.useCallback(async () => {
111
+ await Promise.allSettled(
112
+ channelsRef.current.map((channel) => {
113
+ const channelId = channel.id;
114
+ if (!channelId) return Promise.resolve();
115
+ return apiCall(
116
+ `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,
117
+ { method: "POST", headers: { "x-om-forbidden-redirect": "0", "x-om-unauthorized-redirect": "0" } }
118
+ );
119
+ })
120
+ );
121
+ }, []);
122
+ const startBurst = React.useCallback(() => {
123
+ if (burstTimer.current) clearInterval(burstTimer.current);
124
+ const startedAt = Date.now();
125
+ burstTimer.current = setInterval(() => {
126
+ if (Date.now() - startedAt > BURST_DURATION_MS) {
127
+ if (burstTimer.current) {
128
+ clearInterval(burstTimer.current);
129
+ burstTimer.current = null;
130
+ }
131
+ return;
132
+ }
133
+ void loadThreads();
134
+ }, BURST_INTERVAL_MS);
135
+ }, [loadThreads]);
136
+ const buildOptimisticMessage = React.useCallback(
137
+ (clientId, messageId, values, status) => {
138
+ const channel = channelsRef.current.find(
139
+ (c) => c.id === values.userChannelId
140
+ );
141
+ return {
142
+ id: `optimistic:${clientId}`,
143
+ messageId,
144
+ rfcMessageId: null,
145
+ references: values.references ?? [],
146
+ direction: "outbound",
147
+ fromName: null,
148
+ fromEmail: channel?.externalIdentifier ?? null,
149
+ to: values.to,
150
+ cc: values.cc ?? [],
151
+ subject: values.subject,
152
+ bodyText: values.body,
153
+ sentAt: (/* @__PURE__ */ new Date()).toISOString(),
154
+ providerKey: channel?.providerKey ?? null,
155
+ status
156
+ };
157
+ },
158
+ []
159
+ );
160
+ const sendEmail = React.useCallback(
161
+ async (values) => {
162
+ const operation = async () => {
163
+ const response = await apiCall(
164
+ `/api/customers/people/${encodeURIComponent(personId)}/emails`,
165
+ {
166
+ method: "POST",
167
+ headers: { "content-type": "application/json" },
168
+ body: JSON.stringify(values)
169
+ }
170
+ );
171
+ if (!response.ok) {
172
+ const err = response.result;
173
+ throw new Error(err?.error ?? t("customers.email.errors.sendFailed", "Send failed"));
174
+ }
175
+ return {
176
+ messageId: response.result?.messageId ?? null,
177
+ threadId: response.result?.threadId ?? null
178
+ };
179
+ };
180
+ const result = await runMutation({
181
+ operation,
182
+ context: {
183
+ formId: CONTEXT_ID,
184
+ resourceKind: "customers.person",
185
+ resourceId: personId,
186
+ retryLastMutation
187
+ },
188
+ mutationPayload: values
189
+ });
190
+ return result ?? { messageId: null, threadId: null };
191
+ },
192
+ [personId, runMutation, retryLastMutation, t]
193
+ );
194
+ const setMessageStatus = React.useCallback(
195
+ (matcher, patch) => {
196
+ setOptimistic(
197
+ (prev) => prev.map(
198
+ (entry) => matcher(entry) ? { ...entry, message: { ...entry.message, ...patch } } : entry
199
+ )
200
+ );
201
+ },
202
+ []
203
+ );
204
+ React.useEffect(() => {
205
+ void loadThreads({ showLoading: true });
206
+ void loadChannels();
207
+ }, [loadThreads, loadChannels]);
208
+ React.useEffect(() => {
209
+ const id = setInterval(() => {
210
+ void loadThreads();
211
+ }, BACKGROUND_POLL_MS);
212
+ return () => clearInterval(id);
213
+ }, [loadThreads]);
214
+ React.useEffect(() => () => {
215
+ if (burstTimer.current) clearInterval(burstTimer.current);
216
+ }, []);
217
+ React.useEffect(() => {
218
+ setOptimistic((prev) => {
219
+ if (prev.length === 0) return prev;
220
+ const serverIds = /* @__PURE__ */ new Set();
221
+ for (const thread of threads) {
222
+ for (const message of thread.messages) {
223
+ if (message.messageId) serverIds.add(message.messageId);
224
+ }
225
+ }
226
+ const next = prev.filter((entry) => !(entry.message.messageId && serverIds.has(entry.message.messageId)));
227
+ return next.length === prev.length ? prev : next;
228
+ });
229
+ }, [threads]);
230
+ useAppEvent("customers.email.linked", () => {
231
+ void loadThreads();
232
+ }, [loadThreads]);
233
+ useAppEvent("messages.message.sent", () => {
234
+ void loadThreads();
235
+ }, [loadThreads]);
236
+ useAppEvent("communication_channels.message.received", () => {
237
+ void loadThreads();
238
+ }, [loadThreads]);
239
+ useAppEvent(
240
+ "communication_channels.message.sent",
241
+ (event) => {
242
+ const messageId = readEventMessageId(event);
243
+ if (messageId) setMessageStatus((e) => e.message.messageId === messageId, { status: "sent" });
244
+ void loadThreads();
245
+ },
246
+ [setMessageStatus, loadThreads]
247
+ );
248
+ useAppEvent(
249
+ "communication_channels.message.delivery_failed",
250
+ (event) => {
251
+ const messageId = readEventMessageId(event);
252
+ if (messageId) {
253
+ setMessageStatus((e) => e.message.messageId === messageId, {
254
+ status: "failed",
255
+ statusError: t("customers.email.errors.deliveryFailed", "Delivery failed \u2014 not sent")
256
+ });
257
+ }
258
+ },
259
+ [setMessageStatus, t]
260
+ );
261
+ const onComposeNew = React.useCallback(() => {
262
+ setReplyTo(null);
263
+ setDialogOpen(true);
264
+ }, []);
265
+ const onReply = React.useCallback(
266
+ (thread) => {
267
+ setReplyTo(buildReplyState(thread, defaultRecipient ?? null));
268
+ setDialogOpen(true);
269
+ },
270
+ [defaultRecipient]
271
+ );
272
+ const onSend = React.useCallback(
273
+ async (values) => {
274
+ const { messageId, threadId } = await sendEmail(values);
275
+ flash(t("customers.email.compose.sent", "Email sent"), "success");
276
+ if (messageId) {
277
+ const clientId = crypto.randomUUID();
278
+ const message = buildOptimisticMessage(clientId, messageId, values, "sending");
279
+ setOptimistic((prev) => [
280
+ ...prev,
281
+ { clientId, threadKey: threadId ?? `optimistic:${clientId}`, values, message }
282
+ ]);
283
+ }
284
+ startBurst();
285
+ return { messageId };
286
+ },
287
+ [sendEmail, t, buildOptimisticMessage, startBurst]
288
+ );
289
+ const onRetry = React.useCallback(
290
+ async (message) => {
291
+ const entry = optimisticRef.current.find((e) => e.message.id === message.id);
292
+ if (!entry) return;
293
+ setMessageStatus((e) => e.message.id === message.id, { status: "sending", statusError: null });
294
+ try {
295
+ const { messageId } = await sendEmail(entry.values);
296
+ setMessageStatus((e) => e.message.id === message.id, { messageId, status: "sending" });
297
+ startBurst();
298
+ } catch (err) {
299
+ setMessageStatus((e) => e.message.id === message.id, {
300
+ status: "failed",
301
+ statusError: err instanceof Error ? err.message : t("customers.email.errors.sendFailed", "Send failed")
302
+ });
303
+ }
304
+ },
305
+ [sendEmail, setMessageStatus, startBurst, t]
306
+ );
307
+ const onRefresh = React.useCallback(async () => {
308
+ setLoading(true);
309
+ try {
310
+ await triggerSync();
311
+ await loadThreads();
312
+ } finally {
313
+ setLoading(false);
314
+ }
315
+ startBurst();
316
+ }, [triggerSync, loadThreads, startBurst]);
317
+ const mergedThreads = React.useMemo(
318
+ () => mergeOptimisticEmailThreads(
319
+ threads,
320
+ optimistic.map((entry) => ({ ...entry.message, threadKey: entry.threadKey }))
321
+ ),
322
+ [threads, optimistic]
323
+ );
324
+ const canCompose = channels.length > 0;
325
+ const composeDisabledHint = /* @__PURE__ */ jsx(Button, { asChild: true, variant: "outline", size: "sm", className: "gap-2", children: /* @__PURE__ */ jsxs(Link, { href: "/backend/profile/communication-channels", children: [
326
+ /* @__PURE__ */ jsx(Mail, { className: "h-4 w-4" }),
327
+ t("customers.email.compose.noChannel.cta", "Connect your mailbox")
328
+ ] }) });
329
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
330
+ /* @__PURE__ */ jsx(
331
+ EmailThreadsPanel,
332
+ {
333
+ threads: mergedThreads,
334
+ loading,
335
+ error,
336
+ canCompose,
337
+ composeDisabledHint,
338
+ onComposeNew,
339
+ onReply,
340
+ onRefresh: () => {
341
+ void onRefresh();
342
+ },
343
+ onRetry: (message) => {
344
+ void onRetry(message);
345
+ }
346
+ }
347
+ ),
348
+ /* @__PURE__ */ jsx(
349
+ ComposeEmailDialog,
350
+ {
351
+ open: dialogOpen,
352
+ onOpenChange: setDialogOpen,
353
+ defaultRecipient,
354
+ channels,
355
+ replyTo,
356
+ onSend
357
+ }
358
+ )
359
+ ] });
360
+ }
361
+ var PersonEmailThreadsTab_default = PersonEmailThreadsTab;
362
+ export {
363
+ PersonEmailThreadsTab,
364
+ PersonEmailThreadsTab_default as default
365
+ };
366
+ //# sourceMappingURL=PersonEmailThreadsTab.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/customers/components/detail/PersonEmailThreadsTab.tsx"],
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport Link from 'next/link'\nimport { Mail } from 'lucide-react'\nimport { Button } from '@open-mercato/ui/primitives/button'\nimport {\n EmailThreadsPanel,\n mergeOptimisticEmailThreads,\n type EmailThread,\n type EmailThreadMessage,\n type EmailThreadMessageStatus,\n} from '@open-mercato/ui/backend/messages'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { useAppEvent } from '@open-mercato/ui/backend/injection/useAppEvent'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport {\n ComposeEmailDialog,\n type ComposeEmailChannel,\n type ComposeEmailValues,\n} from './ComposeEmailDialog'\n\ntype PersonEmailThreadsTabProps = {\n personId: string\n defaultRecipient?: string | null\n}\n\nconst CONTEXT_ID = 'customers-person-email-threads'\nconst MAX_REFERENCES = 40\n// Background heartbeat so inbound replies (fetched by the IMAP/push poll and\n// linked asynchronously) surface without a manual page reload.\nconst BACKGROUND_POLL_MS = 20000\n// After a send or a manual refresh, outbound delivery + CRM linking happen on a\n// queue worker \u2014 poll more aggressively for a short window to catch the new\n// message as soon as it lands, then fall back to the background heartbeat.\nconst BURST_INTERVAL_MS = 3000\nconst BURST_DURATION_MS = 36000\n\ntype ReplyState = {\n inReplyTo?: string\n references?: string[]\n to: string[]\n cc?: string[]\n subject: string\n parentMessageId?: string\n} | null\n\n/** A client-side outbound message shown immediately, before the worker confirms delivery. */\ntype OptimisticSend = {\n clientId: string\n threadKey: string\n /** Stored so a failed send can be retried with the same payload. */\n values: ComposeEmailValues\n message: EmailThreadMessage\n}\n\n/** Picks the external address to reply to: latest inbound sender, else a known participant. */\nfunction resolveReplyRecipient(thread: EmailThread, fallback: string | null): string | null {\n for (let i = thread.messages.length - 1; i >= 0; i -= 1) {\n const message = thread.messages[i]\n if (message.direction === 'inbound' && message.fromEmail) return message.fromEmail\n }\n return thread.participants[0] ?? fallback\n}\n\nfunction buildReplyState(thread: EmailThread, fallbackRecipient: string | null): ReplyState {\n const last = thread.messages[thread.messages.length - 1]\n if (!last) return null\n const recipient = resolveReplyRecipient(thread, fallbackRecipient)\n const references = Array.from(\n new Set([...(last.references ?? []), ...(last.rfcMessageId ? [last.rfcMessageId] : [])]),\n ).slice(-MAX_REFERENCES)\n const baseSubject = thread.subject ?? ''\n const subject = /^re:/i.test(baseSubject) ? baseSubject : `Re: ${baseSubject}`.trim()\n return {\n inReplyTo: last.rfcMessageId ?? undefined,\n references: references.length > 0 ? references : undefined,\n to: recipient ? [recipient] : [],\n subject,\n parentMessageId: last.messageId ?? undefined,\n }\n}\n\n/** Read the Open Mercato `messageId` off a delivery event payload, if present. */\nfunction readEventMessageId(event: unknown): string | null {\n const payload = (event as { payload?: unknown } | undefined)?.payload\n const messageId = (payload as { messageId?: unknown } | undefined)?.messageId\n return typeof messageId === 'string' ? messageId : null\n}\n\nexport function PersonEmailThreadsTab({ personId, defaultRecipient }: PersonEmailThreadsTabProps) {\n const t = useT()\n const [threads, setThreads] = React.useState<EmailThread[]>([])\n const [optimistic, setOptimistic] = React.useState<OptimisticSend[]>([])\n const [channels, setChannels] = React.useState<ComposeEmailChannel[]>([])\n const [loading, setLoading] = React.useState(true)\n const [error, setError] = React.useState<string | null>(null)\n const [dialogOpen, setDialogOpen] = React.useState(false)\n const [replyTo, setReplyTo] = React.useState<ReplyState>(null)\n const burstTimer = React.useRef<ReturnType<typeof setInterval> | null>(null)\n const channelsRef = React.useRef<ComposeEmailChannel[]>([])\n channelsRef.current = channels\n const optimisticRef = React.useRef<OptimisticSend[]>([])\n optimisticRef.current = optimistic\n\n const { runMutation, retryLastMutation } = useGuardedMutation<{\n formId: string\n resourceKind: string\n resourceId: string\n retryLastMutation: () => Promise<boolean>\n }>({\n contextId: CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n // `showLoading` drives the panel spinner; background/burst polls run silently\n // so they never flicker the already-rendered thread list.\n const loadThreads = React.useCallback(\n async (opts?: { showLoading?: boolean }) => {\n if (opts?.showLoading) setLoading(true)\n try {\n const response = await apiCall<{ threads?: EmailThread[] }>(\n `/api/customers/people/${encodeURIComponent(personId)}/email-threads`,\n // Background poll: degrade silently on an expired session instead of\n // hijacking the whole page with a login redirect.\n { method: 'GET', headers: { 'x-om-forbidden-redirect': '0', 'x-om-unauthorized-redirect': '0' } },\n )\n if (!response.ok) {\n const err = response.result as { error?: string } | null\n throw new Error(err?.error ?? t('customers.email.threads.loadFailed', 'Failed to load emails'))\n }\n setThreads(Array.isArray(response.result?.threads) ? response.result!.threads! : [])\n setError(null)\n } catch (err) {\n setError(err instanceof Error ? err.message : t('customers.email.threads.loadFailed', 'Failed to load emails'))\n } finally {\n if (opts?.showLoading) setLoading(false)\n }\n },\n [personId, t],\n )\n\n const loadChannels = React.useCallback(async () => {\n try {\n const response = await apiCall<{ items?: unknown[] }>(\n '/api/communication_channels/me/channels',\n { method: 'GET', headers: { 'x-om-forbidden-redirect': '0', 'x-om-unauthorized-redirect': '0' } },\n )\n const items: unknown[] = Array.isArray(response.result?.items) ? response.result!.items! : []\n const connected = items.filter(\n (item) =>\n item !== null &&\n typeof item === 'object' &&\n (item as Record<string, unknown>).status === 'connected',\n ) as ComposeEmailChannel[]\n setChannels(connected)\n } catch {\n setChannels([])\n }\n }, [])\n\n // Poll every connected mailbox now (fetches new mail server-side). Inbound\n // ingest + CRM linking happen on workers, so callers should burst-poll after.\n const triggerSync = React.useCallback(async () => {\n await Promise.allSettled(\n channelsRef.current.map((channel) => {\n const channelId = (channel as { id?: string }).id\n if (!channelId) return Promise.resolve()\n return apiCall(\n `/api/communication_channels/channels/${encodeURIComponent(channelId)}/poll-now`,\n { method: 'POST', headers: { 'x-om-forbidden-redirect': '0', 'x-om-unauthorized-redirect': '0' } },\n )\n }),\n )\n }, [])\n\n const startBurst = React.useCallback(() => {\n if (burstTimer.current) clearInterval(burstTimer.current)\n const startedAt = Date.now()\n burstTimer.current = setInterval(() => {\n if (Date.now() - startedAt > BURST_DURATION_MS) {\n if (burstTimer.current) {\n clearInterval(burstTimer.current)\n burstTimer.current = null\n }\n return\n }\n void loadThreads()\n }, BURST_INTERVAL_MS)\n }, [loadThreads])\n\n // Build the optimistic message rendered immediately after a send, deriving the\n // sender address/provider from the channel the user composed from.\n const buildOptimisticMessage = React.useCallback(\n (\n clientId: string,\n messageId: string | null,\n values: ComposeEmailValues,\n status: EmailThreadMessageStatus,\n ): EmailThreadMessage => {\n const channel = channelsRef.current.find(\n (c) => (c as { id?: string }).id === values.userChannelId,\n ) as { externalIdentifier?: string | null; providerKey?: string | null } | undefined\n return {\n id: `optimistic:${clientId}`,\n messageId,\n rfcMessageId: null,\n references: values.references ?? [],\n direction: 'outbound',\n fromName: null,\n fromEmail: channel?.externalIdentifier ?? null,\n to: values.to,\n cc: values.cc ?? [],\n subject: values.subject,\n bodyText: values.body,\n sentAt: new Date().toISOString(),\n providerKey: channel?.providerKey ?? null,\n status,\n }\n },\n [],\n )\n\n // Wrap the send through the mutation guard so record-lock/conflict handling and\n // retry flows run; shared by the initial send and the failure-retry path.\n const sendEmail = React.useCallback(\n async (values: ComposeEmailValues): Promise<{ messageId: string | null; threadId: string | null }> => {\n const operation = async () => {\n const response = await apiCall<{ messageId?: string; threadId?: string }>(\n `/api/customers/people/${encodeURIComponent(personId)}/emails`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify(values),\n },\n )\n if (!response.ok) {\n const err = response.result as { error?: string } | null\n throw new Error(err?.error ?? t('customers.email.errors.sendFailed', 'Send failed'))\n }\n return {\n messageId: response.result?.messageId ?? null,\n threadId: response.result?.threadId ?? null,\n }\n }\n const result = await runMutation({\n operation,\n context: {\n formId: CONTEXT_ID,\n resourceKind: 'customers.person',\n resourceId: personId,\n retryLastMutation,\n },\n mutationPayload: values as unknown as Record<string, unknown>,\n })\n return result ?? { messageId: null, threadId: null }\n },\n [personId, runMutation, retryLastMutation, t],\n )\n\n const setMessageStatus = React.useCallback(\n (matcher: (entry: OptimisticSend) => boolean, patch: Partial<EmailThreadMessage>) => {\n setOptimistic((prev) =>\n prev.map((entry) =>\n matcher(entry) ? { ...entry, message: { ...entry.message, ...patch } } : entry,\n ),\n )\n },\n [],\n )\n\n // Initial load.\n React.useEffect(() => {\n void loadThreads({ showLoading: true })\n void loadChannels()\n }, [loadThreads, loadChannels])\n\n // Background heartbeat \u2014 surfaces inbound replies without a page reload.\n React.useEffect(() => {\n const id = setInterval(() => { void loadThreads() }, BACKGROUND_POLL_MS)\n return () => clearInterval(id)\n }, [loadThreads])\n\n // Clean up the burst timer on unmount.\n React.useEffect(() => () => {\n if (burstTimer.current) clearInterval(burstTimer.current)\n }, [])\n\n // Drop optimistic placeholders once the server thread set includes the real,\n // linked message (deduped by messageId) so we never show it twice.\n React.useEffect(() => {\n setOptimistic((prev) => {\n if (prev.length === 0) return prev\n const serverIds = new Set<string>()\n for (const thread of threads) {\n for (const message of thread.messages) {\n if (message.messageId) serverIds.add(message.messageId)\n }\n }\n const next = prev.filter((entry) => !(entry.message.messageId && serverIds.has(entry.message.messageId)))\n return next.length === prev.length ? prev : next\n })\n }, [threads])\n\n // Live reconciliation via the DOM event bridge; polling above is the fallback.\n useAppEvent('customers.email.linked', () => { void loadThreads() }, [loadThreads])\n useAppEvent('messages.message.sent', () => { void loadThreads() }, [loadThreads])\n useAppEvent('communication_channels.message.received', () => { void loadThreads() }, [loadThreads])\n // Outbound delivery succeeded: flip the placeholder to \"sent\", then refetch so\n // the real linked message replaces it once the linking subscriber has run.\n useAppEvent(\n 'communication_channels.message.sent',\n (event) => {\n const messageId = readEventMessageId(event)\n if (messageId) setMessageStatus((e) => e.message.messageId === messageId, { status: 'sent' })\n void loadThreads()\n },\n [setMessageStatus, loadThreads],\n )\n // Outbound delivery failed: surface the failure inline with a Retry affordance.\n useAppEvent(\n 'communication_channels.message.delivery_failed',\n (event) => {\n const messageId = readEventMessageId(event)\n if (messageId) {\n setMessageStatus((e) => e.message.messageId === messageId, {\n status: 'failed',\n statusError: t('customers.email.errors.deliveryFailed', 'Delivery failed \u2014 not sent'),\n })\n }\n },\n [setMessageStatus, t],\n )\n\n const onComposeNew = React.useCallback(() => {\n setReplyTo(null)\n setDialogOpen(true)\n }, [])\n\n const onReply = React.useCallback(\n (thread: EmailThread) => {\n setReplyTo(buildReplyState(thread, defaultRecipient ?? null))\n setDialogOpen(true)\n },\n [defaultRecipient],\n )\n\n const onSend = React.useCallback(\n async (values: ComposeEmailValues) => {\n const { messageId, threadId } = await sendEmail(values)\n flash(t('customers.email.compose.sent', 'Email sent'), 'success')\n // Show the message immediately in a \"sending\" state. It reconciles to\n // \"sent\" (or \"failed\" + Retry) via the delivery events above, and is\n // replaced by the server record once the worker links it. Requires a\n // messageId so reconciliation can dedupe; otherwise fall back to polling.\n if (messageId) {\n const clientId = crypto.randomUUID()\n const message = buildOptimisticMessage(clientId, messageId, values, 'sending')\n setOptimistic((prev) => [\n ...prev,\n { clientId, threadKey: threadId ?? `optimistic:${clientId}`, values, message },\n ])\n }\n startBurst()\n return { messageId }\n },\n [sendEmail, t, buildOptimisticMessage, startBurst],\n )\n\n const onRetry = React.useCallback(\n async (message: EmailThreadMessage) => {\n const entry = optimisticRef.current.find((e) => e.message.id === message.id)\n if (!entry) return\n setMessageStatus((e) => e.message.id === message.id, { status: 'sending', statusError: null })\n try {\n const { messageId } = await sendEmail(entry.values)\n // Re-point the placeholder at the new message id so reconciliation works.\n setMessageStatus((e) => e.message.id === message.id, { messageId, status: 'sending' })\n startBurst()\n } catch (err) {\n setMessageStatus((e) => e.message.id === message.id, {\n status: 'failed',\n statusError: err instanceof Error ? err.message : t('customers.email.errors.sendFailed', 'Send failed'),\n })\n }\n },\n [sendEmail, setMessageStatus, startBurst, t],\n )\n\n const onRefresh = React.useCallback(async () => {\n setLoading(true)\n try {\n await triggerSync()\n await loadThreads()\n } finally {\n setLoading(false)\n }\n startBurst()\n }, [triggerSync, loadThreads, startBurst])\n\n const mergedThreads = React.useMemo(\n () =>\n mergeOptimisticEmailThreads(\n threads,\n optimistic.map((entry) => ({ ...entry.message, threadKey: entry.threadKey })),\n ),\n [threads, optimistic],\n )\n\n const canCompose = channels.length > 0\n\n const composeDisabledHint = (\n <Button asChild variant=\"outline\" size=\"sm\" className=\"gap-2\">\n <Link href=\"/backend/profile/communication-channels\">\n <Mail className=\"h-4 w-4\" />\n {t('customers.email.compose.noChannel.cta', 'Connect your mailbox')}\n </Link>\n </Button>\n )\n\n return (\n <>\n <EmailThreadsPanel\n threads={mergedThreads}\n loading={loading}\n error={error}\n canCompose={canCompose}\n composeDisabledHint={composeDisabledHint}\n onComposeNew={onComposeNew}\n onReply={onReply}\n onRefresh={() => { void onRefresh() }}\n onRetry={(message) => { void onRetry(message) }}\n />\n <ComposeEmailDialog\n open={dialogOpen}\n onOpenChange={setDialogOpen}\n defaultRecipient={defaultRecipient}\n channels={channels}\n replyTo={replyTo}\n onSend={onSend}\n />\n </>\n )\n}\n\nexport default PersonEmailThreadsTab\n"],
5
+ "mappings": ";AA+ZM,SAQF,UAPI,KADF;AA7ZN,YAAY,WAAW;AACvB,OAAO,UAAU;AACjB,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AACP,SAAS,eAAe;AACxB,SAAS,0BAA0B;AACnC,SAAS,mBAAmB;AAC5B,SAAS,aAAa;AACtB,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,OAGK;AAOP,MAAM,aAAa;AACnB,MAAM,iBAAiB;AAGvB,MAAM,qBAAqB;AAI3B,MAAM,oBAAoB;AAC1B,MAAM,oBAAoB;AAqB1B,SAAS,sBAAsB,QAAqB,UAAwC;AAC1F,WAAS,IAAI,OAAO,SAAS,SAAS,GA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AAW,MAAM,UAAU,EAAE;AAAA,IAC9E;AAAA,IACF,CAAC,SAAS,UAAU;AAAA,EACtB;AAEA,QAAM,aAAa,SAAS,SAAS;AAErC,QAAM,sBACJ,oBAAC,UAAO,SAAO,MAAC,SAAQ,WAAU,MAAK,MAAK,WAAU,SACpD,+BAAC,QAAK,MAAK,2CACT;AAAA,wBAAC,QAAK,WAAU,WAAU;AAAA,IACzB,EAAE,yCAAyC,sBAAsB;AAAA,KACpE,GACF;AAGF,SACE,iCACE;AAAA;AAAA,MAAC;AAAA;AAAA,QACC,SAAS;AAAA,QACT;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,WAAW,MAAM;AAAE,eAAK,UAAU;AAAA,QAAE;AAAA,QACpC,SAAS,CAAC,YAAY;AAAE,eAAK,QAAQ,OAAO;AAAA,QAAE;AAAA;AAAA,IAChD;AAAA,IACA;AAAA,MAAC;AAAA;AAAA,QACC,MAAM;AAAA,QACN,cAAc;AAAA,QACd;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA;AAAA,IACF;AAAA,KACF;AAEJ;AAEA,IAAO,gCAAQ;",
6
+ "names": []
7
+ }
@@ -15,6 +15,11 @@ function parseDate(value) {
15
15
  function diffDays(from, to) {
16
16
  return Math.floor((to.getTime() - from.getTime()) / DAY_MS);
17
17
  }
18
+ function stringArrayOrNull(value) {
19
+ if (!Array.isArray(value)) return null;
20
+ const strings = value.filter((entry) => typeof entry === "string");
21
+ return strings.length > 0 ? strings : null;
22
+ }
18
23
  async function fetchOpenInteractionCounts(db, dealIds, organizationId, tenantId) {
19
24
  const map = /* @__PURE__ */ new Map();
20
25
  if (dealIds.size === 0) return map;
@@ -126,9 +131,135 @@ const dealPipelineEnricher = {
126
131
  }));
127
132
  }
128
133
  };
129
- const enrichers = [dealPipelineEnricher];
134
+ const privateEmailCountEnricher = {
135
+ id: "customers.private-email-count",
136
+ targetEntity: "customers.person",
137
+ features: ["customers.people.view"],
138
+ priority: 30,
139
+ timeout: 1500,
140
+ fallback: { _privateEmailCount: 0 },
141
+ critical: false,
142
+ async enrichOne(record, context) {
143
+ const enriched = await this.enrichMany([record], context);
144
+ return enriched[0];
145
+ },
146
+ async enrichMany(records, context) {
147
+ if (records.length === 0) return records;
148
+ const db = resolveKyselyClient(context.em);
149
+ if (!db) {
150
+ return records.map((record) => ({ ...record, _privateEmailCount: 0 }));
151
+ }
152
+ const userId = context.userId;
153
+ if (!userId || userId.startsWith("api_key:")) {
154
+ return records.map((record) => ({ ...record, _privateEmailCount: 0 }));
155
+ }
156
+ const personIds = records.map((r) => r.id).filter((id) => typeof id === "string" && id.length > 0);
157
+ if (personIds.length === 0) {
158
+ return records.map((record) => ({ ...record, _privateEmailCount: 0 }));
159
+ }
160
+ const rows = await db.selectFrom("customer_interactions").select(["entity_id"]).select((eb) => eb.fn.countAll().as("count")).where("tenant_id", "=", context.tenantId).where("organization_id", "=", context.organizationId).where("interaction_type", "=", "email").where("visibility", "=", "private").where("deleted_at", "is", null).where("entity_id", "in", personIds).where("author_user_id", "!=", userId).groupBy("entity_id").execute();
161
+ const countMap = /* @__PURE__ */ new Map();
162
+ for (const row of rows) {
163
+ const personId = typeof row.entity_id === "string" ? row.entity_id : null;
164
+ if (!personId) continue;
165
+ const count = typeof row.count === "number" ? row.count : Number(row.count);
166
+ if (Number.isFinite(count)) countMap.set(personId, count);
167
+ }
168
+ return records.map((record) => ({
169
+ ...record,
170
+ _privateEmailCount: countMap.get(record.id) ?? 0
171
+ }));
172
+ }
173
+ };
174
+ const interactionEmailCardEnricher = {
175
+ id: "customers.interaction-email-card",
176
+ // Must match the entity ID passed to applyResponseEnrichers in the interactions
177
+ // GET route (api/interactions/route.ts line 539): 'customers.interaction'.
178
+ targetEntity: "customers.interaction",
179
+ features: ["customers.interactions.view"],
180
+ priority: 25,
181
+ timeout: 1500,
182
+ fallback: {},
183
+ critical: false,
184
+ async enrichOne(record, ctx) {
185
+ const results = await this.enrichMany([record], ctx);
186
+ return results[0];
187
+ },
188
+ async enrichMany(records, ctx) {
189
+ if (records.length === 0) return records;
190
+ const emailRecords = records.filter(
191
+ (r) => r.interactionType === "email" && typeof r.externalMessageId === "string" && r.externalMessageId.length > 0
192
+ );
193
+ if (emailRecords.length === 0) return records;
194
+ const linkIds = Array.from(
195
+ new Set(emailRecords.map((r) => r.externalMessageId))
196
+ );
197
+ const kysely = resolveKyselyClient(ctx.em);
198
+ if (!kysely) {
199
+ return records;
200
+ }
201
+ let linkRows;
202
+ try {
203
+ linkRows = await kysely.selectFrom("message_channel_links").select(["id", "channel_metadata"]).where("tenant_id", "=", ctx.tenantId).where(
204
+ (eb) => eb.or([
205
+ eb("organization_id", "=", ctx.organizationId),
206
+ eb("organization_id", "is", null)
207
+ ])
208
+ ).where("id", "in", linkIds).execute();
209
+ } catch {
210
+ return records;
211
+ }
212
+ const byLinkId = /* @__PURE__ */ new Map();
213
+ for (const row of linkRows) {
214
+ const meta = row.channel_metadata ?? {};
215
+ const fields = {
216
+ externalMessageId: row.id,
217
+ rfcMessageId: typeof meta.messageId === "string" ? meta.messageId : null,
218
+ fromAddress: typeof meta.from === "string" ? meta.from : null,
219
+ toAddresses: stringArrayOrNull(meta.to),
220
+ ccAddresses: stringArrayOrNull(meta.cc),
221
+ // bcc is intentionally NOT surfaced: BCC recipients are blind by design,
222
+ // so exposing them to every teammate who can view a shared email would
223
+ // leak the blind-copy list. Keep it out of the enriched response.
224
+ subject: typeof meta.subject === "string" ? meta.subject : null,
225
+ inReplyTo: typeof meta.inReplyTo === "string" ? meta.inReplyTo : null,
226
+ references: stringArrayOrNull(meta.references)
227
+ };
228
+ byLinkId.set(row.id, fields);
229
+ }
230
+ const currentUserId = ctx.userId;
231
+ return records.map((r) => {
232
+ if (r.interactionType !== "email" || typeof r.externalMessageId !== "string" || r.externalMessageId.length === 0) {
233
+ return r;
234
+ }
235
+ const fields = byLinkId.get(r.externalMessageId);
236
+ if (!fields) return r;
237
+ const visibility = r.visibility === "private" || r.visibility === "shared" ? r.visibility : null;
238
+ const authorUserId = typeof r.authorUserId === "string" ? r.authorUserId : null;
239
+ const isAuthor = Boolean(currentUserId && authorUserId && authorUserId === currentUserId);
240
+ if (visibility === "private" && !isAuthor) {
241
+ return r;
242
+ }
243
+ const existingIntegrations = r._integrations ?? {};
244
+ return {
245
+ ...r,
246
+ _integrations: {
247
+ ...existingIntegrations,
248
+ email: {
249
+ ...fields,
250
+ currentVisibility: visibility,
251
+ isAuthor
252
+ }
253
+ }
254
+ };
255
+ });
256
+ }
257
+ };
258
+ const enrichers = [dealPipelineEnricher, privateEmailCountEnricher, interactionEmailCardEnricher];
130
259
  export {
131
260
  buildPipelineState,
132
- enrichers
261
+ enrichers,
262
+ interactionEmailCardEnricher,
263
+ privateEmailCountEnricher
133
264
  };
134
265
  //# sourceMappingURL=enrichers.js.map