@open-mercato/core 0.6.6-develop.6465.1.019f0fb26f → 0.6.6-develop.6471.1.9ab5bdd79a

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 (1213) hide show
  1. package/dist/bootstrap.js +13 -11
  2. package/dist/bootstrap.js.map +2 -2
  3. package/dist/helpers/integration/queue-runner.js +4 -2
  4. package/dist/helpers/integration/queue-runner.js.map +2 -2
  5. package/dist/modules/api_keys/services/apiKeyService.js +5 -3
  6. package/dist/modules/api_keys/services/apiKeyService.js.map +2 -2
  7. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js +4 -2
  8. package/dist/modules/attachments/api/image/[id]/[[...slug]]/route.js.map +2 -2
  9. package/dist/modules/attachments/api/library/[id]/route.js +3 -1
  10. package/dist/modules/attachments/api/library/[id]/route.js.map +2 -2
  11. package/dist/modules/attachments/api/route.js +8 -6
  12. package/dist/modules/attachments/api/route.js.map +2 -2
  13. package/dist/modules/attachments/components/AttachmentPartitionSettings.js +5 -3
  14. package/dist/modules/attachments/components/AttachmentPartitionSettings.js.map +2 -2
  15. package/dist/modules/attachments/lib/assignmentDetails.js +3 -1
  16. package/dist/modules/attachments/lib/assignmentDetails.js.map +2 -2
  17. package/dist/modules/attachments/lib/drivers/driverFactory.js +3 -1
  18. package/dist/modules/attachments/lib/drivers/driverFactory.js.map +2 -2
  19. package/dist/modules/attachments/lib/ocrQueue.js +10 -11
  20. package/dist/modules/attachments/lib/ocrQueue.js.map +2 -2
  21. package/dist/modules/attachments/lib/ocrService.js +6 -4
  22. package/dist/modules/attachments/lib/ocrService.js.map +2 -2
  23. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js +3 -1
  24. package/dist/modules/audit_logs/api/audit-logs/actions/redo/route.js.map +2 -2
  25. package/dist/modules/audit_logs/api/audit-logs/actions/undo/route.js +3 -1
  26. package/dist/modules/audit_logs/api/audit-logs/actions/undo/route.js.map +2 -2
  27. package/dist/modules/audit_logs/backend/audit-logs/page.js +3 -1
  28. package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
  29. package/dist/modules/audit_logs/components/AuditLogsActions.js +4 -2
  30. package/dist/modules/audit_logs/components/AuditLogsActions.js.map +2 -2
  31. package/dist/modules/audit_logs/services/accessLogService.js +4 -2
  32. package/dist/modules/audit_logs/services/accessLogService.js.map +2 -2
  33. package/dist/modules/audit_logs/services/actionLogService.js +7 -5
  34. package/dist/modules/audit_logs/services/actionLogService.js.map +3 -3
  35. package/dist/modules/auth/api/profile/route.js +4 -2
  36. package/dist/modules/auth/api/profile/route.js.map +2 -2
  37. package/dist/modules/auth/api/reset/confirm.js +3 -1
  38. package/dist/modules/auth/api/reset/confirm.js.map +2 -2
  39. package/dist/modules/auth/api/reset.js +4 -2
  40. package/dist/modules/auth/api/reset.js.map +2 -2
  41. package/dist/modules/auth/api/roles/route.js +3 -1
  42. package/dist/modules/auth/api/roles/route.js.map +2 -2
  43. package/dist/modules/auth/api/sidebar/variants/route.js +3 -1
  44. package/dist/modules/auth/api/sidebar/variants/route.js.map +2 -2
  45. package/dist/modules/auth/api/users/resend-invite/route.js +4 -2
  46. package/dist/modules/auth/api/users/resend-invite/route.js.map +2 -2
  47. package/dist/modules/auth/api/users/route.js +3 -1
  48. package/dist/modules/auth/api/users/route.js.map +2 -2
  49. package/dist/modules/auth/backend/auth/profile/page.js +3 -1
  50. package/dist/modules/auth/backend/auth/profile/page.js.map +2 -2
  51. package/dist/modules/auth/backend/profile/change-password/page.js +3 -1
  52. package/dist/modules/auth/backend/profile/change-password/page.js.map +2 -2
  53. package/dist/modules/auth/backend/users/[id]/edit/page.js +5 -3
  54. package/dist/modules/auth/backend/users/[id]/edit/page.js.map +2 -2
  55. package/dist/modules/auth/backend/users/create/page.js +4 -2
  56. package/dist/modules/auth/backend/users/create/page.js.map +2 -2
  57. package/dist/modules/auth/cli.js +10 -0
  58. package/dist/modules/auth/cli.js.map +2 -2
  59. package/dist/modules/auth/commands/users.js +4 -2
  60. package/dist/modules/auth/commands/users.js.map +2 -2
  61. package/dist/modules/auth/lib/consentIntegrity.js +3 -3
  62. package/dist/modules/auth/lib/consentIntegrity.js.map +2 -2
  63. package/dist/modules/auth/lib/setup-app.js +9 -10
  64. package/dist/modules/auth/lib/setup-app.js.map +2 -2
  65. package/dist/modules/auth/lib/tenantAccess.js +3 -1
  66. package/dist/modules/auth/lib/tenantAccess.js.map +2 -2
  67. package/dist/modules/auth/lib/tokenHash.js +3 -3
  68. package/dist/modules/auth/lib/tokenHash.js.map +2 -2
  69. package/dist/modules/business_rules/api/rules/route.js +4 -2
  70. package/dist/modules/business_rules/api/rules/route.js.map +2 -2
  71. package/dist/modules/business_rules/lib/expression-evaluator.js +7 -5
  72. package/dist/modules/business_rules/lib/expression-evaluator.js.map +2 -2
  73. package/dist/modules/business_rules/lib/rule-engine.js +5 -3
  74. package/dist/modules/business_rules/lib/rule-engine.js.map +2 -2
  75. package/dist/modules/business_rules/lib/rule-evaluator.js +11 -12
  76. package/dist/modules/business_rules/lib/rule-evaluator.js.map +2 -2
  77. package/dist/modules/business_rules/subscribers/crud-rule-trigger.js +3 -1
  78. package/dist/modules/business_rules/subscribers/crud-rule-trigger.js.map +2 -2
  79. package/dist/modules/business_rules/subscribers/rule-execution-failed-notification.js +3 -1
  80. package/dist/modules/business_rules/subscribers/rule-execution-failed-notification.js.map +2 -2
  81. package/dist/modules/catalog/ai-agents-context.js +4 -5
  82. package/dist/modules/catalog/ai-agents-context.js.map +2 -2
  83. package/dist/modules/catalog/ai-tools/_shared.js +3 -1
  84. package/dist/modules/catalog/ai-tools/_shared.js.map +2 -2
  85. package/dist/modules/catalog/ai-tools/authoring-pack.js +3 -1
  86. package/dist/modules/catalog/ai-tools/authoring-pack.js.map +2 -2
  87. package/dist/modules/catalog/ai-tools/merchandising-pack.js +3 -1
  88. package/dist/modules/catalog/ai-tools/merchandising-pack.js.map +2 -2
  89. package/dist/modules/catalog/api/dictionaries/[key]/route.js +3 -1
  90. package/dist/modules/catalog/api/dictionaries/[key]/route.js.map +2 -2
  91. package/dist/modules/catalog/api/prices/route.js +3 -1
  92. package/dist/modules/catalog/api/prices/route.js.map +2 -2
  93. package/dist/modules/catalog/api/products/route.js +5 -3
  94. package/dist/modules/catalog/api/products/route.js.map +2 -2
  95. package/dist/modules/catalog/api/settings/route.js +4 -2
  96. package/dist/modules/catalog/api/settings/route.js.map +2 -2
  97. package/dist/modules/catalog/backend/catalog/products/[id]/page.js +14 -12
  98. package/dist/modules/catalog/backend/catalog/products/[id]/page.js.map +2 -2
  99. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.js +8 -6
  100. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.js.map +2 -2
  101. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/create/page.js +5 -3
  102. package/dist/modules/catalog/backend/catalog/products/[productId]/variants/create/page.js.map +2 -2
  103. package/dist/modules/catalog/backend/catalog/products/create/page.js +5 -6
  104. package/dist/modules/catalog/backend/catalog/products/create/page.js.map +2 -2
  105. package/dist/modules/catalog/backend/catalog/products/optionSchemaClient.js +3 -1
  106. package/dist/modules/catalog/backend/catalog/products/optionSchemaClient.js.map +2 -2
  107. package/dist/modules/catalog/components/PriceKindSettings.js +5 -3
  108. package/dist/modules/catalog/components/PriceKindSettings.js.map +2 -2
  109. package/dist/modules/catalog/components/UnitPriceDisplaySettings.js +4 -2
  110. package/dist/modules/catalog/components/UnitPriceDisplaySettings.js.map +2 -2
  111. package/dist/modules/catalog/inbox-actions.js +4 -2
  112. package/dist/modules/catalog/inbox-actions.js.map +2 -2
  113. package/dist/modules/catalog/seed/examples.js +4 -5
  114. package/dist/modules/catalog/seed/examples.js.map +2 -2
  115. package/dist/modules/catalog/subscribers/low-stock-notification.js +3 -1
  116. package/dist/modules/catalog/subscribers/low-stock-notification.js.map +2 -2
  117. package/dist/modules/catalog/widgets/injection/product-seo/state.js +3 -1
  118. package/dist/modules/catalog/widgets/injection/product-seo/state.js.map +2 -2
  119. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js +12 -11
  120. package/dist/modules/communication_channels/api/get/oauth/[provider]/callback/route.js.map +2 -2
  121. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js +3 -1
  122. package/dist/modules/communication_channels/api/post/channels/[id]/import-history/route.js.map +2 -2
  123. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js +3 -1
  124. package/dist/modules/communication_channels/api/post/channels/[id]/push/register/route.js.map +2 -2
  125. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js +5 -3
  126. package/dist/modules/communication_channels/api/post/webhook/[provider]/route.js.map +2 -2
  127. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js +6 -6
  128. package/dist/modules/communication_channels/api/post/webhooks/gmail/route.js.map +2 -2
  129. package/dist/modules/communication_channels/commands/connect-credential-channel.js +4 -6
  130. package/dist/modules/communication_channels/commands/connect-credential-channel.js.map +2 -2
  131. package/dist/modules/communication_channels/commands/delete-channel.js +3 -3
  132. package/dist/modules/communication_channels/commands/delete-channel.js.map +2 -2
  133. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +4 -5
  134. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
  135. package/dist/modules/communication_channels/commands/disconnect-channel.js +3 -3
  136. package/dist/modules/communication_channels/commands/disconnect-channel.js.map +2 -2
  137. package/dist/modules/communication_channels/commands/ingest-inbound-message.js +5 -12
  138. package/dist/modules/communication_channels/commands/ingest-inbound-message.js.map +2 -2
  139. package/dist/modules/communication_channels/commands/push-unregister.js +3 -3
  140. package/dist/modules/communication_channels/commands/push-unregister.js.map +2 -2
  141. package/dist/modules/communication_channels/commands/reassign-conversation.js +5 -3
  142. package/dist/modules/communication_channels/commands/reassign-conversation.js.map +2 -2
  143. package/dist/modules/communication_channels/lib/dead-letter.js +3 -3
  144. package/dist/modules/communication_channels/lib/dead-letter.js.map +2 -2
  145. package/dist/modules/communication_channels/lib/email-mime.js +4 -6
  146. package/dist/modules/communication_channels/lib/email-mime.js.map +2 -2
  147. package/dist/modules/communication_channels/lib/oauth-client-config.js +5 -3
  148. package/dist/modules/communication_channels/lib/oauth-client-config.js.map +2 -2
  149. package/dist/modules/communication_channels/lib/send-as-user.js +3 -1
  150. package/dist/modules/communication_channels/lib/send-as-user.js.map +2 -2
  151. package/dist/modules/communication_channels/lib/thread-token.js +4 -2
  152. package/dist/modules/communication_channels/lib/thread-token.js.map +2 -2
  153. package/dist/modules/communication_channels/setup.js +3 -4
  154. package/dist/modules/communication_channels/setup.js.map +2 -2
  155. package/dist/modules/communication_channels/workers/channel-import-history.js +4 -6
  156. package/dist/modules/communication_channels/workers/channel-import-history.js.map +2 -2
  157. package/dist/modules/communication_channels/workers/gmail-history-sync.js +8 -16
  158. package/dist/modules/communication_channels/workers/gmail-history-sync.js.map +2 -2
  159. package/dist/modules/communication_channels/workers/gmail-renew-watch.js +5 -7
  160. package/dist/modules/communication_channels/workers/gmail-renew-watch.js.map +2 -2
  161. package/dist/modules/communication_channels/workers/outbound-delivery.js +6 -12
  162. package/dist/modules/communication_channels/workers/outbound-delivery.js.map +2 -2
  163. package/dist/modules/communication_channels/workers/poll-channel.js +7 -15
  164. package/dist/modules/communication_channels/workers/poll-channel.js.map +2 -2
  165. package/dist/modules/communication_channels/workers/poll-tick.js +5 -6
  166. package/dist/modules/communication_channels/workers/poll-tick.js.map +2 -2
  167. package/dist/modules/communication_channels/workers/reaction-processor.js +5 -9
  168. package/dist/modules/communication_channels/workers/reaction-processor.js.map +2 -2
  169. package/dist/modules/configs/api/cache/route.js +4 -2
  170. package/dist/modules/configs/api/cache/route.js.map +2 -2
  171. package/dist/modules/configs/api/system-status/route.js +4 -2
  172. package/dist/modules/configs/api/system-status/route.js.map +2 -2
  173. package/dist/modules/configs/api/upgrade-actions/route.js +4 -2
  174. package/dist/modules/configs/api/upgrade-actions/route.js.map +2 -2
  175. package/dist/modules/configs/components/ModuleTelemetryPanel.js +3 -1
  176. package/dist/modules/configs/components/ModuleTelemetryPanel.js.map +2 -2
  177. package/dist/modules/configs/lib/touchGeneratedBarrels.js +2 -1
  178. package/dist/modules/configs/lib/touchGeneratedBarrels.js.map +2 -2
  179. package/dist/modules/configs/services/upgradeActionsService.js +6 -3
  180. package/dist/modules/configs/services/upgradeActionsService.js.map +2 -2
  181. package/dist/modules/currencies/components/CurrencyFetchingConfig.js +3 -1
  182. package/dist/modules/currencies/components/CurrencyFetchingConfig.js.map +2 -2
  183. package/dist/modules/currencies/lib/exchangeRateFormConfig.js +3 -1
  184. package/dist/modules/currencies/lib/exchangeRateFormConfig.js.map +2 -2
  185. package/dist/modules/currencies/services/providers/nbp.js +6 -4
  186. package/dist/modules/currencies/services/providers/nbp.js.map +2 -2
  187. package/dist/modules/currencies/services/providers/raiffeisen.js +7 -7
  188. package/dist/modules/currencies/services/providers/raiffeisen.js.map +2 -2
  189. package/dist/modules/customer_accounts/api/domain-resolve/all.js +6 -5
  190. package/dist/modules/customer_accounts/api/domain-resolve/all.js.map +2 -2
  191. package/dist/modules/customer_accounts/api/signup.js +4 -2
  192. package/dist/modules/customer_accounts/api/signup.js.map +2 -2
  193. package/dist/modules/customer_accounts/lib/customerAuthServer.js +3 -1
  194. package/dist/modules/customer_accounts/lib/customerAuthServer.js.map +2 -2
  195. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js +3 -1
  196. package/dist/modules/customer_accounts/subscribers/autoLinkCrm.js.map +2 -2
  197. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js +3 -1
  198. package/dist/modules/customer_accounts/subscribers/autoLinkCrmReverse.js.map +2 -2
  199. package/dist/modules/customer_accounts/subscribers/unlinkOnCompanyDelete.js +3 -1
  200. package/dist/modules/customer_accounts/subscribers/unlinkOnCompanyDelete.js.map +2 -2
  201. package/dist/modules/customer_accounts/subscribers/unlinkOnPersonDelete.js +3 -1
  202. package/dist/modules/customer_accounts/subscribers/unlinkOnPersonDelete.js.map +2 -2
  203. package/dist/modules/customers/ai-agents-context.js +4 -5
  204. package/dist/modules/customers/ai-agents-context.js.map +2 -2
  205. package/dist/modules/customers/api/activities/route.js +6 -4
  206. package/dist/modules/customers/api/activities/route.js.map +2 -2
  207. package/dist/modules/customers/api/comments/route.js +3 -1
  208. package/dist/modules/customers/api/comments/route.js.map +2 -2
  209. package/dist/modules/customers/api/companies/[id]/people/route.js +3 -1
  210. package/dist/modules/customers/api/companies/[id]/people/route.js.map +2 -2
  211. package/dist/modules/customers/api/companies/[id]/route.js +5 -3
  212. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  213. package/dist/modules/customers/api/companies/route.js +5 -3
  214. package/dist/modules/customers/api/companies/route.js.map +2 -2
  215. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js +3 -1
  216. package/dist/modules/customers/api/dashboard/widgets/customer-todos/route.js.map +2 -2
  217. package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js +3 -1
  218. package/dist/modules/customers/api/dashboard/widgets/new-customers/route.js.map +2 -2
  219. package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js +3 -1
  220. package/dist/modules/customers/api/dashboard/widgets/new-deals/route.js.map +2 -2
  221. package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js +3 -1
  222. package/dist/modules/customers/api/dashboard/widgets/next-interactions/route.js.map +2 -2
  223. package/dist/modules/customers/api/deals/[id]/companies/route.js +3 -1
  224. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +2 -2
  225. package/dist/modules/customers/api/deals/[id]/people/route.js +3 -1
  226. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  227. package/dist/modules/customers/api/deals/aggregate/route.js +3 -1
  228. package/dist/modules/customers/api/deals/aggregate/route.js.map +2 -2
  229. package/dist/modules/customers/api/deals/bulk-update-owner/route.js +7 -5
  230. package/dist/modules/customers/api/deals/bulk-update-owner/route.js.map +2 -2
  231. package/dist/modules/customers/api/deals/bulk-update-stage/route.js +7 -5
  232. package/dist/modules/customers/api/deals/bulk-update-stage/route.js.map +2 -2
  233. package/dist/modules/customers/api/deals/route.js +3 -1
  234. package/dist/modules/customers/api/deals/route.js.map +2 -2
  235. package/dist/modules/customers/api/deals/summary/route.js +3 -1
  236. package/dist/modules/customers/api/deals/summary/route.js.map +2 -2
  237. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +4 -2
  238. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  239. package/dist/modules/customers/api/dictionaries/[kind]/route.js +5 -3
  240. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  241. package/dist/modules/customers/api/dictionaries/cache.js +3 -1
  242. package/dist/modules/customers/api/dictionaries/cache.js.map +2 -2
  243. package/dist/modules/customers/api/dictionaries/context.js +3 -1
  244. package/dist/modules/customers/api/dictionaries/context.js.map +2 -2
  245. package/dist/modules/customers/api/dictionaries/currency/route.js +3 -1
  246. package/dist/modules/customers/api/dictionaries/currency/route.js.map +2 -2
  247. package/dist/modules/customers/api/dictionaries/kind-settings/route.js +4 -2
  248. package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +2 -2
  249. package/dist/modules/customers/api/entity-roles-factory.js +7 -5
  250. package/dist/modules/customers/api/entity-roles-factory.js.map +2 -2
  251. package/dist/modules/customers/api/interactions/cancel/route.js +3 -1
  252. package/dist/modules/customers/api/interactions/cancel/route.js.map +2 -2
  253. package/dist/modules/customers/api/interactions/complete/route.js +3 -1
  254. package/dist/modules/customers/api/interactions/complete/route.js.map +2 -2
  255. package/dist/modules/customers/api/interactions/conflicts/route.js +3 -1
  256. package/dist/modules/customers/api/interactions/conflicts/route.js.map +2 -2
  257. package/dist/modules/customers/api/interactions/counts/route.js +3 -1
  258. package/dist/modules/customers/api/interactions/counts/route.js.map +2 -2
  259. package/dist/modules/customers/api/interactions/route.js +7 -4
  260. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  261. package/dist/modules/customers/api/interactions/tasks/route.js +3 -1
  262. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  263. package/dist/modules/customers/api/labels/assign/route.js +3 -1
  264. package/dist/modules/customers/api/labels/assign/route.js.map +2 -2
  265. package/dist/modules/customers/api/labels/route.js +6 -3
  266. package/dist/modules/customers/api/labels/route.js.map +2 -2
  267. package/dist/modules/customers/api/labels/unassign/route.js +3 -1
  268. package/dist/modules/customers/api/labels/unassign/route.js.map +2 -2
  269. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +3 -1
  270. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +2 -2
  271. package/dist/modules/customers/api/people/[id]/route.js +5 -3
  272. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  273. package/dist/modules/customers/api/people/route.js +5 -3
  274. package/dist/modules/customers/api/people/route.js.map +2 -2
  275. package/dist/modules/customers/api/pipeline-stages/reorder/route.js +3 -1
  276. package/dist/modules/customers/api/pipeline-stages/reorder/route.js.map +2 -2
  277. package/dist/modules/customers/api/pipeline-stages/route.js +6 -4
  278. package/dist/modules/customers/api/pipeline-stages/route.js.map +2 -2
  279. package/dist/modules/customers/api/pipelines/route.js +6 -4
  280. package/dist/modules/customers/api/pipelines/route.js.map +2 -2
  281. package/dist/modules/customers/api/settings/address-format/route.js +4 -2
  282. package/dist/modules/customers/api/settings/address-format/route.js.map +2 -2
  283. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js +4 -2
  284. package/dist/modules/customers/api/settings/dictionary-sort-modes/route.js.map +2 -2
  285. package/dist/modules/customers/api/settings/stuck-threshold/route.js +4 -2
  286. package/dist/modules/customers/api/settings/stuck-threshold/route.js.map +2 -2
  287. package/dist/modules/customers/api/tags/assign/route.js +3 -1
  288. package/dist/modules/customers/api/tags/assign/route.js.map +2 -2
  289. package/dist/modules/customers/api/tags/unassign/route.js +3 -1
  290. package/dist/modules/customers/api/tags/unassign/route.js.map +2 -2
  291. package/dist/modules/customers/api/todos/route.js +6 -4
  292. package/dist/modules/customers/api/todos/route.js.map +2 -2
  293. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +5 -3
  294. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +2 -2
  295. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.js +3 -1
  296. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.js.map +2 -2
  297. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js +3 -1
  298. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js.map +2 -2
  299. package/dist/modules/customers/backend/customers/deals/map/components/DealsMapCanvasImpl.js +4 -2
  300. package/dist/modules/customers/backend/customers/deals/map/components/DealsMapCanvasImpl.js.map +2 -2
  301. package/dist/modules/customers/backend/customers/deals/page.js +4 -2
  302. package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
  303. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js +5 -3
  304. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js.map +2 -2
  305. package/dist/modules/customers/commands/deals.js +3 -1
  306. package/dist/modules/customers/commands/deals.js.map +2 -2
  307. package/dist/modules/customers/commands/dictionaries.js +3 -1
  308. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  309. package/dist/modules/customers/commands/interactions.js +4 -2
  310. package/dist/modules/customers/commands/interactions.js.map +2 -2
  311. package/dist/modules/customers/commands/shared.js +4 -2
  312. package/dist/modules/customers/commands/shared.js.map +2 -2
  313. package/dist/modules/customers/commands/todos.js +3 -1
  314. package/dist/modules/customers/commands/todos.js.map +2 -2
  315. package/dist/modules/customers/components/DictionarySettings.js +5 -3
  316. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  317. package/dist/modules/customers/components/DictionarySortSettings.js +3 -1
  318. package/dist/modules/customers/components/DictionarySortSettings.js.map +2 -2
  319. package/dist/modules/customers/components/detail/ActivitiesCard.js +3 -1
  320. package/dist/modules/customers/components/detail/ActivitiesCard.js.map +2 -2
  321. package/dist/modules/customers/components/detail/ActivitiesDayStrip.js +3 -1
  322. package/dist/modules/customers/components/detail/ActivitiesDayStrip.js.map +2 -2
  323. package/dist/modules/customers/components/detail/ActivitiesSection.js +6 -4
  324. package/dist/modules/customers/components/detail/ActivitiesSection.js.map +2 -2
  325. package/dist/modules/customers/components/detail/ActivityCard.js +3 -1
  326. package/dist/modules/customers/components/detail/ActivityCard.js.map +2 -2
  327. package/dist/modules/customers/components/detail/ChangelogTab.js +3 -1
  328. package/dist/modules/customers/components/detail/ChangelogTab.js.map +2 -2
  329. package/dist/modules/customers/components/detail/CompanyCard.js +3 -1
  330. package/dist/modules/customers/components/detail/CompanyCard.js.map +2 -2
  331. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js +3 -1
  332. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js.map +2 -2
  333. package/dist/modules/customers/components/detail/EntityTagsDialog.js +3 -1
  334. package/dist/modules/customers/components/detail/EntityTagsDialog.js.map +2 -2
  335. package/dist/modules/customers/components/detail/InlineActivityComposer.js +3 -1
  336. package/dist/modules/customers/components/detail/InlineActivityComposer.js.map +2 -2
  337. package/dist/modules/customers/components/detail/ManageTagsDialog.js +3 -1
  338. package/dist/modules/customers/components/detail/ManageTagsDialog.js.map +2 -2
  339. package/dist/modules/customers/components/detail/RoleAssignmentRow.js +5 -3
  340. package/dist/modules/customers/components/detail/RoleAssignmentRow.js.map +2 -2
  341. package/dist/modules/customers/components/detail/RolesSection.js +4 -2
  342. package/dist/modules/customers/components/detail/RolesSection.js.map +2 -2
  343. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js +5 -3
  344. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js.map +2 -2
  345. package/dist/modules/customers/components/linking/LinkEntityDialog.js +4 -2
  346. package/dist/modules/customers/components/linking/LinkEntityDialog.js.map +2 -2
  347. package/dist/modules/customers/inbox-actions.js +3 -1
  348. package/dist/modules/customers/inbox-actions.js.map +2 -2
  349. package/dist/modules/customers/lib/bulkDeals.js +3 -1
  350. package/dist/modules/customers/lib/bulkDeals.js.map +2 -2
  351. package/dist/modules/customers/lib/dealClosureNotification.js +4 -2
  352. package/dist/modules/customers/lib/dealClosureNotification.js.map +2 -2
  353. package/dist/modules/customers/lib/dealStageTransitionTable.js +3 -1
  354. package/dist/modules/customers/lib/dealStageTransitionTable.js.map +2 -2
  355. package/dist/modules/customers/lib/interactionFeatureFlags.js +3 -1
  356. package/dist/modules/customers/lib/interactionFeatureFlags.js.map +2 -2
  357. package/dist/modules/customers/lib/todoCompatibility.js +3 -1
  358. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  359. package/dist/modules/customers/search.js +14 -7
  360. package/dist/modules/customers/search.js.map +2 -2
  361. package/dist/modules/customers/widgets/dashboard/customer-todos/widget.client.js +3 -1
  362. package/dist/modules/customers/widgets/dashboard/customer-todos/widget.client.js.map +2 -2
  363. package/dist/modules/customers/widgets/dashboard/new-customers/widget.client.js +3 -1
  364. package/dist/modules/customers/widgets/dashboard/new-customers/widget.client.js.map +2 -2
  365. package/dist/modules/customers/widgets/dashboard/new-deals/widget.client.js +3 -1
  366. package/dist/modules/customers/widgets/dashboard/new-deals/widget.client.js.map +2 -2
  367. package/dist/modules/customers/widgets/dashboard/next-interactions/widget.client.js +3 -1
  368. package/dist/modules/customers/widgets/dashboard/next-interactions/widget.client.js.map +2 -2
  369. package/dist/modules/dashboards/api/widgets/data/batch/route.js +3 -1
  370. package/dist/modules/dashboards/api/widgets/data/batch/route.js.map +2 -2
  371. package/dist/modules/dashboards/api/widgets/data/route.js +3 -1
  372. package/dist/modules/dashboards/api/widgets/data/route.js.map +2 -2
  373. package/dist/modules/dashboards/components/WidgetVisibilityEditor.js +5 -3
  374. package/dist/modules/dashboards/components/WidgetVisibilityEditor.js.map +2 -2
  375. package/dist/modules/dashboards/widgets/dashboard/aov-kpi/widget.client.js +3 -1
  376. package/dist/modules/dashboards/widgets/dashboard/aov-kpi/widget.client.js.map +2 -2
  377. package/dist/modules/dashboards/widgets/dashboard/new-customers-kpi/widget.client.js +3 -1
  378. package/dist/modules/dashboards/widgets/dashboard/new-customers-kpi/widget.client.js.map +2 -2
  379. package/dist/modules/dashboards/widgets/dashboard/orders-by-status/widget.client.js +3 -1
  380. package/dist/modules/dashboards/widgets/dashboard/orders-by-status/widget.client.js.map +2 -2
  381. package/dist/modules/dashboards/widgets/dashboard/orders-kpi/widget.client.js +3 -1
  382. package/dist/modules/dashboards/widgets/dashboard/orders-kpi/widget.client.js.map +2 -2
  383. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js +3 -1
  384. package/dist/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.js.map +2 -2
  385. package/dist/modules/dashboards/widgets/dashboard/revenue-kpi/widget.client.js +3 -1
  386. package/dist/modules/dashboards/widgets/dashboard/revenue-kpi/widget.client.js.map +2 -2
  387. package/dist/modules/dashboards/widgets/dashboard/revenue-trend/widget.client.js +3 -1
  388. package/dist/modules/dashboards/widgets/dashboard/revenue-trend/widget.client.js.map +2 -2
  389. package/dist/modules/dashboards/widgets/dashboard/sales-by-region/widget.client.js +3 -1
  390. package/dist/modules/dashboards/widgets/dashboard/sales-by-region/widget.client.js.map +2 -2
  391. package/dist/modules/dashboards/widgets/dashboard/top-customers/widget.client.js +3 -1
  392. package/dist/modules/dashboards/widgets/dashboard/top-customers/widget.client.js.map +2 -2
  393. package/dist/modules/dashboards/widgets/dashboard/top-products/widget.client.js +3 -1
  394. package/dist/modules/dashboards/widgets/dashboard/top-products/widget.client.js.map +2 -2
  395. package/dist/modules/data_sync/api/run.js +3 -1
  396. package/dist/modules/data_sync/api/run.js.map +2 -2
  397. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js +1 -1
  398. package/dist/modules/data_sync/backend/data-sync/runs/[id]/page.js.map +2 -2
  399. package/dist/modules/data_sync/lib/adapter-registry.js +11 -4
  400. package/dist/modules/data_sync/lib/adapter-registry.js.map +2 -2
  401. package/dist/modules/data_sync/lib/sync-engine.js +23 -2
  402. package/dist/modules/data_sync/lib/sync-engine.js.map +2 -2
  403. package/dist/modules/data_sync/workers/sync-export.js +3 -1
  404. package/dist/modules/data_sync/workers/sync-export.js.map +2 -2
  405. package/dist/modules/data_sync/workers/sync-import.js +3 -1
  406. package/dist/modules/data_sync/workers/sync-import.js.map +2 -2
  407. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +4 -2
  408. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  409. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js +3 -1
  410. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js.map +2 -2
  411. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +4 -2
  412. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  413. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js +3 -1
  414. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js.map +2 -2
  415. package/dist/modules/dictionaries/api/[dictionaryId]/route.js +5 -3
  416. package/dist/modules/dictionaries/api/[dictionaryId]/route.js.map +2 -2
  417. package/dist/modules/dictionaries/api/context.js +3 -1
  418. package/dist/modules/dictionaries/api/context.js.map +2 -2
  419. package/dist/modules/dictionaries/api/route.js +4 -2
  420. package/dist/modules/dictionaries/api/route.js.map +2 -2
  421. package/dist/modules/dictionaries/components/DictionariesManager.js +5 -3
  422. package/dist/modules/dictionaries/components/DictionariesManager.js.map +2 -2
  423. package/dist/modules/dictionaries/components/DictionaryEntriesEditor.js +4 -2
  424. package/dist/modules/dictionaries/components/DictionaryEntriesEditor.js.map +2 -2
  425. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js +4 -2
  426. package/dist/modules/dictionaries/components/DictionaryEntrySelect.js.map +2 -2
  427. package/dist/modules/dictionaries/components/DictionarySelectControl.js +3 -1
  428. package/dist/modules/dictionaries/components/DictionarySelectControl.js.map +2 -2
  429. package/dist/modules/dictionaries/fields/dictionary.js +3 -1
  430. package/dist/modules/dictionaries/fields/dictionary.js.map +2 -2
  431. package/dist/modules/directory/api/organization-branding/route.js +3 -1
  432. package/dist/modules/directory/api/organization-branding/route.js.map +2 -2
  433. package/dist/modules/directory/api/organization-switcher/route.js +3 -1
  434. package/dist/modules/directory/api/organization-switcher/route.js.map +2 -2
  435. package/dist/modules/directory/commands/tenants.js +5 -3
  436. package/dist/modules/directory/commands/tenants.js.map +2 -2
  437. package/dist/modules/directory/utils/organizationScope.js +6 -4
  438. package/dist/modules/directory/utils/organizationScope.js.map +2 -2
  439. package/dist/modules/entities/api/definitions.cache.js +3 -1
  440. package/dist/modules/entities/api/definitions.cache.js.map +2 -2
  441. package/dist/modules/entities/api/definitions.js +7 -5
  442. package/dist/modules/entities/api/definitions.js.map +2 -2
  443. package/dist/modules/entities/api/records.js +4 -8
  444. package/dist/modules/entities/api/records.js.map +2 -2
  445. package/dist/modules/entities/components/EncryptionManager.js +3 -1
  446. package/dist/modules/entities/components/EncryptionManager.js.map +2 -2
  447. package/dist/modules/entities/lib/makeActivityRoute.js +3 -1
  448. package/dist/modules/entities/lib/makeActivityRoute.js.map +2 -2
  449. package/dist/modules/feature_toggles/api/overrides/route.js +3 -1
  450. package/dist/modules/feature_toggles/api/overrides/route.js.map +2 -2
  451. package/dist/modules/feature_toggles/lib/feature-flag-check.js +5 -9
  452. package/dist/modules/feature_toggles/lib/feature-flag-check.js.map +2 -2
  453. package/dist/modules/inbox_ops/api/emails/[id]/reprocess/route.js +4 -2
  454. package/dist/modules/inbox_ops/api/emails/[id]/reprocess/route.js.map +2 -2
  455. package/dist/modules/inbox_ops/api/emails/[id]/route.js +4 -2
  456. package/dist/modules/inbox_ops/api/emails/[id]/route.js.map +2 -2
  457. package/dist/modules/inbox_ops/api/emails/route.js +3 -1
  458. package/dist/modules/inbox_ops/api/emails/route.js.map +2 -2
  459. package/dist/modules/inbox_ops/api/extract/route.js +3 -1
  460. package/dist/modules/inbox_ops/api/extract/route.js.map +2 -2
  461. package/dist/modules/inbox_ops/api/proposals/[id]/actions/[actionId]/route.js +3 -1
  462. package/dist/modules/inbox_ops/api/proposals/[id]/actions/[actionId]/route.js.map +2 -2
  463. package/dist/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.js +4 -2
  464. package/dist/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.js.map +2 -2
  465. package/dist/modules/inbox_ops/api/proposals/counts/route.js +4 -2
  466. package/dist/modules/inbox_ops/api/proposals/counts/route.js.map +2 -2
  467. package/dist/modules/inbox_ops/api/proposals/route.js +3 -1
  468. package/dist/modules/inbox_ops/api/proposals/route.js.map +2 -2
  469. package/dist/modules/inbox_ops/api/routeHelpers.js +3 -1
  470. package/dist/modules/inbox_ops/api/routeHelpers.js.map +2 -2
  471. package/dist/modules/inbox_ops/api/settings/route.js +3 -1
  472. package/dist/modules/inbox_ops/api/settings/route.js.map +2 -2
  473. package/dist/modules/inbox_ops/api/webhook/inbound.js +7 -5
  474. package/dist/modules/inbox_ops/api/webhook/inbound.js.map +2 -2
  475. package/dist/modules/inbox_ops/lib/cache.js +4 -2
  476. package/dist/modules/inbox_ops/lib/cache.js.map +2 -2
  477. package/dist/modules/inbox_ops/lib/catalogLookup.js +3 -1
  478. package/dist/modules/inbox_ops/lib/catalogLookup.js.map +2 -2
  479. package/dist/modules/inbox_ops/lib/eventBus.js +3 -4
  480. package/dist/modules/inbox_ops/lib/eventBus.js.map +2 -2
  481. package/dist/modules/inbox_ops/lib/messagesIntegration.js +4 -8
  482. package/dist/modules/inbox_ops/lib/messagesIntegration.js.map +2 -2
  483. package/dist/modules/inbox_ops/subscribers/executionAuditor.js +3 -1
  484. package/dist/modules/inbox_ops/subscribers/executionAuditor.js.map +2 -2
  485. package/dist/modules/inbox_ops/subscribers/extractionWorker.js +10 -8
  486. package/dist/modules/inbox_ops/subscribers/extractionWorker.js.map +2 -2
  487. package/dist/modules/inbox_ops/subscribers/proposalNotifier.js +3 -1
  488. package/dist/modules/inbox_ops/subscribers/proposalNotifier.js.map +2 -2
  489. package/dist/modules/messages/api/[id]/route.js +3 -4
  490. package/dist/modules/messages/api/[id]/route.js.map +2 -2
  491. package/dist/modules/messages/commands/actions.js +3 -1
  492. package/dist/modules/messages/commands/actions.js.map +2 -2
  493. package/dist/modules/messages/components/MessagesInboxPageClient.js +3 -1
  494. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  495. package/dist/modules/messages/lib/email-sender.js +3 -7
  496. package/dist/modules/messages/lib/email-sender.js.map +2 -2
  497. package/dist/modules/messages/lib/message-objects-registry.js +3 -1
  498. package/dist/modules/messages/lib/message-objects-registry.js.map +2 -2
  499. package/dist/modules/messages/lib/message-types-registry.js +3 -1
  500. package/dist/modules/messages/lib/message-types-registry.js.map +2 -2
  501. package/dist/modules/messages/workers/send-email.worker.js +6 -4
  502. package/dist/modules/messages/workers/send-email.worker.js.map +2 -2
  503. package/dist/modules/notifications/lib/notificationMapper.js +3 -4
  504. package/dist/modules/notifications/lib/notificationMapper.js.map +2 -2
  505. package/dist/modules/notifications/lib/notificationService.js +4 -5
  506. package/dist/modules/notifications/lib/notificationService.js.map +2 -2
  507. package/dist/modules/notifications/subscribers/deliver-notification.js +8 -13
  508. package/dist/modules/notifications/subscribers/deliver-notification.js.map +2 -2
  509. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +3 -1
  510. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
  511. package/dist/modules/perspectives/services/perspectiveService.js +3 -3
  512. package/dist/modules/perspectives/services/perspectiveService.js.map +2 -2
  513. package/dist/modules/planner/api/access.js +3 -3
  514. package/dist/modules/planner/api/access.js.map +2 -2
  515. package/dist/modules/planner/api/availability-date-specific.js +3 -1
  516. package/dist/modules/planner/api/availability-date-specific.js.map +2 -2
  517. package/dist/modules/planner/api/availability-weekly.js +3 -1
  518. package/dist/modules/planner/api/availability-weekly.js.map +2 -2
  519. package/dist/modules/planner/backend/planner/availability-rulesets/page.js +4 -2
  520. package/dist/modules/planner/backend/planner/availability-rulesets/page.js.map +2 -2
  521. package/dist/modules/planner/components/AvailabilityRulesEditor.js +3 -1
  522. package/dist/modules/planner/components/AvailabilityRulesEditor.js.map +2 -2
  523. package/dist/modules/progress/api/jobs/route.js +3 -1
  524. package/dist/modules/progress/api/jobs/route.js.map +2 -2
  525. package/dist/modules/query_index/components/QueryIndexesTable.js +5 -3
  526. package/dist/modules/query_index/components/QueryIndexesTable.js.map +2 -2
  527. package/dist/modules/query_index/lib/batch.js +4 -2
  528. package/dist/modules/query_index/lib/batch.js.map +2 -2
  529. package/dist/modules/query_index/lib/coverage.js +3 -1
  530. package/dist/modules/query_index/lib/coverage.js.map +2 -2
  531. package/dist/modules/query_index/lib/engine.js +13 -18
  532. package/dist/modules/query_index/lib/engine.js.map +2 -2
  533. package/dist/modules/query_index/lib/reindexer.js +8 -6
  534. package/dist/modules/query_index/lib/reindexer.js.map +2 -2
  535. package/dist/modules/query_index/lib/search-tokens.js +3 -1
  536. package/dist/modules/query_index/lib/search-tokens.js.map +2 -2
  537. package/dist/modules/query_index/subscribers/coverage_refresh.js +3 -1
  538. package/dist/modules/query_index/subscribers/coverage_refresh.js.map +2 -2
  539. package/dist/modules/resources/api/comments.js +3 -1
  540. package/dist/modules/resources/api/comments.js.map +2 -2
  541. package/dist/modules/resources/api/resources/tags/assign/route.js +3 -1
  542. package/dist/modules/resources/api/resources/tags/assign/route.js.map +2 -2
  543. package/dist/modules/resources/api/resources/tags/unassign/route.js +3 -1
  544. package/dist/modules/resources/api/resources/tags/unassign/route.js.map +2 -2
  545. package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js +3 -1
  546. package/dist/modules/resources/backend/resources/resource-types/[id]/edit/page.js.map +2 -2
  547. package/dist/modules/resources/backend/resources/resource-types/page.js +4 -2
  548. package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
  549. package/dist/modules/resources/commands/activities.js +6 -5
  550. package/dist/modules/resources/commands/activities.js.map +2 -2
  551. package/dist/modules/resources/commands/comments.js +6 -4
  552. package/dist/modules/resources/commands/comments.js.map +2 -2
  553. package/dist/modules/resources/commands/shared.js +24 -1
  554. package/dist/modules/resources/commands/shared.js.map +2 -2
  555. package/dist/modules/sales/api/channels/route.js +3 -1
  556. package/dist/modules/sales/api/channels/route.js.map +2 -2
  557. package/dist/modules/sales/api/document-history/route.js +3 -1
  558. package/dist/modules/sales/api/document-history/route.js.map +2 -2
  559. package/dist/modules/sales/api/document-numbers/route.js +3 -1
  560. package/dist/modules/sales/api/document-numbers/route.js.map +2 -2
  561. package/dist/modules/sales/api/quotes/accept/route.js +4 -2
  562. package/dist/modules/sales/api/quotes/accept/route.js.map +2 -2
  563. package/dist/modules/sales/api/quotes/convert/route.js +3 -1
  564. package/dist/modules/sales/api/quotes/convert/route.js.map +2 -2
  565. package/dist/modules/sales/api/quotes/public/[token]/route.js +3 -1
  566. package/dist/modules/sales/api/quotes/public/[token]/route.js.map +2 -2
  567. package/dist/modules/sales/api/quotes/send/route.js +3 -1
  568. package/dist/modules/sales/api/quotes/send/route.js.map +2 -2
  569. package/dist/modules/sales/api/returns/[id]/route.js +3 -1
  570. package/dist/modules/sales/api/returns/[id]/route.js.map +2 -2
  571. package/dist/modules/sales/api/settings/document-numbers/route.js +4 -2
  572. package/dist/modules/sales/api/settings/document-numbers/route.js.map +2 -2
  573. package/dist/modules/sales/api/settings/order-editing/route.js +4 -2
  574. package/dist/modules/sales/api/settings/order-editing/route.js.map +2 -2
  575. package/dist/modules/sales/backend/sales/channels/[channelId]/edit/page.js +3 -1
  576. package/dist/modules/sales/backend/sales/channels/[channelId]/edit/page.js.map +2 -2
  577. package/dist/modules/sales/backend/sales/channels/offers/page.js +6 -4
  578. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  579. package/dist/modules/sales/backend/sales/channels/page.js +4 -2
  580. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  581. package/dist/modules/sales/backend/sales/documents/[id]/page.js +20 -18
  582. package/dist/modules/sales/backend/sales/documents/[id]/page.js.map +2 -2
  583. package/dist/modules/sales/commands/documents.js +4 -8
  584. package/dist/modules/sales/commands/documents.js.map +2 -2
  585. package/dist/modules/sales/commands/payments.js +3 -1
  586. package/dist/modules/sales/commands/payments.js.map +2 -2
  587. package/dist/modules/sales/commands/shipments.js +3 -1
  588. package/dist/modules/sales/commands/shipments.js.map +2 -2
  589. package/dist/modules/sales/components/AdjustmentKindSettings.js +5 -3
  590. package/dist/modules/sales/components/AdjustmentKindSettings.js.map +2 -2
  591. package/dist/modules/sales/components/DocumentNumberSettings.js +4 -2
  592. package/dist/modules/sales/components/DocumentNumberSettings.js.map +2 -2
  593. package/dist/modules/sales/components/OrderEditingSettings.js +4 -2
  594. package/dist/modules/sales/components/OrderEditingSettings.js.map +2 -2
  595. package/dist/modules/sales/components/PaymentMethodsSettings.js +5 -3
  596. package/dist/modules/sales/components/PaymentMethodsSettings.js.map +2 -2
  597. package/dist/modules/sales/components/ShippingMethodsSettings.js +5 -3
  598. package/dist/modules/sales/components/ShippingMethodsSettings.js.map +2 -2
  599. package/dist/modules/sales/components/StatusSettings.js +5 -3
  600. package/dist/modules/sales/components/StatusSettings.js.map +2 -2
  601. package/dist/modules/sales/components/TaxRatesSettings.js +5 -3
  602. package/dist/modules/sales/components/TaxRatesSettings.js.map +2 -2
  603. package/dist/modules/sales/components/channels/ChannelOfferForm.js +16 -14
  604. package/dist/modules/sales/components/channels/ChannelOfferForm.js.map +2 -2
  605. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js +4 -2
  606. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js.map +2 -2
  607. package/dist/modules/sales/components/documents/AddressesSection.js +5 -3
  608. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  609. package/dist/modules/sales/components/documents/AdjustmentDialog.js +3 -1
  610. package/dist/modules/sales/components/documents/AdjustmentDialog.js.map +2 -2
  611. package/dist/modules/sales/components/documents/AdjustmentsSection.js +5 -3
  612. package/dist/modules/sales/components/documents/AdjustmentsSection.js.map +2 -2
  613. package/dist/modules/sales/components/documents/ItemsSection.js +6 -4
  614. package/dist/modules/sales/components/documents/ItemsSection.js.map +2 -2
  615. package/dist/modules/sales/components/documents/LineItemDialog.js +8 -6
  616. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  617. package/dist/modules/sales/components/documents/PaymentDialog.js +5 -3
  618. package/dist/modules/sales/components/documents/PaymentDialog.js.map +2 -2
  619. package/dist/modules/sales/components/documents/PaymentsSection.js +4 -2
  620. package/dist/modules/sales/components/documents/PaymentsSection.js.map +2 -2
  621. package/dist/modules/sales/components/documents/SalesDocumentForm.js +14 -12
  622. package/dist/modules/sales/components/documents/SalesDocumentForm.js.map +2 -2
  623. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +5 -3
  624. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  625. package/dist/modules/sales/components/documents/ShipmentDialog.js +9 -7
  626. package/dist/modules/sales/components/documents/ShipmentDialog.js.map +2 -2
  627. package/dist/modules/sales/components/documents/ShipmentsSection.js +4 -2
  628. package/dist/modules/sales/components/documents/ShipmentsSection.js.map +2 -2
  629. package/dist/modules/sales/frontend/quote/[token]/page.js +4 -2
  630. package/dist/modules/sales/frontend/quote/[token]/page.js.map +2 -2
  631. package/dist/modules/sales/seed/examples.js +7 -9
  632. package/dist/modules/sales/seed/examples.js.map +2 -2
  633. package/dist/modules/sales/subscribers/quote-expiring-notification.js +3 -1
  634. package/dist/modules/sales/subscribers/quote-expiring-notification.js.map +2 -2
  635. package/dist/modules/sales/subscribers/reconcileOnAddressDelete.js +3 -1
  636. package/dist/modules/sales/subscribers/reconcileOnAddressDelete.js.map +2 -2
  637. package/dist/modules/sales/subscribers/reconcileOnCompanyDelete.js +3 -1
  638. package/dist/modules/sales/subscribers/reconcileOnCompanyDelete.js.map +2 -2
  639. package/dist/modules/sales/subscribers/reconcileOnCustomerDelete.js +3 -1
  640. package/dist/modules/sales/subscribers/reconcileOnCustomerDelete.js.map +2 -2
  641. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js +5 -3
  642. package/dist/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.js.map +2 -2
  643. package/dist/modules/sales/widgets/dashboard/new-orders/widget.client.js +3 -1
  644. package/dist/modules/sales/widgets/dashboard/new-orders/widget.client.js.map +2 -2
  645. package/dist/modules/sales/widgets/dashboard/new-quotes/widget.client.js +3 -1
  646. package/dist/modules/sales/widgets/dashboard/new-quotes/widget.client.js.map +2 -2
  647. package/dist/modules/shipping_carriers/api/tracking/route.js +5 -0
  648. package/dist/modules/shipping_carriers/api/tracking/route.js.map +2 -2
  649. package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js +3 -1
  650. package/dist/modules/shipping_carriers/api/webhook/[provider]/route.js.map +2 -2
  651. package/dist/modules/shipping_carriers/lib/shipping-service.js +41 -19
  652. package/dist/modules/shipping_carriers/lib/shipping-service.js.map +2 -2
  653. package/dist/modules/shipping_carriers/lib/upstream-error-response.js +3 -1
  654. package/dist/modules/shipping_carriers/lib/upstream-error-response.js.map +2 -2
  655. package/dist/modules/shipping_carriers/workers/webhook-processor.js +3 -5
  656. package/dist/modules/shipping_carriers/workers/webhook-processor.js.map +2 -2
  657. package/dist/modules/staff/api/comments.js +3 -1
  658. package/dist/modules/staff/api/comments.js.map +2 -2
  659. package/dist/modules/staff/api/leave-requests/accept/route.js +3 -1
  660. package/dist/modules/staff/api/leave-requests/accept/route.js.map +2 -2
  661. package/dist/modules/staff/api/leave-requests/reject/route.js +3 -1
  662. package/dist/modules/staff/api/leave-requests/reject/route.js.map +2 -2
  663. package/dist/modules/staff/api/team-members/assignable/route.js +3 -1
  664. package/dist/modules/staff/api/team-members/assignable/route.js.map +2 -2
  665. package/dist/modules/staff/api/team-members/self/route.js +4 -2
  666. package/dist/modules/staff/api/team-members/self/route.js.map +2 -2
  667. package/dist/modules/staff/api/team-members/tags/assign/route.js +3 -1
  668. package/dist/modules/staff/api/team-members/tags/assign/route.js.map +2 -2
  669. package/dist/modules/staff/api/team-members/tags/unassign/route.js +3 -1
  670. package/dist/modules/staff/api/team-members/tags/unassign/route.js.map +2 -2
  671. package/dist/modules/staff/api/timesheets/my-projects/[projectId]/route.js +3 -1
  672. package/dist/modules/staff/api/timesheets/my-projects/[projectId]/route.js.map +2 -2
  673. package/dist/modules/staff/api/timesheets/my-projects/route.js +3 -1
  674. package/dist/modules/staff/api/timesheets/my-projects/route.js.map +2 -2
  675. package/dist/modules/staff/api/timesheets/projects/kpis/route.js +3 -1
  676. package/dist/modules/staff/api/timesheets/projects/kpis/route.js.map +2 -2
  677. package/dist/modules/staff/api/timesheets/time-entries/[id]/segments/route.js +3 -1
  678. package/dist/modules/staff/api/timesheets/time-entries/[id]/segments/route.js.map +2 -2
  679. package/dist/modules/staff/api/timesheets/time-entries/[id]/timer-start/route.js +4 -2
  680. package/dist/modules/staff/api/timesheets/time-entries/[id]/timer-start/route.js.map +2 -2
  681. package/dist/modules/staff/api/timesheets/time-entries/[id]/timer-stop/route.js +4 -2
  682. package/dist/modules/staff/api/timesheets/time-entries/[id]/timer-stop/route.js.map +2 -2
  683. package/dist/modules/staff/api/timesheets/time-entries/bulk/route.js +3 -1
  684. package/dist/modules/staff/api/timesheets/time-entries/bulk/route.js.map +2 -2
  685. package/dist/modules/staff/api/timesheets/time-entries/start-timer/route.js +3 -1
  686. package/dist/modules/staff/api/timesheets/time-entries/start-timer/route.js.map +2 -2
  687. package/dist/modules/staff/backend/staff/team-members/page.js +4 -2
  688. package/dist/modules/staff/backend/staff/team-members/page.js.map +2 -2
  689. package/dist/modules/staff/backend/staff/team-roles/page.js +4 -2
  690. package/dist/modules/staff/backend/staff/team-roles/page.js.map +2 -2
  691. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +4 -2
  692. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
  693. package/dist/modules/staff/backend/staff/teams/page.js +4 -2
  694. package/dist/modules/staff/backend/staff/teams/page.js.map +2 -2
  695. package/dist/modules/staff/backend/staff/timesheets/page.js +7 -5
  696. package/dist/modules/staff/backend/staff/timesheets/page.js.map +2 -2
  697. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/page.js +3 -1
  698. package/dist/modules/staff/backend/staff/timesheets/projects/[id]/page.js.map +2 -2
  699. package/dist/modules/staff/backend/staff/timesheets/projects/page.js +4 -2
  700. package/dist/modules/staff/backend/staff/timesheets/projects/page.js.map +2 -2
  701. package/dist/modules/staff/commands/timesheets-entries.js +3 -1
  702. package/dist/modules/staff/commands/timesheets-entries.js.map +2 -2
  703. package/dist/modules/staff/widgets/dashboard/timesheets-hours-by-project/widget.client.js +3 -1
  704. package/dist/modules/staff/widgets/dashboard/timesheets-hours-by-project/widget.client.js.map +2 -2
  705. package/dist/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.js +5 -3
  706. package/dist/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.js.map +2 -2
  707. package/dist/modules/sync_excel/api/import/route.js +3 -1
  708. package/dist/modules/sync_excel/api/import/route.js.map +2 -2
  709. package/dist/modules/translations/api/[entityType]/[entityId]/route.js +5 -3
  710. package/dist/modules/translations/api/[entityType]/[entityId]/route.js.map +2 -2
  711. package/dist/modules/translations/api/get/locales.js +3 -1
  712. package/dist/modules/translations/api/get/locales.js.map +2 -2
  713. package/dist/modules/translations/api/put/locales.js +3 -1
  714. package/dist/modules/translations/api/put/locales.js.map +2 -2
  715. package/dist/modules/translations/components/TranslationManager.js +3 -1
  716. package/dist/modules/translations/components/TranslationManager.js.map +2 -2
  717. package/dist/modules/translations/subscribers/cleanup.js +3 -1
  718. package/dist/modules/translations/subscribers/cleanup.js.map +2 -2
  719. package/dist/modules/workflows/api/definitions/[id]/customize/route.js +4 -2
  720. package/dist/modules/workflows/api/definitions/[id]/customize/route.js.map +2 -2
  721. package/dist/modules/workflows/api/definitions/[id]/reset-to-code/route.js +4 -2
  722. package/dist/modules/workflows/api/definitions/[id]/reset-to-code/route.js.map +2 -2
  723. package/dist/modules/workflows/api/definitions/[id]/route.js +6 -4
  724. package/dist/modules/workflows/api/definitions/[id]/route.js.map +2 -2
  725. package/dist/modules/workflows/api/definitions/route.js +4 -2
  726. package/dist/modules/workflows/api/definitions/route.js.map +2 -2
  727. package/dist/modules/workflows/api/events/[id]/route.js +3 -1
  728. package/dist/modules/workflows/api/events/[id]/route.js.map +2 -2
  729. package/dist/modules/workflows/api/events/route.js +3 -1
  730. package/dist/modules/workflows/api/events/route.js.map +2 -2
  731. package/dist/modules/workflows/api/instances/[id]/advance/route.js +3 -1
  732. package/dist/modules/workflows/api/instances/[id]/advance/route.js.map +2 -2
  733. package/dist/modules/workflows/api/instances/[id]/cancel/route.js +3 -1
  734. package/dist/modules/workflows/api/instances/[id]/cancel/route.js.map +2 -2
  735. package/dist/modules/workflows/api/instances/[id]/events/route.js +3 -1
  736. package/dist/modules/workflows/api/instances/[id]/events/route.js.map +2 -2
  737. package/dist/modules/workflows/api/instances/[id]/retry/route.js +3 -1
  738. package/dist/modules/workflows/api/instances/[id]/retry/route.js.map +2 -2
  739. package/dist/modules/workflows/api/instances/[id]/route.js +3 -1
  740. package/dist/modules/workflows/api/instances/[id]/route.js.map +2 -2
  741. package/dist/modules/workflows/api/instances/[id]/signal/route.js +5 -7
  742. package/dist/modules/workflows/api/instances/[id]/signal/route.js.map +2 -2
  743. package/dist/modules/workflows/api/instances/route.js +5 -3
  744. package/dist/modules/workflows/api/instances/route.js.map +2 -2
  745. package/dist/modules/workflows/api/instances/validate-start/route.js +3 -1
  746. package/dist/modules/workflows/api/instances/validate-start/route.js.map +2 -2
  747. package/dist/modules/workflows/api/signals/route.js +3 -1
  748. package/dist/modules/workflows/api/signals/route.js.map +2 -2
  749. package/dist/modules/workflows/api/tasks/[id]/claim/route.js +3 -1
  750. package/dist/modules/workflows/api/tasks/[id]/claim/route.js.map +2 -2
  751. package/dist/modules/workflows/api/tasks/[id]/complete/route.js +3 -1
  752. package/dist/modules/workflows/api/tasks/[id]/complete/route.js.map +2 -2
  753. package/dist/modules/workflows/api/tasks/[id]/route.js +3 -1
  754. package/dist/modules/workflows/api/tasks/[id]/route.js.map +2 -2
  755. package/dist/modules/workflows/api/tasks/route.js +3 -1
  756. package/dist/modules/workflows/api/tasks/route.js.map +2 -2
  757. package/dist/modules/workflows/backend/definitions/visual-editor/page.js +4 -2
  758. package/dist/modules/workflows/backend/definitions/visual-editor/page.js.map +2 -2
  759. package/dist/modules/workflows/backend/instances/[id]/page.js +5 -3
  760. package/dist/modules/workflows/backend/instances/[id]/page.js.map +2 -2
  761. package/dist/modules/workflows/backend/tasks/[id]/page.js +3 -1
  762. package/dist/modules/workflows/backend/tasks/[id]/page.js.map +2 -2
  763. package/dist/modules/workflows/components/BusinessRulesSelector.js +5 -3
  764. package/dist/modules/workflows/components/BusinessRulesSelector.js.map +2 -2
  765. package/dist/modules/workflows/components/WorkflowSelector.js +5 -3
  766. package/dist/modules/workflows/components/WorkflowSelector.js.map +2 -2
  767. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js +3 -1
  768. package/dist/modules/workflows/components/fields/BusinessRuleConditionsEditor.js.map +2 -2
  769. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js +3 -1
  770. package/dist/modules/workflows/components/fields/StartPreConditionsEditor.js.map +2 -2
  771. package/dist/modules/workflows/components/fields/WorkflowSelectorField.js +3 -1
  772. package/dist/modules/workflows/components/fields/WorkflowSelectorField.js.map +2 -2
  773. package/dist/modules/workflows/frontend/checkout-demo/page.js +8 -7
  774. package/dist/modules/workflows/frontend/checkout-demo/page.js.map +2 -2
  775. package/dist/modules/workflows/lib/activity-executor.js +25 -21
  776. package/dist/modules/workflows/lib/activity-executor.js.map +2 -2
  777. package/dist/modules/workflows/lib/activity-worker-handler.js +8 -15
  778. package/dist/modules/workflows/lib/activity-worker-handler.js.map +2 -2
  779. package/dist/modules/workflows/lib/code-registry.js +7 -7
  780. package/dist/modules/workflows/lib/code-registry.js.map +2 -2
  781. package/dist/modules/workflows/lib/compensation-handler.js +4 -2
  782. package/dist/modules/workflows/lib/compensation-handler.js.map +2 -2
  783. package/dist/modules/workflows/lib/edgeFormTransforms.js +3 -1
  784. package/dist/modules/workflows/lib/edgeFormTransforms.js.map +2 -2
  785. package/dist/modules/workflows/lib/event-trigger-service.js +5 -3
  786. package/dist/modules/workflows/lib/event-trigger-service.js.map +2 -2
  787. package/dist/modules/workflows/lib/nodeFormTransforms.js +3 -1
  788. package/dist/modules/workflows/lib/nodeFormTransforms.js.map +2 -2
  789. package/dist/modules/workflows/lib/seeds.js +16 -2
  790. package/dist/modules/workflows/lib/seeds.js.map +2 -2
  791. package/dist/modules/workflows/lib/signal-handler.js +3 -1
  792. package/dist/modules/workflows/lib/signal-handler.js.map +2 -2
  793. package/dist/modules/workflows/lib/start-validator.js +9 -3
  794. package/dist/modules/workflows/lib/start-validator.js.map +2 -2
  795. package/dist/modules/workflows/lib/step-handler.js +3 -1
  796. package/dist/modules/workflows/lib/step-handler.js.map +2 -2
  797. package/dist/modules/workflows/lib/task-handler.js +3 -1
  798. package/dist/modules/workflows/lib/task-handler.js.map +2 -2
  799. package/dist/modules/workflows/lib/transition-handler.js +5 -3
  800. package/dist/modules/workflows/lib/transition-handler.js.map +2 -2
  801. package/dist/modules/workflows/lib/workflow-executor.js +27 -15
  802. package/dist/modules/workflows/lib/workflow-executor.js.map +2 -2
  803. package/dist/modules/workflows/subscribers/event-trigger.js +21 -18
  804. package/dist/modules/workflows/subscribers/event-trigger.js.map +2 -2
  805. package/dist/modules/workflows/subscribers/task-assigned-notification.js +3 -1
  806. package/dist/modules/workflows/subscribers/task-assigned-notification.js.map +2 -2
  807. package/dist/modules/workflows/workers/workflow-activities.worker.js +30 -20
  808. package/dist/modules/workflows/workers/workflow-activities.worker.js.map +2 -2
  809. package/package.json +7 -7
  810. package/src/bootstrap.ts +14 -11
  811. package/src/helpers/integration/queue-runner.ts +2 -2
  812. package/src/modules/api_keys/services/apiKeyService.ts +6 -3
  813. package/src/modules/attachments/api/image/[id]/[[...slug]]/route.ts +5 -2
  814. package/src/modules/attachments/api/library/[id]/route.ts +4 -1
  815. package/src/modules/attachments/api/route.ts +9 -6
  816. package/src/modules/attachments/components/AttachmentPartitionSettings.tsx +6 -3
  817. package/src/modules/attachments/lib/assignmentDetails.ts +4 -1
  818. package/src/modules/attachments/lib/drivers/driverFactory.ts +4 -1
  819. package/src/modules/attachments/lib/ocrQueue.ts +11 -11
  820. package/src/modules/attachments/lib/ocrService.ts +7 -4
  821. package/src/modules/audit_logs/api/audit-logs/actions/redo/route.ts +4 -1
  822. package/src/modules/audit_logs/api/audit-logs/actions/undo/route.ts +4 -1
  823. package/src/modules/audit_logs/backend/audit-logs/page.tsx +4 -1
  824. package/src/modules/audit_logs/components/AuditLogsActions.tsx +5 -2
  825. package/src/modules/audit_logs/services/accessLogService.ts +5 -4
  826. package/src/modules/audit_logs/services/actionLogService.ts +5 -2
  827. package/src/modules/auth/api/profile/route.ts +5 -2
  828. package/src/modules/auth/api/reset/confirm.ts +4 -1
  829. package/src/modules/auth/api/reset.ts +5 -2
  830. package/src/modules/auth/api/roles/route.ts +4 -1
  831. package/src/modules/auth/api/sidebar/variants/route.ts +4 -2
  832. package/src/modules/auth/api/users/resend-invite/route.ts +5 -2
  833. package/src/modules/auth/api/users/route.ts +4 -1
  834. package/src/modules/auth/backend/auth/profile/page.tsx +4 -1
  835. package/src/modules/auth/backend/profile/change-password/page.tsx +4 -1
  836. package/src/modules/auth/backend/users/[id]/edit/page.tsx +6 -3
  837. package/src/modules/auth/backend/users/create/page.tsx +5 -2
  838. package/src/modules/auth/cli.ts +10 -0
  839. package/src/modules/auth/commands/users.ts +5 -2
  840. package/src/modules/auth/lib/consentIntegrity.ts +4 -4
  841. package/src/modules/auth/lib/setup-app.ts +10 -10
  842. package/src/modules/auth/lib/tenantAccess.ts +4 -1
  843. package/src/modules/auth/lib/tokenHash.ts +4 -4
  844. package/src/modules/business_rules/api/rules/route.ts +5 -2
  845. package/src/modules/business_rules/lib/expression-evaluator.ts +8 -6
  846. package/src/modules/business_rules/lib/rule-engine.ts +6 -3
  847. package/src/modules/business_rules/lib/rule-evaluator.ts +11 -11
  848. package/src/modules/business_rules/subscribers/crud-rule-trigger.ts +4 -1
  849. package/src/modules/business_rules/subscribers/rule-execution-failed-notification.ts +4 -1
  850. package/src/modules/catalog/ai-agents-context.ts +5 -5
  851. package/src/modules/catalog/ai-tools/_shared.ts +4 -1
  852. package/src/modules/catalog/ai-tools/authoring-pack.ts +4 -1
  853. package/src/modules/catalog/ai-tools/merchandising-pack.ts +4 -1
  854. package/src/modules/catalog/api/dictionaries/[key]/route.ts +4 -1
  855. package/src/modules/catalog/api/prices/route.ts +4 -1
  856. package/src/modules/catalog/api/products/route.ts +6 -3
  857. package/src/modules/catalog/api/settings/route.ts +5 -2
  858. package/src/modules/catalog/backend/catalog/products/[id]/page.tsx +15 -12
  859. package/src/modules/catalog/backend/catalog/products/[productId]/variants/[variantId]/page.tsx +9 -6
  860. package/src/modules/catalog/backend/catalog/products/[productId]/variants/create/page.tsx +6 -3
  861. package/src/modules/catalog/backend/catalog/products/create/page.tsx +6 -6
  862. package/src/modules/catalog/backend/catalog/products/optionSchemaClient.ts +4 -1
  863. package/src/modules/catalog/components/PriceKindSettings.tsx +6 -3
  864. package/src/modules/catalog/components/UnitPriceDisplaySettings.tsx +5 -2
  865. package/src/modules/catalog/inbox-actions.ts +5 -2
  866. package/src/modules/catalog/seed/examples.ts +5 -5
  867. package/src/modules/catalog/subscribers/low-stock-notification.ts +4 -1
  868. package/src/modules/catalog/widgets/injection/product-seo/state.ts +4 -1
  869. package/src/modules/communication_channels/api/get/oauth/[provider]/callback/route.ts +13 -13
  870. package/src/modules/communication_channels/api/post/channels/[id]/import-history/route.ts +4 -1
  871. package/src/modules/communication_channels/api/post/channels/[id]/push/register/route.ts +4 -1
  872. package/src/modules/communication_channels/api/post/webhook/[provider]/route.ts +6 -3
  873. package/src/modules/communication_channels/api/post/webhooks/gmail/route.ts +7 -6
  874. package/src/modules/communication_channels/commands/connect-credential-channel.ts +5 -10
  875. package/src/modules/communication_channels/commands/delete-channel.ts +4 -5
  876. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +5 -5
  877. package/src/modules/communication_channels/commands/disconnect-channel.ts +4 -5
  878. package/src/modules/communication_channels/commands/ingest-inbound-message.ts +6 -12
  879. package/src/modules/communication_channels/commands/push-unregister.ts +4 -3
  880. package/src/modules/communication_channels/commands/reassign-conversation.ts +6 -3
  881. package/src/modules/communication_channels/lib/dead-letter.ts +4 -5
  882. package/src/modules/communication_channels/lib/email-mime.ts +5 -6
  883. package/src/modules/communication_channels/lib/oauth-client-config.ts +7 -3
  884. package/src/modules/communication_channels/lib/send-as-user.ts +4 -1
  885. package/src/modules/communication_channels/lib/thread-token.ts +5 -2
  886. package/src/modules/communication_channels/setup.ts +4 -4
  887. package/src/modules/communication_channels/workers/channel-import-history.ts +5 -8
  888. package/src/modules/communication_channels/workers/gmail-history-sync.ts +9 -18
  889. package/src/modules/communication_channels/workers/gmail-renew-watch.ts +6 -9
  890. package/src/modules/communication_channels/workers/outbound-delivery.ts +7 -12
  891. package/src/modules/communication_channels/workers/poll-channel.ts +8 -15
  892. package/src/modules/communication_channels/workers/poll-tick.ts +6 -6
  893. package/src/modules/communication_channels/workers/reaction-processor.ts +6 -9
  894. package/src/modules/configs/api/cache/route.ts +5 -2
  895. package/src/modules/configs/api/system-status/route.ts +5 -2
  896. package/src/modules/configs/api/upgrade-actions/route.ts +5 -2
  897. package/src/modules/configs/components/ModuleTelemetryPanel.tsx +4 -1
  898. package/src/modules/configs/lib/touchGeneratedBarrels.ts +1 -1
  899. package/src/modules/configs/services/upgradeActionsService.ts +7 -3
  900. package/src/modules/currencies/components/CurrencyFetchingConfig.tsx +4 -1
  901. package/src/modules/currencies/lib/exchangeRateFormConfig.ts +4 -1
  902. package/src/modules/currencies/services/providers/nbp.ts +7 -4
  903. package/src/modules/currencies/services/providers/raiffeisen.ts +8 -7
  904. package/src/modules/customer_accounts/api/domain-resolve/all.ts +7 -5
  905. package/src/modules/customer_accounts/api/signup.ts +5 -2
  906. package/src/modules/customer_accounts/lib/customerAuthServer.ts +4 -1
  907. package/src/modules/customer_accounts/subscribers/autoLinkCrm.ts +4 -1
  908. package/src/modules/customer_accounts/subscribers/autoLinkCrmReverse.ts +4 -1
  909. package/src/modules/customer_accounts/subscribers/unlinkOnCompanyDelete.ts +4 -1
  910. package/src/modules/customer_accounts/subscribers/unlinkOnPersonDelete.ts +4 -1
  911. package/src/modules/customers/ai-agents-context.ts +5 -5
  912. package/src/modules/customers/api/activities/route.ts +7 -4
  913. package/src/modules/customers/api/comments/route.ts +4 -1
  914. package/src/modules/customers/api/companies/[id]/people/route.ts +4 -1
  915. package/src/modules/customers/api/companies/[id]/route.ts +6 -3
  916. package/src/modules/customers/api/companies/route.ts +6 -3
  917. package/src/modules/customers/api/dashboard/widgets/customer-todos/route.ts +4 -1
  918. package/src/modules/customers/api/dashboard/widgets/new-customers/route.ts +4 -1
  919. package/src/modules/customers/api/dashboard/widgets/new-deals/route.ts +4 -1
  920. package/src/modules/customers/api/dashboard/widgets/next-interactions/route.ts +4 -1
  921. package/src/modules/customers/api/deals/[id]/companies/route.ts +4 -1
  922. package/src/modules/customers/api/deals/[id]/people/route.ts +4 -1
  923. package/src/modules/customers/api/deals/aggregate/route.ts +4 -1
  924. package/src/modules/customers/api/deals/bulk-update-owner/route.ts +8 -5
  925. package/src/modules/customers/api/deals/bulk-update-stage/route.ts +8 -5
  926. package/src/modules/customers/api/deals/route.ts +4 -1
  927. package/src/modules/customers/api/deals/summary/route.ts +4 -1
  928. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +5 -2
  929. package/src/modules/customers/api/dictionaries/[kind]/route.ts +6 -3
  930. package/src/modules/customers/api/dictionaries/cache.ts +4 -1
  931. package/src/modules/customers/api/dictionaries/context.ts +4 -1
  932. package/src/modules/customers/api/dictionaries/currency/route.ts +4 -1
  933. package/src/modules/customers/api/dictionaries/kind-settings/route.ts +5 -2
  934. package/src/modules/customers/api/entity-roles-factory.ts +8 -5
  935. package/src/modules/customers/api/interactions/cancel/route.ts +4 -1
  936. package/src/modules/customers/api/interactions/complete/route.ts +4 -1
  937. package/src/modules/customers/api/interactions/conflicts/route.ts +4 -1
  938. package/src/modules/customers/api/interactions/counts/route.ts +4 -1
  939. package/src/modules/customers/api/interactions/route.ts +8 -4
  940. package/src/modules/customers/api/interactions/tasks/route.ts +4 -1
  941. package/src/modules/customers/api/labels/assign/route.ts +4 -1
  942. package/src/modules/customers/api/labels/route.ts +7 -3
  943. package/src/modules/customers/api/labels/unassign/route.ts +4 -1
  944. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +4 -1
  945. package/src/modules/customers/api/people/[id]/route.ts +6 -3
  946. package/src/modules/customers/api/people/route.ts +6 -3
  947. package/src/modules/customers/api/pipeline-stages/reorder/route.ts +4 -1
  948. package/src/modules/customers/api/pipeline-stages/route.ts +7 -4
  949. package/src/modules/customers/api/pipelines/route.ts +7 -4
  950. package/src/modules/customers/api/settings/address-format/route.ts +5 -2
  951. package/src/modules/customers/api/settings/dictionary-sort-modes/route.ts +5 -2
  952. package/src/modules/customers/api/settings/stuck-threshold/route.ts +5 -2
  953. package/src/modules/customers/api/tags/assign/route.ts +4 -1
  954. package/src/modules/customers/api/tags/unassign/route.ts +4 -1
  955. package/src/modules/customers/api/todos/route.ts +7 -4
  956. package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +6 -3
  957. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.ts +4 -1
  958. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.ts +4 -1
  959. package/src/modules/customers/backend/customers/deals/map/components/DealsMapCanvasImpl.tsx +5 -3
  960. package/src/modules/customers/backend/customers/deals/page.tsx +5 -2
  961. package/src/modules/customers/backend/customers/people-v2/[id]/page.tsx +6 -3
  962. package/src/modules/customers/commands/deals.ts +4 -1
  963. package/src/modules/customers/commands/dictionaries.ts +4 -1
  964. package/src/modules/customers/commands/interactions.ts +5 -2
  965. package/src/modules/customers/commands/shared.ts +5 -2
  966. package/src/modules/customers/commands/todos.ts +4 -1
  967. package/src/modules/customers/components/DictionarySettings.tsx +6 -3
  968. package/src/modules/customers/components/DictionarySortSettings.tsx +4 -1
  969. package/src/modules/customers/components/detail/ActivitiesCard.tsx +4 -1
  970. package/src/modules/customers/components/detail/ActivitiesDayStrip.tsx +4 -1
  971. package/src/modules/customers/components/detail/ActivitiesSection.tsx +7 -4
  972. package/src/modules/customers/components/detail/ActivityCard.tsx +4 -1
  973. package/src/modules/customers/components/detail/ChangelogTab.tsx +4 -1
  974. package/src/modules/customers/components/detail/CompanyCard.tsx +4 -1
  975. package/src/modules/customers/components/detail/ConfirmDealLostDialog.tsx +4 -1
  976. package/src/modules/customers/components/detail/EntityTagsDialog.tsx +4 -1
  977. package/src/modules/customers/components/detail/InlineActivityComposer.tsx +4 -1
  978. package/src/modules/customers/components/detail/ManageTagsDialog.tsx +4 -1
  979. package/src/modules/customers/components/detail/RoleAssignmentRow.tsx +6 -3
  980. package/src/modules/customers/components/detail/RolesSection.tsx +5 -2
  981. package/src/modules/customers/components/detail/hooks/useInteractionMutations.ts +6 -3
  982. package/src/modules/customers/components/linking/LinkEntityDialog.tsx +5 -2
  983. package/src/modules/customers/inbox-actions.ts +4 -1
  984. package/src/modules/customers/lib/bulkDeals.ts +4 -1
  985. package/src/modules/customers/lib/dealClosureNotification.ts +5 -2
  986. package/src/modules/customers/lib/dealStageTransitionTable.ts +4 -1
  987. package/src/modules/customers/lib/interactionFeatureFlags.ts +5 -1
  988. package/src/modules/customers/lib/todoCompatibility.ts +4 -1
  989. package/src/modules/customers/search.ts +15 -7
  990. package/src/modules/customers/widgets/dashboard/customer-todos/widget.client.tsx +4 -1
  991. package/src/modules/customers/widgets/dashboard/new-customers/widget.client.tsx +4 -1
  992. package/src/modules/customers/widgets/dashboard/new-deals/widget.client.tsx +4 -1
  993. package/src/modules/customers/widgets/dashboard/next-interactions/widget.client.tsx +4 -1
  994. package/src/modules/dashboards/api/widgets/data/batch/route.ts +4 -1
  995. package/src/modules/dashboards/api/widgets/data/route.ts +4 -1
  996. package/src/modules/dashboards/components/WidgetVisibilityEditor.tsx +6 -3
  997. package/src/modules/dashboards/widgets/dashboard/aov-kpi/widget.client.tsx +4 -1
  998. package/src/modules/dashboards/widgets/dashboard/new-customers-kpi/widget.client.tsx +4 -1
  999. package/src/modules/dashboards/widgets/dashboard/orders-by-status/widget.client.tsx +4 -1
  1000. package/src/modules/dashboards/widgets/dashboard/orders-kpi/widget.client.tsx +4 -1
  1001. package/src/modules/dashboards/widgets/dashboard/pipeline-summary/widget.client.tsx +4 -1
  1002. package/src/modules/dashboards/widgets/dashboard/revenue-kpi/widget.client.tsx +4 -1
  1003. package/src/modules/dashboards/widgets/dashboard/revenue-trend/widget.client.tsx +4 -1
  1004. package/src/modules/dashboards/widgets/dashboard/sales-by-region/widget.client.tsx +4 -1
  1005. package/src/modules/dashboards/widgets/dashboard/top-customers/widget.client.tsx +4 -1
  1006. package/src/modules/dashboards/widgets/dashboard/top-products/widget.client.tsx +4 -1
  1007. package/src/modules/data_sync/api/run.ts +4 -1
  1008. package/src/modules/data_sync/backend/data-sync/runs/[id]/page.tsx +3 -1
  1009. package/src/modules/data_sync/lib/adapter-registry.ts +16 -4
  1010. package/src/modules/data_sync/lib/sync-engine.ts +31 -2
  1011. package/src/modules/data_sync/workers/sync-export.ts +4 -1
  1012. package/src/modules/data_sync/workers/sync-import.ts +4 -1
  1013. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +5 -2
  1014. package/src/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.ts +4 -1
  1015. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +5 -2
  1016. package/src/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.ts +4 -1
  1017. package/src/modules/dictionaries/api/[dictionaryId]/route.ts +6 -3
  1018. package/src/modules/dictionaries/api/context.ts +4 -1
  1019. package/src/modules/dictionaries/api/route.ts +5 -2
  1020. package/src/modules/dictionaries/components/DictionariesManager.tsx +6 -3
  1021. package/src/modules/dictionaries/components/DictionaryEntriesEditor.tsx +5 -2
  1022. package/src/modules/dictionaries/components/DictionaryEntrySelect.tsx +5 -2
  1023. package/src/modules/dictionaries/components/DictionarySelectControl.tsx +4 -1
  1024. package/src/modules/dictionaries/fields/dictionary.tsx +4 -1
  1025. package/src/modules/directory/api/organization-branding/route.ts +4 -1
  1026. package/src/modules/directory/api/organization-switcher/route.ts +4 -1
  1027. package/src/modules/directory/commands/tenants.ts +6 -3
  1028. package/src/modules/directory/utils/organizationScope.ts +7 -4
  1029. package/src/modules/entities/api/definitions.cache.ts +4 -1
  1030. package/src/modules/entities/api/definitions.ts +8 -5
  1031. package/src/modules/entities/api/records.ts +5 -2
  1032. package/src/modules/entities/components/EncryptionManager.tsx +4 -1
  1033. package/src/modules/entities/lib/makeActivityRoute.ts +4 -1
  1034. package/src/modules/feature_toggles/api/overrides/route.ts +4 -1
  1035. package/src/modules/feature_toggles/lib/feature-flag-check.ts +6 -9
  1036. package/src/modules/inbox_ops/api/emails/[id]/reprocess/route.ts +5 -2
  1037. package/src/modules/inbox_ops/api/emails/[id]/route.ts +5 -2
  1038. package/src/modules/inbox_ops/api/emails/route.ts +4 -1
  1039. package/src/modules/inbox_ops/api/extract/route.ts +4 -1
  1040. package/src/modules/inbox_ops/api/proposals/[id]/actions/[actionId]/route.ts +4 -1
  1041. package/src/modules/inbox_ops/api/proposals/[id]/replies/[replyId]/send/route.ts +5 -2
  1042. package/src/modules/inbox_ops/api/proposals/counts/route.ts +5 -2
  1043. package/src/modules/inbox_ops/api/proposals/route.ts +4 -1
  1044. package/src/modules/inbox_ops/api/routeHelpers.ts +4 -1
  1045. package/src/modules/inbox_ops/api/settings/route.ts +4 -1
  1046. package/src/modules/inbox_ops/api/webhook/inbound.ts +8 -5
  1047. package/src/modules/inbox_ops/lib/cache.ts +5 -2
  1048. package/src/modules/inbox_ops/lib/catalogLookup.ts +4 -1
  1049. package/src/modules/inbox_ops/lib/eventBus.ts +4 -4
  1050. package/src/modules/inbox_ops/lib/messagesIntegration.ts +5 -8
  1051. package/src/modules/inbox_ops/subscribers/executionAuditor.ts +5 -1
  1052. package/src/modules/inbox_ops/subscribers/extractionWorker.ts +11 -8
  1053. package/src/modules/inbox_ops/subscribers/proposalNotifier.ts +4 -1
  1054. package/src/modules/messages/api/[id]/route.ts +4 -4
  1055. package/src/modules/messages/commands/actions.ts +4 -1
  1056. package/src/modules/messages/components/MessagesInboxPageClient.tsx +4 -1
  1057. package/src/modules/messages/lib/email-sender.ts +4 -7
  1058. package/src/modules/messages/lib/message-objects-registry.ts +4 -1
  1059. package/src/modules/messages/lib/message-types-registry.ts +4 -1
  1060. package/src/modules/messages/workers/send-email.worker.ts +7 -4
  1061. package/src/modules/notifications/lib/notificationMapper.ts +4 -4
  1062. package/src/modules/notifications/lib/notificationService.ts +4 -5
  1063. package/src/modules/notifications/subscribers/deliver-notification.ts +9 -14
  1064. package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +4 -1
  1065. package/src/modules/perspectives/services/perspectiveService.ts +4 -3
  1066. package/src/modules/planner/api/access.ts +4 -3
  1067. package/src/modules/planner/api/availability-date-specific.ts +4 -1
  1068. package/src/modules/planner/api/availability-weekly.ts +4 -1
  1069. package/src/modules/planner/backend/planner/availability-rulesets/page.tsx +5 -2
  1070. package/src/modules/planner/components/AvailabilityRulesEditor.tsx +4 -1
  1071. package/src/modules/progress/api/jobs/route.ts +4 -1
  1072. package/src/modules/query_index/components/QueryIndexesTable.tsx +6 -3
  1073. package/src/modules/query_index/lib/batch.ts +5 -2
  1074. package/src/modules/query_index/lib/coverage.ts +4 -1
  1075. package/src/modules/query_index/lib/engine.ts +14 -17
  1076. package/src/modules/query_index/lib/reindexer.ts +9 -6
  1077. package/src/modules/query_index/lib/search-tokens.ts +4 -2
  1078. package/src/modules/query_index/subscribers/coverage_refresh.ts +4 -1
  1079. package/src/modules/resources/api/comments.ts +4 -1
  1080. package/src/modules/resources/api/resources/tags/assign/route.ts +4 -1
  1081. package/src/modules/resources/api/resources/tags/unassign/route.ts +4 -1
  1082. package/src/modules/resources/backend/resources/resource-types/[id]/edit/page.tsx +4 -1
  1083. package/src/modules/resources/backend/resources/resource-types/page.tsx +5 -2
  1084. package/src/modules/resources/commands/activities.ts +5 -4
  1085. package/src/modules/resources/commands/comments.ts +6 -4
  1086. package/src/modules/resources/commands/shared.ts +36 -0
  1087. package/src/modules/sales/api/channels/route.ts +4 -1
  1088. package/src/modules/sales/api/document-history/route.ts +4 -1
  1089. package/src/modules/sales/api/document-numbers/route.ts +4 -1
  1090. package/src/modules/sales/api/quotes/accept/route.ts +5 -2
  1091. package/src/modules/sales/api/quotes/convert/route.ts +4 -1
  1092. package/src/modules/sales/api/quotes/public/[token]/route.ts +4 -1
  1093. package/src/modules/sales/api/quotes/send/route.ts +4 -1
  1094. package/src/modules/sales/api/returns/[id]/route.ts +4 -1
  1095. package/src/modules/sales/api/settings/document-numbers/route.ts +5 -2
  1096. package/src/modules/sales/api/settings/order-editing/route.ts +5 -2
  1097. package/src/modules/sales/backend/sales/channels/[channelId]/edit/page.tsx +4 -1
  1098. package/src/modules/sales/backend/sales/channels/offers/page.tsx +7 -4
  1099. package/src/modules/sales/backend/sales/channels/page.tsx +5 -2
  1100. package/src/modules/sales/backend/sales/documents/[id]/page.tsx +21 -18
  1101. package/src/modules/sales/commands/documents.ts +5 -8
  1102. package/src/modules/sales/commands/payments.ts +4 -1
  1103. package/src/modules/sales/commands/shipments.ts +4 -2
  1104. package/src/modules/sales/components/AdjustmentKindSettings.tsx +6 -3
  1105. package/src/modules/sales/components/DocumentNumberSettings.tsx +5 -2
  1106. package/src/modules/sales/components/OrderEditingSettings.tsx +5 -2
  1107. package/src/modules/sales/components/PaymentMethodsSettings.tsx +6 -3
  1108. package/src/modules/sales/components/ShippingMethodsSettings.tsx +6 -3
  1109. package/src/modules/sales/components/StatusSettings.tsx +6 -3
  1110. package/src/modules/sales/components/TaxRatesSettings.tsx +6 -3
  1111. package/src/modules/sales/components/channels/ChannelOfferForm.tsx +17 -14
  1112. package/src/modules/sales/components/channels/SalesChannelOffersPanel.tsx +5 -2
  1113. package/src/modules/sales/components/documents/AddressesSection.tsx +6 -3
  1114. package/src/modules/sales/components/documents/AdjustmentDialog.tsx +4 -1
  1115. package/src/modules/sales/components/documents/AdjustmentsSection.tsx +6 -3
  1116. package/src/modules/sales/components/documents/ItemsSection.tsx +7 -4
  1117. package/src/modules/sales/components/documents/LineItemDialog.tsx +9 -6
  1118. package/src/modules/sales/components/documents/PaymentDialog.tsx +6 -3
  1119. package/src/modules/sales/components/documents/PaymentsSection.tsx +5 -2
  1120. package/src/modules/sales/components/documents/SalesDocumentForm.tsx +15 -12
  1121. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +6 -3
  1122. package/src/modules/sales/components/documents/ShipmentDialog.tsx +10 -7
  1123. package/src/modules/sales/components/documents/ShipmentsSection.tsx +5 -2
  1124. package/src/modules/sales/frontend/quote/[token]/page.tsx +5 -2
  1125. package/src/modules/sales/seed/examples.ts +8 -9
  1126. package/src/modules/sales/subscribers/quote-expiring-notification.ts +4 -1
  1127. package/src/modules/sales/subscribers/reconcileOnAddressDelete.ts +4 -1
  1128. package/src/modules/sales/subscribers/reconcileOnCompanyDelete.ts +4 -1
  1129. package/src/modules/sales/subscribers/reconcileOnCustomerDelete.ts +4 -1
  1130. package/src/modules/sales/widgets/dashboard/makeDashboardWidgetRoute.ts +6 -3
  1131. package/src/modules/sales/widgets/dashboard/new-orders/widget.client.tsx +274 -271
  1132. package/src/modules/sales/widgets/dashboard/new-quotes/widget.client.tsx +280 -277
  1133. package/src/modules/shipping_carriers/api/tracking/route.ts +5 -1
  1134. package/src/modules/shipping_carriers/api/webhook/[provider]/route.ts +4 -1
  1135. package/src/modules/shipping_carriers/lib/shipping-service.ts +47 -22
  1136. package/src/modules/shipping_carriers/lib/upstream-error-response.ts +4 -1
  1137. package/src/modules/shipping_carriers/workers/webhook-processor.ts +4 -5
  1138. package/src/modules/staff/api/comments.ts +4 -1
  1139. package/src/modules/staff/api/leave-requests/accept/route.ts +4 -1
  1140. package/src/modules/staff/api/leave-requests/reject/route.ts +4 -1
  1141. package/src/modules/staff/api/team-members/assignable/route.ts +4 -1
  1142. package/src/modules/staff/api/team-members/self/route.ts +5 -2
  1143. package/src/modules/staff/api/team-members/tags/assign/route.ts +4 -1
  1144. package/src/modules/staff/api/team-members/tags/unassign/route.ts +4 -1
  1145. package/src/modules/staff/api/timesheets/my-projects/[projectId]/route.ts +4 -1
  1146. package/src/modules/staff/api/timesheets/my-projects/route.ts +4 -1
  1147. package/src/modules/staff/api/timesheets/projects/kpis/route.ts +4 -1
  1148. package/src/modules/staff/api/timesheets/time-entries/[id]/segments/route.ts +4 -1
  1149. package/src/modules/staff/api/timesheets/time-entries/[id]/timer-start/route.ts +5 -2
  1150. package/src/modules/staff/api/timesheets/time-entries/[id]/timer-stop/route.ts +5 -2
  1151. package/src/modules/staff/api/timesheets/time-entries/bulk/route.ts +4 -1
  1152. package/src/modules/staff/api/timesheets/time-entries/start-timer/route.ts +4 -1
  1153. package/src/modules/staff/backend/staff/team-members/page.tsx +5 -2
  1154. package/src/modules/staff/backend/staff/team-roles/page.tsx +5 -2
  1155. package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +5 -2
  1156. package/src/modules/staff/backend/staff/teams/page.tsx +5 -2
  1157. package/src/modules/staff/backend/staff/timesheets/page.tsx +8 -5
  1158. package/src/modules/staff/backend/staff/timesheets/projects/[id]/page.tsx +4 -1
  1159. package/src/modules/staff/backend/staff/timesheets/projects/page.tsx +5 -2
  1160. package/src/modules/staff/commands/timesheets-entries.ts +4 -1
  1161. package/src/modules/staff/widgets/dashboard/timesheets-hours-by-project/widget.client.tsx +4 -1
  1162. package/src/modules/staff/widgets/dashboard/timesheets-time-reporting/widget.client.tsx +6 -3
  1163. package/src/modules/sync_excel/api/import/route.ts +4 -1
  1164. package/src/modules/translations/api/[entityType]/[entityId]/route.ts +6 -3
  1165. package/src/modules/translations/api/get/locales.ts +4 -1
  1166. package/src/modules/translations/api/put/locales.ts +4 -1
  1167. package/src/modules/translations/components/TranslationManager.tsx +4 -1
  1168. package/src/modules/translations/subscribers/cleanup.ts +4 -1
  1169. package/src/modules/workflows/api/definitions/[id]/customize/route.ts +5 -2
  1170. package/src/modules/workflows/api/definitions/[id]/reset-to-code/route.ts +5 -2
  1171. package/src/modules/workflows/api/definitions/[id]/route.ts +7 -4
  1172. package/src/modules/workflows/api/definitions/route.ts +5 -2
  1173. package/src/modules/workflows/api/events/[id]/route.ts +4 -1
  1174. package/src/modules/workflows/api/events/route.ts +4 -1
  1175. package/src/modules/workflows/api/instances/[id]/advance/route.ts +4 -1
  1176. package/src/modules/workflows/api/instances/[id]/cancel/route.ts +4 -1
  1177. package/src/modules/workflows/api/instances/[id]/events/route.ts +4 -1
  1178. package/src/modules/workflows/api/instances/[id]/retry/route.ts +4 -1
  1179. package/src/modules/workflows/api/instances/[id]/route.ts +4 -1
  1180. package/src/modules/workflows/api/instances/[id]/signal/route.ts +6 -7
  1181. package/src/modules/workflows/api/instances/route.ts +6 -3
  1182. package/src/modules/workflows/api/instances/validate-start/route.ts +4 -1
  1183. package/src/modules/workflows/api/signals/route.ts +4 -1
  1184. package/src/modules/workflows/api/tasks/[id]/claim/route.ts +4 -1
  1185. package/src/modules/workflows/api/tasks/[id]/complete/route.ts +4 -1
  1186. package/src/modules/workflows/api/tasks/[id]/route.ts +4 -1
  1187. package/src/modules/workflows/api/tasks/route.ts +4 -1
  1188. package/src/modules/workflows/backend/definitions/visual-editor/page.tsx +5 -2
  1189. package/src/modules/workflows/backend/instances/[id]/page.tsx +6 -3
  1190. package/src/modules/workflows/backend/tasks/[id]/page.tsx +4 -1
  1191. package/src/modules/workflows/components/BusinessRulesSelector.tsx +6 -3
  1192. package/src/modules/workflows/components/WorkflowSelector.tsx +6 -3
  1193. package/src/modules/workflows/components/fields/BusinessRuleConditionsEditor.tsx +4 -1
  1194. package/src/modules/workflows/components/fields/StartPreConditionsEditor.tsx +4 -1
  1195. package/src/modules/workflows/components/fields/WorkflowSelectorField.tsx +4 -1
  1196. package/src/modules/workflows/frontend/checkout-demo/page.tsx +9 -7
  1197. package/src/modules/workflows/lib/activity-executor.ts +26 -21
  1198. package/src/modules/workflows/lib/activity-worker-handler.ts +9 -15
  1199. package/src/modules/workflows/lib/code-registry.ts +8 -7
  1200. package/src/modules/workflows/lib/compensation-handler.ts +5 -2
  1201. package/src/modules/workflows/lib/edgeFormTransforms.ts +4 -1
  1202. package/src/modules/workflows/lib/event-trigger-service.ts +6 -3
  1203. package/src/modules/workflows/lib/nodeFormTransforms.ts +4 -1
  1204. package/src/modules/workflows/lib/seeds.ts +17 -2
  1205. package/src/modules/workflows/lib/signal-handler.ts +4 -1
  1206. package/src/modules/workflows/lib/start-validator.ts +10 -3
  1207. package/src/modules/workflows/lib/step-handler.ts +4 -1
  1208. package/src/modules/workflows/lib/task-handler.ts +4 -1
  1209. package/src/modules/workflows/lib/transition-handler.ts +6 -3
  1210. package/src/modules/workflows/lib/workflow-executor.ts +28 -15
  1211. package/src/modules/workflows/subscribers/event-trigger.ts +22 -24
  1212. package/src/modules/workflows/subscribers/task-assigned-notification.ts +4 -1
  1213. package/src/modules/workflows/workers/workflow-activities.worker.ts +31 -20
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/inbox_ops/api/settings/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { InboxSettings } from '../../data/entities'\nimport { updateSettingsSchema } from '../../data/validators'\nimport { resolveRequestContext, handleRouteError } from '../routeHelpers'\nimport {\n resolveCache,\n createSettingsCacheKey,\n createSettingsCacheTag,\n invalidateSettingsCache,\n SETTINGS_CACHE_TTL_MS,\n} from '../../lib/cache'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['inbox_ops.settings.manage'] },\n PATCH: { requireAuth: true, requireFeatures: ['inbox_ops.settings.manage'] },\n}\n\nexport async function GET(req: Request) {\n try {\n const ctx = await resolveRequestContext(req)\n const cache = resolveCache(ctx.container)\n\n if (cache) {\n const cacheKey = createSettingsCacheKey(ctx.tenantId)\n const cached = await runWithCacheTenant(ctx.tenantId, () => cache.get(cacheKey))\n if (cached) {\n return NextResponse.json(cached)\n }\n }\n\n const settings = await findOneWithDecryption(\n ctx.em,\n InboxSettings,\n {\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n deletedAt: null,\n },\n undefined,\n ctx.scope,\n )\n\n const responseBody = {\n settings: settings ? {\n id: settings.id,\n inboxAddress: settings.inboxAddress,\n isActive: settings.isActive,\n workingLanguage: settings.workingLanguage,\n // Surface only whether a per-tenant secret exists \u2014 never the value.\n webhookSecretSet: Boolean(settings.webhookSecret),\n updatedAt: settings.updatedAt instanceof Date ? settings.updatedAt.toISOString() : (settings.updatedAt ?? null),\n } : null,\n }\n\n if (cache) {\n const cacheKey = createSettingsCacheKey(ctx.tenantId)\n const tag = createSettingsCacheTag(ctx.tenantId)\n try {\n await runWithCacheTenant(ctx.tenantId, () =>\n cache.set(cacheKey, responseBody, { ttl: SETTINGS_CACHE_TTL_MS, tags: [tag] }),\n )\n } catch (err) {\n console.warn('[inbox_ops:settings] Failed to set cache', err)\n }\n }\n\n return NextResponse.json(responseBody)\n } catch (err) {\n return handleRouteError(err, 'load settings')\n }\n}\n\nexport async function PATCH(req: Request) {\n try {\n const ctx = await resolveRequestContext(req)\n\n const body = await req.json()\n const parsed = updateSettingsSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid request', details: parsed.error.issues }, { status: 400 })\n }\n\n const settings = await findOneWithDecryption(\n ctx.em,\n InboxSettings,\n {\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n deletedAt: null,\n },\n undefined,\n ctx.scope,\n )\n\n if (!settings) {\n return NextResponse.json({ error: 'Settings not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite when two tabs edit the same inbox\n // settings record. Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'inbox_ops.settings',\n resourceId: settings.id,\n current: settings.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n if (parsed.data.workingLanguage !== undefined) {\n settings.workingLanguage = parsed.data.workingLanguage\n }\n if (parsed.data.isActive !== undefined) {\n settings.isActive = parsed.data.isActive\n }\n if (parsed.data.webhookSecret !== undefined) {\n // Empty/null clears the per-tenant secret (reverts to the global key).\n settings.webhookSecret = parsed.data.webhookSecret ? parsed.data.webhookSecret : null\n }\n\n await ctx.em.flush()\n\n const cache = resolveCache(ctx.container)\n await runWithCacheTenant(ctx.tenantId, () => invalidateSettingsCache(cache, ctx.tenantId))\n\n return NextResponse.json({\n ok: true,\n settings: {\n id: settings.id,\n inboxAddress: settings.inboxAddress,\n isActive: settings.isActive,\n workingLanguage: settings.workingLanguage,\n webhookSecretSet: Boolean(settings.webhookSecret),\n updatedAt: settings.updatedAt instanceof Date ? settings.updatedAt.toISOString() : (settings.updatedAt ?? null),\n },\n })\n } catch (err) {\n return handleRouteError(err, 'update settings')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'InboxOps',\n summary: 'Settings',\n methods: {\n GET: {\n summary: 'Get tenant inbox configuration',\n description: 'Returns the forwarding address and configuration for this tenant',\n responses: [\n { status: 200, description: 'Inbox settings' },\n ],\n },\n PATCH: {\n summary: 'Update tenant inbox configuration',\n description: 'Updates working language and/or active status',\n responses: [\n { status: 200, description: 'Updated settings' },\n { status: 404, description: 'Settings not found' },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,6BAA6B;AACtC,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,wBAAwB;AACxD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,2BAA2B,EAAE;AAAA,EACzE,OAAO,EAAE,aAAa,MAAM,iBAAiB,CAAC,2BAA2B,EAAE;AAC7E;AAEA,eAAsB,IAAI,KAAc;AACtC,MAAI;AACF,UAAM,MAAM,MAAM,sBAAsB,GAAG;AAC3C,UAAM,QAAQ,aAAa,IAAI,SAAS;AAExC,QAAI,OAAO;AACT,YAAM,WAAW,uBAAuB,IAAI,QAAQ;AACpD,YAAM,SAAS,MAAM,mBAAmB,IAAI,UAAU,MAAM,MAAM,IAAI,QAAQ,CAAC;AAC/E,UAAI,QAAQ;AACV,eAAO,aAAa,KAAK,MAAM;AAAA,MACjC;AAAA,IACF;AAEA,UAAM,WAAW,MAAM;AAAA,MACrB,IAAI;AAAA,MACJ;AAAA,MACA;AAAA,QACE,gBAAgB,IAAI;AAAA,QACpB,UAAU,IAAI;AAAA,QACd,WAAW;AAAA,MACb;AAAA,MACA;AAAA,MACA,IAAI;AAAA,IACN;AAEA,UAAM,eAAe;AAAA,MACnB,UAAU,WAAW;AAAA,QACnB,IAAI,SAAS;AAAA,QACb,cAAc,SAAS;AAAA,QACvB,UAAU,SAAS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AAA,MAC/C;AAAA,IACF;AAAA,IACA,OAAO;AAAA,MACL,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mBAAmB;AAAA,QAC/C,EAAE,QAAQ,KAAK,aAAa,qBAAqB;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { runWithCacheTenant } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { enforceCommandOptimisticLockWithGuards } from '@open-mercato/shared/lib/crud/optimistic-lock-command'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { InboxSettings } from '../../data/entities'\nimport { updateSettingsSchema } from '../../data/validators'\nimport { resolveRequestContext, handleRouteError } from '../routeHelpers'\nimport {\n resolveCache,\n createSettingsCacheKey,\n createSettingsCacheTag,\n invalidateSettingsCache,\n SETTINGS_CACHE_TTL_MS,\n} from '../../lib/cache'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'settings' })\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['inbox_ops.settings.manage'] },\n PATCH: { requireAuth: true, requireFeatures: ['inbox_ops.settings.manage'] },\n}\n\nexport async function GET(req: Request) {\n try {\n const ctx = await resolveRequestContext(req)\n const cache = resolveCache(ctx.container)\n\n if (cache) {\n const cacheKey = createSettingsCacheKey(ctx.tenantId)\n const cached = await runWithCacheTenant(ctx.tenantId, () => cache.get(cacheKey))\n if (cached) {\n return NextResponse.json(cached)\n }\n }\n\n const settings = await findOneWithDecryption(\n ctx.em,\n InboxSettings,\n {\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n deletedAt: null,\n },\n undefined,\n ctx.scope,\n )\n\n const responseBody = {\n settings: settings ? {\n id: settings.id,\n inboxAddress: settings.inboxAddress,\n isActive: settings.isActive,\n workingLanguage: settings.workingLanguage,\n // Surface only whether a per-tenant secret exists \u2014 never the value.\n webhookSecretSet: Boolean(settings.webhookSecret),\n updatedAt: settings.updatedAt instanceof Date ? settings.updatedAt.toISOString() : (settings.updatedAt ?? null),\n } : null,\n }\n\n if (cache) {\n const cacheKey = createSettingsCacheKey(ctx.tenantId)\n const tag = createSettingsCacheTag(ctx.tenantId)\n try {\n await runWithCacheTenant(ctx.tenantId, () =>\n cache.set(cacheKey, responseBody, { ttl: SETTINGS_CACHE_TTL_MS, tags: [tag] }),\n )\n } catch (err) {\n logger.warn('Failed to set cache', { err })\n }\n }\n\n return NextResponse.json(responseBody)\n } catch (err) {\n return handleRouteError(err, 'load settings')\n }\n}\n\nexport async function PATCH(req: Request) {\n try {\n const ctx = await resolveRequestContext(req)\n\n const body = await req.json()\n const parsed = updateSettingsSchema.safeParse(body)\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid request', details: parsed.error.issues }, { status: 400 })\n }\n\n const settings = await findOneWithDecryption(\n ctx.em,\n InboxSettings,\n {\n organizationId: ctx.organizationId,\n tenantId: ctx.tenantId,\n deletedAt: null,\n },\n undefined,\n ctx.scope,\n )\n\n if (!settings) {\n return NextResponse.json({ error: 'Settings not found' }, { status: 404 })\n }\n\n // Optimistic lock: refuse a stale overwrite when two tabs edit the same inbox\n // settings record. Strictly additive \u2014 a no-op without the expected-version header.\n try {\n await enforceCommandOptimisticLockWithGuards(ctx.container, {\n resourceKind: 'inbox_ops.settings',\n resourceId: settings.id,\n current: settings.updatedAt ?? null,\n request: req,\n })\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n throw err\n }\n\n if (parsed.data.workingLanguage !== undefined) {\n settings.workingLanguage = parsed.data.workingLanguage\n }\n if (parsed.data.isActive !== undefined) {\n settings.isActive = parsed.data.isActive\n }\n if (parsed.data.webhookSecret !== undefined) {\n // Empty/null clears the per-tenant secret (reverts to the global key).\n settings.webhookSecret = parsed.data.webhookSecret ? parsed.data.webhookSecret : null\n }\n\n await ctx.em.flush()\n\n const cache = resolveCache(ctx.container)\n await runWithCacheTenant(ctx.tenantId, () => invalidateSettingsCache(cache, ctx.tenantId))\n\n return NextResponse.json({\n ok: true,\n settings: {\n id: settings.id,\n inboxAddress: settings.inboxAddress,\n isActive: settings.isActive,\n workingLanguage: settings.workingLanguage,\n webhookSecretSet: Boolean(settings.webhookSecret),\n updatedAt: settings.updatedAt instanceof Date ? settings.updatedAt.toISOString() : (settings.updatedAt ?? null),\n },\n })\n } catch (err) {\n return handleRouteError(err, 'update settings')\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'InboxOps',\n summary: 'Settings',\n methods: {\n GET: {\n summary: 'Get tenant inbox configuration',\n description: 'Returns the forwarding address and configuration for this tenant',\n responses: [\n { status: 200, description: 'Inbox settings' },\n ],\n },\n PATCH: {\n summary: 'Update tenant inbox configuration',\n description: 'Updates working language and/or active status',\n responses: [\n { status: 200, description: 'Updated settings' },\n { status: 404, description: 'Settings not found' },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAE7B,SAAS,0BAA0B;AACnC,SAAS,6BAA6B;AACtC,SAAS,8CAA8C;AACvD,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAC9B,SAAS,4BAA4B;AACrC,SAAS,uBAAuB,wBAAwB;AACxD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAEjE,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,2BAA2B,EAAE;AAAA,EACzE,OAAO,EAAE,aAAa,MAAM,iBAAiB,CAAC,2BAA2B,EAAE;AAC7E;AAEA,eAAsB,IAAI,KAAc;AACtC,MAAI;AACF,UAAM,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Q,CAAC;AAEzF,WAAO,aAAa,KAAK;AAAA,MACvB,IAAI;AAAA,MACJ,UAAU;AAAA,QACR,IAAI,SAAS;AAAA,QACb,cAAc,SAAS;AAAA,QACvB,UAAU,SAAS;AAAA,QACnB,iBAAiB,SAAS;AAAA,QAC1B,kBAAkB,QAAQ,SAAS,aAAa;AAAA,QAChD,WAAW,SAAS,qBAAqB,OAAO,SAAS,UAAU,YAAY,IAAK,SAAS,aAAa;AAAA,MAC5G;AAAA,IACF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,WAAO,iBAAiB,KAAK,iBAAiB;AAAA,EAChD;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,EACT,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,iBAAiB;AAAA,MAC/C;AAAA,IACF;AAAA,IACA,OAAO;AAAA,MACL,SAAS;AAAA,MACT,aAAa;AAAA,MACb,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,mBAAmB;AAAA,QAC/C,EAAE,QAAQ,KAAK,aAAa,qBAAqB;AAAA,MACnD;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -9,6 +9,8 @@ import { InboxSettings, InboxEmail } from "../../data/entities.js";
9
9
  import { parseInboundEmail } from "../../lib/emailParser.js";
10
10
  import { checkRateLimit } from "../../lib/rateLimiter.js";
11
11
  import { emitInboxOpsEvent } from "../../events.js";
12
+ import { createLogger } from "@open-mercato/shared/lib/logger";
13
+ const logger = createLogger("inbox_ops").child({ component: "webhook" });
12
14
  const metadata = {
13
15
  POST: { requireAuth: false }
14
16
  };
@@ -83,7 +85,7 @@ async function verifyAndParse(req, rawBody) {
83
85
  if (customSig) {
84
86
  const webhookSecret = process.env.INBOX_OPS_WEBHOOK_SECRET;
85
87
  if (!webhookSecret) {
86
- console.error("[inbox_ops:webhook] INBOX_OPS_WEBHOOK_SECRET not configured");
88
+ logger.error("INBOX_OPS_WEBHOOK_SECRET not configured");
87
89
  return { ok: false, response: NextResponse.json({ error: "Service unavailable" }, { status: 503 }) };
88
90
  }
89
91
  const timestamp = req.headers.get("x-webhook-timestamp") || "";
@@ -101,7 +103,7 @@ async function verifyAndParse(req, rawBody) {
101
103
  if (svixId) {
102
104
  const signingSecret = process.env.RESEND_WEBHOOK_SIGNING_SECRET;
103
105
  if (!signingSecret) {
104
- console.error("[inbox_ops:webhook] RESEND_WEBHOOK_SIGNING_SECRET not configured");
106
+ logger.error("RESEND_WEBHOOK_SIGNING_SECRET not configured");
105
107
  return { ok: false, response: NextResponse.json({ error: "Service unavailable" }, { status: 503 }) };
106
108
  }
107
109
  const headers = {
@@ -135,7 +137,7 @@ async function POST(req) {
135
137
  const hasCustomSecret = Boolean(process.env.INBOX_OPS_WEBHOOK_SECRET);
136
138
  const hasResendSecret = Boolean(process.env.RESEND_WEBHOOK_SIGNING_SECRET);
137
139
  if (!hasCustomSecret && !hasResendSecret) {
138
- console.error("[inbox_ops:webhook] Neither INBOX_OPS_WEBHOOK_SECRET nor RESEND_WEBHOOK_SIGNING_SECRET is configured");
140
+ logger.error("Neither INBOX_OPS_WEBHOOK_SECRET nor RESEND_WEBHOOK_SIGNING_SECRET is configured");
139
141
  return NextResponse.json({ error: "Service unavailable" }, { status: 503 });
140
142
  }
141
143
  const contentLength = parseInt(req.headers.get("content-length") || "0", 10);
@@ -245,7 +247,7 @@ async function POST(req) {
245
247
  toAddress
246
248
  });
247
249
  } catch (eventError) {
248
- console.error("[inbox_ops:webhook] Failed to emit deduplicated event:", eventError);
250
+ logger.error("Failed to emit deduplicated event", { err: eventError });
249
251
  }
250
252
  return NextResponse.json({ ok: true });
251
253
  }
@@ -283,7 +285,7 @@ async function POST(req) {
283
285
  subject: parsed.subject
284
286
  });
285
287
  } catch (eventError) {
286
- console.error("[inbox_ops:webhook] Failed to emit email.received event:", eventError);
288
+ logger.error("Failed to emit email.received event", { err: eventError });
287
289
  }
288
290
  return NextResponse.json({ ok: true });
289
291
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/inbox_ops/api/webhook/inbound.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { createHmac, timingSafeEqual } from 'node:crypto'\nimport { z } from 'zod'\nimport { Webhook } from 'svix'\nimport { Resend } from 'resend'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { InboxSettings, InboxEmail } from '../../data/entities'\nimport { parseInboundEmail } from '../../lib/emailParser'\nimport { checkRateLimit } from '../../lib/rateLimiter'\nimport { emitInboxOpsEvent } from '../../events'\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\nconst MAX_PAYLOAD_SIZE = 2 * 1024 * 1024 // 2MB\nconst REPLAY_WINDOW_MS = 5 * 60 * 1000 // 5 minutes\n\nfunction isTimestampFresh(timestamp: string): boolean {\n if (!timestamp) return false\n const timestampMs = parseInt(timestamp, 10) * 1000\n if (isNaN(timestampMs)) return false\n return Math.abs(Date.now() - timestampMs) <= REPLAY_WINDOW_MS\n}\n\nfunction verifyHmacSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string,\n): boolean {\n if (!signature || !timestamp || !secret) return false\n\n if (!isTimestampFresh(timestamp)) return false\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex')\n const received = signature.startsWith('sha256=')\n ? signature.slice('sha256='.length)\n : signature\n\n try {\n if (received.length !== expected.length) return false\n return timingSafeEqual(\n Buffer.from(received, 'hex'),\n Buffer.from(expected, 'hex'),\n )\n } catch {\n return false\n }\n}\n\n// True when the signature verifies against ANY of the candidate secrets. Used\n// to bind the inbound signature to the resolved tenant: once the target inbox\n// declares its own per-tenant secret, the global INBOX_OPS_WEBHOOK_SECRET is no\n// longer accepted for that inbox, so a holder of the global key alone cannot\n// forge mail into a tenant that opted into a dedicated secret.\nfunction verifyHmacAgainstAny(\n payload: string,\n signature: string,\n timestamp: string,\n secrets: string[],\n): boolean {\n for (const secret of secrets) {\n if (secret && verifyHmacSignature(payload, signature, timestamp, secret)) return true\n }\n return false\n}\n\n// Stable, non-reversible identifier for the pre-DB global rate-limit bucket.\n// Keying on the configured signing secret (rather than the attacker-set `to` or\n// the per-request signature) means the bucket is request-invariant for a given\n// secret, so rotating recipients or mutating the body cannot dilute the limit.\nfunction secretFingerprint(secret: string): string {\n return createHmac('sha256', 'inbox_ops:rate_limit:salt').update(secret).digest('hex').slice(0, 32)\n}\n\nfunction verifySvixSignature(\n rawBody: string,\n headers: Record<string, string>,\n secret: string,\n): boolean {\n try {\n const wh = new Webhook(secret)\n wh.verify(rawBody, {\n 'svix-id': headers['svix-id'],\n 'svix-timestamp': headers['svix-timestamp'],\n 'svix-signature': headers['svix-signature'],\n })\n return true\n } catch {\n return false\n }\n}\n\nasync function fetchResendEmail(emailId: string): Promise<{\n from?: string\n to?: string[]\n subject?: string\n text?: string\n html?: string\n messageId?: string\n replyTo?: string\n inReplyTo?: string\n references?: string[]\n}> {\n const apiKey = process.env.RESEND_API_KEY\n if (!apiKey) throw new Error('RESEND_API_KEY is required to fetch Resend inbound emails')\n\n const resend = new Resend(apiKey)\n const { data, error } = await resend.emails.receiving.get(emailId)\n if (error || !data) {\n throw new Error(`Failed to fetch Resend email ${emailId}: ${error?.message || 'unknown error'}`)\n }\n\n return {\n from: data.from,\n to: data.to,\n subject: data.subject,\n text: data.text ?? undefined,\n html: data.html ?? undefined,\n messageId: data.message_id,\n replyTo: data.reply_to?.[0] ?? undefined,\n inReplyTo: data.headers?.['in-reply-to'] ?? undefined,\n references: data.headers?.['references']?.split(/\\s+/).filter(Boolean),\n }\n}\n\ntype VerifiedPayload =\n | { kind: 'custom'; payload: Record<string, unknown>; signature: string; timestamp: string }\n | { kind: 'resend'; emailFields: Awaited<ReturnType<typeof fetchResendEmail>>; to: string[] }\n\nasync function verifyAndParse(req: Request, rawBody: string): Promise<\n | { ok: true; data: VerifiedPayload }\n | { ok: false; response: NextResponse }\n> {\n const customSig = req.headers.get('x-webhook-signature')\n const svixId = req.headers.get('svix-id')\n\n if (customSig) {\n const webhookSecret = process.env.INBOX_OPS_WEBHOOK_SECRET\n if (!webhookSecret) {\n console.error('[inbox_ops:webhook] INBOX_OPS_WEBHOOK_SECRET not configured')\n return { ok: false, response: NextResponse.json({ error: 'Service unavailable' }, { status: 503 }) }\n }\n const timestamp = req.headers.get('x-webhook-timestamp') || ''\n // Cheap, secret-independent gate first: reject replayed/stale requests\n // before parsing. The HMAC itself is verified later, against the secret\n // bound to the resolved inbox (see the POST handler), so a holder of the\n // global secret cannot inject into a tenant that owns its own secret.\n if (!isTimestampFresh(timestamp)) {\n return { ok: false, response: NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) }\n }\n let payload: Record<string, unknown>\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false, response: NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n }\n return { ok: true, data: { kind: 'custom', payload, signature: customSig, timestamp } }\n }\n\n if (svixId) {\n const signingSecret = process.env.RESEND_WEBHOOK_SIGNING_SECRET\n if (!signingSecret) {\n console.error('[inbox_ops:webhook] RESEND_WEBHOOK_SIGNING_SECRET not configured')\n return { ok: false, response: NextResponse.json({ error: 'Service unavailable' }, { status: 503 }) }\n }\n const headers: Record<string, string> = {\n 'svix-id': svixId,\n 'svix-timestamp': req.headers.get('svix-timestamp') || '',\n 'svix-signature': req.headers.get('svix-signature') || '',\n }\n if (!verifySvixSignature(rawBody, headers, signingSecret)) {\n return { ok: false, response: NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) }\n }\n let envelope: { type?: string; data?: { email_id?: string; from?: string; to?: string[] } }\n try {\n envelope = JSON.parse(rawBody)\n } catch {\n return { ok: false, response: NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n }\n if (envelope.type !== 'email.received') {\n return { ok: false, response: NextResponse.json({ ok: true }) }\n }\n const emailId = envelope.data?.email_id\n if (!emailId) {\n return { ok: false, response: NextResponse.json({ error: 'Missing email_id in Resend payload' }, { status: 400 }) }\n }\n const emailFields = await fetchResendEmail(emailId)\n const to = emailFields.to || envelope.data?.to || []\n return { ok: true, data: { kind: 'resend', emailFields, to } }\n }\n\n return { ok: false, response: NextResponse.json({ error: 'Missing signature headers' }, { status: 400 }) }\n}\n\nexport async function POST(req: Request) {\n const hasCustomSecret = Boolean(process.env.INBOX_OPS_WEBHOOK_SECRET)\n const hasResendSecret = Boolean(process.env.RESEND_WEBHOOK_SIGNING_SECRET)\n if (!hasCustomSecret && !hasResendSecret) {\n console.error('[inbox_ops:webhook] Neither INBOX_OPS_WEBHOOK_SECRET nor RESEND_WEBHOOK_SIGNING_SECRET is configured')\n return NextResponse.json({ error: 'Service unavailable' }, { status: 503 })\n }\n\n const contentLength = parseInt(req.headers.get('content-length') || '0', 10)\n if (contentLength > MAX_PAYLOAD_SIZE) {\n return NextResponse.json({ error: 'Payload too large' }, { status: 413 })\n }\n\n let rawBody: string\n try {\n rawBody = await req.text()\n } catch {\n return NextResponse.json({ error: 'Bad request' }, { status: 400 })\n }\n\n if (rawBody.length > MAX_PAYLOAD_SIZE) {\n return NextResponse.json({ error: 'Payload too large' }, { status: 413 })\n }\n\n const verified = await verifyAndParse(req, rawBody)\n if (!verified.ok) {\n return verified.response\n }\n\n let toAddress: string | null\n let emailInput: Parameters<typeof parseInboundEmail>[0]\n\n if (verified.data.kind === 'custom') {\n const payload = verified.data.payload\n toAddress = extractToAddress(payload)\n emailInput = {\n from: payload.from as string | undefined,\n to: payload.to as string | string[] | undefined,\n subject: payload.subject as string | undefined,\n text: payload.text as string | undefined,\n html: payload.html as string | undefined,\n messageId: payload.messageId as string | undefined,\n replyTo: payload.replyTo as string | undefined,\n inReplyTo: payload.inReplyTo as string | undefined,\n references: payload.references as string | string[] | undefined,\n }\n } else {\n const { emailFields, to } = verified.data\n toAddress = to.length > 0 ? to[0].toLowerCase() : null\n emailInput = {\n from: emailFields.from,\n to: emailFields.to,\n subject: emailFields.subject,\n text: emailFields.text,\n html: emailFields.html,\n messageId: emailFields.messageId,\n replyTo: emailFields.replyTo,\n inReplyTo: emailFields.inReplyTo,\n references: emailFields.references,\n }\n }\n\n if (!toAddress) {\n return NextResponse.json({ error: 'Missing recipient address' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n\n let cache: CacheStrategy | null = null\n try {\n cache = container.resolve('cache') as CacheStrategy\n } catch {\n // Cache not available \u2014 the limiter now fails closed with a process-local\n // bucket instead of waving the request through.\n }\n\n // Pre-DB global bucket keyed on the configured signing secret (custom) or the\n // static Resend path, NOT on the attacker-controllable `to` and NOT on the\n // per-request signature (which mutates with timestamp/body, so it would mint a\n // fresh bucket every request and never throttle). The per-tenant secret lives\n // behind the encrypted-column lookup, so the only secret available here without\n // a DB hit is the global one \u2014 keying on it caps total inbound volume for the\n // custom path and runs BEFORE the lookup so a flood cannot amplify DB work.\n const globalBucketKey = verified.data.kind === 'custom'\n ? `webhook:secret:${secretFingerprint(process.env.INBOX_OPS_WEBHOOK_SECRET || '')}`\n : 'webhook:resend'\n const globalRateCheck = await checkRateLimit(cache, globalBucketKey)\n if (!globalRateCheck.allowed) {\n return rateLimitedResponse(globalRateCheck.retryAfterSeconds)\n }\n\n const em = (container.resolve('em') as EntityManager).fork()\n\n // No explicit scope: decryptEntitiesWithFallbackScope reads tenant/org off the\n // resolved row, which is exactly what binds webhook_secret to its own tenant.\n const settings = await findOneWithDecryption(\n em,\n InboxSettings,\n {\n inboxAddress: toAddress.toLowerCase(),\n isActive: true,\n deletedAt: null,\n },\n )\n\n // Final HMAC verification for the custom provider path: bind the signature to\n // the resolved tenant. When the inbox declares its own secret, ONLY that\n // secret is accepted; otherwise the global secret is accepted (back-compat).\n // For an unknown `to` we still require the global secret so the endpoint never\n // behaves as an unauthenticated probe oracle.\n if (verified.data.kind === 'custom') {\n const globalSecret = process.env.INBOX_OPS_WEBHOOK_SECRET || ''\n const inboxSecret = settings?.webhookSecret || ''\n const acceptableSecrets = inboxSecret ? [inboxSecret] : [globalSecret]\n const signatureValid = verifyHmacAgainstAny(\n rawBody,\n verified.data.signature,\n verified.data.timestamp,\n acceptableSecrets,\n )\n if (!signatureValid) {\n return NextResponse.json({ error: 'Invalid signature' }, { status: 400 })\n }\n }\n\n if (!settings) {\n return NextResponse.json({ ok: true })\n }\n\n // Per-tenant bucket keyed on the RESOLVED tenant (not the raw `to`), so it\n // cannot be diluted by alias addresses that map to the same inbox.\n const tenantRateCheck = await checkRateLimit(\n cache,\n `webhook:tenant:${settings.tenantId}`,\n settings.tenantId,\n )\n if (!tenantRateCheck.allowed) {\n return rateLimitedResponse(tenantRateCheck.retryAfterSeconds)\n }\n\n const parsed = parseInboundEmail(emailInput)\n\n const isDuplicate = await checkDuplicate(em, settings, parsed.messageId, parsed.contentHash)\n if (isDuplicate) {\n try {\n await emitInboxOpsEvent('inbox_ops.email.deduplicated', {\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n toAddress,\n })\n } catch (eventError) {\n console.error('[inbox_ops:webhook] Failed to emit deduplicated event:', eventError)\n }\n return NextResponse.json({ ok: true })\n }\n\n const maxTextSize = parseInt(process.env.INBOX_OPS_MAX_TEXT_SIZE || '204800', 10)\n const cleanedText = parsed.cleanedText.slice(0, maxTextSize)\n\n const email = em.create(InboxEmail, {\n messageId: parsed.messageId,\n contentHash: parsed.contentHash,\n forwardedByAddress: parsed.from.email,\n forwardedByName: parsed.from.name || null,\n toAddress,\n subject: parsed.subject,\n replyTo: parsed.replyTo,\n inReplyTo: parsed.inReplyTo,\n emailReferences: parsed.references,\n rawText: parsed.rawText,\n rawHtml: parsed.rawHtml,\n cleanedText,\n threadMessages: parsed.threadMessages,\n detectedLanguage: parsed.detectedLanguage,\n receivedAt: new Date(),\n status: 'received' as const,\n isActive: true,\n organizationId: settings.organizationId,\n tenantId: settings.tenantId,\n })\n\n em.persist(email)\n await em.flush()\n\n try {\n await emitInboxOpsEvent('inbox_ops.email.received', {\n emailId: email.id,\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n forwardedByAddress: parsed.from.email,\n subject: parsed.subject,\n })\n } catch (eventError) {\n console.error('[inbox_ops:webhook] Failed to emit email.received event:', eventError)\n }\n\n return NextResponse.json({ ok: true })\n}\n\nfunction rateLimitedResponse(retryAfterSeconds?: number): NextResponse {\n return NextResponse.json(\n { error: 'Rate limit exceeded' },\n {\n status: 429,\n headers: retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n },\n )\n}\n\nfunction extractToAddress(payload: Record<string, unknown>): string | null {\n const to = payload.to\n if (typeof to === 'string') {\n const match = to.match(/<([^>]+)>/)\n return match ? match[1].toLowerCase() : to.trim().toLowerCase()\n }\n if (Array.isArray(to) && to.length > 0) {\n const first = to[0]\n if (typeof first === 'string') {\n const match = first.match(/<([^>]+)>/)\n return match ? match[1].toLowerCase() : first.trim().toLowerCase()\n }\n }\n return null\n}\n\nasync function checkDuplicate(\n em: EntityManager,\n settings: InboxSettings,\n messageId: string | null | undefined,\n contentHash: string | null | undefined,\n): Promise<boolean> {\n const encScope = {\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n }\n const whereBase = {\n organizationId: settings.organizationId,\n tenantId: settings.tenantId,\n deletedAt: null,\n }\n\n if (messageId) {\n const byMessageId = await findOneWithDecryption(em, InboxEmail, { ...whereBase, messageId }, undefined, encScope)\n if (byMessageId) return true\n }\n\n if (contentHash) {\n const byHash = await findOneWithDecryption(em, InboxEmail, { ...whereBase, contentHash }, undefined, encScope)\n if (byHash) return true\n }\n\n return false\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'InboxOps',\n summary: 'Inbound email webhook',\n methods: {\n POST: {\n summary: 'Receive forwarded email from provider webhook',\n description: 'Public endpoint \u2014 validated by provider HMAC signature or Resend/Svix signature. Rate limited per tenant.',\n requestBody: {\n contentType: 'application/json',\n schema: z.object({\n from: z.string().optional(),\n to: z.union([z.string(), z.array(z.string())]).optional(),\n subject: z.string().optional(),\n text: z.string().optional(),\n html: z.string().optional(),\n messageId: z.string().optional(),\n replyTo: z.string().optional(),\n inReplyTo: z.string().optional(),\n references: z.union([z.string(), z.array(z.string())]).optional(),\n }),\n },\n responses: [\n { status: 200, description: 'Email received and queued for processing' },\n { status: 400, description: 'Invalid payload or signature' },\n { status: 413, description: 'Payload too large' },\n { status: 429, description: 'Rate limit exceeded' },\n { status: 503, description: 'Webhook secret not configured' },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,uBAAuB;AAC5C,SAAS,SAAS;AAClB,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAIvC,SAAS,6BAA6B;AACtC,SAAS,eAAe,kBAAkB;AAC1C,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAE3B,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM;AAC7B;AAEA,MAAM,mBAAmB,IAAI,OAAO;AACpC,MAAM,mBAAmB,IAAI,KAAK;AAElC,SAAS,iBAAiB,WAA4B;AACpD,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,cAAc,SAAS,WAAW,EAAE,IAAI;AAC9C,MAAI,MAAM,WAAW,EAAG,QAAO;AAC/B,SAAO,KAAK,IAAI,KAAK,IAAI,IAAI,WAAW,KAAK;AAC/C;AAEA,SAAS,oBACP,SACA,WACA,WACA,QACS;AACT,MAAI,CAAC,aAAa,CAAC,aAAa,CAAC,OAAQ,QAAO;AAEhD,MAAI,CAAC,iBAAiB,SAAS,EAAG,QAAO;AAEzC,QAAM,WAAW,WAAW,UA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C,CAAC,CAAC,EAAE,SAAS;AAAA,QAClE,CAAC;AAAA,MACH;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,+BAA+B;AAAA,QAC3D,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,QAChD,EAAE,QAAQ,KAAK,aAAa,sBAAsB;AAAA,QAClD,EAAE,QAAQ,KAAK,aAAa,gCAAgC;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { createHmac, timingSafeEqual } from 'node:crypto'\nimport { z } from 'zod'\nimport { Webhook } from 'svix'\nimport { Resend } from 'resend'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CacheStrategy } from '@open-mercato/cache'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { InboxSettings, InboxEmail } from '../../data/entities'\nimport { parseInboundEmail } from '../../lib/emailParser'\nimport { checkRateLimit } from '../../lib/rateLimiter'\nimport { emitInboxOpsEvent } from '../../events'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'webhook' })\n\nexport const metadata = {\n POST: { requireAuth: false },\n}\n\nconst MAX_PAYLOAD_SIZE = 2 * 1024 * 1024 // 2MB\nconst REPLAY_WINDOW_MS = 5 * 60 * 1000 // 5 minutes\n\nfunction isTimestampFresh(timestamp: string): boolean {\n if (!timestamp) return false\n const timestampMs = parseInt(timestamp, 10) * 1000\n if (isNaN(timestampMs)) return false\n return Math.abs(Date.now() - timestampMs) <= REPLAY_WINDOW_MS\n}\n\nfunction verifyHmacSignature(\n payload: string,\n signature: string,\n timestamp: string,\n secret: string,\n): boolean {\n if (!signature || !timestamp || !secret) return false\n\n if (!isTimestampFresh(timestamp)) return false\n\n const expected = createHmac('sha256', secret)\n .update(`${timestamp}.${payload}`)\n .digest('hex')\n const received = signature.startsWith('sha256=')\n ? signature.slice('sha256='.length)\n : signature\n\n try {\n if (received.length !== expected.length) return false\n return timingSafeEqual(\n Buffer.from(received, 'hex'),\n Buffer.from(expected, 'hex'),\n )\n } catch {\n return false\n }\n}\n\n// True when the signature verifies against ANY of the candidate secrets. Used\n// to bind the inbound signature to the resolved tenant: once the target inbox\n// declares its own per-tenant secret, the global INBOX_OPS_WEBHOOK_SECRET is no\n// longer accepted for that inbox, so a holder of the global key alone cannot\n// forge mail into a tenant that opted into a dedicated secret.\nfunction verifyHmacAgainstAny(\n payload: string,\n signature: string,\n timestamp: string,\n secrets: string[],\n): boolean {\n for (const secret of secrets) {\n if (secret && verifyHmacSignature(payload, signature, timestamp, secret)) return true\n }\n return false\n}\n\n// Stable, non-reversible identifier for the pre-DB global rate-limit bucket.\n// Keying on the configured signing secret (rather than the attacker-set `to` or\n// the per-request signature) means the bucket is request-invariant for a given\n// secret, so rotating recipients or mutating the body cannot dilute the limit.\nfunction secretFingerprint(secret: string): string {\n return createHmac('sha256', 'inbox_ops:rate_limit:salt').update(secret).digest('hex').slice(0, 32)\n}\n\nfunction verifySvixSignature(\n rawBody: string,\n headers: Record<string, string>,\n secret: string,\n): boolean {\n try {\n const wh = new Webhook(secret)\n wh.verify(rawBody, {\n 'svix-id': headers['svix-id'],\n 'svix-timestamp': headers['svix-timestamp'],\n 'svix-signature': headers['svix-signature'],\n })\n return true\n } catch {\n return false\n }\n}\n\nasync function fetchResendEmail(emailId: string): Promise<{\n from?: string\n to?: string[]\n subject?: string\n text?: string\n html?: string\n messageId?: string\n replyTo?: string\n inReplyTo?: string\n references?: string[]\n}> {\n const apiKey = process.env.RESEND_API_KEY\n if (!apiKey) throw new Error('RESEND_API_KEY is required to fetch Resend inbound emails')\n\n const resend = new Resend(apiKey)\n const { data, error } = await resend.emails.receiving.get(emailId)\n if (error || !data) {\n throw new Error(`Failed to fetch Resend email ${emailId}: ${error?.message || 'unknown error'}`)\n }\n\n return {\n from: data.from,\n to: data.to,\n subject: data.subject,\n text: data.text ?? undefined,\n html: data.html ?? undefined,\n messageId: data.message_id,\n replyTo: data.reply_to?.[0] ?? undefined,\n inReplyTo: data.headers?.['in-reply-to'] ?? undefined,\n references: data.headers?.['references']?.split(/\\s+/).filter(Boolean),\n }\n}\n\ntype VerifiedPayload =\n | { kind: 'custom'; payload: Record<string, unknown>; signature: string; timestamp: string }\n | { kind: 'resend'; emailFields: Awaited<ReturnType<typeof fetchResendEmail>>; to: string[] }\n\nasync function verifyAndParse(req: Request, rawBody: string): Promise<\n | { ok: true; data: VerifiedPayload }\n | { ok: false; response: NextResponse }\n> {\n const customSig = req.headers.get('x-webhook-signature')\n const svixId = req.headers.get('svix-id')\n\n if (customSig) {\n const webhookSecret = process.env.INBOX_OPS_WEBHOOK_SECRET\n if (!webhookSecret) {\n logger.error('INBOX_OPS_WEBHOOK_SECRET not configured')\n return { ok: false, response: NextResponse.json({ error: 'Service unavailable' }, { status: 503 }) }\n }\n const timestamp = req.headers.get('x-webhook-timestamp') || ''\n // Cheap, secret-independent gate first: reject replayed/stale requests\n // before parsing. The HMAC itself is verified later, against the secret\n // bound to the resolved inbox (see the POST handler), so a holder of the\n // global secret cannot inject into a tenant that owns its own secret.\n if (!isTimestampFresh(timestamp)) {\n return { ok: false, response: NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) }\n }\n let payload: Record<string, unknown>\n try {\n payload = JSON.parse(rawBody)\n } catch {\n return { ok: false, response: NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n }\n return { ok: true, data: { kind: 'custom', payload, signature: customSig, timestamp } }\n }\n\n if (svixId) {\n const signingSecret = process.env.RESEND_WEBHOOK_SIGNING_SECRET\n if (!signingSecret) {\n logger.error('RESEND_WEBHOOK_SIGNING_SECRET not configured')\n return { ok: false, response: NextResponse.json({ error: 'Service unavailable' }, { status: 503 }) }\n }\n const headers: Record<string, string> = {\n 'svix-id': svixId,\n 'svix-timestamp': req.headers.get('svix-timestamp') || '',\n 'svix-signature': req.headers.get('svix-signature') || '',\n }\n if (!verifySvixSignature(rawBody, headers, signingSecret)) {\n return { ok: false, response: NextResponse.json({ error: 'Invalid signature' }, { status: 400 }) }\n }\n let envelope: { type?: string; data?: { email_id?: string; from?: string; to?: string[] } }\n try {\n envelope = JSON.parse(rawBody)\n } catch {\n return { ok: false, response: NextResponse.json({ error: 'Invalid JSON' }, { status: 400 }) }\n }\n if (envelope.type !== 'email.received') {\n return { ok: false, response: NextResponse.json({ ok: true }) }\n }\n const emailId = envelope.data?.email_id\n if (!emailId) {\n return { ok: false, response: NextResponse.json({ error: 'Missing email_id in Resend payload' }, { status: 400 }) }\n }\n const emailFields = await fetchResendEmail(emailId)\n const to = emailFields.to || envelope.data?.to || []\n return { ok: true, data: { kind: 'resend', emailFields, to } }\n }\n\n return { ok: false, response: NextResponse.json({ error: 'Missing signature headers' }, { status: 400 }) }\n}\n\nexport async function POST(req: Request) {\n const hasCustomSecret = Boolean(process.env.INBOX_OPS_WEBHOOK_SECRET)\n const hasResendSecret = Boolean(process.env.RESEND_WEBHOOK_SIGNING_SECRET)\n if (!hasCustomSecret && !hasResendSecret) {\n logger.error('Neither INBOX_OPS_WEBHOOK_SECRET nor RESEND_WEBHOOK_SIGNING_SECRET is configured')\n return NextResponse.json({ error: 'Service unavailable' }, { status: 503 })\n }\n\n const contentLength = parseInt(req.headers.get('content-length') || '0', 10)\n if (contentLength > MAX_PAYLOAD_SIZE) {\n return NextResponse.json({ error: 'Payload too large' }, { status: 413 })\n }\n\n let rawBody: string\n try {\n rawBody = await req.text()\n } catch {\n return NextResponse.json({ error: 'Bad request' }, { status: 400 })\n }\n\n if (rawBody.length > MAX_PAYLOAD_SIZE) {\n return NextResponse.json({ error: 'Payload too large' }, { status: 413 })\n }\n\n const verified = await verifyAndParse(req, rawBody)\n if (!verified.ok) {\n return verified.response\n }\n\n let toAddress: string | null\n let emailInput: Parameters<typeof parseInboundEmail>[0]\n\n if (verified.data.kind === 'custom') {\n const payload = verified.data.payload\n toAddress = extractToAddress(payload)\n emailInput = {\n from: payload.from as string | undefined,\n to: payload.to as string | string[] | undefined,\n subject: payload.subject as string | undefined,\n text: payload.text as string | undefined,\n html: payload.html as string | undefined,\n messageId: payload.messageId as string | undefined,\n replyTo: payload.replyTo as string | undefined,\n inReplyTo: payload.inReplyTo as string | undefined,\n references: payload.references as string | string[] | undefined,\n }\n } else {\n const { emailFields, to } = verified.data\n toAddress = to.length > 0 ? to[0].toLowerCase() : null\n emailInput = {\n from: emailFields.from,\n to: emailFields.to,\n subject: emailFields.subject,\n text: emailFields.text,\n html: emailFields.html,\n messageId: emailFields.messageId,\n replyTo: emailFields.replyTo,\n inReplyTo: emailFields.inReplyTo,\n references: emailFields.references,\n }\n }\n\n if (!toAddress) {\n return NextResponse.json({ error: 'Missing recipient address' }, { status: 400 })\n }\n\n const container = await createRequestContainer()\n\n let cache: CacheStrategy | null = null\n try {\n cache = container.resolve('cache') as CacheStrategy\n } catch {\n // Cache not available \u2014 the limiter now fails closed with a process-local\n // bucket instead of waving the request through.\n }\n\n // Pre-DB global bucket keyed on the configured signing secret (custom) or the\n // static Resend path, NOT on the attacker-controllable `to` and NOT on the\n // per-request signature (which mutates with timestamp/body, so it would mint a\n // fresh bucket every request and never throttle). The per-tenant secret lives\n // behind the encrypted-column lookup, so the only secret available here without\n // a DB hit is the global one \u2014 keying on it caps total inbound volume for the\n // custom path and runs BEFORE the lookup so a flood cannot amplify DB work.\n const globalBucketKey = verified.data.kind === 'custom'\n ? `webhook:secret:${secretFingerprint(process.env.INBOX_OPS_WEBHOOK_SECRET || '')}`\n : 'webhook:resend'\n const globalRateCheck = await checkRateLimit(cache, globalBucketKey)\n if (!globalRateCheck.allowed) {\n return rateLimitedResponse(globalRateCheck.retryAfterSeconds)\n }\n\n const em = (container.resolve('em') as EntityManager).fork()\n\n // No explicit scope: decryptEntitiesWithFallbackScope reads tenant/org off the\n // resolved row, which is exactly what binds webhook_secret to its own tenant.\n const settings = await findOneWithDecryption(\n em,\n InboxSettings,\n {\n inboxAddress: toAddress.toLowerCase(),\n isActive: true,\n deletedAt: null,\n },\n )\n\n // Final HMAC verification for the custom provider path: bind the signature to\n // the resolved tenant. When the inbox declares its own secret, ONLY that\n // secret is accepted; otherwise the global secret is accepted (back-compat).\n // For an unknown `to` we still require the global secret so the endpoint never\n // behaves as an unauthenticated probe oracle.\n if (verified.data.kind === 'custom') {\n const globalSecret = process.env.INBOX_OPS_WEBHOOK_SECRET || ''\n const inboxSecret = settings?.webhookSecret || ''\n const acceptableSecrets = inboxSecret ? [inboxSecret] : [globalSecret]\n const signatureValid = verifyHmacAgainstAny(\n rawBody,\n verified.data.signature,\n verified.data.timestamp,\n acceptableSecrets,\n )\n if (!signatureValid) {\n return NextResponse.json({ error: 'Invalid signature' }, { status: 400 })\n }\n }\n\n if (!settings) {\n return NextResponse.json({ ok: true })\n }\n\n // Per-tenant bucket keyed on the RESOLVED tenant (not the raw `to`), so it\n // cannot be diluted by alias addresses that map to the same inbox.\n const tenantRateCheck = await checkRateLimit(\n cache,\n `webhook:tenant:${settings.tenantId}`,\n settings.tenantId,\n )\n if (!tenantRateCheck.allowed) {\n return rateLimitedResponse(tenantRateCheck.retryAfterSeconds)\n }\n\n const parsed = parseInboundEmail(emailInput)\n\n const isDuplicate = await checkDuplicate(em, settings, parsed.messageId, parsed.contentHash)\n if (isDuplicate) {\n try {\n await emitInboxOpsEvent('inbox_ops.email.deduplicated', {\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n toAddress,\n })\n } catch (eventError) {\n logger.error('Failed to emit deduplicated event', { err: eventError })\n }\n return NextResponse.json({ ok: true })\n }\n\n const maxTextSize = parseInt(process.env.INBOX_OPS_MAX_TEXT_SIZE || '204800', 10)\n const cleanedText = parsed.cleanedText.slice(0, maxTextSize)\n\n const email = em.create(InboxEmail, {\n messageId: parsed.messageId,\n contentHash: parsed.contentHash,\n forwardedByAddress: parsed.from.email,\n forwardedByName: parsed.from.name || null,\n toAddress,\n subject: parsed.subject,\n replyTo: parsed.replyTo,\n inReplyTo: parsed.inReplyTo,\n emailReferences: parsed.references,\n rawText: parsed.rawText,\n rawHtml: parsed.rawHtml,\n cleanedText,\n threadMessages: parsed.threadMessages,\n detectedLanguage: parsed.detectedLanguage,\n receivedAt: new Date(),\n status: 'received' as const,\n isActive: true,\n organizationId: settings.organizationId,\n tenantId: settings.tenantId,\n })\n\n em.persist(email)\n await em.flush()\n\n try {\n await emitInboxOpsEvent('inbox_ops.email.received', {\n emailId: email.id,\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n forwardedByAddress: parsed.from.email,\n subject: parsed.subject,\n })\n } catch (eventError) {\n logger.error('Failed to emit email.received event', { err: eventError })\n }\n\n return NextResponse.json({ ok: true })\n}\n\nfunction rateLimitedResponse(retryAfterSeconds?: number): NextResponse {\n return NextResponse.json(\n { error: 'Rate limit exceeded' },\n {\n status: 429,\n headers: retryAfterSeconds ? { 'Retry-After': String(retryAfterSeconds) } : undefined,\n },\n )\n}\n\nfunction extractToAddress(payload: Record<string, unknown>): string | null {\n const to = payload.to\n if (typeof to === 'string') {\n const match = to.match(/<([^>]+)>/)\n return match ? match[1].toLowerCase() : to.trim().toLowerCase()\n }\n if (Array.isArray(to) && to.length > 0) {\n const first = to[0]\n if (typeof first === 'string') {\n const match = first.match(/<([^>]+)>/)\n return match ? match[1].toLowerCase() : first.trim().toLowerCase()\n }\n }\n return null\n}\n\nasync function checkDuplicate(\n em: EntityManager,\n settings: InboxSettings,\n messageId: string | null | undefined,\n contentHash: string | null | undefined,\n): Promise<boolean> {\n const encScope = {\n tenantId: settings.tenantId,\n organizationId: settings.organizationId,\n }\n const whereBase = {\n organizationId: settings.organizationId,\n tenantId: settings.tenantId,\n deletedAt: null,\n }\n\n if (messageId) {\n const byMessageId = await findOneWithDecryption(em, InboxEmail, { ...whereBase, messageId }, undefined, encScope)\n if (byMessageId) return true\n }\n\n if (contentHash) {\n const byHash = await findOneWithDecryption(em, InboxEmail, { ...whereBase, contentHash }, undefined, encScope)\n if (byHash) return true\n }\n\n return false\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'InboxOps',\n summary: 'Inbound email webhook',\n methods: {\n POST: {\n summary: 'Receive forwarded email from provider webhook',\n description: 'Public endpoint \u2014 validated by provider HMAC signature or Resend/Svix signature. Rate limited per tenant.',\n requestBody: {\n contentType: 'application/json',\n schema: z.object({\n from: z.string().optional(),\n to: z.union([z.string(), z.array(z.string())]).optional(),\n subject: z.string().optional(),\n text: z.string().optional(),\n html: z.string().optional(),\n messageId: z.string().optional(),\n replyTo: z.string().optional(),\n inReplyTo: z.string().optional(),\n references: z.union([z.string(), z.array(z.string())]).optional(),\n }),\n },\n responses: [\n { status: 200, description: 'Email received and queued for processing' },\n { status: 400, description: 'Invalid payload or signature' },\n { status: 413, description: 'Payload too large' },\n { status: 429, description: 'Rate limit exceeded' },\n { status: 503, description: 'Webhook secret not configured' },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,YAAY,uBAAuB;AAC5C,SAAS,SAAS;AAClB,SAAS,eAAe;AACxB,SAAS,cAAc;AACvB,SAAS,8BAA8B;AAIvC,SAAS,6BAA6B;AACtC,SAAS,eAAe,kBAAkB;AAC1C,SAAS,yBAAyB;AAClC,SAAS,sBAAsB;AAC/B,SAAS,yBAAyB;AAClC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,UAAU,CAAC;AAEhE,MAAM,WAAW;AAAA,EACtB,MAAM,EAAE,aAAa,MAAM;AAC7B;AAEA,MAAM,mBAAmB,IAAI,OAAO;AACpC,MAAM,mBAAmB,IAAI,KAAK;AAElC,SAAS,iBAAiB,WAA4B;AACpD,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,cAAc,SAAS,WAAW,EAAE,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S;AAAA,UAC7B,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,UAC1B,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,UAC1B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,UAC/B,SAAS,EAAE,OAAO,EAAE,SAAS;AAAA,UAC7B,WAAW,EAAE,OAAO,EAAE,SAAS;AAAA,UAC/B,YAAY,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS;AAAA,QAClE,CAAC;AAAA,MACH;AAAA,MACA,WAAW;AAAA,QACT,EAAE,QAAQ,KAAK,aAAa,2CAA2C;AAAA,QACvE,EAAE,QAAQ,KAAK,aAAa,+BAA+B;AAAA,QAC3D,EAAE,QAAQ,KAAK,aAAa,oBAAoB;AAAA,QAChD,EAAE,QAAQ,KAAK,aAAa,sBAAsB;AAAA,QAClD,EAAE,QAAQ,KAAK,aAAa,gCAAgC;AAAA,MAC9D;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,5 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ const logger = createLogger("inbox_ops").child({ component: "cache" });
1
3
  const COUNTS_CACHE_PREFIX = "inbox_ops:counts";
2
4
  const SETTINGS_CACHE_PREFIX = "inbox_ops:settings";
3
5
  const COUNTS_CACHE_TTL_MS = 30 * 1e3;
@@ -20,7 +22,7 @@ async function invalidateCountsCache(cache, tenantId) {
20
22
  try {
21
23
  await cache.deleteByTags([tag]);
22
24
  } catch (err) {
23
- console.warn("[inbox_ops:cache] Failed to invalidate counts cache", err);
25
+ logger.warn("Failed to invalidate counts cache", { err });
24
26
  }
25
27
  }
26
28
  async function invalidateSettingsCache(cache, tenantId) {
@@ -29,7 +31,7 @@ async function invalidateSettingsCache(cache, tenantId) {
29
31
  try {
30
32
  await cache.deleteByTags([tag]);
31
33
  } catch (err) {
32
- console.warn("[inbox_ops:cache] Failed to invalidate settings cache", err);
34
+ logger.warn("Failed to invalidate settings cache", { err });
33
35
  }
34
36
  }
35
37
  function resolveCache(container) {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/inbox_ops/lib/cache.ts"],
4
- "sourcesContent": ["import type { CacheStrategy } from '@open-mercato/cache'\n\nconst COUNTS_CACHE_PREFIX = 'inbox_ops:counts'\nconst SETTINGS_CACHE_PREFIX = 'inbox_ops:settings'\n\n// Cache key and tag share the same value intentionally \u2014 each tenant has exactly\n// one counts entry and one settings entry, so a 1:1 key-to-tag mapping suffices.\n\nexport const COUNTS_CACHE_TTL_MS = 30 * 1000\nexport const SETTINGS_CACHE_TTL_MS = 5 * 60 * 1000\n\nexport function createCountsCacheKey(tenantId: string): string {\n return `${COUNTS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createCountsCacheTag(tenantId: string): string {\n return `${COUNTS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createSettingsCacheKey(tenantId: string): string {\n return `${SETTINGS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createSettingsCacheTag(tenantId: string): string {\n return `${SETTINGS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport async function invalidateCountsCache(\n cache: CacheStrategy | null | undefined,\n tenantId: string,\n): Promise<void> {\n if (!cache?.deleteByTags) return\n const tag = createCountsCacheTag(tenantId)\n try {\n await cache.deleteByTags([tag])\n } catch (err) {\n console.warn('[inbox_ops:cache] Failed to invalidate counts cache', err)\n }\n}\n\nexport async function invalidateSettingsCache(\n cache: CacheStrategy | null | undefined,\n tenantId: string,\n): Promise<void> {\n if (!cache?.deleteByTags) return\n const tag = createSettingsCacheTag(tenantId)\n try {\n await cache.deleteByTags([tag])\n } catch (err) {\n console.warn('[inbox_ops:cache] Failed to invalidate settings cache', err)\n }\n}\n\nexport function resolveCache(container: { resolve: (name: string) => unknown }): CacheStrategy | null {\n try {\n return container.resolve('cache') as CacheStrategy\n } catch {\n return null\n }\n}\n"],
5
- "mappings": "AAEA,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAKvB,MAAM,sBAAsB,KAAK;AACjC,MAAM,wBAAwB,IAAI,KAAK;AAEvC,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,GAAG,mBAAmB,IAAI,QAAQ;AAC3C;AAEO,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,GAAG,mBAAmB,IAAI,QAAQ;AAC3C;AAEO,SAAS,uBAAuB,UAA0B;AAC/D,SAAO,GAAG,qBAAqB,IAAI,QAAQ;AAC7C;AAEO,SAAS,uBAAuB,UAA0B;AAC/D,SAAO,GAAG,qBAAqB,IAAI,QAAQ;AAC7C;AAEA,eAAsB,sBACpB,OACA,UACe;AACf,MAAI,CAAC,OAAO,aAAc;AAC1B,QAAM,MAAM,qBAAqB,QAAQ;AACzC,MAAI;AACF,UAAM,MAAM,aAAa,CAAC,GAAG,CAAC;AAAA,EAChC,SAAS,KAAK;AACZ,YAAQ,KAAK,uDAAuD,GAAG;AAAA,EACzE;AACF;AAEA,eAAsB,wBACpB,OACA,UACe;AACf,MAAI,CAAC,OAAO,aAAc;AAC1B,QAAM,MAAM,uBAAuB,QAAQ;AAC3C,MAAI;AACF,UAAM,MAAM,aAAa,CAAC,GAAG,CAAC;AAAA,EAChC,SAAS,KAAK;AACZ,YAAQ,KAAK,yDAAyD,GAAG;AAAA,EAC3E;AACF;AAEO,SAAS,aAAa,WAAyE;AACpG,MAAI;AACF,WAAO,UAAU,QAAQ,OAAO;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import type { CacheStrategy } from '@open-mercato/cache'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'cache' })\n\nconst COUNTS_CACHE_PREFIX = 'inbox_ops:counts'\nconst SETTINGS_CACHE_PREFIX = 'inbox_ops:settings'\n\n// Cache key and tag share the same value intentionally \u2014 each tenant has exactly\n// one counts entry and one settings entry, so a 1:1 key-to-tag mapping suffices.\n\nexport const COUNTS_CACHE_TTL_MS = 30 * 1000\nexport const SETTINGS_CACHE_TTL_MS = 5 * 60 * 1000\n\nexport function createCountsCacheKey(tenantId: string): string {\n return `${COUNTS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createCountsCacheTag(tenantId: string): string {\n return `${COUNTS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createSettingsCacheKey(tenantId: string): string {\n return `${SETTINGS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport function createSettingsCacheTag(tenantId: string): string {\n return `${SETTINGS_CACHE_PREFIX}:${tenantId}`\n}\n\nexport async function invalidateCountsCache(\n cache: CacheStrategy | null | undefined,\n tenantId: string,\n): Promise<void> {\n if (!cache?.deleteByTags) return\n const tag = createCountsCacheTag(tenantId)\n try {\n await cache.deleteByTags([tag])\n } catch (err) {\n logger.warn('Failed to invalidate counts cache', { err })\n }\n}\n\nexport async function invalidateSettingsCache(\n cache: CacheStrategy | null | undefined,\n tenantId: string,\n): Promise<void> {\n if (!cache?.deleteByTags) return\n const tag = createSettingsCacheTag(tenantId)\n try {\n await cache.deleteByTags([tag])\n } catch (err) {\n logger.warn('Failed to invalidate settings cache', { err })\n }\n}\n\nexport function resolveCache(container: { resolve: (name: string) => unknown }): CacheStrategy | null {\n try {\n return container.resolve('cache') as CacheStrategy\n } catch {\n return null\n }\n}\n"],
5
+ "mappings": "AACA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,QAAQ,CAAC;AAErE,MAAM,sBAAsB;AAC5B,MAAM,wBAAwB;AAKvB,MAAM,sBAAsB,KAAK;AACjC,MAAM,wBAAwB,IAAI,KAAK;AAEvC,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,GAAG,mBAAmB,IAAI,QAAQ;AAC3C;AAEO,SAAS,qBAAqB,UAA0B;AAC7D,SAAO,GAAG,mBAAmB,IAAI,QAAQ;AAC3C;AAEO,SAAS,uBAAuB,UAA0B;AAC/D,SAAO,GAAG,qBAAqB,IAAI,QAAQ;AAC7C;AAEO,SAAS,uBAAuB,UAA0B;AAC/D,SAAO,GAAG,qBAAqB,IAAI,QAAQ;AAC7C;AAEA,eAAsB,sBACpB,OACA,UACe;AACf,MAAI,CAAC,OAAO,aAAc;AAC1B,QAAM,MAAM,qBAAqB,QAAQ;AACzC,MAAI;AACF,UAAM,MAAM,aAAa,CAAC,GAAG,CAAC;AAAA,EAChC,SAAS,KAAK;AACZ,WAAO,KAAK,qCAAqC,EAAE,IAAI,CAAC;AAAA,EAC1D;AACF;AAEA,eAAsB,wBACpB,OACA,UACe;AACf,MAAI,CAAC,OAAO,aAAc;AAC1B,QAAM,MAAM,uBAAuB,QAAQ;AAC3C,MAAI;AACF,UAAM,MAAM,aAAa,CAAC,GAAG,CAAC;AAAA,EAChC,SAAS,KAAK;AACZ,WAAO,KAAK,uCAAuC,EAAE,IAAI,CAAC;AAAA,EAC5D;AACF;AAEO,SAAS,aAAa,WAAyE;AACpG,MAAI;AACF,WAAO,UAAU,QAAQ,OAAO;AAAA,EAClC,QAAQ;AACN,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,6 @@
1
1
  import { findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ const logger = createLogger("inbox_ops").child({ component: "catalog-lookup" });
2
4
  const MAX_CATALOG_PRODUCTS = 50;
3
5
  async function fetchCatalogProductsForExtraction(em, scope, deps) {
4
6
  if (!deps?.catalogProductClass || !deps?.catalogProductPriceClass) return [];
@@ -43,7 +45,7 @@ async function fetchCatalogProductsForExtraction(em, scope, deps) {
43
45
  price: priceByProduct.get(product.id)
44
46
  }));
45
47
  } catch (err) {
46
- console.error("[inbox_ops:catalogLookup] Failed to fetch catalog products:", err);
48
+ logger.error("Failed to fetch catalog products", { err });
47
49
  return [];
48
50
  }
49
51
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/inbox_ops/lib/catalogLookup.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EntityClass } from '@mikro-orm/core'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\n\ninterface CatalogProductForExtraction {\n id: string\n name: string\n sku?: string\n price?: string\n}\n\ninterface CatalogProductLike {\n id: string\n title: string\n sku?: string | null\n tenantId?: string\n organizationId?: string\n deletedAt?: Date | null\n updatedAt?: Date\n}\n\ninterface CatalogProductPriceLike {\n product?: unknown\n unitPriceNet?: string | null\n unitPriceGross?: string | null\n tenantId?: string\n organizationId?: string\n createdAt?: Date\n}\n\ninterface CatalogLookupDeps {\n catalogProductClass: EntityClass<CatalogProductLike>\n catalogProductPriceClass: EntityClass<CatalogProductPriceLike>\n}\n\nconst MAX_CATALOG_PRODUCTS = 50\n\nexport async function fetchCatalogProductsForExtraction(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n deps?: CatalogLookupDeps,\n): Promise<CatalogProductForExtraction[]> {\n if (!deps?.catalogProductClass || !deps?.catalogProductPriceClass) return []\n\n try {\n const products = await findWithDecryption(\n em,\n deps.catalogProductClass,\n {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n { limit: MAX_CATALOG_PRODUCTS, orderBy: { updatedAt: 'DESC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (!products || products.length === 0) return []\n\n const productIds = products.map((p) => p.id)\n\n const prices = await findWithDecryption(\n em,\n deps.catalogProductPriceClass,\n {\n product: { $in: productIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n },\n { orderBy: { createdAt: 'DESC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n const priceByProduct = new Map<string, string>()\n for (const price of prices) {\n const rawProduct = price.product\n const productId = typeof rawProduct === 'string'\n ? rawProduct\n : rawProduct && typeof rawProduct === 'object' && 'id' in rawProduct\n ? String((rawProduct as Record<string, unknown>).id)\n : undefined\n if (productId && !priceByProduct.has(productId)) {\n const amount = price.unitPriceNet ?? price.unitPriceGross ?? null\n if (amount) priceByProduct.set(productId, amount)\n }\n }\n\n return products.map((product) => ({\n id: product.id,\n name: product.title,\n sku: product.sku ?? undefined,\n price: priceByProduct.get(product.id),\n }))\n } catch (err) {\n console.error('[inbox_ops:catalogLookup] Failed to fetch catalog products:', err)\n return []\n }\n}\n"],
5
- "mappings": "AAEA,SAAS,0BAA0B;AAiCnC,MAAM,uBAAuB;AAE7B,eAAsB,kCACpB,IACA,OACA,MACwC;AACxC,MAAI,CAAC,MAAM,uBAAuB,CAAC,MAAM,yBAA0B,QAAO,CAAC;AAE3E,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA,KAAK;AAAA,MACL;AAAA,QACE,gBAAgB,MAAM;AAAA,QACtB,UAAU,MAAM;AAAA,QAChB,WAAW;AAAA,MACb;AAAA,MACA,EAAE,OAAO,sBAAsB,SAAS,EAAE,WAAW,OAAO,EAAE;AAAA,MAC9D,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,IACnE;AAEA,QAAI,CAAC,YAAY,SAAS,WAAW,EAAG,QAAO,CAAC;AAEhD,UAAM,aAAa,SAAS,IAAI,CAAC,MAAM,EAAE,EAAE;AAE3C,UAAM,SAAS,MAAM;AAAA,MACnB;AAAA,MACA,KAAK;AAAA,MACL;AAAA,QACE,SAAS,EAAE,KAAK,WAAW;AAAA,QAC3B,gBAAgB,MAAM;AAAA,QACtB,UAAU,MAAM;AAAA,MAClB;AAAA,MACA,EAAE,SAAS,EAAE,WAAW,OAAO,EAAE;AAAA,MACjC,EAAE,UAAU,MAAM,UAAU,gBAAgB,MAAM,eAAe;AAAA,IACnE;AAEA,UAAM,iBAAiB,oBAAI,IAAoB;AAC/C,eAAW,SAAS,QAAQ;AAC1B,YAAM,aAAa,MAAM;AACzB,YAAM,YAAY,OAAO,eAAe,WACpC,aACA,cAAc,OAAO,eAAe,YAAY,QAAQ,aACtD,OAAQ,WAAuC,EAAE,IACjD;AACN,UAAI,aAAa,CAAC,eAAe,IAAI,SAAS,GAAG;AAC/C,cAAM,SAAS,MAAM,gBAAgB,MAAM,kBAAkB;AAC7D,YAAI,OAAQ,gBAAe,IAAI,WAAW,MAAM;AAAA,MAClD;AAAA,IACF;AAEA,WAAO,SAAS,IAAI,CAAC,aAAa;AAAA,MAChC,IAAI,QAAQ;AAAA,MACZ,MAAM,QAAQ;AAAA,MACd,KAAK,QAAQ,OAAO;AAAA,MACpB,OAAO,eAAe,IAAI,QAAQ,EAAE;AAAA,IACtC,EAAE;AAAA,EACJ,SAAS,KAAK;AACZ,YAAQ,MAAM,+DAA+D,GAAG;AAChF,WAAO,CAAC;AAAA,EACV;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { EntityClass } from '@mikro-orm/core'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'catalog-lookup' })\n\ninterface CatalogProductForExtraction {\n id: string\n name: string\n sku?: string\n price?: string\n}\n\ninterface CatalogProductLike {\n id: string\n title: string\n sku?: string | null\n tenantId?: string\n organizationId?: string\n deletedAt?: Date | null\n updatedAt?: Date\n}\n\ninterface CatalogProductPriceLike {\n product?: unknown\n unitPriceNet?: string | null\n unitPriceGross?: string | null\n tenantId?: string\n organizationId?: string\n createdAt?: Date\n}\n\ninterface CatalogLookupDeps {\n catalogProductClass: EntityClass<CatalogProductLike>\n catalogProductPriceClass: EntityClass<CatalogProductPriceLike>\n}\n\nconst MAX_CATALOG_PRODUCTS = 50\n\nexport async function fetchCatalogProductsForExtraction(\n em: EntityManager,\n scope: { tenantId: string; organizationId: string },\n deps?: CatalogLookupDeps,\n): Promise<CatalogProductForExtraction[]> {\n if (!deps?.catalogProductClass || !deps?.catalogProductPriceClass) return []\n\n try {\n const products = await findWithDecryption(\n em,\n deps.catalogProductClass,\n {\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n deletedAt: null,\n },\n { limit: MAX_CATALOG_PRODUCTS, orderBy: { updatedAt: 'DESC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n if (!products || products.length === 0) return []\n\n const productIds = products.map((p) => p.id)\n\n const prices = await findWithDecryption(\n em,\n deps.catalogProductPriceClass,\n {\n product: { $in: productIds },\n organizationId: scope.organizationId,\n tenantId: scope.tenantId,\n },\n { orderBy: { createdAt: 'DESC' } },\n { tenantId: scope.tenantId, organizationId: scope.organizationId },\n )\n\n const priceByProduct = new Map<string, string>()\n for (const price of prices) {\n const rawProduct = price.product\n const productId = typeof rawProduct === 'string'\n ? rawProduct\n : rawProduct && typeof rawProduct === 'object' && 'id' in rawProduct\n ? String((rawProduct as Record<string, unknown>).id)\n : undefined\n if (productId && !priceByProduct.has(productId)) {\n const amount = price.unitPriceNet ?? price.unitPriceGross ?? null\n if (amount) priceByProduct.set(productId, amount)\n }\n }\n\n return products.map((product) => ({\n id: product.id,\n name: product.title,\n sku: product.sku ?? undefined,\n price: priceByProduct.get(product.id),\n }))\n } catch (err) {\n logger.error('Failed to fetch catalog products', { err })\n return []\n }\n}\n"],
5
+ "mappings": "AAEA,SAAS,0BAA0B;AACnC,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,iBAAiB,CAAC;AAiC9E,MAAM,uBAAuB;AAE7B,eAAsB,kCACpB,IACA,OACA,MACwC;AACxC,MAAI,CAAC,MAAM,uBAAuB,CAAC,MAAM,yBAA0B,QAAO,CAAC;AAE3E,MAAI;AACF,UAAM,WAAW,MAAM;AAAA,MACrB;AAAA,MACA,KAAK;AAAA,MACL;AAAA,QACE,gBAAgB,MAAM;AAAA,QACtB,UAAU,MAAM;AAAA,QAChB,WAAW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/shared/lib/logger";
2
+ const logger = createLogger("inbox_ops");
1
3
  function resolveOptionalEventBus(container) {
2
4
  try {
3
5
  return container.resolve("eventBus");
4
6
  } catch (error) {
5
- console.warn(
6
- "[inbox_ops] Event bus unavailable:",
7
- error instanceof Error ? error.message : String(error)
8
- );
7
+ logger.warn("Event bus unavailable", { err: error });
9
8
  return null;
10
9
  }
11
10
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/inbox_ops/lib/eventBus.ts"],
4
- "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EventBus } from '@open-mercato/events/types'\n\nexport function resolveOptionalEventBus(container: AwilixContainer): EventBus | null {\n try {\n return container.resolve('eventBus') as EventBus\n } catch (error) {\n console.warn(\n '[inbox_ops] Event bus unavailable:',\n error instanceof Error ? error.message : String(error),\n )\n return null\n }\n}\n\n"],
5
- "mappings": "AAGO,SAAS,wBAAwB,WAA6C;AACnF,MAAI;AACF,WAAO,UAAU,QAAQ,UAAU;AAAA,EACrC,SAAS,OAAO;AACd,YAAQ;AAAA,MACN;AAAA,MACA,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IACvD;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EventBus } from '@open-mercato/events/types'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops')\n\nexport function resolveOptionalEventBus(container: AwilixContainer): EventBus | null {\n try {\n return container.resolve('eventBus') as EventBus\n } catch (error) {\n logger.warn('Event bus unavailable', { err: error })\n return null\n }\n}\n\n"],
5
+ "mappings": "AAEA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEhC,SAAS,wBAAwB,WAA6C;AACnF,MAAI;AACF,WAAO,UAAU,QAAQ,UAAU;AAAA,EACrC,SAAS,OAAO;AACd,WAAO,KAAK,yBAAyB,EAAE,KAAK,MAAM,CAAC;AACnD,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,4 +1,6 @@
1
1
  import { getRecipientUserIdsForFeature } from "../../notifications/lib/notificationRecipients.js";
2
+ import { createLogger } from "@open-mercato/shared/lib/logger";
3
+ const logger = createLogger("inbox_ops").child({ component: "messages" });
2
4
  function asContainer(resolver) {
3
5
  return resolver;
4
6
  }
@@ -81,10 +83,7 @@ async function createMessageRecordForEmail(email, ctx) {
81
83
  const messageId = result?.id ?? null;
82
84
  return messageId;
83
85
  } catch (err) {
84
- console.error(
85
- "[inbox_ops:messages] Failed to create message record for email:",
86
- err instanceof Error ? err.message : String(err)
87
- );
86
+ logger.error("Failed to create message record for email", { err });
88
87
  return null;
89
88
  }
90
89
  }
@@ -140,10 +139,7 @@ async function createMessageRecordForReply(reply, inboxEmailId, ctx) {
140
139
  if (!messageId) return null;
141
140
  return { messageId };
142
141
  } catch (err) {
143
- console.error(
144
- "[inbox_ops:messages] Failed to create reply message record:",
145
- err instanceof Error ? err.message : String(err)
146
- );
142
+ logger.error("Failed to create reply message record", { err });
147
143
  return null;
148
144
  }
149
145
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/inbox_ops/lib/messagesIntegration.ts"],
4
- "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { getRecipientUserIdsForFeature } from '../../notifications/lib/notificationRecipients'\n\ninterface ResolverLike {\n resolve: <T = unknown>(name: string) => T\n}\n\nfunction asContainer(resolver: ResolverLike): AwilixContainer {\n return resolver as unknown as AwilixContainer\n}\n\ninterface MessagesIntegrationScope {\n tenantId: string\n organizationId: string\n userId: string\n}\n\ninterface MessagesIntegrationContext {\n container: ResolverLike\n scope: MessagesIntegrationScope\n}\n\ninterface InboxEmailData {\n id: string\n subject: string\n cleanedText?: string | null\n rawText?: string | null\n forwardedByAddress: string\n forwardedByName?: string | null\n status: string\n}\n\ninterface DraftReplyData {\n to: string\n toName?: string | null\n subject: string\n body: string\n}\n\nconst SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * Resolve a real user ID to use as the message sender.\n * Tries to find the forwarding user by email in the auth users table,\n * then falls back to the first recipient (admin with proposals.view).\n * Last resort: SYSTEM_USER_ID (zero UUID).\n */\nexport async function resolveMessageSenderUserId(\n em: EntityManager,\n forwardedByEmail: string,\n recipientUserIds: string[],\n scope: { tenantId: string; organizationId: string },\n): Promise<string> {\n try {\n // users.email is a plaintext login field, not encrypted at field level,\n // so findOneWithDecryption is unnecessary here.\n const db = em.getKysely<any>() as any\n const normalizedEmail = forwardedByEmail.trim().toLowerCase()\n if (normalizedEmail) {\n const row = await db\n .selectFrom('users')\n .select('id')\n .where('email', '=', normalizedEmail)\n .where('deleted_at', 'is', null)\n .executeTakeFirst() as { id?: string } | undefined\n if (row?.id) return row.id\n }\n } catch {\n // User lookup failed \u2014 fall through\n }\n if (recipientUserIds.length > 0) return recipientUserIds[0]\n return SYSTEM_USER_ID\n}\n\nfunction resolveCommandBus(container: ResolverLike): CommandBus | null {\n try {\n const bus = container.resolve('commandBus') as CommandBus\n return bus && typeof bus.execute === 'function' ? bus : null\n } catch {\n return null\n }\n}\n\n/**\n * Creates an internal message record for an incoming inbox email.\n *\n * The message is delivered to all users with the `inbox_ops.proposals.view`\n * feature in the tenant \u2014 mirroring the same audience that sees proposals\n * in the inbox_ops module. This follows the shared-queue pattern used by\n * all major ERP/CRM systems (Salesforce queues, Dynamics 365 queues,\n * HubSpot shared inboxes, Odoo team followers).\n */\nexport async function createMessageRecordForEmail(\n email: InboxEmailData,\n ctx: MessagesIntegrationContext,\n): Promise<string | null> {\n try {\n const commandBus = resolveCommandBus(ctx.container)\n if (!commandBus) return null\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>()\n const recipientUserIds = await getRecipientUserIdsForFeature(\n db, ctx.scope.tenantId, 'inbox_ops.proposals.view',\n )\n\n const recipients = recipientUserIds.map((userId) => ({ userId, type: 'to' as const }))\n // Use rawText (full thread) instead of cleanedText (stripped quotes) so\n // the Messages module preserves the complete email conversation.\n const bodyText = email.rawText || email.cleanedText || ''\n\n // Resolve a real user as sender \u2014 prefer the forwarding user, fall back\n // to the first recipient (admin with proposals.view feature) so the\n // Messages UI can display an actual user name instead of the zero UUID.\n const senderUserId = await resolveMessageSenderUserId(\n em, email.forwardedByAddress, recipientUserIds, ctx.scope,\n )\n\n const { result } = await commandBus.execute('messages.messages.compose', {\n input: {\n type: 'inbox_ops.email',\n visibility: recipients.length > 0 ? 'internal' as const : 'public' as const,\n sourceEntityType: 'inbox_ops:inbox_email',\n sourceEntityId: email.id,\n externalEmail: email.forwardedByAddress,\n externalName: email.forwardedByName || undefined,\n recipients,\n subject: email.subject,\n body: bodyText.slice(0, 50000),\n bodyFormat: 'text' as const,\n priority: 'normal' as const,\n isDraft: false,\n sendViaEmail: false,\n objects: [\n {\n entityModule: 'inbox_ops',\n entityType: 'inbox_email',\n entityId: email.id,\n actionRequired: false,\n },\n ],\n tenantId: ctx.scope.tenantId,\n organizationId: ctx.scope.organizationId,\n userId: senderUserId,\n },\n ctx: {\n container: asContainer(ctx.container),\n auth: null,\n organizationScope: null,\n selectedOrganizationId: ctx.scope.organizationId,\n organizationIds: [ctx.scope.organizationId],\n },\n })\n\n const messageId = (result as { id: string })?.id ?? null\n return messageId\n } catch (err) {\n console.error(\n '[inbox_ops:messages] Failed to create message record for email:',\n err instanceof Error ? err.message : String(err),\n )\n return null\n }\n}\n\nexport async function createMessageRecordForReply(\n reply: DraftReplyData,\n inboxEmailId: string,\n ctx: MessagesIntegrationContext,\n): Promise<{ messageId: string } | null> {\n try {\n const commandBus = resolveCommandBus(ctx.container)\n if (!commandBus) return null\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>()\n const recipientUserIds = await getRecipientUserIdsForFeature(\n db, ctx.scope.tenantId, 'inbox_ops.proposals.view',\n )\n if (recipientUserIds.length === 0) return null\n\n const recipients = recipientUserIds.map((userId) => ({ userId, type: 'to' as const }))\n\n const { result } = await commandBus.execute('messages.messages.compose', {\n input: {\n type: 'inbox_ops.reply',\n visibility: 'internal' as const,\n sourceEntityType: 'inbox_ops:inbox_email',\n sourceEntityId: inboxEmailId,\n externalEmail: reply.to,\n externalName: reply.toName ?? undefined,\n recipients,\n subject: reply.subject,\n body: reply.body,\n bodyFormat: 'text' as const,\n priority: 'normal' as const,\n isDraft: false,\n sendViaEmail: false,\n objects: [\n {\n entityModule: 'inbox_ops',\n entityType: 'inbox_email',\n entityId: inboxEmailId,\n actionRequired: false,\n },\n ],\n tenantId: ctx.scope.tenantId,\n organizationId: ctx.scope.organizationId,\n userId: ctx.scope.userId,\n },\n ctx: {\n container: asContainer(ctx.container),\n auth: null,\n organizationScope: null,\n selectedOrganizationId: ctx.scope.organizationId,\n organizationIds: [ctx.scope.organizationId],\n },\n })\n\n const messageId = (result as { id: string })?.id ?? null\n if (!messageId) return null\n return { messageId }\n } catch (err) {\n console.error(\n '[inbox_ops:messages] Failed to create reply message record:',\n err instanceof Error ? err.message : String(err),\n )\n return null\n }\n}\n"],
5
- "mappings": "AAGA,SAAS,qCAAqC;AAM9C,SAAS,YAAY,UAAyC;AAC5D,SAAO;AACT;AA8BA,MAAM,iBAAiB;AAQvB,eAAsB,2BACpB,IACA,kBACA,kBACA,OACiB;AACjB,MAAI;AAGF,UAAM,KAAK,GAAG,UAAe;AAC7B,UAAM,kBAAkB,iBAAiB,KAAK,EAAE,YAAY;AAC5D,QAAI,iBAAiB;AACnB,YAAM,MAAM,MAAM,GACf,WAAW,OAAO,EAClB,OAAO,IAAI,EACX,MAAM,SAAS,KAAK,eAAe,EACnC,MAAM,cAAc,MAAM,IAAI,EAC9B,iBAAiB;AACpB,UAAI,KAAK,GAAI,QAAO,IAAI;AAAA,IAC1B;AAAA,EACF,QAAQ;AAAA,EAER;AACA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;AAAA,YACE,cAAc;AAAA,YACd,YAAY;AAAA,YACZ,UAAU;AAAA,YACV,gBAAgB;AAAA,UAClB;AAAA,QACF;AAAA,QACA,UAAU,IAAI,MAAM;AAAA,QACpB,gBAAgB,IAAI,MAAM;AAAA,QAC1B,QAAQ,IAAI,MAAM;AAAA,MACpB;AAAA,MACA,KAAK;AAAA,QACH,WAAW,YAAY,IAAI,SAAS;AAAA,QACpC,MAAM;AAAA,QACN,mBAAmB;AAAA,QACnB,wBAAwB,IAAI,MAAM;AAAA,QAClC,iBAAiB,CAAC,IAAI,MAAM,cAAc;AAAA,MAC5C;AAAA,IACF,CAAC;AAED,UAAM,YAAa,QAA2B,MAAM;AACpD,QAAI,CAAC,UAAW,QAAO;AACvB,WAAO,EAAE,UAAU;AAAA,EACrB,SAAS,KAAK;AACZ,YAAQ;AAAA,MACN;AAAA,MACA,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IACjD;AACA,WAAO;AAAA,EACT;AACF;",
4
+ "sourcesContent": ["import type { AwilixContainer } from 'awilix'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { getRecipientUserIdsForFeature } from '../../notifications/lib/notificationRecipients'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'messages' })\n\ninterface ResolverLike {\n resolve: <T = unknown>(name: string) => T\n}\n\nfunction asContainer(resolver: ResolverLike): AwilixContainer {\n return resolver as unknown as AwilixContainer\n}\n\ninterface MessagesIntegrationScope {\n tenantId: string\n organizationId: string\n userId: string\n}\n\ninterface MessagesIntegrationContext {\n container: ResolverLike\n scope: MessagesIntegrationScope\n}\n\ninterface InboxEmailData {\n id: string\n subject: string\n cleanedText?: string | null\n rawText?: string | null\n forwardedByAddress: string\n forwardedByName?: string | null\n status: string\n}\n\ninterface DraftReplyData {\n to: string\n toName?: string | null\n subject: string\n body: string\n}\n\nconst SYSTEM_USER_ID = '00000000-0000-0000-0000-000000000000'\n\n/**\n * Resolve a real user ID to use as the message sender.\n * Tries to find the forwarding user by email in the auth users table,\n * then falls back to the first recipient (admin with proposals.view).\n * Last resort: SYSTEM_USER_ID (zero UUID).\n */\nexport async function resolveMessageSenderUserId(\n em: EntityManager,\n forwardedByEmail: string,\n recipientUserIds: string[],\n scope: { tenantId: string; organizationId: string },\n): Promise<string> {\n try {\n // users.email is a plaintext login field, not encrypted at field level,\n // so findOneWithDecryption is unnecessary here.\n const db = em.getKysely<any>() as any\n const normalizedEmail = forwardedByEmail.trim().toLowerCase()\n if (normalizedEmail) {\n const row = await db\n .selectFrom('users')\n .select('id')\n .where('email', '=', normalizedEmail)\n .where('deleted_at', 'is', null)\n .executeTakeFirst() as { id?: string } | undefined\n if (row?.id) return row.id\n }\n } catch {\n // User lookup failed \u2014 fall through\n }\n if (recipientUserIds.length > 0) return recipientUserIds[0]\n return SYSTEM_USER_ID\n}\n\nfunction resolveCommandBus(container: ResolverLike): CommandBus | null {\n try {\n const bus = container.resolve('commandBus') as CommandBus\n return bus && typeof bus.execute === 'function' ? bus : null\n } catch {\n return null\n }\n}\n\n/**\n * Creates an internal message record for an incoming inbox email.\n *\n * The message is delivered to all users with the `inbox_ops.proposals.view`\n * feature in the tenant \u2014 mirroring the same audience that sees proposals\n * in the inbox_ops module. This follows the shared-queue pattern used by\n * all major ERP/CRM systems (Salesforce queues, Dynamics 365 queues,\n * HubSpot shared inboxes, Odoo team followers).\n */\nexport async function createMessageRecordForEmail(\n email: InboxEmailData,\n ctx: MessagesIntegrationContext,\n): Promise<string | null> {\n try {\n const commandBus = resolveCommandBus(ctx.container)\n if (!commandBus) return null\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>()\n const recipientUserIds = await getRecipientUserIdsForFeature(\n db, ctx.scope.tenantId, 'inbox_ops.proposals.view',\n )\n\n const recipients = recipientUserIds.map((userId) => ({ userId, type: 'to' as const }))\n // Use rawText (full thread) instead of cleanedText (stripped quotes) so\n // the Messages module preserves the complete email conversation.\n const bodyText = email.rawText || email.cleanedText || ''\n\n // Resolve a real user as sender \u2014 prefer the forwarding user, fall back\n // to the first recipient (admin with proposals.view feature) so the\n // Messages UI can display an actual user name instead of the zero UUID.\n const senderUserId = await resolveMessageSenderUserId(\n em, email.forwardedByAddress, recipientUserIds, ctx.scope,\n )\n\n const { result } = await commandBus.execute('messages.messages.compose', {\n input: {\n type: 'inbox_ops.email',\n visibility: recipients.length > 0 ? 'internal' as const : 'public' as const,\n sourceEntityType: 'inbox_ops:inbox_email',\n sourceEntityId: email.id,\n externalEmail: email.forwardedByAddress,\n externalName: email.forwardedByName || undefined,\n recipients,\n subject: email.subject,\n body: bodyText.slice(0, 50000),\n bodyFormat: 'text' as const,\n priority: 'normal' as const,\n isDraft: false,\n sendViaEmail: false,\n objects: [\n {\n entityModule: 'inbox_ops',\n entityType: 'inbox_email',\n entityId: email.id,\n actionRequired: false,\n },\n ],\n tenantId: ctx.scope.tenantId,\n organizationId: ctx.scope.organizationId,\n userId: senderUserId,\n },\n ctx: {\n container: asContainer(ctx.container),\n auth: null,\n organizationScope: null,\n selectedOrganizationId: ctx.scope.organizationId,\n organizationIds: [ctx.scope.organizationId],\n },\n })\n\n const messageId = (result as { id: string })?.id ?? null\n return messageId\n } catch (err) {\n logger.error('Failed to create message record for email', { err })\n return null\n }\n}\n\nexport async function createMessageRecordForReply(\n reply: DraftReplyData,\n inboxEmailId: string,\n ctx: MessagesIntegrationContext,\n): Promise<{ messageId: string } | null> {\n try {\n const commandBus = resolveCommandBus(ctx.container)\n if (!commandBus) return null\n\n const em = ctx.container.resolve('em') as EntityManager\n const db = em.getKysely<any>()\n const recipientUserIds = await getRecipientUserIdsForFeature(\n db, ctx.scope.tenantId, 'inbox_ops.proposals.view',\n )\n if (recipientUserIds.length === 0) return null\n\n const recipients = recipientUserIds.map((userId) => ({ userId, type: 'to' as const }))\n\n const { result } = await commandBus.execute('messages.messages.compose', {\n input: {\n type: 'inbox_ops.reply',\n visibility: 'internal' as const,\n sourceEntityType: 'inbox_ops:inbox_email',\n sourceEntityId: inboxEmailId,\n externalEmail: reply.to,\n externalName: reply.toName ?? undefined,\n recipients,\n subject: reply.subject,\n body: reply.body,\n bodyFormat: 'text' as const,\n priority: 'normal' as const,\n isDraft: false,\n sendViaEmail: false,\n objects: [\n {\n entityModule: 'inbox_ops',\n entityType: 'inbox_email',\n entityId: inboxEmailId,\n actionRequired: false,\n },\n ],\n tenantId: ctx.scope.tenantId,\n organizationId: ctx.scope.organizationId,\n userId: ctx.scope.userId,\n },\n ctx: {\n container: asContainer(ctx.container),\n auth: null,\n organizationScope: null,\n selectedOrganizationId: ctx.scope.organizationId,\n organizationIds: [ctx.scope.organizationId],\n },\n })\n\n const messageId = (result as { id: string })?.id ?? null\n if (!messageId) return null\n return { messageId }\n } catch (err) {\n logger.error('Failed to create reply message record', { err })\n return null\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,qCAAqC;AAC9C,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,WAAW,CAAC;AAMxE,SAAS,YAAY,UAAyC;AAC5D,SAAO;AACT;AA8BA,MAAM,iBAAiB;AAQvB,eAAsB,2BACpB,IACA,kBACA,kBACA,OACiB;AACjB,MAAI;AAGF,UAAM,KAAK,GAAG,UAAe;AAC7B,UAAM,kBAAkB,iBAAiB,KAAK,EAAE,YAAY;AAC5D,QAAI,iBAAiB;AACnB,YAAM,MAAM,MAAM,GACf,WAAW,OAAO,EAClB,OAAO,IAAI,EACX,MAAM,SAAS,KAAK,eAAe,EACnC,MAAM,cAAc,MAAM,IAAI,EAC9B,iBAAiB;AACpB,UAAI,KAAK,GAAI,QAAO,IAAI;AAAA,IAC1B;AAAA,EACF,QAAQ;AAAA,EAER;AACA,MAAI,iBAAiB,SAAS,EAAG,QAAO,iBAAiB,CAAC;AAC1D,SAAO;AACT;AAEA,SAAS,kBAAkB,WAA4C;AACrE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BAAgB,IAAI,MAAM;AAAA,QAC1B,QAAQ,IAAI,MAAM;AAAA,MACpB;AAAA,MACA,KAAK;AAAA,QACH,WAAW,YAAY,IAAI,SAAS;AAAA,QACpC,MAAM;AAAA,QACN,mBAAmB;AAAA,QACnB,wBAAwB,IAAI,MAAM;AAAA,QAClC,iBAAiB,CAAC,IAAI,MAAM,cAAc;AAAA,MAC5C;AAAA,IACF,CAAC;AAED,UAAM,YAAa,QAA2B,MAAM;AACpD,QAAI,CAAC,UAAW,QAAO;AACvB,WAAO,EAAE,UAAU;AAAA,EACrB,SAAS,KAAK;AACZ,WAAO,MAAM,yCAAyC,EAAE,IAAI,CAAC;AAC7D,WAAO;AAAA,EACT;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,3 +1,5 @@
1
+ import { createLogger } from "@open-mercato/shared/lib/logger";
2
+ const logger = createLogger("inbox_ops").child({ component: "execution-auditor" });
1
3
  const metadata = {
2
4
  event: "inbox_ops.action.executed",
3
5
  persistent: true,
@@ -22,7 +24,7 @@ async function handle(payload, ctx) {
22
24
  }
23
25
  });
24
26
  } catch (err) {
25
- console.error("[inbox_ops:execution-auditor] Failed to write audit log:", err);
27
+ logger.error("Failed to write audit log", { err });
26
28
  throw err;
27
29
  }
28
30
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/inbox_ops/subscribers/executionAuditor.ts"],
4
- "sourcesContent": ["export const metadata = {\n event: 'inbox_ops.action.executed',\n persistent: true,\n id: 'inbox_ops:execution-auditor',\n}\n\ninterface ActionExecutedPayload {\n actionId: string\n proposalId: string\n actionType: string\n createdEntityId: string | null\n createdEntityType: string | null\n executedByUserId: string\n tenantId: string\n organizationId: string | null\n}\n\ninterface DataEngineWithAudit {\n audit?: (entry: {\n action: string\n resourceKind: string\n resourceId: string\n userId: string\n tenantId: string\n organizationId: string | null\n payload: Record<string, unknown>\n }) => Promise<void>\n}\n\ninterface ResolverContext {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(payload: ActionExecutedPayload, ctx: ResolverContext) {\n try {\n const dataEngine = ctx.resolve<DataEngineWithAudit>('dataEngine')\n if (!dataEngine?.audit) return\n\n await dataEngine.audit({\n action: 'inbox_ops.action.executed',\n resourceKind: `inbox_ops.${payload.actionType}`,\n resourceId: payload.actionId,\n userId: payload.executedByUserId,\n tenantId: payload.tenantId,\n organizationId: payload.organizationId,\n payload: {\n proposalId: payload.proposalId,\n actionType: payload.actionType,\n createdEntityId: payload.createdEntityId,\n createdEntityType: payload.createdEntityType,\n },\n })\n } catch (err) {\n console.error('[inbox_ops:execution-auditor] Failed to write audit log:', err)\n throw err\n }\n}\n"],
5
- "mappings": "AAAO,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AA6BA,eAAO,OAA8B,SAAgC,KAAsB;AACzF,MAAI;AACF,UAAM,aAAa,IAAI,QAA6B,YAAY;AAChE,QAAI,CAAC,YAAY,MAAO;AAExB,UAAM,WAAW,MAAM;AAAA,MACrB,QAAQ;AAAA,MACR,cAAc,aAAa,QAAQ,UAAU;AAAA,MAC7C,YAAY,QAAQ;AAAA,MACpB,QAAQ,QAAQ;AAAA,MAChB,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ;AAAA,MACxB,SAAS;AAAA,QACP,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,QACpB,iBAAiB,QAAQ;AAAA,QACzB,mBAAmB,QAAQ;AAAA,MAC7B;AAAA,IACF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,YAAQ,MAAM,4DAA4D,GAAG;AAC7E,UAAM;AAAA,EACR;AACF;",
4
+ "sourcesContent": ["import { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('inbox_ops').child({ component: 'execution-auditor' })\n\nexport const metadata = {\n event: 'inbox_ops.action.executed',\n persistent: true,\n id: 'inbox_ops:execution-auditor',\n}\n\ninterface ActionExecutedPayload {\n actionId: string\n proposalId: string\n actionType: string\n createdEntityId: string | null\n createdEntityType: string | null\n executedByUserId: string\n tenantId: string\n organizationId: string | null\n}\n\ninterface DataEngineWithAudit {\n audit?: (entry: {\n action: string\n resourceKind: string\n resourceId: string\n userId: string\n tenantId: string\n organizationId: string | null\n payload: Record<string, unknown>\n }) => Promise<void>\n}\n\ninterface ResolverContext {\n resolve: <T = unknown>(name: string) => T\n}\n\nexport default async function handle(payload: ActionExecutedPayload, ctx: ResolverContext) {\n try {\n const dataEngine = ctx.resolve<DataEngineWithAudit>('dataEngine')\n if (!dataEngine?.audit) return\n\n await dataEngine.audit({\n action: 'inbox_ops.action.executed',\n resourceKind: `inbox_ops.${payload.actionType}`,\n resourceId: payload.actionId,\n userId: payload.executedByUserId,\n tenantId: payload.tenantId,\n organizationId: payload.organizationId,\n payload: {\n proposalId: payload.proposalId,\n actionType: payload.actionType,\n createdEntityId: payload.createdEntityId,\n createdEntityType: payload.createdEntityType,\n },\n })\n } catch (err) {\n logger.error('Failed to write audit log', { err })\n throw err\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW,EAAE,MAAM,EAAE,WAAW,oBAAoB,CAAC;AAE1E,MAAM,WAAW;AAAA,EACtB,OAAO;AAAA,EACP,YAAY;AAAA,EACZ,IAAI;AACN;AA6BA,eAAO,OAA8B,SAAgC,KAAsB;AACzF,MAAI;AACF,UAAM,aAAa,IAAI,QAA6B,YAAY;AAChE,QAAI,CAAC,YAAY,MAAO;AAExB,UAAM,WAAW,MAAM;AAAA,MACrB,QAAQ;AAAA,MACR,cAAc,aAAa,QAAQ,UAAU;AAAA,MAC7C,YAAY,QAAQ;AAAA,MACpB,QAAQ,QAAQ;AAAA,MAChB,UAAU,QAAQ;AAAA,MAClB,gBAAgB,QAAQ;AAAA,MACxB,SAAS;AAAA,QACP,YAAY,QAAQ;AAAA,QACpB,YAAY,QAAQ;AAAA,QACpB,iBAAiB,QAAQ;AAAA,QACzB,mBAAmB,QAAQ;AAAA,MAC7B;AAAA,IACF,CAAC;AAAA,EACH,SAAS,KAAK;AACZ,WAAO,MAAM,6BAA6B,EAAE,IAAI,CAAC;AACjD,UAAM;AAAA,EACR;AACF;",
6
6
  "names": []
7
7
  }
@@ -15,6 +15,8 @@ import { runWithCacheTenant } from "@open-mercato/cache";
15
15
  import { emitInboxOpsEvent } from "../events.js";
16
16
  import { createMessageRecordForEmail } from "../lib/messagesIntegration.js";
17
17
  import { resolveCache, invalidateCountsCache } from "../lib/cache.js";
18
+ import { createLogger } from "@open-mercato/shared/lib/logger";
19
+ const logger = createLogger("inbox_ops").child({ component: "extraction-worker" });
18
20
  const SYSTEM_USER_ID = "00000000-0000-0000-0000-000000000000";
19
21
  const metadata = {
20
22
  event: "inbox_ops.email.received",
@@ -25,7 +27,7 @@ function tryResolve(ctx, name) {
25
27
  try {
26
28
  return ctx.resolve(name);
27
29
  } catch {
28
- console.debug(`[inbox_ops:extraction] optional dependency "${name}" not available`);
30
+ logger.debug("Optional dependency not available", { name });
29
31
  return void 0;
30
32
  }
31
33
  }
@@ -70,7 +72,7 @@ async function handle(payload, ctx) {
70
72
  { tenantId: payload.tenantId, organizationId: payload.organizationId }
71
73
  );
72
74
  if (!email) {
73
- console.error(`[inbox_ops:extraction-worker] Email not found: ${payload.emailId}`);
75
+ logger.error("Email not found", { emailId: payload.emailId });
74
76
  return;
75
77
  }
76
78
  try {
@@ -130,7 +132,7 @@ async function handle(payload, ctx) {
130
132
  error: email.processingError
131
133
  });
132
134
  } catch (eventError) {
133
- console.error("[inbox_ops:extraction-worker] Failed to emit email.failed event:", eventError);
135
+ logger.error("Failed to emit email.failed event", { err: eventError });
134
136
  }
135
137
  return;
136
138
  }
@@ -412,7 +414,7 @@ async function handle(payload, ctx) {
412
414
  const cache = resolveCache(ctx);
413
415
  await runWithCacheTenant(email.tenantId, () => invalidateCountsCache(cache, email.tenantId));
414
416
  } catch (cacheErr) {
415
- console.warn("[inbox_ops:extraction-worker] Cache invalidation failed (non-fatal):", cacheErr);
417
+ logger.warn("Cache invalidation failed (non-fatal)", { err: cacheErr });
416
418
  }
417
419
  try {
418
420
  await createMessageRecordForEmail(
@@ -435,7 +437,7 @@ async function handle(payload, ctx) {
435
437
  }
436
438
  );
437
439
  } catch (msgErr) {
438
- console.error("[inbox_ops:extraction-worker] Messages integration failed (non-fatal):", msgErr);
440
+ logger.error("Messages integration failed (non-fatal)", { err: msgErr });
439
441
  }
440
442
  try {
441
443
  await emitInboxOpsEvent("inbox_ops.email.processed", {
@@ -454,7 +456,7 @@ async function handle(payload, ctx) {
454
456
  summary: proposal.summary
455
457
  });
456
458
  } catch (eventError) {
457
- console.error("[inbox_ops:extraction-worker] Failed to emit events:", eventError);
459
+ logger.error("Failed to emit events", { err: eventError });
458
460
  }
459
461
  } catch (err) {
460
462
  email.status = "failed";
@@ -468,9 +470,9 @@ async function handle(payload, ctx) {
468
470
  error: email.processingError
469
471
  });
470
472
  } catch (eventError) {
471
- console.error("[inbox_ops:extraction-worker] Failed to emit email.failed event:", eventError);
473
+ logger.error("Failed to emit email.failed event", { err: eventError });
472
474
  }
473
- console.error("[inbox_ops:extraction-worker] Extraction failed:", err);
475
+ logger.error("Extraction failed", { err });
474
476
  }
475
477
  }
476
478
  function normalizeOrderPayloadFields(payload) {