@open-mercato/core 0.9.0 → 0.9.1-develop.7459.1.99e3accd30

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 (243) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/customer_dictionary_entry/index.js +2 -0
  3. package/dist/generated/entities/customer_dictionary_entry/index.js.map +2 -2
  4. package/dist/generated/entities/customer_interaction/index.js +2 -0
  5. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  6. package/dist/generated/entity-fields-registry.js +2 -0
  7. package/dist/generated/entity-fields-registry.js.map +2 -2
  8. package/dist/modules/catalog/commands/categories.js +1 -1
  9. package/dist/modules/catalog/commands/categories.js.map +2 -2
  10. package/dist/modules/catalog/commands/productDeleteChildren.js +389 -0
  11. package/dist/modules/catalog/commands/productDeleteChildren.js.map +7 -0
  12. package/dist/modules/catalog/commands/products.js +52 -17
  13. package/dist/modules/catalog/commands/products.js.map +2 -2
  14. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js +4 -6
  15. package/dist/modules/communication_channels/api/post/channels/connect/credentials/route.js.map +2 -2
  16. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js +4 -6
  17. package/dist/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.js.map +2 -2
  18. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js +47 -11
  19. package/dist/modules/communication_channels/api/post/oauth/[provider]/initiate/route.js.map +3 -3
  20. package/dist/modules/communication_channels/commands/deliver-outbound-message.js +5 -1
  21. package/dist/modules/communication_channels/commands/deliver-outbound-message.js.map +2 -2
  22. package/dist/modules/communication_channels/lib/inbound-message-origin.js +1 -1
  23. package/dist/modules/communication_channels/lib/inbound-message-origin.js.map +2 -2
  24. package/dist/modules/communication_channels/lib/oauth-state.js +4 -1
  25. package/dist/modules/communication_channels/lib/oauth-state.js.map +2 -2
  26. package/dist/modules/communication_channels/lib/use-connect-channel.js +10 -0
  27. package/dist/modules/communication_channels/lib/use-connect-channel.js.map +2 -2
  28. package/dist/modules/customers/api/activity-types/route.js +151 -0
  29. package/dist/modules/customers/api/activity-types/route.js.map +7 -0
  30. package/dist/modules/customers/api/deals/[id]/people/route.js +58 -5
  31. package/dist/modules/customers/api/deals/[id]/people/route.js.map +2 -2
  32. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +13 -5
  33. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  34. package/dist/modules/customers/api/dictionaries/[kind]/route.js +20 -5
  35. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  36. package/dist/modules/customers/api/interactions/route.js +3 -0
  37. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  38. package/dist/modules/customers/api/interactions/tasks/route.js +1 -0
  39. package/dist/modules/customers/api/interactions/tasks/route.js.map +2 -2
  40. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js +18 -0
  41. package/dist/modules/customers/backend/config/customers/pipeline-stages/page.meta.js.map +2 -2
  42. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js +0 -23
  43. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js.map +2 -2
  44. package/dist/modules/customers/backend/customers/deals/[id]/page.js +15 -17
  45. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +2 -2
  46. package/dist/modules/customers/calendar-event-types.js +548 -0
  47. package/dist/modules/customers/calendar-event-types.js.map +7 -0
  48. package/dist/modules/customers/commands/dictionaries.js +70 -10
  49. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  50. package/dist/modules/customers/commands/interactions.js +187 -22
  51. package/dist/modules/customers/commands/interactions.js.map +3 -3
  52. package/dist/modules/customers/components/ActivityTypeEditor.js +288 -0
  53. package/dist/modules/customers/components/ActivityTypeEditor.js.map +7 -0
  54. package/dist/modules/customers/components/DictionarySettings.js +3 -1
  55. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  56. package/dist/modules/customers/components/calendar/CalendarEventEditor.js +391 -297
  57. package/dist/modules/customers/components/calendar/CalendarEventEditor.js.map +3 -3
  58. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js +9 -74
  59. package/dist/modules/customers/components/calendar/CalendarSettingsModal.js.map +2 -2
  60. package/dist/modules/customers/components/calendar/TimeGrid.js +20 -16
  61. package/dist/modules/customers/components/calendar/TimeGrid.js.map +2 -2
  62. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js +218 -0
  63. package/dist/modules/customers/components/calendar/editor/EventTypePanel.js.map +7 -0
  64. package/dist/modules/customers/components/calendar/editor/LocationField.js +7 -3
  65. package/dist/modules/customers/components/calendar/editor/LocationField.js.map +2 -2
  66. package/dist/modules/customers/components/calendar/editor/PeopleField.js +5 -2
  67. package/dist/modules/customers/components/calendar/editor/PeopleField.js.map +2 -2
  68. package/dist/modules/customers/components/calendar/editor/PriorityField.js +3 -1
  69. package/dist/modules/customers/components/calendar/editor/PriorityField.js.map +2 -2
  70. package/dist/modules/customers/components/calendar/editor/RepeatField.js +9 -1
  71. package/dist/modules/customers/components/calendar/editor/RepeatField.js.map +2 -2
  72. package/dist/modules/customers/components/calendar/editor/ResourcesField.js +4 -1
  73. package/dist/modules/customers/components/calendar/editor/ResourcesField.js.map +2 -2
  74. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js +15 -7
  75. package/dist/modules/customers/components/calendar/editor/ScheduleSection.js.map +2 -2
  76. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js +3 -1
  77. package/dist/modules/customers/components/calendar/editor/SegmentGroup.js.map +2 -2
  78. package/dist/modules/customers/components/calendar/editor/hooks.js +28 -13
  79. package/dist/modules/customers/components/calendar/editor/hooks.js.map +3 -3
  80. package/dist/modules/customers/components/calendar/editor/inputs.js +14 -6
  81. package/dist/modules/customers/components/calendar/editor/inputs.js.map +2 -2
  82. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js +54 -0
  83. package/dist/modules/customers/components/calendar/editor/useCalendarCustomFields.js.map +7 -0
  84. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js +82 -0
  85. package/dist/modules/customers/components/calendar/editor/useEventTypeCatalog.js.map +7 -0
  86. package/dist/modules/customers/components/calendar/types.js +1 -0
  87. package/dist/modules/customers/components/calendar/types.js.map +2 -2
  88. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +78 -343
  89. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  90. package/dist/modules/customers/components/detail/CreatePersonDialog.js +12 -11
  91. package/dist/modules/customers/components/detail/CreatePersonDialog.js.map +2 -2
  92. package/dist/modules/customers/components/detail/DealForm.js +7 -3
  93. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  94. package/dist/modules/customers/components/detail/DealPeopleSection.js +206 -0
  95. package/dist/modules/customers/components/detail/DealPeopleSection.js.map +7 -0
  96. package/dist/modules/customers/components/detail/LinkedPeopleSection.js +342 -0
  97. package/dist/modules/customers/components/detail/LinkedPeopleSection.js.map +7 -0
  98. package/dist/modules/customers/components/detail/PersonCard.js +5 -2
  99. package/dist/modules/customers/components/detail/PersonCard.js.map +2 -2
  100. package/dist/modules/customers/components/linking/adapters/personAdapter.js +3 -0
  101. package/dist/modules/customers/components/linking/adapters/personAdapter.js.map +2 -2
  102. package/dist/modules/customers/data/entities.js +6 -0
  103. package/dist/modules/customers/data/entities.js.map +2 -2
  104. package/dist/modules/customers/data/validators.js +39 -10
  105. package/dist/modules/customers/data/validators.js.map +2 -2
  106. package/dist/modules/customers/di.js +20 -1
  107. package/dist/modules/customers/di.js.map +2 -2
  108. package/dist/modules/customers/extension-points.js +13 -0
  109. package/dist/modules/customers/extension-points.js.map +2 -2
  110. package/dist/modules/customers/lib/calendar/conflicts.js +59 -16
  111. package/dist/modules/customers/lib/calendar/conflicts.js.map +2 -2
  112. package/dist/modules/customers/lib/calendar/editorPayload.js +34 -16
  113. package/dist/modules/customers/lib/calendar/editorPayload.js.map +2 -2
  114. package/dist/modules/customers/lib/calendar/eventTypeResolver.js +197 -0
  115. package/dist/modules/customers/lib/calendar/eventTypeResolver.js.map +7 -0
  116. package/dist/modules/customers/lib/calendar/interactionApplicability.js +67 -0
  117. package/dist/modules/customers/lib/calendar/interactionApplicability.js.map +7 -0
  118. package/dist/modules/customers/lib/calendar/mapItem.js +5 -2
  119. package/dist/modules/customers/lib/calendar/mapItem.js.map +2 -2
  120. package/dist/modules/customers/lib/calendar/recurrence.js +62 -1
  121. package/dist/modules/customers/lib/calendar/recurrence.js.map +2 -2
  122. package/dist/modules/customers/lib/calendar/timezone.js +111 -0
  123. package/dist/modules/customers/lib/calendar/timezone.js.map +7 -0
  124. package/dist/modules/customers/lib/interactionReadModel.js +1 -0
  125. package/dist/modules/customers/lib/interactionReadModel.js.map +2 -2
  126. package/dist/modules/customers/lib/todoCompatibility.js +1 -0
  127. package/dist/modules/customers/lib/todoCompatibility.js.map +2 -2
  128. package/dist/modules/customers/migrations/Migration20260928175058_customers.js +17 -0
  129. package/dist/modules/customers/migrations/Migration20260928175058_customers.js.map +7 -0
  130. package/dist/modules/customers/migrations/Migration20260930110235_customers.js +17 -0
  131. package/dist/modules/customers/migrations/Migration20260930110235_customers.js.map +7 -0
  132. package/dist/modules/dictionaries/components/DictionaryTable.js +60 -51
  133. package/dist/modules/dictionaries/components/DictionaryTable.js.map +2 -2
  134. package/dist/modules/messages/subscribers/message-notification.js +13 -1
  135. package/dist/modules/messages/subscribers/message-notification.js.map +2 -2
  136. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js +201 -53
  137. package/dist/modules/payment_gateways/api/webhook/[provider]/route.js.map +2 -2
  138. package/dist/modules/payment_gateways/lib/gateway-service.js +37 -11
  139. package/dist/modules/payment_gateways/lib/gateway-service.js.map +2 -2
  140. package/dist/modules/planner/lib/availabilityMerge.js +101 -38
  141. package/dist/modules/planner/lib/availabilityMerge.js.map +3 -3
  142. package/dist/modules/planner/services/plannerAvailabilityService.js.map +2 -2
  143. package/dist/modules/sales/components/documents/LineItemDialog.js +159 -81
  144. package/dist/modules/sales/components/documents/LineItemDialog.js.map +2 -2
  145. package/dist/modules/sales/components/documents/lineItemUtils.js +7 -0
  146. package/dist/modules/sales/components/documents/lineItemUtils.js.map +2 -2
  147. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js +12 -7
  148. package/dist/modules/staff/backend/staff/time-tracking/projects/[id]/page.js.map +2 -2
  149. package/dist/modules/sync_excel/lib/adapters/customers.js +28 -25
  150. package/dist/modules/sync_excel/lib/adapters/customers.js.map +2 -2
  151. package/generated/entities/customer_dictionary_entry/index.ts +1 -0
  152. package/generated/entities/customer_interaction/index.ts +1 -0
  153. package/generated/entity-fields-registry.ts +2 -0
  154. package/package.json +9 -8
  155. package/src/modules/auth/i18n/de.json +3 -0
  156. package/src/modules/auth/i18n/en.json +3 -0
  157. package/src/modules/auth/i18n/es.json +3 -0
  158. package/src/modules/auth/i18n/ko.json +3 -0
  159. package/src/modules/auth/i18n/pl.json +3 -0
  160. package/src/modules/catalog/commands/categories.ts +1 -1
  161. package/src/modules/catalog/commands/productDeleteChildren.ts +557 -0
  162. package/src/modules/catalog/commands/products.ts +58 -17
  163. package/src/modules/communication_channels/api/post/channels/connect/credentials/route.ts +4 -6
  164. package/src/modules/communication_channels/api/post/channels/connect/tenant-credentials/route.ts +4 -6
  165. package/src/modules/communication_channels/api/post/oauth/[provider]/initiate/route.ts +46 -10
  166. package/src/modules/communication_channels/commands/deliver-outbound-message.ts +6 -1
  167. package/src/modules/communication_channels/i18n/de.json +4 -0
  168. package/src/modules/communication_channels/i18n/en.json +4 -0
  169. package/src/modules/communication_channels/i18n/es.json +4 -0
  170. package/src/modules/communication_channels/i18n/ko.json +4 -0
  171. package/src/modules/communication_channels/i18n/pl.json +4 -0
  172. package/src/modules/communication_channels/lib/inbound-message-origin.ts +2 -6
  173. package/src/modules/communication_channels/lib/oauth-state.ts +4 -1
  174. package/src/modules/communication_channels/lib/use-connect-channel.ts +10 -0
  175. package/src/modules/customers/api/activity-types/route.ts +154 -0
  176. package/src/modules/customers/api/deals/[id]/people/route.ts +82 -3
  177. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +9 -1
  178. package/src/modules/customers/api/dictionaries/[kind]/route.ts +18 -2
  179. package/src/modules/customers/api/interactions/route.ts +4 -0
  180. package/src/modules/customers/api/interactions/tasks/route.ts +1 -0
  181. package/src/modules/customers/backend/config/customers/pipeline-stages/page.meta.ts +20 -0
  182. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.ts +0 -29
  183. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +15 -17
  184. package/src/modules/customers/calendar-event-types.ts +674 -0
  185. package/src/modules/customers/commands/dictionaries.ts +84 -8
  186. package/src/modules/customers/commands/interactions.ts +244 -21
  187. package/src/modules/customers/components/ActivityTypeEditor.tsx +239 -0
  188. package/src/modules/customers/components/DictionarySettings.tsx +5 -3
  189. package/src/modules/customers/components/calendar/CalendarEventEditor.tsx +347 -218
  190. package/src/modules/customers/components/calendar/CalendarSettingsModal.tsx +18 -96
  191. package/src/modules/customers/components/calendar/TimeGrid.tsx +20 -18
  192. package/src/modules/customers/components/calendar/editor/EventTypePanel.tsx +230 -0
  193. package/src/modules/customers/components/calendar/editor/LocationField.tsx +7 -1
  194. package/src/modules/customers/components/calendar/editor/PeopleField.tsx +4 -0
  195. package/src/modules/customers/components/calendar/editor/PriorityField.tsx +3 -0
  196. package/src/modules/customers/components/calendar/editor/RepeatField.tsx +10 -0
  197. package/src/modules/customers/components/calendar/editor/ResourcesField.tsx +4 -0
  198. package/src/modules/customers/components/calendar/editor/ScheduleSection.tsx +16 -4
  199. package/src/modules/customers/components/calendar/editor/SegmentGroup.tsx +3 -0
  200. package/src/modules/customers/components/calendar/editor/hooks.ts +29 -13
  201. package/src/modules/customers/components/calendar/editor/inputs.tsx +17 -5
  202. package/src/modules/customers/components/calendar/editor/useCalendarCustomFields.ts +49 -0
  203. package/src/modules/customers/components/calendar/editor/useEventTypeCatalog.ts +100 -0
  204. package/src/modules/customers/components/calendar/types.ts +1 -0
  205. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +94 -388
  206. package/src/modules/customers/components/detail/CreatePersonDialog.tsx +39 -19
  207. package/src/modules/customers/components/detail/DealForm.tsx +7 -3
  208. package/src/modules/customers/components/detail/DealPeopleSection.tsx +256 -0
  209. package/src/modules/customers/components/detail/LinkedPeopleSection.tsx +474 -0
  210. package/src/modules/customers/components/detail/PersonCard.tsx +12 -4
  211. package/src/modules/customers/components/detail/types.ts +1 -0
  212. package/src/modules/customers/components/linking/adapters/personAdapter.tsx +4 -0
  213. package/src/modules/customers/data/entities.ts +8 -1
  214. package/src/modules/customers/data/validators.ts +42 -7
  215. package/src/modules/customers/di.ts +21 -0
  216. package/src/modules/customers/extension-points.ts +13 -0
  217. package/src/modules/customers/i18n/de.json +104 -8
  218. package/src/modules/customers/i18n/en.json +104 -8
  219. package/src/modules/customers/i18n/es.json +104 -8
  220. package/src/modules/customers/i18n/ko.json +104 -8
  221. package/src/modules/customers/i18n/pl.json +104 -8
  222. package/src/modules/customers/lib/calendar/conflicts.ts +106 -27
  223. package/src/modules/customers/lib/calendar/editorPayload.ts +39 -19
  224. package/src/modules/customers/lib/calendar/eventTypeResolver.ts +258 -0
  225. package/src/modules/customers/lib/calendar/interactionApplicability.ts +99 -0
  226. package/src/modules/customers/lib/calendar/mapItem.ts +6 -2
  227. package/src/modules/customers/lib/calendar/recurrence.ts +65 -1
  228. package/src/modules/customers/lib/calendar/timezone.ts +117 -0
  229. package/src/modules/customers/lib/interactionReadModel.ts +1 -0
  230. package/src/modules/customers/lib/todoCompatibility.ts +2 -0
  231. package/src/modules/customers/migrations/.snapshot-open-mercato.json +34 -0
  232. package/src/modules/customers/migrations/Migration20260928175058_customers.ts +15 -0
  233. package/src/modules/customers/migrations/Migration20260930110235_customers.ts +15 -0
  234. package/src/modules/dictionaries/components/DictionaryTable.tsx +63 -56
  235. package/src/modules/messages/subscribers/message-notification.ts +13 -3
  236. package/src/modules/payment_gateways/api/webhook/[provider]/route.ts +243 -62
  237. package/src/modules/payment_gateways/lib/gateway-service.ts +39 -12
  238. package/src/modules/planner/lib/availabilityMerge.ts +106 -41
  239. package/src/modules/planner/services/plannerAvailabilityService.ts +4 -0
  240. package/src/modules/sales/components/documents/LineItemDialog.tsx +194 -111
  241. package/src/modules/sales/components/documents/lineItemUtils.ts +18 -0
  242. package/src/modules/staff/backend/staff/time-tracking/projects/[id]/page.tsx +25 -13
  243. package/src/modules/sync_excel/lib/adapters/customers.ts +33 -27
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/lib/oauth-state.ts"],
4
- "sourcesContent": ["import crypto from 'node:crypto'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst oauthStateLogger = createLogger('communication_channels').child({ component: 'oauth-state' })\n\n/**\n * OAuth state-cookie helper for the communication_channels hub.\n *\n * **Ported (re-implemented locally), NOT imported, from `packages/enterprise/src/modules/sso/lib/state-cookie.ts`.**\n * Root `AGENTS.md` rule: `@open-mercato/core` MUST NOT import from `@open-mercato/enterprise`.\n *\n * Design (per email integration spec \u00A7 OSS Independence + \u00A7 Hub Deltas \u2192 Delta 7):\n * - AES-256-GCM payload encryption.\n * - HKDF (SHA-256) key derivation from `OM_HUB_OAUTH_STATE_KEY` (falling back to\n * `KMS_MASTER_KEY`). In production those dedicated keys are required; only in\n * dev/test do we fall back to `JWT_SECRET` so envs that configure one secret\n * still work. Production refuses the `JWT_SECRET` fallback so a session-secret\n * leak cannot also forge OAuth-state cookies.\n * - 5-minute TTL \u2014 short window to bound replay surface.\n * - Payload binds the initiating `userId` so the callback rejects state cookies\n * used by a different session.\n * - Single-use consume-on-read via a short-TTL cache marker keyed by\n * `tenantId:state` (see {@link consumeOAuthStateOnce}) so a captured cookie\n * cannot re-drive the callback within the TTL. **This guarantee only holds\n * across all replicas when `CACHE_STRATEGY=redis`.** With\n * `CACHE_STRATEGY=memory` (the default) the marker is process-local \u2014 a\n * replayed callback that reaches a different replica succeeds within the TTL.\n * Multi-replica deployments MUST use a shared cache (`CACHE_STRATEGY=redis`).\n *\n * The output is a base64url string that we set on an HttpOnly + SameSite=Lax cookie.\n * Forgery requires the encryption key (KMS-managed in production).\n */\n\nconst ALGORITHM = 'aes-256-gcm'\nconst IV_LENGTH = 12\nconst TAG_LENGTH = 16\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS = 5 * 60 * 1000\nconst HKDF_SALT = Buffer.from('open-mercato-channels-oauth-state-v1')\nconst HKDF_INFO = Buffer.from('communication_channels-oauth-state-cookie')\n\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME =\n 'om_cc_oauth_state'\n\nexport const DEFAULT_OAUTH_RETURN_URL = '/backend/profile/communication-channels'\n\n/** Cache tag for OAuth-state consume markers (invalidation / diagnostics). */\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_CACHE_TAG =\n 'communication_channels:oauth-state'\n\n/** Errors thrown by the helpers. Stable for tests + route mapping. */\nexport class OAuthStateError extends Error {\n override name = 'OAuthStateError'\n constructor(\n message: string,\n readonly code:\n | 'missing_secret'\n | 'invalid_cookie'\n | 'expired'\n | 'user_mismatch'\n | 'decrypt_failed'\n | 'replay',\n ) {\n super(message)\n }\n}\n\n/**\n * Canonical state-cookie payload \u2014 provider-agnostic. Each OAuth provider\n * adapter (Gmail, \u2026) packs its own per-flow nonce / verifier into\n * the `extra` field rather than extending this shape.\n */\nexport interface OAuthStatePayload {\n /** Nonce-like opaque value mirrored into the OAuth `state` query parameter. */\n state: string\n /** Per-flow CSRF nonce, returned alongside the OAuth response. */\n nonce: string\n /** Tenant-scoped user that initiated the flow. Validated on callback. */\n userId: string\n /** Tenant scope so the callback can pin the channel to the same tenant. */\n tenantId: string\n /** Optional organization id for multi-org tenants. */\n organizationId?: string | null\n /** Provider key (e.g. `gmail`) \u2014 routes the callback. */\n providerKey: string\n /** Where to redirect on success. Defaults to the profile page in the route. */\n returnUrl?: string\n /** Wall-clock expiry (ms since epoch). */\n expiresAt: number\n /** Provider-specific extras (PKCE code_verifier, scopes, login_hint, \u2026). */\n extra?: Record<string, unknown>\n}\n\n/**\n * Minimal cache surface used by {@link consumeOAuthStateOnce}. Matches the\n * `has` / `set` subset of `@open-mercato/cache`'s `CacheStrategy` so callers\n * can pass `container.resolve('cache')` directly.\n */\nexport type OAuthStateConsumeStore = {\n has(key: string): Promise<boolean>\n set(\n key: string,\n value: unknown,\n options?: { ttl?: number; tags?: string[] },\n ): Promise<void>\n}\n\nexport function isSafeOAuthReturnUrl(value: string | null | undefined): value is string {\n if (typeof value !== 'string') return false\n if (value.length === 0 || value.length > 2048) return false\n if (!value.startsWith('/') || value.startsWith('//')) return false\n if (value.includes('\\\\')) return false\n try {\n const base = new URL('https://open-mercato.local')\n const parsed = new URL(value, base)\n return parsed.origin === base.origin && parsed.pathname.startsWith('/')\n } catch {\n return false\n }\n}\n\nexport function normalizeOAuthReturnUrl(\n value: string | null | undefined,\n fallback: string = DEFAULT_OAUTH_RETURN_URL,\n): string {\n return isSafeOAuthReturnUrl(value) ? value : fallback\n}\n\nfunction deriveKey(secret: string): Buffer {\n return Buffer.from(crypto.hkdfSync('sha256', secret, HKDF_SALT, HKDF_INFO, 32))\n}\n\nfunction getSecret(): string {\n const dedicated = process.env.OM_HUB_OAUTH_STATE_KEY ?? process.env.KMS_MASTER_KEY\n if (dedicated) return dedicated\n // No dedicated key configured. Fail closed in production rather than deriving\n // the state-cookie key from JWT_SECRET (the platform session-signing secret) \u2014\n // sharing that key means a JWT_SECRET leak also lets an attacker forge OAuth\n // state cookies, bypassing the userId/tenant binding. In non-production we fall\n // back to JWT_SECRET so dev/test envs that only configure one secret still work.\n if (process.env.NODE_ENV === 'production') {\n throw new Error('[internal] OM_HUB_OAUTH_STATE_KEY or KMS_MASTER_KEY required in production')\n }\n const fallback = process.env.JWT_SECRET\n if (!fallback) {\n throw new OAuthStateError(\n 'OM_HUB_OAUTH_STATE_KEY (or fallback KMS_MASTER_KEY / JWT_SECRET) must be set',\n 'missing_secret',\n )\n }\n return fallback\n}\n\n/** Cache key for a consumed OAuth `state` nonce. Exported for tests. */\nexport function oauthStateConsumedCacheKey(tenantId: string, state: string): string {\n return `communication_channels:oauth-state:used:${tenantId}:${state}`\n}\n\n/** Encrypt + sign a state payload. Output is a base64url string suitable for a cookie. */\nexport function encryptOAuthState(payload: OAuthStatePayload): string {\n const key = deriveKey(getSecret())\n const iv = crypto.randomBytes(IV_LENGTH)\n const json = JSON.stringify(payload)\n\n const cipher = crypto.createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n\n return Buffer.concat([iv, tag, ciphertext]).toString('base64url')\n}\n\n/**\n * Decrypt + verify a state cookie. Returns the payload or `null` if the cookie\n * is malformed / tampered. Returns the payload (NOT null) when the cookie has\n * expired \u2014 callers should check `expiresAt` themselves with the verification\n * helper below for stable status codes.\n */\nexport function decryptOAuthState(cookie: string): OAuthStatePayload | null {\n try {\n const key = deriveKey(getSecret())\n const combined = Buffer.from(cookie, 'base64url')\n if (combined.length < IV_LENGTH + TAG_LENGTH) return null\n\n const iv = combined.subarray(0, IV_LENGTH)\n const tag = combined.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH)\n const ciphertext = combined.subarray(IV_LENGTH + TAG_LENGTH)\n\n const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)\n decipher.setAuthTag(tag)\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')\n\n return JSON.parse(decrypted) as OAuthStatePayload\n } catch {\n return null\n }\n}\n\n/**\n * Verify a state cookie against the current session.\n *\n * Throws an {@link OAuthStateError} with a stable `code` field on any check\n * failure so route handlers can map to consistent HTTP responses + redirect\n * flash codes.\n *\n * Crypto + binding checks only \u2014 callers MUST also call\n * {@link consumeOAuthStateOnce} so the state cannot be replayed within the TTL.\n */\nexport function verifyOAuthState(input: {\n cookie: string | null | undefined\n expectedUserId: string\n expectedProviderKey?: string\n expectedState?: string\n now?: number\n}): OAuthStatePayload {\n if (!input.cookie) {\n throw new OAuthStateError('Missing state cookie', 'invalid_cookie')\n }\n const payload = decryptOAuthState(input.cookie)\n if (!payload) {\n throw new OAuthStateError('Invalid state cookie', 'decrypt_failed')\n }\n const now = input.now ?? Date.now()\n if (payload.expiresAt < now) {\n throw new OAuthStateError('State cookie expired', 'expired')\n }\n if (payload.userId !== input.expectedUserId) {\n throw new OAuthStateError('State cookie userId mismatch', 'user_mismatch')\n }\n if (input.expectedProviderKey && payload.providerKey !== input.expectedProviderKey) {\n throw new OAuthStateError('State cookie providerKey mismatch', 'invalid_cookie')\n }\n if (input.expectedState && payload.state !== input.expectedState) {\n throw new OAuthStateError('State cookie state nonce mismatch', 'invalid_cookie')\n }\n return payload\n}\n\n/**\n * Mark a verified OAuth `state` as consumed in a short-TTL store.\n *\n * First successful call records a used-marker until `expiresAt` (or 1s minimum).\n * A second call with the same `state` throws {@link OAuthStateError} `replay`.\n *\n * Call immediately after {@link verifyOAuthState} on the callback path so a\n * captured valid cookie cannot re-drive the flow within the cookie TTL.\n *\n * Note: the `has`\u2192`set` pattern is not atomic. Two concurrent callbacks racing\n * on the same `state` both pass the `has` check and both proceed \u2014 the\n * single-use guarantee requires an atomic `setNx` which `CacheStrategy` does\n * not currently expose. The race window is milliseconds; document it rather\n * than silently claiming it is closed.\n */\nexport async function consumeOAuthStateOnce(\n store: OAuthStateConsumeStore,\n payload: Pick<OAuthStatePayload, 'state' | 'expiresAt' | 'tenantId'>,\n now: number = Date.now(),\n): Promise<void> {\n const key = oauthStateConsumedCacheKey(payload.tenantId, payload.state)\n if (await store.has(key)) {\n throw new OAuthStateError('State cookie already used', 'replay')\n }\n const ttl = Math.max(payload.expiresAt - now, 1_000)\n await store.set(key, 1, {\n ttl,\n tags: [`${COMMUNICATION_CHANNELS_OAUTH_STATE_CACHE_TAG}:${payload.tenantId}`],\n })\n}\n\n/**\n * Create a fresh state payload + matching `state` query parameter. PKCE\n * verifiers are NOT generated here \u2014 the provider adapter decides whether it\n * needs PKCE and packs the verifier into `extra` itself.\n */\nexport function createOAuthState(params: {\n userId: string\n tenantId: string\n organizationId?: string | null\n providerKey: string\n returnUrl?: string\n extra?: Record<string, unknown>\n}): { payload: OAuthStatePayload; cookie: string; stateParam: string } {\n const state = crypto.randomBytes(32).toString('base64url')\n const nonce = crypto.randomBytes(16).toString('base64url')\n const payload: OAuthStatePayload = {\n state,\n nonce,\n userId: params.userId,\n tenantId: params.tenantId,\n organizationId: params.organizationId ?? null,\n providerKey: params.providerKey,\n returnUrl: params.returnUrl,\n extra: params.extra,\n expiresAt: Date.now() + COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS,\n }\n const cookie = encryptOAuthState(payload)\n return { payload, cookie, stateParam: state }\n}\n\nlet memoryCacheStartupWarningEmitted = false\n\n/**\n * Emit a one-time startup warning unless the cache strategy is redis. Every other\n * strategy (memory, sqlite, jsonfile) keeps replay markers per process or per node,\n * so the single-use guarantee only holds across replicas on redis.\n */\nexport function emitOAuthStateMemoryCacheStartupWarningIfNeeded(\n env: NodeJS.ProcessEnv = process.env,\n): void {\n if (memoryCacheStartupWarningEmitted) return\n const strategy = (env.CACHE_STRATEGY ?? 'memory').trim().toLowerCase()\n if (strategy === 'redis') return\n memoryCacheStartupWarningEmitted = true\n oauthStateLogger.warn(\n `OAuth state single-use protection needs a store shared across replicas. CACHE_STRATEGY=${strategy} is per-process or per-node; multi-replica deployments MUST set CACHE_STRATEGY=redis.`,\n { context: 'startup', startup: true, cacheStrategy: strategy },\n )\n}\n\n/** Test helper \u2014 reset the one-time startup warning latch. */\nexport function resetOAuthStateMemoryCacheStartupWarningForTests(): void {\n memoryCacheStartupWarningEmitted = false\n}\n\nemitOAuthStateMemoryCacheStartupWarningIfNeeded()\n"],
5
- "mappings": "AAAA,OAAO,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,IACjB,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,aAAa,OAAO;AAAA,IACpB,WAAW,OAAO;AAAA,IAClB,OAAO,OAAO;AAAA,IACd,WAAW,KAAK,IAAI,IAAI;AAAA,EAC1B;AACA,QAAM,SAAS,kBAAkB,OAAO;AACxC,SAAO,EAAE,SAAS,QAAQ,YAAY,MAAM;AAC9C;AAEA,IAAI,mCAAmC;AAOhC,SAAS,gDACd,MAAyB,QAAQ,KAC3B;AACN,MAAI,iCAAkC;AACtC,QAAM,YAAY,IAAI,kBAAkB,UAAU,KAAK,EAAE,YAAY;AACrE,MAAI,aAAa,QAAS;AAC1B,qCAAmC;AACnC,mBAAiB;AAAA,IACf,0FAA0F,QAAQ;AAAA,IAClG,EAAE,SAAS,WAAW,SAAS,MAAM,eAAe,SAAS;AAAA,EAC/D;AACF;AAGO,SAAS,mDAAyD;AACvE,qCAAmC;AACrC;AAEA,gDAAgD;",
4
+ "sourcesContent": ["import crypto from 'node:crypto'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst oauthStateLogger = createLogger('communication_channels').child({ component: 'oauth-state' })\n\n/**\n * OAuth state-cookie helper for the communication_channels hub.\n *\n * **Ported (re-implemented locally), NOT imported, from `packages/enterprise/src/modules/sso/lib/state-cookie.ts`.**\n * Root `AGENTS.md` rule: `@open-mercato/core` MUST NOT import from `@open-mercato/enterprise`.\n *\n * Design (per email integration spec \u00A7 OSS Independence + \u00A7 Hub Deltas \u2192 Delta 7):\n * - AES-256-GCM payload encryption.\n * - HKDF (SHA-256) key derivation from `OM_HUB_OAUTH_STATE_KEY` (falling back to\n * `KMS_MASTER_KEY`). In production those dedicated keys are required; only in\n * dev/test do we fall back to `JWT_SECRET` so envs that configure one secret\n * still work. Production refuses the `JWT_SECRET` fallback so a session-secret\n * leak cannot also forge OAuth-state cookies.\n * - 5-minute TTL \u2014 short window to bound replay surface.\n * - Payload binds the initiating `userId` so the callback rejects state cookies\n * used by a different session.\n * - Single-use consume-on-read via a short-TTL cache marker keyed by\n * `tenantId:state` (see {@link consumeOAuthStateOnce}) so a captured cookie\n * cannot re-drive the callback within the TTL. **This guarantee only holds\n * across all replicas when `CACHE_STRATEGY=redis`.** With\n * `CACHE_STRATEGY=memory` (the default) the marker is process-local \u2014 a\n * replayed callback that reaches a different replica succeeds within the TTL.\n * Multi-replica deployments MUST use a shared cache (`CACHE_STRATEGY=redis`).\n *\n * The output is a base64url string that we set on an HttpOnly + SameSite=Lax cookie.\n * Forgery requires the encryption key (KMS-managed in production).\n */\n\nconst ALGORITHM = 'aes-256-gcm'\nconst IV_LENGTH = 12\nconst TAG_LENGTH = 16\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS = 5 * 60 * 1000\nconst HKDF_SALT = Buffer.from('open-mercato-channels-oauth-state-v1')\nconst HKDF_INFO = Buffer.from('communication_channels-oauth-state-cookie')\n\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_COOKIE_NAME =\n 'om_cc_oauth_state'\n\nexport const DEFAULT_OAUTH_RETURN_URL = '/backend/profile/communication-channels'\n\n/** Cache tag for OAuth-state consume markers (invalidation / diagnostics). */\nexport const COMMUNICATION_CHANNELS_OAUTH_STATE_CACHE_TAG =\n 'communication_channels:oauth-state'\n\n/** Errors thrown by the helpers. Stable for tests + route mapping. */\nexport class OAuthStateError extends Error {\n override name = 'OAuthStateError'\n constructor(\n message: string,\n readonly code:\n | 'missing_secret'\n | 'invalid_cookie'\n | 'expired'\n | 'user_mismatch'\n | 'decrypt_failed'\n | 'replay',\n ) {\n super(message)\n }\n}\n\n/**\n * Canonical state-cookie payload \u2014 provider-agnostic. Each OAuth provider\n * adapter (Gmail, \u2026) packs its own per-flow nonce / verifier into\n * the `extra` field rather than extending this shape.\n */\nexport interface OAuthStatePayload {\n /** Nonce-like opaque value mirrored into the OAuth `state` query parameter. */\n state: string\n /** Per-flow CSRF nonce, returned alongside the OAuth response. */\n nonce: string\n /** Tenant-scoped user that initiated the flow. Validated on callback. */\n userId: string\n /** Tenant scope so the callback can pin the channel to the same tenant. */\n tenantId: string\n /** Optional organization id for multi-org tenants. */\n organizationId?: string | null\n /** Provider key (e.g. `gmail`) \u2014 routes the callback. */\n providerKey: string\n /** Where to redirect on success. Defaults to the profile page in the route. */\n returnUrl?: string\n /** Wall-clock expiry (ms since epoch). */\n expiresAt: number\n /** Provider-specific extras (PKCE code_verifier, scopes, login_hint, \u2026). */\n extra?: Record<string, unknown>\n}\n\n/**\n * Minimal cache surface used by {@link consumeOAuthStateOnce}. Matches the\n * `has` / `set` subset of `@open-mercato/cache`'s `CacheStrategy` so callers\n * can pass `container.resolve('cache')` directly.\n */\nexport type OAuthStateConsumeStore = {\n has(key: string): Promise<boolean>\n set(\n key: string,\n value: unknown,\n options?: { ttl?: number; tags?: string[] },\n ): Promise<void>\n}\n\nexport function isSafeOAuthReturnUrl(value: string | null | undefined): value is string {\n if (typeof value !== 'string') return false\n if (value.length === 0 || value.length > 2048) return false\n if (!value.startsWith('/') || value.startsWith('//')) return false\n if (value.includes('\\\\')) return false\n try {\n const base = new URL('https://open-mercato.local')\n const parsed = new URL(value, base)\n return parsed.origin === base.origin && parsed.pathname.startsWith('/')\n } catch {\n return false\n }\n}\n\nexport function normalizeOAuthReturnUrl(\n value: string | null | undefined,\n fallback: string = DEFAULT_OAUTH_RETURN_URL,\n): string {\n return isSafeOAuthReturnUrl(value) ? value : fallback\n}\n\nfunction deriveKey(secret: string): Buffer {\n return Buffer.from(crypto.hkdfSync('sha256', secret, HKDF_SALT, HKDF_INFO, 32))\n}\n\nfunction getSecret(): string {\n const dedicated = process.env.OM_HUB_OAUTH_STATE_KEY ?? process.env.KMS_MASTER_KEY\n if (dedicated) return dedicated\n // No dedicated key configured. Fail closed in production rather than deriving\n // the state-cookie key from JWT_SECRET (the platform session-signing secret) \u2014\n // sharing that key means a JWT_SECRET leak also lets an attacker forge OAuth\n // state cookies, bypassing the userId/tenant binding. In non-production we fall\n // back to JWT_SECRET so dev/test envs that only configure one secret still work.\n if (process.env.NODE_ENV === 'production') {\n throw new OAuthStateError(\n '[internal] OM_HUB_OAUTH_STATE_KEY or KMS_MASTER_KEY required in production',\n 'missing_secret',\n )\n }\n const fallback = process.env.JWT_SECRET\n if (!fallback) {\n throw new OAuthStateError(\n 'OM_HUB_OAUTH_STATE_KEY (or fallback KMS_MASTER_KEY / JWT_SECRET) must be set',\n 'missing_secret',\n )\n }\n return fallback\n}\n\n/** Cache key for a consumed OAuth `state` nonce. Exported for tests. */\nexport function oauthStateConsumedCacheKey(tenantId: string, state: string): string {\n return `communication_channels:oauth-state:used:${tenantId}:${state}`\n}\n\n/** Encrypt + sign a state payload. Output is a base64url string suitable for a cookie. */\nexport function encryptOAuthState(payload: OAuthStatePayload): string {\n const key = deriveKey(getSecret())\n const iv = crypto.randomBytes(IV_LENGTH)\n const json = JSON.stringify(payload)\n\n const cipher = crypto.createCipheriv(ALGORITHM, key, iv)\n const ciphertext = Buffer.concat([cipher.update(json, 'utf8'), cipher.final()])\n const tag = cipher.getAuthTag()\n\n return Buffer.concat([iv, tag, ciphertext]).toString('base64url')\n}\n\n/**\n * Decrypt + verify a state cookie. Returns the payload or `null` if the cookie\n * is malformed / tampered. Returns the payload (NOT null) when the cookie has\n * expired \u2014 callers should check `expiresAt` themselves with the verification\n * helper below for stable status codes.\n */\nexport function decryptOAuthState(cookie: string): OAuthStatePayload | null {\n try {\n const key = deriveKey(getSecret())\n const combined = Buffer.from(cookie, 'base64url')\n if (combined.length < IV_LENGTH + TAG_LENGTH) return null\n\n const iv = combined.subarray(0, IV_LENGTH)\n const tag = combined.subarray(IV_LENGTH, IV_LENGTH + TAG_LENGTH)\n const ciphertext = combined.subarray(IV_LENGTH + TAG_LENGTH)\n\n const decipher = crypto.createDecipheriv(ALGORITHM, key, iv)\n decipher.setAuthTag(tag)\n const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')\n\n return JSON.parse(decrypted) as OAuthStatePayload\n } catch {\n return null\n }\n}\n\n/**\n * Verify a state cookie against the current session.\n *\n * Throws an {@link OAuthStateError} with a stable `code` field on any check\n * failure so route handlers can map to consistent HTTP responses + redirect\n * flash codes.\n *\n * Crypto + binding checks only \u2014 callers MUST also call\n * {@link consumeOAuthStateOnce} so the state cannot be replayed within the TTL.\n */\nexport function verifyOAuthState(input: {\n cookie: string | null | undefined\n expectedUserId: string\n expectedProviderKey?: string\n expectedState?: string\n now?: number\n}): OAuthStatePayload {\n if (!input.cookie) {\n throw new OAuthStateError('Missing state cookie', 'invalid_cookie')\n }\n const payload = decryptOAuthState(input.cookie)\n if (!payload) {\n throw new OAuthStateError('Invalid state cookie', 'decrypt_failed')\n }\n const now = input.now ?? Date.now()\n if (payload.expiresAt < now) {\n throw new OAuthStateError('State cookie expired', 'expired')\n }\n if (payload.userId !== input.expectedUserId) {\n throw new OAuthStateError('State cookie userId mismatch', 'user_mismatch')\n }\n if (input.expectedProviderKey && payload.providerKey !== input.expectedProviderKey) {\n throw new OAuthStateError('State cookie providerKey mismatch', 'invalid_cookie')\n }\n if (input.expectedState && payload.state !== input.expectedState) {\n throw new OAuthStateError('State cookie state nonce mismatch', 'invalid_cookie')\n }\n return payload\n}\n\n/**\n * Mark a verified OAuth `state` as consumed in a short-TTL store.\n *\n * First successful call records a used-marker until `expiresAt` (or 1s minimum).\n * A second call with the same `state` throws {@link OAuthStateError} `replay`.\n *\n * Call immediately after {@link verifyOAuthState} on the callback path so a\n * captured valid cookie cannot re-drive the flow within the cookie TTL.\n *\n * Note: the `has`\u2192`set` pattern is not atomic. Two concurrent callbacks racing\n * on the same `state` both pass the `has` check and both proceed \u2014 the\n * single-use guarantee requires an atomic `setNx` which `CacheStrategy` does\n * not currently expose. The race window is milliseconds; document it rather\n * than silently claiming it is closed.\n */\nexport async function consumeOAuthStateOnce(\n store: OAuthStateConsumeStore,\n payload: Pick<OAuthStatePayload, 'state' | 'expiresAt' | 'tenantId'>,\n now: number = Date.now(),\n): Promise<void> {\n const key = oauthStateConsumedCacheKey(payload.tenantId, payload.state)\n if (await store.has(key)) {\n throw new OAuthStateError('State cookie already used', 'replay')\n }\n const ttl = Math.max(payload.expiresAt - now, 1_000)\n await store.set(key, 1, {\n ttl,\n tags: [`${COMMUNICATION_CHANNELS_OAUTH_STATE_CACHE_TAG}:${payload.tenantId}`],\n })\n}\n\n/**\n * Create a fresh state payload + matching `state` query parameter. PKCE\n * verifiers are NOT generated here \u2014 the provider adapter decides whether it\n * needs PKCE and packs the verifier into `extra` itself.\n */\nexport function createOAuthState(params: {\n userId: string\n tenantId: string\n organizationId?: string | null\n providerKey: string\n returnUrl?: string\n extra?: Record<string, unknown>\n}): { payload: OAuthStatePayload; cookie: string; stateParam: string } {\n const state = crypto.randomBytes(32).toString('base64url')\n const nonce = crypto.randomBytes(16).toString('base64url')\n const payload: OAuthStatePayload = {\n state,\n nonce,\n userId: params.userId,\n tenantId: params.tenantId,\n organizationId: params.organizationId ?? null,\n providerKey: params.providerKey,\n returnUrl: params.returnUrl,\n extra: params.extra,\n expiresAt: Date.now() + COMMUNICATION_CHANNELS_OAUTH_STATE_TTL_MS,\n }\n const cookie = encryptOAuthState(payload)\n return { payload, cookie, stateParam: state }\n}\n\nlet memoryCacheStartupWarningEmitted = false\n\n/**\n * Emit a one-time startup warning unless the cache strategy is redis. Every other\n * strategy (memory, sqlite, jsonfile) keeps replay markers per process or per node,\n * so the single-use guarantee only holds across replicas on redis.\n */\nexport function emitOAuthStateMemoryCacheStartupWarningIfNeeded(\n env: NodeJS.ProcessEnv = process.env,\n): void {\n if (memoryCacheStartupWarningEmitted) return\n const strategy = (env.CACHE_STRATEGY ?? 'memory').trim().toLowerCase()\n if (strategy === 'redis') return\n memoryCacheStartupWarningEmitted = true\n oauthStateLogger.warn(\n `OAuth state single-use protection needs a store shared across replicas. CACHE_STRATEGY=${strategy} is per-process or per-node; multi-replica deployments MUST set CACHE_STRATEGY=redis.`,\n { context: 'startup', startup: true, cacheStrategy: strategy },\n )\n}\n\n/** Test helper \u2014 reset the one-time startup warning latch. */\nexport function resetOAuthStateMemoryCacheStartupWarningForTests(): void {\n memoryCacheStartupWarningEmitted = false\n}\n\nemitOAuthStateMemoryCacheStartupWarningIfNeeded()\n"],
5
+ "mappings": "AAAA,OAAO,YAAY;AACnB,SAAS,oBAAoB;AAE7B,MAAM,mBAAmB,aAAa,wBAAwB,EAAE,MAAM,EAAE,WAAW,cAAc,CAAC;AA8BlG,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,aAAa;AACZ,MAAM,4CAA4C,IAAI,KAAK;AAClE,MAAM,YAAY,OAAO,KAAK,sCAAsC;AACpE,MAAM,YAAY,OAAO,KAAK,2CAA2C;AAElE,MAAM,iDACX;AAEK,MAAM,2BAA2B;AAGjC,MAAM,+CACX;AAGK,MAAM,wBAAwB,MAAM;AAAA,EAEzC,YACE,SACS,MAOT;AACA,UAAM,OAAO;AARJ;AAHX,SAAS,OAAO;AAAA,EAYhB;AACF;AA0CO,SAAS,qBAAqB,OAAmD;AACtF,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,MAAI,MAAM,WAAW,KAAK,MAAM,SAAS,KAAM,QAAO;AACtD,MAAI,CAAC,MAAM,WAAW,GAAG,KAAK,MAAM,WAAW,IAAI,EAAG,QAAO;AAC7D,MAAI,MAAM,SAAS,IAAI,EAAG,QAAO;AACjC,MAAI;AACF,UAAM,OAAO,IAAI,IAAI,4BAA4B;AACjD,UAAM,SAAS,IAAI,IAAI,OAAO,IAAI;AAClC,WAAO,OAAO,WAAW,KAAK,UAAU,OAAO,SAAS,WAAW,GAAG;AAAA,EACxE,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,wBACd,OACA,WAAmB,0BACX;AACR,SAAO,qBAAqB,KAAK,IAAI,QAAQ;AAC/C;AAEA,SAAS,UAAU,QAAwB;AACzC,SAAO,OAAO,KAAK,OAAO,SAAS,UAAU,QAAQ,WAAW,WAAW,EAAE,CAAC;AAChF;AAEA,SAAS,YAAoB;AA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AE,EAAE,SAAS,WAAW;AACzD,QAAM,QAAQ,OAAO,YAAY,EAAE,EAAE,SAAS,WAAW;AACzD,QAAM,UAA6B;AAAA,IACjC;AAAA,IACA;AAAA,IACA,QAAQ,OAAO;AAAA,IACf,UAAU,OAAO;AAAA,IACjB,gBAAgB,OAAO,kBAAkB;AAAA,IACzC,aAAa,OAAO;AAAA,IACpB,WAAW,OAAO;AAAA,IAClB,OAAO,OAAO;AAAA,IACd,WAAW,KAAK,IAAI,IAAI;AAAA,EAC1B;AACA,QAAM,SAAS,kBAAkB,OAAO;AACxC,SAAO,EAAE,SAAS,QAAQ,YAAY,MAAM;AAC9C;AAEA,IAAI,mCAAmC;AAOhC,SAAS,gDACd,MAAyB,QAAQ,KAC3B;AACN,MAAI,iCAAkC;AACtC,QAAM,YAAY,IAAI,kBAAkB,UAAU,KAAK,EAAE,YAAY;AACrE,MAAI,aAAa,QAAS;AAC1B,qCAAmC;AACnC,mBAAiB;AAAA,IACf,0FAA0F,QAAQ;AAAA,IAClG,EAAE,SAAS,WAAW,SAAS,MAAM,eAAe,SAAS;AAAA,EAC/D;AACF;AAGO,SAAS,mDAAyD;AACvE,qCAAmC;AACrC;AAEA,gDAAgD;",
6
6
  "names": []
7
7
  }
@@ -32,6 +32,16 @@ function useConnectChannel(options) {
32
32
  });
33
33
  const body = response.result;
34
34
  if (!response.ok || !body?.authorizeUrl) {
35
+ if (body?.code === "missing_secret") {
36
+ flash(
37
+ t(
38
+ "communication_channels.profile.connect.notAvailable",
39
+ "Mailbox connection is not available. Ask an administrator to configure the OAuth state key."
40
+ ),
41
+ "error"
42
+ );
43
+ return;
44
+ }
35
45
  if (body?.code === "oauth_client_not_configured") {
36
46
  flash(
37
47
  t(
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/communication_channels/lib/use-connect-channel.ts"],
4
- "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\n\ntype InitiateResponse = { authorizeUrl?: string; error?: string; code?: string }\n\n/**\n * Shared OAuth \"connect\" flow for email channel provider widgets (Gmail and\n * other OAuth providers). Wraps the guarded-mutation contract + `/oauth/<provider>/initiate`\n * call + redirect, so each provider widget only supplies its own button chrome.\n */\nexport function useConnectChannel(options: {\n providerKey: string\n returnUrl?: string\n}): { connect: () => Promise<void>; pending: boolean } {\n const { providerKey } = options\n const returnUrl = options.returnUrl ?? '/backend/profile/communication-channels'\n const t = useT()\n const [pending, setPending] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation({\n contextId: `channel-${providerKey}-connect`,\n blockedMessage: t('communication_channels.profile.connect.blocked', 'Connection blocked by validation'),\n })\n const mutationContext = React.useMemo(\n () => ({ providerKey, retryLastMutation }),\n [providerKey, retryLastMutation],\n )\n\n const connect = React.useCallback(async () => {\n if (pending) return\n setPending(true)\n try {\n const response = await runMutation({\n context: mutationContext,\n mutationPayload: { providerKey },\n operation: () =>\n apiCall<InitiateResponse>(`/api/communication_channels/oauth/${providerKey}/initiate`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ returnUrl }),\n }),\n })\n const body = response.result as InitiateResponse | undefined\n if (!response.ok || !body?.authorizeUrl) {\n if (body?.code === 'oauth_client_not_configured') {\n flash(\n t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n ),\n 'error',\n )\n return\n }\n flash(\n body?.error ??\n t('communication_channels.profile.connect.oauthFailed', 'Could not start OAuth connection.'),\n 'error',\n )\n return\n }\n window.location.assign(body.authorizeUrl)\n } finally {\n setPending(false)\n }\n }, [mutationContext, pending, providerKey, returnUrl, runMutation, t])\n\n return { connect, pending }\n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AK;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,iBAAiB,SAAS,aAAa,WAAW,aAAa,CAAC,CAAC;AAErE,SAAO,EAAE,SAAS,QAAQ;AAC5B;",
4
+ "sourcesContent": ["'use client'\n\nimport * as React from 'react'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport { flash } from '@open-mercato/ui/backend/FlashMessages'\nimport { useGuardedMutation } from '@open-mercato/ui/backend/injection/useGuardedMutation'\nimport { apiCall } from '@open-mercato/ui/backend/utils/apiCall'\n\ntype InitiateResponse = { authorizeUrl?: string; error?: string; code?: string }\n\n/**\n * Shared OAuth \"connect\" flow for email channel provider widgets (Gmail and\n * other OAuth providers). Wraps the guarded-mutation contract + `/oauth/<provider>/initiate`\n * call + redirect, so each provider widget only supplies its own button chrome.\n */\nexport function useConnectChannel(options: {\n providerKey: string\n returnUrl?: string\n}): { connect: () => Promise<void>; pending: boolean } {\n const { providerKey } = options\n const returnUrl = options.returnUrl ?? '/backend/profile/communication-channels'\n const t = useT()\n const [pending, setPending] = React.useState(false)\n const { runMutation, retryLastMutation } = useGuardedMutation({\n contextId: `channel-${providerKey}-connect`,\n blockedMessage: t('communication_channels.profile.connect.blocked', 'Connection blocked by validation'),\n })\n const mutationContext = React.useMemo(\n () => ({ providerKey, retryLastMutation }),\n [providerKey, retryLastMutation],\n )\n\n const connect = React.useCallback(async () => {\n if (pending) return\n setPending(true)\n try {\n const response = await runMutation({\n context: mutationContext,\n mutationPayload: { providerKey },\n operation: () =>\n apiCall<InitiateResponse>(`/api/communication_channels/oauth/${providerKey}/initiate`, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ returnUrl }),\n }),\n })\n const body = response.result as InitiateResponse | undefined\n if (!response.ok || !body?.authorizeUrl) {\n if (body?.code === 'missing_secret') {\n flash(\n t(\n 'communication_channels.profile.connect.notAvailable',\n 'Mailbox connection is not available. Ask an administrator to configure the OAuth state key.',\n ),\n 'error',\n )\n return\n }\n if (body?.code === 'oauth_client_not_configured') {\n flash(\n t(\n 'communication_channels.profile.connect.notConfigured',\n 'This provider is not configured yet. Ask an administrator to add the OAuth Client ID and Secret under Integrations before connecting a mailbox.',\n ),\n 'error',\n )\n return\n }\n flash(\n body?.error ??\n t('communication_channels.profile.connect.oauthFailed', 'Could not start OAuth connection.'),\n 'error',\n )\n return\n }\n window.location.assign(body.authorizeUrl)\n } finally {\n setPending(false)\n }\n }, [mutationContext, pending, providerKey, returnUrl, runMutation, t])\n\n return { connect, pending }\n}\n"],
5
+ "mappings": ";AAEA,YAAY,WAAW;AACvB,SAAS,YAAY;AACrB,SAAS,aAAa;AACtB,SAAS,0BAA0B;AACnC,SAAS,eAAe;AASjB,SAAS,kBAAkB,SAGqB;AACrD,QAAM,EAAE,YAAY,IAAI;AACxB,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,IAAI,KAAK;AACf,QAAM,CAAC,SAAS,UAAU,IAAI,MAAM,SAAS,KAAK;AAClD,QAAM,EAAE,aAAa,kBAAkB,IAAI,mBAAmB;AAAA,IAC5D,WAAW,WAAW,WAAW;AAAA,IACjC,gBAAgB,EAAE,kDAAkD,kCAAkC;AAAA,EACxG,CAAC;AACD,QAAM,kBAAkB,MAAM;AAAA,IAC5B,OAAO,EAAE,aAAa,kBAAkB;AAAA,IACxC,CAAC,aAAa,iBAAiB;AAAA,EACjC;AAEA,QAAM,UAAU,MAAM,YAAY,YAAY;AAC5C,QAAI,QAAS;AACb,eAAW,IAAI;AACf,QAAI;AACF,YAAM,WAAW,MAAM,YAAY;AAAA,QACjC,SAAS;AAAA,QACT,iBAAiB,EAAE,YAAY;AAAA,QAC/B,WAAW,MACT,QAA0B,qCAAqC,WAAW,aAAa;AAAA,UACrF,QAAQ;AAAA,UACR,SAAS,EAAE,gBAAgB,mBAAmB;AAAA,UAC9C,MAAM,KAAK,UAAU,EAAE,UAAU,CAAC;AAAA,QACpC,CAAC;AAAA,MACL,CAAC;AACD,YAAM,OAAO,SAAS;AACtB,UAAI,CAAC,SAAS,MAAM,CAAC,MAAM,cAAc;AACvC,YAAI,MAAM,SAAS,kBAAkB;AACnC;AAAA,YACE;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,YACA;AAAA,UACF;AACA;AAAA,QACF;AACA,YAAI,MAAM,SAAS,+BAA+B;AAChD;AAAA,YACE;AAAA,cACE;AAAA,cACA;AAAA,YACF;AAAA,YACA;AAAA,UACF;AACA;AAAA,QACF;AACA;AAAA,UACE,MAAM,SACJ,EAAE,sDAAsD,mCAAmC;AAAA,UAC7F;AAAA,QACF;AACA;AAAA,MACF;AACA,aAAO,SAAS,OAAO,KAAK,YAAY;AAAA,IAC1C,UAAE;AACA,iBAAW,KAAK;AAAA,IAClB;AAAA,EACF,GAAG,CAAC,iBAAiB,SAAS,aAAa,WAAW,aAAa,CAAC,CAAC;AAErE,SAAO,EAAE,SAAS,QAAQ;AAC5B;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,151 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { isCrudHttpError } from "@open-mercato/shared/lib/crud/errors";
4
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
5
+ import { createLogger } from "@open-mercato/shared/lib/logger";
6
+ import { getTelemetryRuntime } from "@open-mercato/shared/lib/telemetry/runtime";
7
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
8
+ import { resolveDictionaryRouteContext } from "../dictionaries/context.js";
9
+ import { createDictionaryCacheTags, DICTIONARY_CACHE_TTL_MS } from "../dictionaries/cache.js";
10
+ import { getInjectionRegistryVersion } from "@open-mercato/shared/modules/widgets/injection-loader";
11
+ import {
12
+ resolveScopedCalendarEventTypes
13
+ } from "../../lib/calendar/eventTypeResolver.js";
14
+ import { calendarEventTypeBehaviorSchema } from "../../calendar-event-types.js";
15
+ import { getCalendarEventTypeRegistryVersion } from "../../calendar-event-types.js";
16
+ const logger = createLogger("customers");
17
+ function reportActivityTypeError(error, code, attributes) {
18
+ try {
19
+ getTelemetryRuntime()?.reportError(error, { module: "customers", code, attributes });
20
+ } catch {
21
+ }
22
+ }
23
+ const querySchema = z.object({ organizationId: z.string().uuid().optional() });
24
+ const responseSchema = z.object({
25
+ fallbackKey: z.literal("meeting"),
26
+ items: z.array(z.object({
27
+ key: z.string(),
28
+ label: z.string(),
29
+ labelKey: z.string().optional(),
30
+ icon: z.string().nullable().optional(),
31
+ color: z.string().nullable().optional(),
32
+ behavior: calendarEventTypeBehaviorSchema,
33
+ selectable: z.boolean(),
34
+ panelKey: z.string().optional(),
35
+ source: z.string(),
36
+ provenance: z.record(z.string(), z.unknown()),
37
+ historical: z.boolean(),
38
+ fallbackReason: z.enum(["tombstoned", "module-unavailable", "unknown"]).optional(),
39
+ adminConfigurable: z.boolean(),
40
+ isInherited: z.boolean(),
41
+ isLocalOverride: z.boolean(),
42
+ updatedAt: z.string().nullable(),
43
+ missingCustomFieldsetIds: z.array(z.string()),
44
+ inactiveDictionaryOverride: z.boolean().optional()
45
+ }))
46
+ });
47
+ const metadata = {
48
+ GET: { requireAuth: true }
49
+ };
50
+ async function GET(req) {
51
+ try {
52
+ const url = new URL(req.url);
53
+ const query = querySchema.parse({ organizationId: url.searchParams.get("organizationId") ?? void 0 });
54
+ const context = await resolveDictionaryRouteContext(req, { selectedId: query.organizationId });
55
+ if (!context.organizationId) {
56
+ return NextResponse.json({ error: context.translate("customers.errors.organization_required", "Organization context is required") }, { status: 400 });
57
+ }
58
+ const organizationId = context.organizationId;
59
+ const rbac = context.container.resolve("rbacService");
60
+ const actorId = context.auth?.sub;
61
+ if (!rbac || !actorId) {
62
+ throw new CrudHttpError(403, { error: context.translate("customers.calendar.activityTypes.errors.forbidden", "You do not have permission to view activity types.") });
63
+ }
64
+ const permissionScope = { tenantId: context.tenantId, organizationId };
65
+ const canViewInteractions = await rbac.userHasAllFeatures(actorId, ["customers.interactions.view"], permissionScope);
66
+ const canManageSettings = canViewInteractions || await rbac.userHasAllFeatures(actorId, ["customers.settings.manage"], permissionScope);
67
+ if (!canManageSettings) {
68
+ throw new CrudHttpError(403, { error: context.translate("customers.calendar.activityTypes.errors.forbidden", "You do not have permission to view activity types.") });
69
+ }
70
+ const hierarchy = context.container.resolve("organizationHierarchyService");
71
+ const ancestors = await hierarchy.resolveAncestorIds({ tenantId: context.tenantId, organizationId });
72
+ if (ancestors === null) {
73
+ throw new CrudHttpError(403, { error: context.translate("customers.errors.organization_forbidden", "Organization not accessible") });
74
+ }
75
+ const scopeIds = Array.from(/* @__PURE__ */ new Set([organizationId, ...ancestors.slice().reverse()]));
76
+ const cacheKey = `customers:activity-types:${context.tenantId}:org=${organizationId}:scope=${scopeIds.join("|")}:widgets=${getInjectionRegistryVersion()}:registry=${getCalendarEventTypeRegistryVersion()}`;
77
+ const cached = await context.cache?.get(cacheKey);
78
+ if (cached) return NextResponse.json(cached);
79
+ let catalog;
80
+ try {
81
+ catalog = await resolveScopedCalendarEventTypes({
82
+ em: context.em,
83
+ tenantId: context.tenantId,
84
+ organizationId,
85
+ readableOrganizationIds: scopeIds
86
+ });
87
+ } catch (err) {
88
+ logger.error("customers.activity_types.resolve failed", {
89
+ err,
90
+ tenantId: context.tenantId,
91
+ organizationId
92
+ });
93
+ reportActivityTypeError(err, "customers.activity_type_catalog_resolution_failed", {
94
+ tenantId: context.tenantId,
95
+ organizationId
96
+ });
97
+ return NextResponse.json({
98
+ error: context.translate("customers.calendar.activityTypes.errors.loadFailed", "Failed to load activity types"),
99
+ code: "activity_type_catalog_unavailable"
100
+ }, { status: 503 });
101
+ }
102
+ if (context.cache) {
103
+ await context.cache.set(cacheKey, catalog, {
104
+ ttl: DICTIONARY_CACHE_TTL_MS,
105
+ tags: createDictionaryCacheTags({
106
+ tenantId: context.tenantId,
107
+ mappedKind: "activity_type",
108
+ organizationIds: scopeIds
109
+ })
110
+ }).catch((err) => {
111
+ logger.warn("customers.activity_types cache write failed", { err });
112
+ reportActivityTypeError(err, "customers.activity_type_catalog_cache_write_failed", {
113
+ tenantId: context.tenantId,
114
+ organizationId
115
+ });
116
+ });
117
+ }
118
+ return NextResponse.json(catalog);
119
+ } catch (err) {
120
+ if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status });
121
+ logger.error("customers.activity_types request failed", { err });
122
+ reportActivityTypeError(err, "customers.activity_type_catalog_request_failed");
123
+ const { translate } = await resolveTranslations();
124
+ return NextResponse.json({
125
+ error: translate("customers.calendar.activityTypes.errors.loadFailed", "Failed to load activity types")
126
+ }, { status: err instanceof z.ZodError ? 400 : 500 });
127
+ }
128
+ }
129
+ const openApi = {
130
+ tag: "Customers",
131
+ summary: "Effective calendar activity types",
132
+ methods: {
133
+ GET: {
134
+ summary: "List effective calendar activity types",
135
+ description: "Returns the tenant and organization scoped calendar activity-type catalog. Requires customers.interactions.view or customers.settings.manage.",
136
+ responses: [{ status: 200, description: "Effective activity-type catalog", schema: responseSchema }],
137
+ errors: [
138
+ { status: 400, description: "Organization scope is required", schema: z.object({ error: z.string() }) },
139
+ { status: 401, description: "Unauthorized", schema: z.object({ error: z.string() }) },
140
+ { status: 403, description: "Forbidden", schema: z.object({ error: z.string() }) },
141
+ { status: 500, description: "Unexpected server error", schema: z.object({ error: z.string() }) }
142
+ ]
143
+ }
144
+ }
145
+ };
146
+ export {
147
+ GET,
148
+ metadata,
149
+ openApi
150
+ };
151
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/customers/api/activity-types/route.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { isCrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport type { RbacService } from '@open-mercato/core/modules/auth/services/rbacService'\nimport type { OrganizationHierarchyService } from '@open-mercato/shared/lib/auth/principal-service'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\nimport { getTelemetryRuntime } from '@open-mercato/shared/lib/telemetry/runtime'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport { resolveDictionaryRouteContext } from '../dictionaries/context'\nimport { createDictionaryCacheTags, DICTIONARY_CACHE_TTL_MS } from '../dictionaries/cache'\nimport { getInjectionRegistryVersion } from '@open-mercato/shared/modules/widgets/injection-loader'\nimport {\n resolveScopedCalendarEventTypes,\n} from '../../lib/calendar/eventTypeResolver'\nimport { calendarEventTypeBehaviorSchema } from '../../calendar-event-types'\nimport { getCalendarEventTypeRegistryVersion } from '../../calendar-event-types'\n\nconst logger = createLogger('customers')\n\nfunction reportActivityTypeError(error: unknown, code: string, attributes?: Record<string, string>): void {\n try {\n getTelemetryRuntime()?.reportError(error, { module: 'customers', code, attributes })\n } catch {}\n}\n\nconst querySchema = z.object({ organizationId: z.string().uuid().optional() })\nconst responseSchema = z.object({\n fallbackKey: z.literal('meeting'),\n items: z.array(z.object({\n key: z.string(),\n label: z.string(),\n labelKey: z.string().optional(),\n icon: z.string().nullable().optional(),\n color: z.string().nullable().optional(),\n behavior: calendarEventTypeBehaviorSchema,\n selectable: z.boolean(),\n panelKey: z.string().optional(),\n source: z.string(),\n provenance: z.record(z.string(), z.unknown()),\n historical: z.boolean(),\n fallbackReason: z.enum(['tombstoned', 'module-unavailable', 'unknown']).optional(),\n adminConfigurable: z.boolean(),\n isInherited: z.boolean(),\n isLocalOverride: z.boolean(),\n updatedAt: z.string().nullable(),\n missingCustomFieldsetIds: z.array(z.string()),\n inactiveDictionaryOverride: z.boolean().optional(),\n })),\n})\n\nexport const metadata = {\n GET: { requireAuth: true },\n}\n\nexport async function GET(req: Request) {\n try {\n const url = new URL(req.url)\n const query = querySchema.parse({ organizationId: url.searchParams.get('organizationId') ?? undefined })\n const context = await resolveDictionaryRouteContext(req, { selectedId: query.organizationId })\n if (!context.organizationId) {\n return NextResponse.json({ error: context.translate('customers.errors.organization_required', 'Organization context is required') }, { status: 400 })\n }\n const organizationId = context.organizationId\n const rbac = context.container.resolve('rbacService') as RbacService | undefined\n const actorId = context.auth?.sub\n if (!rbac || !actorId) {\n throw new CrudHttpError(403, { error: context.translate('customers.calendar.activityTypes.errors.forbidden', 'You do not have permission to view activity types.') })\n }\n const permissionScope = { tenantId: context.tenantId, organizationId }\n const canViewInteractions = await rbac.userHasAllFeatures(actorId, ['customers.interactions.view'], permissionScope)\n const canManageSettings = canViewInteractions || await rbac.userHasAllFeatures(actorId, ['customers.settings.manage'], permissionScope)\n if (!canManageSettings) {\n throw new CrudHttpError(403, { error: context.translate('customers.calendar.activityTypes.errors.forbidden', 'You do not have permission to view activity types.') })\n }\n const hierarchy = context.container.resolve('organizationHierarchyService') as OrganizationHierarchyService\n const ancestors = await hierarchy.resolveAncestorIds({ tenantId: context.tenantId, organizationId })\n if (ancestors === null) {\n throw new CrudHttpError(403, { error: context.translate('customers.errors.organization_forbidden', 'Organization not accessible') })\n }\n const scopeIds = Array.from(new Set([organizationId, ...ancestors.slice().reverse()]))\n const cacheKey = `customers:activity-types:${context.tenantId}:org=${organizationId}:scope=${scopeIds.join('|')}:widgets=${getInjectionRegistryVersion()}:registry=${getCalendarEventTypeRegistryVersion()}`\n const cached = await context.cache?.get(cacheKey)\n if (cached) return NextResponse.json(cached)\n\n let catalog\n try {\n catalog = await resolveScopedCalendarEventTypes({\n em: context.em,\n tenantId: context.tenantId,\n organizationId,\n readableOrganizationIds: scopeIds,\n })\n } catch (err) {\n logger.error('customers.activity_types.resolve failed', {\n err,\n tenantId: context.tenantId,\n organizationId,\n })\n reportActivityTypeError(err, 'customers.activity_type_catalog_resolution_failed', {\n tenantId: context.tenantId,\n organizationId,\n })\n return NextResponse.json({\n error: context.translate('customers.calendar.activityTypes.errors.loadFailed', 'Failed to load activity types'),\n code: 'activity_type_catalog_unavailable',\n }, { status: 503 })\n }\n if (context.cache) {\n await context.cache.set(cacheKey, catalog, {\n ttl: DICTIONARY_CACHE_TTL_MS,\n tags: createDictionaryCacheTags({\n tenantId: context.tenantId,\n mappedKind: 'activity_type',\n organizationIds: scopeIds,\n }),\n }).catch((err) => {\n logger.warn('customers.activity_types cache write failed', { err })\n reportActivityTypeError(err, 'customers.activity_type_catalog_cache_write_failed', {\n tenantId: context.tenantId,\n organizationId,\n })\n })\n }\n return NextResponse.json(catalog)\n } catch (err) {\n if (isCrudHttpError(err)) return NextResponse.json(err.body, { status: err.status })\n logger.error('customers.activity_types request failed', { err })\n reportActivityTypeError(err, 'customers.activity_type_catalog_request_failed')\n const { translate } = await resolveTranslations()\n return NextResponse.json({\n error: translate('customers.calendar.activityTypes.errors.loadFailed', 'Failed to load activity types'),\n }, { status: err instanceof z.ZodError ? 400 : 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Effective calendar activity types',\n methods: {\n GET: {\n summary: 'List effective calendar activity types',\n description: 'Returns the tenant and organization scoped calendar activity-type catalog. Requires customers.interactions.view or customers.settings.manage.',\n responses: [{ status: 200, description: 'Effective activity-type catalog', schema: responseSchema }],\n errors: [\n { status: 400, description: 'Organization scope is required', schema: z.object({ error: z.string() }) },\n { status: 401, description: 'Unauthorized', schema: z.object({ error: z.string() }) },\n { status: 403, description: 'Forbidden', schema: z.object({ error: z.string() }) },\n { status: 500, description: 'Unexpected server error', schema: z.object({ error: z.string() }) },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,uBAAuB;AAChC,SAAS,qBAAqB;AAG9B,SAAS,oBAAoB;AAC7B,SAAS,2BAA2B;AACpC,SAAS,2BAA2B;AACpC,SAAS,qCAAqC;AAC9C,SAAS,2BAA2B,+BAA+B;AACnE,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,OACK;AACP,SAAS,uCAAuC;AAChD,SAAS,2CAA2C;AAEpD,MAAM,SAAS,aAAa,WAAW;AAEvC,SAAS,wBAAwB,OAAgB,MAAc,YAA2C;AACxG,MA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E,QAAQ,IAAI,OAAO,CAAC;AACnF,WAAO,MAAM,2CAA2C,EAAE,IAAI,CAAC;AAC/D,4BAAwB,KAAK,gDAAgD;AAC7E,UAAM,EAAE,UAAU,IAAI,MAAM,oBAAoB;AAChD,WAAO,aAAa,KAAK;AAAA,MACvB,OAAO,UAAU,sDAAsD,+BAA+B;AAAA,IACxG,GAAG,EAAE,QAAQ,eAAe,EAAE,WAAW,MAAM,IAAI,CAAC;AAAA,EACtD;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,CAAC,EAAE,QAAQ,KAAK,aAAa,mCAAmC,QAAQ,eAAe,CAAC;AAAA,MACnG,QAAQ;AAAA,QACN,EAAE,QAAQ,KAAK,aAAa,kCAAkC,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACtG,EAAE,QAAQ,KAAK,aAAa,gBAAgB,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACpF,EAAE,QAAQ,KAAK,aAAa,aAAa,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,QACjF,EAAE,QAAQ,KAAK,aAAa,2BAA2B,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE;AAAA,MACjG;AAAA,IACF;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -8,7 +8,11 @@ import { resolveSingleOrganizationIdOrDeny } from "@open-mercato/core/modules/di
8
8
  import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
9
9
  import { findOneWithDecryption, findWithDecryption } from "@open-mercato/shared/lib/encryption/find";
10
10
  import { isOrganizationReadAccessAllowed } from "@open-mercato/core/modules/directory/utils/organizationScopeGuard";
11
- import { CustomerDeal, CustomerDealPersonLink } from "../../../../data/entities.js";
11
+ import {
12
+ CustomerDeal,
13
+ CustomerDealPersonLink,
14
+ CustomerPersonProfile
15
+ } from "../../../../data/entities.js";
12
16
  import { createLogger } from "@open-mercato/shared/lib/logger";
13
17
  const logger = createLogger("customers");
14
18
  const paramsSchema = z.object({
@@ -28,7 +32,17 @@ function normalizeSort(sort) {
28
32
  function matchesSearch(item, query) {
29
33
  const normalized = query.trim().toLowerCase();
30
34
  if (!normalized.length) return true;
31
- return [item.label, item.subtitle].filter((value) => typeof value === "string" && value.length > 0).some((value) => value.toLowerCase().includes(normalized));
35
+ return [
36
+ item.label,
37
+ item.subtitle,
38
+ item.primaryEmail,
39
+ item.primaryPhone,
40
+ item.jobTitle,
41
+ item.department,
42
+ item.status,
43
+ item.lifecycleStage,
44
+ item.source
45
+ ].filter((value) => typeof value === "string" && value.length > 0).some((value) => value.toLowerCase().includes(normalized));
32
46
  }
33
47
  function sortItems(items, sort) {
34
48
  if (sort === "recent") {
@@ -87,16 +101,44 @@ async function GET(req, ctx) {
87
101
  { populate: ["person"] },
88
102
  entityScope
89
103
  );
104
+ const personIds = links.map((link) => link.person?.id).filter((personId) => typeof personId === "string" && personId.length > 0);
105
+ const profiles = personIds.length > 0 ? await findWithDecryption(
106
+ em,
107
+ CustomerPersonProfile,
108
+ {
109
+ entity: { $in: personIds },
110
+ tenantId: deal.tenantId,
111
+ organizationId: deal.organizationId
112
+ },
113
+ {},
114
+ entityScope
115
+ ) : [];
116
+ const profileByPersonId = new Map(
117
+ profiles.map((profile) => [profile.entity.id, profile])
118
+ );
90
119
  const items = links.map((link) => {
91
120
  const person = link.person;
92
121
  if (!person?.id) return null;
122
+ const profile = profileByPersonId.get(person.id) ?? null;
123
+ const displayName = person.displayName ?? person.primaryEmail ?? person.id;
93
124
  return {
94
125
  id: person.id,
95
- label: person.displayName ?? person.primaryEmail ?? person.id,
126
+ label: displayName,
96
127
  subtitle: person.primaryEmail ?? person.primaryPhone ?? null,
97
128
  kind: "person",
98
129
  linkedAt: link.createdAt.toISOString(),
99
- isPrimary: link.isPrimary === true
130
+ isPrimary: link.isPrimary === true,
131
+ displayName,
132
+ primaryEmail: person.primaryEmail ?? null,
133
+ primaryPhone: person.primaryPhone ?? null,
134
+ status: person.status ?? null,
135
+ lifecycleStage: person.lifecycleStage ?? null,
136
+ jobTitle: profile?.jobTitle ?? null,
137
+ department: profile?.department ?? null,
138
+ createdAt: person.createdAt.toISOString(),
139
+ organizationId: person.organizationId,
140
+ temperature: person.temperature ?? null,
141
+ source: person.source ?? null
100
142
  };
101
143
  }).filter((item) => item !== null);
102
144
  const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? "")) : items;
@@ -138,7 +180,18 @@ const openApi = {
138
180
  subtitle: z.string().nullable(),
139
181
  kind: z.literal("person"),
140
182
  linkedAt: z.string(),
141
- isPrimary: z.boolean()
183
+ isPrimary: z.boolean(),
184
+ displayName: z.string(),
185
+ primaryEmail: z.string().nullable(),
186
+ primaryPhone: z.string().nullable(),
187
+ status: z.string().nullable(),
188
+ lifecycleStage: z.string().nullable(),
189
+ jobTitle: z.string().nullable(),
190
+ department: z.string().nullable(),
191
+ createdAt: z.string(),
192
+ organizationId: z.string().uuid().nullable(),
193
+ temperature: z.string().nullable(),
194
+ source: z.string().nullable()
142
195
  })
143
196
  ),
144
197
  total: z.number().int().nonnegative(),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../../src/modules/customers/api/deals/%5Bid%5D/people/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport { CustomerDeal, CustomerDealPersonLink, CustomerEntity } from '../../../../data/entities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealPersonItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'person'\n linkedAt: string\n isPrimary: boolean\n}\n\nfunction matchesSearch(item: DealPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [item.label, item.subtitle]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealPersonItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: resolveSingleOrganizationIdOrDeny(scope, auth) ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw notFound(translate('customers.errors.deal_not_found', 'Deal not found'))\n }\n\n // Existence oracle (#5504): deny a cross-org read as not-found \u2014 identical to\n // the parent-not-found above \u2014 so it cannot reveal that a deal exists in an\n // organization the caller cannot see.\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: deal.organizationId })) {\n throw notFound(translate('customers.errors.deal_not_found', 'Deal not found'))\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal.id },\n { populate: ['person'] },\n entityScope,\n )\n\n const items = links\n .map((link) => {\n const person = link.person as CustomerEntity | null\n if (!person?.id) return null\n return {\n id: person.id,\n label: person.displayName ?? person.primaryEmail ?? person.id,\n subtitle: person.primaryEmail ?? person.primaryPhone ?? null,\n kind: 'person',\n linkedAt: link.createdAt.toISOString(),\n isPrimary: link.isPrimary === true,\n } satisfies DealPersonItem\n })\n .filter((item): item is DealPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n logger.error('customers.deals.people.GET', { err: error })\n return NextResponse.json({ error: translate('customers.errors.deal_people_load_failed', 'Failed to load linked people') }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked people for a deal',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked people',\n schema: z.object({\n items: z.array(\n z.object({\n id: z.string().uuid(),\n label: z.string(),\n subtitle: z.string().nullable(),\n kind: z.literal('person'),\n linkedAt: z.string(),\n isPrimary: z.boolean(),\n }),\n ),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,eAAe,iBAAiB,gBAAgB;AACzD,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,SAAS,2BAA2B;AAEpC,SAAS,uBAAuB,0BAA0B;AAC1D,SAAS,uCAAuC;AAChD,SAAS,cAAc,8BAA8C;AACrE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAEvC,MAAM,eAAe,EAAE,OAAO;AA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AAA,MAChB;AAAA,IACF,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,gBAAgB,KAAK,GAAG;AAC1B,aAAO,aAAa,KAAK,MAAM,MAAM,EAAE,QAAQ,MAAM,OAAO,CAAC;AAAA,IAC/D;AACA,WAAO,MAAM,8BAA8B,EAAE,KAAK,MAAM,CAAC;AACzD,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,4CAA4C,8BAA8B,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EAC5I;AACF;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AAAA,EACL,SAAS;AAAA,IACP,KAAK;AAAA,MACH,SAAS;AAAA,MACT,OAAO;AAAA,MACP,WAAW;AAAA,QACT;AAAA,UACE,QAAQ;AAAA,UACR,aAAa;AAAA,UACb,QAAQ,EAAE,OAAO;AAAA,YACf,OAAO,EAAE;AAAA,cACP,EAAE,OAAO;AAAA,gBACP,IAAI,EAAE,OAAO,EAAE,KAAK;AAAA,gBACpB,OAAO,EAAE,OAAO;AAAA,gBAChB,UAAU,EAAE,OAAO,EAAE,SAAS;AAAA,gBAC9B,MAAM,EAAE,QAAQ,QAAQ;AAAA,gBACxB,UAAU,EAAE,OAAO;AAAA,gBACnB,WAAW,EAAE,QAAQ;AAAA,cACvB,CAAC;AAAA,YACH;AAAA,YACA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError, isCrudHttpError, notFound } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveSingleOrganizationIdOrDeny } from '@open-mercato/core/modules/directory/utils/organizationScopeFilter'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findOneWithDecryption, findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { isOrganizationReadAccessAllowed } from '@open-mercato/core/modules/directory/utils/organizationScopeGuard'\nimport {\n CustomerDeal,\n CustomerDealPersonLink,\n CustomerEntity,\n CustomerPersonProfile,\n} from '../../../../data/entities'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['label-asc', 'label-desc', 'name-asc', 'name-desc', 'recent']).default('label-asc'),\n})\n\ntype DealLinkedEntitySort = 'label-asc' | 'label-desc' | 'recent'\n\nfunction normalizeSort(sort: z.infer<typeof querySchema>['sort']): DealLinkedEntitySort {\n if (sort === 'name-asc') return 'label-asc'\n if (sort === 'name-desc') return 'label-desc'\n return sort\n}\n\ntype DealPersonItem = {\n id: string\n label: string\n subtitle: string | null\n kind: 'person'\n linkedAt: string\n isPrimary: boolean\n // Added for the shared linked-people card, which renders the same shape the company\n // endpoint already returns. Purely additive: every key above keeps its meaning, so\n // `DealLinkedEntitiesTab` and any third-party consumer are unaffected.\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n status: string | null\n lifecycleStage: string | null\n jobTitle: string | null\n department: string | null\n createdAt: string\n organizationId: string\n temperature: string | null\n source: string | null\n}\n\nfunction matchesSearch(item: DealPersonItem, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [\n item.label,\n item.subtitle,\n item.primaryEmail,\n item.primaryPhone,\n item.jobTitle,\n item.department,\n item.status,\n item.lifecycleStage,\n item.source,\n ]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nfunction sortItems(items: DealPersonItem[], sort: 'label-asc' | 'label-desc' | 'recent'): DealPersonItem[] {\n if (sort === 'recent') {\n return [...items].sort((left, right) => {\n const compare = new Date(right.linkedAt).getTime() - new Date(left.linkedAt).getTime()\n if (compare !== 0) return compare\n return left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n })\n }\n return [...items].sort((left, right) => {\n const compare = left.label.localeCompare(right.label, undefined, { sensitivity: 'base' })\n return sort === 'label-asc' ? compare : -compare\n })\n}\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view'] },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) throw new CrudHttpError(401, { error: 'Unauthorized' })\n\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n const decryptionScope = {\n tenantId: auth.tenantId,\n organizationId: resolveSingleOrganizationIdOrDeny(scope, auth) ?? null,\n }\n\n const deal = await findOneWithDecryption(\n em,\n CustomerDeal,\n { id, tenantId: auth.tenantId, deletedAt: null },\n {},\n decryptionScope,\n )\n if (!deal) {\n throw notFound(translate('customers.errors.deal_not_found', 'Deal not found'))\n }\n\n // Existence oracle (#5504): deny a cross-org read as not-found \u2014 identical to\n // the parent-not-found above \u2014 so it cannot reveal that a deal exists in an\n // organization the caller cannot see.\n if (!isOrganizationReadAccessAllowed({ scope, auth, organizationId: deal.organizationId })) {\n throw notFound(translate('customers.errors.deal_not_found', 'Deal not found'))\n }\n\n const entityScope = { tenantId: deal.tenantId, organizationId: deal.organizationId }\n const links = await findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: deal.id },\n { populate: ['person'] },\n entityScope,\n )\n\n // One batched read for the profile-only columns, keyed by every linked person \u2014 not one\n // query per row. The handler filters, sorts and paginates in memory below, so the batch\n // covers the whole link set rather than the page; that is fine at the expected scale of\n // tens of contacts per deal, and the in-memory pipeline is what to revisit first if it\n // ever is not.\n const personIds = links\n .map((link) => (link.person as CustomerEntity | null)?.id)\n .filter((personId): personId is string => typeof personId === 'string' && personId.length > 0)\n\n const profiles = personIds.length > 0\n ? await findWithDecryption(\n em,\n CustomerPersonProfile,\n {\n entity: { $in: personIds },\n tenantId: deal.tenantId,\n organizationId: deal.organizationId,\n },\n {},\n entityScope,\n )\n : []\n const profileByPersonId = new Map(\n profiles.map((profile) => [(profile.entity as { id: string }).id, profile]),\n )\n\n const items = links\n .map((link) => {\n const person = link.person as CustomerEntity | null\n if (!person?.id) return null\n const profile = profileByPersonId.get(person.id) ?? null\n const displayName = person.displayName ?? person.primaryEmail ?? person.id\n return {\n id: person.id,\n label: displayName,\n subtitle: person.primaryEmail ?? person.primaryPhone ?? null,\n kind: 'person',\n linkedAt: link.createdAt.toISOString(),\n isPrimary: link.isPrimary === true,\n displayName,\n primaryEmail: person.primaryEmail ?? null,\n primaryPhone: person.primaryPhone ?? null,\n status: person.status ?? null,\n lifecycleStage: person.lifecycleStage ?? null,\n jobTitle: profile?.jobTitle ?? null,\n department: profile?.department ?? null,\n createdAt: person.createdAt.toISOString(),\n organizationId: person.organizationId,\n temperature: person.temperature ?? null,\n source: person.source ?? null,\n } satisfies DealPersonItem\n })\n .filter((item): item is DealPersonItem => item !== null)\n\n const filtered = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? '')) : items\n const sorted = sortItems(filtered, normalizeSort(query.sort))\n const total = sorted.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sorted.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (error) {\n if (isCrudHttpError(error)) {\n return NextResponse.json(error.body, { status: error.status })\n }\n logger.error('customers.deals.people.GET', { err: error })\n return NextResponse.json({ error: translate('customers.errors.deal_people_load_failed', 'Failed to load linked people') }, { status: 500 })\n }\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked people for a deal',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Paginated linked people',\n schema: z.object({\n items: z.array(\n z.object({\n id: z.string().uuid(),\n label: z.string(),\n subtitle: z.string().nullable(),\n kind: z.literal('person'),\n linkedAt: z.string(),\n isPrimary: z.boolean(),\n displayName: z.string(),\n primaryEmail: z.string().nullable(),\n primaryPhone: z.string().nullable(),\n status: z.string().nullable(),\n lifecycleStage: z.string().nullable(),\n jobTitle: z.string().nullable(),\n department: z.string().nullable(),\n createdAt: z.string(),\n organizationId: z.string().uuid().nullable(),\n temperature: z.string().nullable(),\n source: z.string().nullable(),\n }),\n ),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,eAAe,iBAAiB,gBAAgB;AACzD,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,yCAAyC;AAClD,SAAS,2BAA2B;AAEpC,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AA,YACA,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY;AAAA,YACpC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAC5B,UAAU,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,YAChC,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA,UACpC,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -14,6 +14,7 @@ import {
14
14
  } from "@open-mercato/shared/lib/crud/mutation-guard";
15
15
  import { createLogger } from "@open-mercato/shared/lib/logger";
16
16
  import { getCommandInterceptorHttpRejection } from "@open-mercato/shared/lib/commands/errors";
17
+ import { calendarEventTypeBehaviorSchema } from "../../../../calendar-event-types.js";
17
18
  const logger = createLogger("customers");
18
19
  const paramsSchema = z.object({
19
20
  id: z.string().uuid()
@@ -22,8 +23,9 @@ const patchSchema = z.object({
22
23
  value: z.string().trim().min(1).max(150).optional(),
23
24
  label: z.string().trim().max(150).optional(),
24
25
  color: z.union([z.string().trim(), z.null()]).optional(),
25
- icon: z.union([z.string().trim(), z.null()]).optional()
26
- }).refine((input) => input.value !== void 0 || input.label !== void 0 || input.color !== void 0 || input.icon !== void 0, {
26
+ icon: z.union([z.string().trim(), z.null()]).optional(),
27
+ behavior: calendarEventTypeBehaviorSchema.nullable().optional()
28
+ }).refine((input) => input.value !== void 0 || input.label !== void 0 || input.color !== void 0 || input.icon !== void 0 || input.behavior !== void 0, {
27
29
  message: "No changes provided"
28
30
  });
29
31
  const metadata = {
@@ -69,7 +71,8 @@ async function PATCH(req, ctx) {
69
71
  value: payload.value,
70
72
  label: payload.label,
71
73
  color: payload.color,
72
- icon: payload.icon
74
+ icon: payload.icon,
75
+ behavior: payload.behavior
73
76
  },
74
77
  ctx: routeContext.ctx
75
78
  });
@@ -92,6 +95,7 @@ async function PATCH(req, ctx) {
92
95
  )
93
96
  });
94
97
  }
98
+ if (typeof err.body.code === "string") throw err;
95
99
  throw new CrudHttpError(409, { error: routeContext.translate("customers.config.dictionaries.errors.duplicate", "An entry with this value already exists") });
96
100
  }
97
101
  if (err.status === 400) {
@@ -127,8 +131,10 @@ async function PATCH(req, ctx) {
127
131
  label: entry.label,
128
132
  color: entry.color,
129
133
  icon: entry.icon,
134
+ ...mappedKind === "activity_type" ? { behavior: entry.activityTypeBehavior ?? null } : {},
130
135
  organizationId: entry.organizationId,
131
- isInherited: false
136
+ isInherited: false,
137
+ updatedAt: entry.updatedAt
132
138
  });
133
139
  if (logEntry?.undoToken && logEntry?.id && logEntry?.commandId) {
134
140
  response.headers.set(
@@ -279,8 +285,10 @@ const dictionaryEntrySchema = z.object({
279
285
  label: z.string().nullable().optional(),
280
286
  color: z.string().nullable().optional(),
281
287
  icon: z.string().nullable().optional(),
288
+ behavior: calendarEventTypeBehaviorSchema.nullable().optional(),
282
289
  organizationId: z.string().uuid().nullable().optional(),
283
- isInherited: z.boolean().optional()
290
+ isInherited: z.boolean().optional(),
291
+ updatedAt: z.date().or(z.string()).optional()
284
292
  });
285
293
  const dictionaryDeleteResponseSchema = z.object({
286
294
  success: z.literal(true)