@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/customers/lib/calendar/mapItem.ts"],
4
- "sourcesContent": ["import { addMinutes } from 'date-fns/addMinutes'\nimport { endOfDay } from 'date-fns/endOfDay'\nimport { startOfDay } from 'date-fns/startOfDay'\nimport type {\n CalendarInteractionPayload,\n CalendarItem,\n CalendarItemStatus,\n CalendarLocationKind,\n CalendarParticipant,\n CalendarPlatform,\n} from '../../components/calendar/types'\nimport { categoryOf } from './categories'\nimport { participantActorKey } from './participantIdentity'\n\nconst DEFAULT_DURATION_MINUTES = 30\n\nfunction narrowStatus(status: string): CalendarItemStatus {\n if (status === 'done') return 'done'\n if (status === 'canceled') return 'canceled'\n return 'planned'\n}\n\nexport function detectPlatform(location: string | null): CalendarPlatform | null {\n if (!location) return null\n const normalized = location.toLowerCase()\n if (normalized.includes('zoom.us') || normalized.includes('zoom')) return 'zoom'\n if (normalized.includes('meet.google') || normalized.includes('on meet')) return 'meet'\n if (normalized.includes('slack')) return 'slack'\n if (normalized.includes('teams')) return 'teams'\n return null\n}\n\nfunction detectLocationKind(location: string | null, platform: CalendarPlatform | null): CalendarLocationKind | null {\n if (!location) return null\n const normalized = location.trim().toLowerCase()\n if (normalized.startsWith('http') || normalized.startsWith('www')) return 'url'\n if (platform) return 'platform'\n return 'venue'\n}\n\nfunction mapParticipants(payload: CalendarInteractionPayload): CalendarParticipant[] {\n const participants = payload.participants\n if (!Array.isArray(participants)) return []\n const seen = new Set<string>()\n const mapped: CalendarParticipant[] = []\n for (const participant of participants) {\n const dedupeKey = participantActorKey(participant)\n if (dedupeKey) {\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n }\n const entry: CalendarParticipant = {}\n if (typeof participant.userId === 'string') entry.userId = participant.userId\n if (typeof participant.name === 'string') entry.name = participant.name\n if (typeof participant.email === 'string') entry.email = participant.email\n if (typeof participant.status === 'string') entry.status = participant.status\n mapped.push(entry)\n }\n return mapped\n}\n\nexport function mapInteractionToCalendarItem(\n payload: CalendarInteractionPayload,\n typeColorByType: Record<string, string | null>,\n): CalendarItem | null {\n const effectiveStartRaw = payload.occurredAt ?? payload.scheduledAt ?? null\n if (!effectiveStartRaw) return null\n const parsedStart = new Date(effectiveStartRaw)\n if (Number.isNaN(parsedStart.getTime())) return null\n\n const allDay = payload.allDay === true\n const durationMinutes = payload.durationMinutes ?? DEFAULT_DURATION_MINUTES\n const start = allDay ? startOfDay(parsedStart) : parsedStart\n const end = allDay ? endOfDay(parsedStart) : addMinutes(parsedStart, durationMinutes)\n\n const location = payload.location ?? null\n const platform = detectPlatform(location)\n\n return {\n id: payload.id,\n title: payload.title ?? '',\n interactionType: payload.interactionType,\n category: categoryOf(payload.interactionType),\n status: narrowStatus(payload.status),\n start,\n end,\n allDay,\n location,\n platform,\n locationKind: detectLocationKind(location, platform),\n participants: mapParticipants(payload),\n ownerUserId: payload.ownerUserId ?? null,\n entityId: payload.entityId ?? null,\n dealId: payload.dealId ?? null,\n color: payload.appearanceColor ?? typeColorByType[payload.interactionType] ?? null,\n isRecurringOccurrence: false,\n updatedAt: payload.updatedAt ?? null,\n raw: payload,\n }\n}\n"],
5
- "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAS3B,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AAEpC,MAAM,2BAA2B;AA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;AACA,SAAO;AACT;AAEO,SAAS,6BACd,SACA,iBACqB;AACrB,QAAM,oBAAoB,QAAQ,cAAc,QAAQ,eAAe;AACvE,MAAI,CAAC,kBAAmB,QAAO;AAC/B,QAAM,cAAc,IAAI,KAAK,iBAAiB;AAC9C,MAAI,OAAO,MAAM,YAAY,QAAQ,CAAC,EAAG,QAAO;AAEhD,QAAM,SAAS,QAAQ,WAAW;AAClC,QAAM,kBAAkB,QAAQ,mBAAmB;AACnD,QAAM,QAAQ,SAAS,WAAW,WAAW,IAAI;AACjD,QAAM,MAAM,SAAS,SAAS,WAAW,IAAI,WAAW,aAAa,eAAe;AAEpF,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,WAAW,eAAe,QAAQ;AAExC,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,OAAO,QAAQ,SAAS;AAAA,IACxB,iBAAiB,QAAQ;AAAA,IACzB,UAAU,WAAW,QAAQ,eAAe;AAAA,IAC5C,QAAQ,aAAa,QAAQ,MAAM;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,mBAAmB,UAAU,QAAQ;AAAA,IACnD,cAAc,gBAAgB,OAAO;AAAA,IACrC,aAAa,QAAQ,eAAe;AAAA,IACpC,UAAU,QAAQ,YAAY;AAAA,IAC9B,QAAQ,QAAQ,UAAU;AAAA,IAC1B,OAAO,QAAQ,mBAAmB,gBAAgB,QAAQ,eAAe,KAAK;AAAA,IAC9E,uBAAuB;AAAA,IACvB,WAAW,QAAQ,aAAa;AAAA,IAChC,KAAK;AAAA,EACP;AACF;",
4
+ "sourcesContent": ["import { addMinutes } from 'date-fns/addMinutes'\nimport { endOfDay } from 'date-fns/endOfDay'\nimport { startOfDay } from 'date-fns/startOfDay'\nimport type {\n CalendarInteractionPayload,\n CalendarItem,\n CalendarItemStatus,\n CalendarLocationKind,\n CalendarParticipant,\n CalendarPlatform,\n} from '../../components/calendar/types'\nimport { categoryOf } from './categories'\nimport { participantActorKey } from './participantIdentity'\nimport { calendarDayEndInstant, calendarDayStartInstant, calendarInstantToWallTime, isCalendarTimezone } from './timezone'\n\nconst DEFAULT_DURATION_MINUTES = 30\n\nfunction narrowStatus(status: string): CalendarItemStatus {\n if (status === 'done') return 'done'\n if (status === 'canceled') return 'canceled'\n return 'planned'\n}\n\nexport function detectPlatform(location: string | null): CalendarPlatform | null {\n if (!location) return null\n const normalized = location.toLowerCase()\n if (normalized.includes('zoom.us') || normalized.includes('zoom')) return 'zoom'\n if (normalized.includes('meet.google') || normalized.includes('on meet')) return 'meet'\n if (normalized.includes('slack')) return 'slack'\n if (normalized.includes('teams')) return 'teams'\n return null\n}\n\nfunction detectLocationKind(location: string | null, platform: CalendarPlatform | null): CalendarLocationKind | null {\n if (!location) return null\n const normalized = location.trim().toLowerCase()\n if (normalized.startsWith('http') || normalized.startsWith('www')) return 'url'\n if (platform) return 'platform'\n return 'venue'\n}\n\nfunction mapParticipants(payload: CalendarInteractionPayload): CalendarParticipant[] {\n const participants = payload.participants\n if (!Array.isArray(participants)) return []\n const seen = new Set<string>()\n const mapped: CalendarParticipant[] = []\n for (const participant of participants) {\n const dedupeKey = participantActorKey(participant)\n if (dedupeKey) {\n if (seen.has(dedupeKey)) continue\n seen.add(dedupeKey)\n }\n const entry: CalendarParticipant = {}\n if (typeof participant.userId === 'string') entry.userId = participant.userId\n if (typeof participant.name === 'string') entry.name = participant.name\n if (typeof participant.email === 'string') entry.email = participant.email\n if (typeof participant.status === 'string') entry.status = participant.status\n mapped.push(entry)\n }\n return mapped\n}\n\nexport function mapInteractionToCalendarItem(\n payload: CalendarInteractionPayload,\n typeColorByType: Record<string, string | null>,\n): CalendarItem | null {\n const effectiveStartRaw = payload.occurredAt ?? payload.scheduledAt ?? null\n if (!effectiveStartRaw) return null\n const parsedStart = new Date(effectiveStartRaw)\n if (Number.isNaN(parsedStart.getTime())) return null\n\n const allDay = payload.allDay === true\n const durationMinutes = payload.durationMinutes ?? DEFAULT_DURATION_MINUTES\n const eventDate = allDay && isCalendarTimezone(payload.timezone) ? calendarInstantToWallTime(parsedStart, payload.timezone).date : null\n const start = eventDate ? calendarDayStartInstant(eventDate, payload.timezone as string) : allDay ? startOfDay(parsedStart) : parsedStart\n const end = eventDate ? calendarDayEndInstant(eventDate, payload.timezone as string) : allDay ? endOfDay(parsedStart) : addMinutes(parsedStart, durationMinutes)\n\n if (!start || !end) return null\n\n const location = payload.location ?? null\n const platform = detectPlatform(location)\n\n return {\n id: payload.id,\n title: payload.title ?? '',\n interactionType: payload.interactionType,\n category: categoryOf(payload.interactionType),\n status: narrowStatus(payload.status),\n start,\n end,\n allDay,\n location,\n platform,\n locationKind: detectLocationKind(location, platform),\n participants: mapParticipants(payload),\n ownerUserId: payload.ownerUserId ?? null,\n entityId: payload.entityId ?? null,\n dealId: payload.dealId ?? null,\n color: payload.appearanceColor ?? typeColorByType[payload.interactionType] ?? null,\n isRecurringOccurrence: false,\n updatedAt: payload.updatedAt ?? null,\n raw: payload,\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,kBAAkB;AAC3B,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAS3B,SAAS,kBAAkB;AAC3B,SAAS,2BAA2B;AACpC,SAAS,uBAAuB,yBAAyB,2BAA2B,0BAA0B;AAE9G,MAAM,2BAA2B;AAEjC,SAAS,aAAa,QAAoC;AACxD,MAAI,WAAW,OAAQ,QAAO;AAC9B,MAAI,WAAW,WAAY,QAAO;AAClC,SAAO;AACT;AAEO,SAAS,eAAe,UAAkD;AAC/E,MAAI,CAAC,SAAU,QAAO;AACtB,QAAM,aAAa,SAAS,YAAY;AACxC,MAAI,WAAW,SAAS,SAAS,KAAK,WAAW,SAAS,MAAM,EAAG,QAAO;AAC1E,MAAI,WAAW,SAAS,aAAa,KAAK,WAAW,SAAS,SAAS,EAAG,QAAO;AACjF,MAAI,WAAW,SAAS,OAAO,EAAG,QAAO;AACzC,MAAI,WAAW,SAAS,OAAO,EAAG,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,YAAY,wBAAwB,WAAW,QAAQ,QAAkB,IAAI,SAAS,WAAW,WAAW,IAAI;AAC9H,QAAM,MAAM,YAAY,sBAAsB,WAAW,QAAQ,QAAkB,IAAI,SAAS,SAAS,WAAW,IAAI,WAAW,aAAa,eAAe;AAE/J,MAAI,CAAC,SAAS,CAAC,IAAK,QAAO;AAE3B,QAAM,WAAW,QAAQ,YAAY;AACrC,QAAM,WAAW,eAAe,QAAQ;AAExC,SAAO;AAAA,IACL,IAAI,QAAQ;AAAA,IACZ,OAAO,QAAQ,SAAS;AAAA,IACxB,iBAAiB,QAAQ;AAAA,IACzB,UAAU,WAAW,QAAQ,eAAe;AAAA,IAC5C,QAAQ,aAAa,QAAQ,MAAM;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,mBAAmB,UAAU,QAAQ;AAAA,IACnD,cAAc,gBAAgB,OAAO;AAAA,IACrC,aAAa,QAAQ,eAAe;AAAA,IACpC,UAAU,QAAQ,YAAY;AAAA,IAC9B,QAAQ,QAAQ,UAAU;AAAA,IAC1B,OAAO,QAAQ,mBAAmB,gBAAgB,QAAQ,eAAe,KAAK;AAAA,IAC9E,uBAAuB;AAAA,IACvB,WAAW,QAAQ,aAAa;AAAA,IAChC,KAAK;AAAA,EACP;AACF;",
6
6
  "names": []
7
7
  }
@@ -1,5 +1,7 @@
1
1
  import { addDays } from "date-fns/addDays";
2
+ import { calendarDayEndInstant, calendarDayStartInstant, calendarInstantToWallTime, calendarRecurrenceWallTimeToInstant, isCalendarTimezone } from "./timezone.js";
2
3
  const MAX_OCCURRENCES_PER_WINDOW = 100;
4
+ const DAY_MS = 24 * 60 * 60 * 1e3;
3
5
  const WEEKDAY_TOKENS = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"];
4
6
  const UNTIL_PATTERN = /^(\d{4})(\d{2})(\d{2})T(\d{2})(\d{2})(\d{2})Z$/;
5
7
  function parseUntil(value) {
@@ -68,14 +70,66 @@ function parseRecurrenceEndTime(rawRecurrenceEnd) {
68
70
  }
69
71
  function occursOn(date, rule, seriesStartWeekday) {
70
72
  if (rule.freq === "DAILY") return true;
71
- const allowedWeekdays = rule.byDay ?? [seriesStartWeekday];
73
+ const allowedWeekdays = [...new Set(rule.byDay ?? [seriesStartWeekday])];
72
74
  return allowedWeekdays.includes(date.getDay());
73
75
  }
76
+ function countMatchingDays(startDay, endDay, rule, seriesStartWeekday) {
77
+ const dayCount = Math.max(0, endDay - startDay);
78
+ if (rule.freq === "DAILY") return dayCount;
79
+ const allowedWeekdays = [...new Set(rule.byDay ?? [seriesStartWeekday])];
80
+ const fullWeeks = Math.floor(dayCount / 7);
81
+ let matches = fullWeeks * allowedWeekdays.length;
82
+ const remainder = dayCount % 7;
83
+ const startWeekday = new Date(startDay * DAY_MS).getUTCDay();
84
+ for (let offset = 0; offset < remainder; offset += 1) {
85
+ if (allowedWeekdays.includes((startWeekday + offset) % 7)) matches += 1;
86
+ }
87
+ return matches;
88
+ }
89
+ function utcDay(date) {
90
+ return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS);
91
+ }
92
+ function expandZonedOccurrences(item, range, rule, timezone) {
93
+ const startWall = calendarInstantToWallTime(item.start, timezone);
94
+ const cursor = /* @__PURE__ */ new Date(`${startWall.date}T00:00:00Z`);
95
+ const seriesStartDay = Math.floor(cursor.getTime() / DAY_MS);
96
+ const earliestRelevant = new Date(range.from.getTime() - Math.max(0, item.end.getTime() - item.start.getTime()));
97
+ const earliestWallDate = calendarInstantToWallTime(earliestRelevant, timezone).date;
98
+ const earliestDay = Math.floor((/* @__PURE__ */ new Date(`${earliestWallDate}T00:00:00Z`)).getTime() / DAY_MS);
99
+ const finalDate = calendarInstantToWallTime(range.to, timezone).date;
100
+ const seriesWeekday = cursor.getUTCDay();
101
+ const duration = item.end.getTime() - item.start.getTime();
102
+ const recurrenceEnd = typeof item.raw.recurrenceEnd === "string" ? new Date(item.raw.recurrenceEnd).getTime() : null;
103
+ const occurrences = [];
104
+ let occurrenceIndex = 0;
105
+ if (earliestDay > seriesStartDay) {
106
+ occurrenceIndex = countMatchingDays(seriesStartDay, earliestDay, rule, seriesWeekday);
107
+ cursor.setUTCDate(cursor.getUTCDate() + earliestDay - seriesStartDay);
108
+ }
109
+ while (cursor.toISOString().slice(0, 10) <= finalDate) {
110
+ const date = cursor.toISOString().slice(0, 10);
111
+ const start = item.allDay ? calendarDayStartInstant(date, timezone) : calendarRecurrenceWallTimeToInstant(date, startWall.time, timezone);
112
+ if (start && (rule.until && start > rule.until || recurrenceEnd !== null && start.getTime() > recurrenceEnd)) break;
113
+ const matches = rule.freq === "DAILY" || (rule.byDay ?? [seriesWeekday]).includes(cursor.getUTCDay());
114
+ if (start && matches) {
115
+ if (rule.count !== null && occurrenceIndex >= rule.count) break;
116
+ const end = item.allDay ? calendarDayEndInstant(date, timezone) : new Date(start.getTime() + duration);
117
+ if (end && start <= range.to && end > range.from) {
118
+ occurrences.push({ ...item, id: `${item.id}:${occurrenceIndex}`, start, end, isRecurringOccurrence: true });
119
+ if (occurrences.length >= MAX_OCCURRENCES_PER_WINDOW) break;
120
+ }
121
+ occurrenceIndex += 1;
122
+ }
123
+ cursor.setUTCDate(cursor.getUTCDate() + 1);
124
+ }
125
+ return occurrences;
126
+ }
74
127
  function expandOccurrences(item, range) {
75
128
  const rawRule = item.raw.recurrenceRule;
76
129
  if (typeof rawRule !== "string" || rawRule.trim().length === 0) return [item];
77
130
  const rule = parseRecurrenceRule(rawRule);
78
131
  if (!rule) return [item];
132
+ if (isCalendarTimezone(item.raw.timezone)) return expandZonedOccurrences(item, range, rule, item.raw.timezone);
79
133
  const durationMs = item.end.getTime() - item.start.getTime();
80
134
  const recurrenceEndTime = parseRecurrenceEndTime(item.raw.recurrenceEnd);
81
135
  const untilTime = rule.until ? rule.until.getTime() : null;
@@ -83,6 +137,13 @@ function expandOccurrences(item, range) {
83
137
  const occurrences = [];
84
138
  let occurrenceIndex = 0;
85
139
  let cursor = new Date(item.start);
140
+ const seriesStartDay = utcDay(cursor);
141
+ const earliestRelevant = new Date(range.from.getTime() - Math.max(0, durationMs));
142
+ const earliestDay = utcDay(earliestRelevant);
143
+ if (earliestDay > seriesStartDay) {
144
+ occurrenceIndex = countMatchingDays(seriesStartDay, earliestDay, rule, seriesStartWeekday);
145
+ cursor = addDays(cursor, earliestDay - seriesStartDay);
146
+ }
86
147
  while (cursor.getTime() <= range.to.getTime()) {
87
148
  if (untilTime !== null && cursor.getTime() > untilTime) break;
88
149
  if (recurrenceEndTime !== null && cursor.getTime() > recurrenceEndTime) break;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/modules/customers/lib/calendar/recurrence.ts"],
4
- "sourcesContent": ["import { addDays } from 'date-fns/addDays'\nimport type { CalendarItem, CalendarRange } from '../../components/calendar/types'\n\nconst MAX_OCCURRENCES_PER_WINDOW = 100\n\nconst WEEKDAY_TOKENS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'] as const\n\nconst UNTIL_PATTERN = /^(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z$/\n\nexport type ParsedRecurrenceRule = {\n freq: 'DAILY' | 'WEEKLY'\n byDay: number[] | null\n count: number | null\n until: Date | null\n}\n\nfunction parseUntil(value: string): Date | null {\n const match = UNTIL_PATTERN.exec(value)\n if (!match) return null\n const [, year, month, day, hours, minutes, seconds] = match\n const parsed = new Date(\n Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hours), Number(minutes), Number(seconds)),\n )\n return Number.isNaN(parsed.getTime()) ? null : parsed\n}\n\nexport function parseRecurrenceRule(rule: string): ParsedRecurrenceRule | null {\n const parts = rule\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.length > 0)\n if (parts.length === 0) return null\n\n let freq: ParsedRecurrenceRule['freq'] | null = null\n let byDay: number[] | null = null\n let count: number | null = null\n let until: Date | null = null\n\n for (const part of parts) {\n const separatorIndex = part.indexOf('=')\n if (separatorIndex <= 0) return null\n const key = part.slice(0, separatorIndex).toUpperCase()\n const value = part.slice(separatorIndex + 1)\n if (key === 'FREQ') {\n if (value !== 'DAILY' && value !== 'WEEKLY') return null\n freq = value\n } else if (key === 'BYDAY') {\n const tokens = value\n .split(',')\n .map((token) => token.trim().toUpperCase())\n .filter((token) => token.length > 0)\n if (tokens.length === 0) return null\n const weekdays: number[] = []\n for (const token of tokens) {\n const weekday = WEEKDAY_TOKENS.indexOf(token as (typeof WEEKDAY_TOKENS)[number])\n if (weekday === -1) return null\n weekdays.push(weekday)\n }\n byDay = weekdays\n } else if (key === 'COUNT') {\n const parsedCount = Number(value)\n if (!Number.isInteger(parsedCount) || parsedCount < 1) return null\n count = parsedCount\n } else if (key === 'UNTIL') {\n const parsedUntil = parseUntil(value)\n if (!parsedUntil) return null\n until = parsedUntil\n } else {\n return null\n }\n }\n\n if (!freq) return null\n return { freq, byDay, count, until }\n}\n\nfunction parseRecurrenceEndTime(rawRecurrenceEnd: string | null | undefined): number | null {\n if (typeof rawRecurrenceEnd !== 'string' || rawRecurrenceEnd.length === 0) return null\n const parsed = new Date(rawRecurrenceEnd)\n if (Number.isNaN(parsed.getTime())) return null\n const endOfDayLocal = new Date(\n parsed.getUTCFullYear(),\n parsed.getUTCMonth(),\n parsed.getUTCDate(),\n 23,\n 59,\n 59,\n 999,\n )\n return endOfDayLocal.getTime()\n}\n\nfunction occursOn(date: Date, rule: ParsedRecurrenceRule, seriesStartWeekday: number): boolean {\n if (rule.freq === 'DAILY') return true\n const allowedWeekdays = rule.byDay ?? [seriesStartWeekday]\n return allowedWeekdays.includes(date.getDay())\n}\n\nexport function expandOccurrences(item: CalendarItem, range: CalendarRange): CalendarItem[] {\n const rawRule = item.raw.recurrenceRule\n if (typeof rawRule !== 'string' || rawRule.trim().length === 0) return [item]\n const rule = parseRecurrenceRule(rawRule)\n if (!rule) return [item]\n\n const durationMs = item.end.getTime() - item.start.getTime()\n const recurrenceEndTime = parseRecurrenceEndTime(item.raw.recurrenceEnd)\n const untilTime = rule.until ? rule.until.getTime() : null\n const seriesStartWeekday = item.start.getDay()\n\n const occurrences: CalendarItem[] = []\n let occurrenceIndex = 0\n let cursor = new Date(item.start)\n\n while (cursor.getTime() <= range.to.getTime()) {\n if (untilTime !== null && cursor.getTime() > untilTime) break\n if (recurrenceEndTime !== null && cursor.getTime() > recurrenceEndTime) break\n if (occursOn(cursor, rule, seriesStartWeekday)) {\n if (rule.count !== null && occurrenceIndex >= rule.count) break\n const occurrenceStart = new Date(cursor)\n const occurrenceEnd = new Date(occurrenceStart.getTime() + durationMs)\n if (occurrenceStart.getTime() <= range.to.getTime() && occurrenceEnd.getTime() > range.from.getTime()) {\n occurrences.push({\n ...item,\n id: `${item.id}:${occurrenceIndex}`,\n start: occurrenceStart,\n end: occurrenceEnd,\n isRecurringOccurrence: true,\n })\n if (occurrences.length >= MAX_OCCURRENCES_PER_WINDOW) break\n }\n occurrenceIndex += 1\n }\n cursor = addDays(cursor, 1)\n }\n\n return occurrences\n}\n"],
5
- "mappings": "AAAA,SAAS,eAAe;AAGxB,MAAM,6BAA6B;AAEnC,MAAM,iBAAiB,CAAC,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,IAAI;AAEhE,MAAM,gBAAgB;AAStB,SAAS,WAAW,OAA4B;AAC9C,QAAM,QAAQ,cAAc,KAAK,KAAK;AACtC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,EAAE,MAAM,OAAO,KAAK,OAAO,SAAS,OAAO,IAAI;AACtD,QAAM,SAAS,IAAI;AAAA,IACjB,KAAK,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK,IAAI,GAAG,OAAO,GAAG,GAAG,OAAO,KAAK,GAAG,OAAO,OAAO,GAAG,OAAO,OAAO,CAAC;AAAA,EACxG;AACA,SAAO,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,OAAO;AACjD;AAEO,SAAS,oBAAoB,MAA2C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,QAAQ,IAAI,kBAAmB;AACxE,QAAI,SAAS,QAAQ,MAAM,kBAAkB,GAAG;AAC9C,UAAI,KAAK,UAAU,QAAQ,mBAAmB,KAAK,MAAO;AAC1D,YAAM,kBAAkB,IAAI,KAAK,MAAM;AACvC,YAAM,gBAAgB,IAAI,KAAK,gBAAgB,QAAQ,IAAI,UAAU;AACrE,UAAI,gBAAgB,QAAQ,KAAK,MAAM,GAAG,QAAQ,KAAK,cAAc,QAAQ,IAAI,MAAM,KAAK,QAAQ,GAAG;AACrG,oBAAY,KAAK;AAAA,UACf,GAAG;AAAA,UACH,IAAI,GAAG,KAAK,EAAE,IAAI,eAAe;AAAA,UACjC,OAAO;AAAA,UACP,KAAK;AAAA,UACL,uBAAuB;AAAA,QACzB,CAAC;AACD,YAAI,YAAY,UAAU,2BAA4B;AAAA,MACxD;AACA,yBAAmB;AAAA,IACrB;AACA,aAAS,QAAQ,QAAQ,CAAC;AAAA,EAC5B;AAEA,SAAO;AACT;",
4
+ "sourcesContent": ["import { addDays } from 'date-fns/addDays'\nimport { calendarDayEndInstant, calendarDayStartInstant, calendarInstantToWallTime, calendarRecurrenceWallTimeToInstant, isCalendarTimezone } from './timezone'\nimport type { CalendarItem, CalendarRange } from '../../components/calendar/types'\n\nconst MAX_OCCURRENCES_PER_WINDOW = 100\nconst DAY_MS = 24 * 60 * 60 * 1000\n\nconst WEEKDAY_TOKENS = ['SU', 'MO', 'TU', 'WE', 'TH', 'FR', 'SA'] as const\n\nconst UNTIL_PATTERN = /^(\\d{4})(\\d{2})(\\d{2})T(\\d{2})(\\d{2})(\\d{2})Z$/\n\nexport type ParsedRecurrenceRule = {\n freq: 'DAILY' | 'WEEKLY'\n byDay: number[] | null\n count: number | null\n until: Date | null\n}\n\nfunction parseUntil(value: string): Date | null {\n const match = UNTIL_PATTERN.exec(value)\n if (!match) return null\n const [, year, month, day, hours, minutes, seconds] = match\n const parsed = new Date(\n Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hours), Number(minutes), Number(seconds)),\n )\n return Number.isNaN(parsed.getTime()) ? null : parsed\n}\n\nexport function parseRecurrenceRule(rule: string): ParsedRecurrenceRule | null {\n const parts = rule\n .split(';')\n .map((part) => part.trim())\n .filter((part) => part.length > 0)\n if (parts.length === 0) return null\n\n let freq: ParsedRecurrenceRule['freq'] | null = null\n let byDay: number[] | null = null\n let count: number | null = null\n let until: Date | null = null\n\n for (const part of parts) {\n const separatorIndex = part.indexOf('=')\n if (separatorIndex <= 0) return null\n const key = part.slice(0, separatorIndex).toUpperCase()\n const value = part.slice(separatorIndex + 1)\n if (key === 'FREQ') {\n if (value !== 'DAILY' && value !== 'WEEKLY') return null\n freq = value\n } else if (key === 'BYDAY') {\n const tokens = value\n .split(',')\n .map((token) => token.trim().toUpperCase())\n .filter((token) => token.length > 0)\n if (tokens.length === 0) return null\n const weekdays: number[] = []\n for (const token of tokens) {\n const weekday = WEEKDAY_TOKENS.indexOf(token as (typeof WEEKDAY_TOKENS)[number])\n if (weekday === -1) return null\n weekdays.push(weekday)\n }\n byDay = weekdays\n } else if (key === 'COUNT') {\n const parsedCount = Number(value)\n if (!Number.isInteger(parsedCount) || parsedCount < 1) return null\n count = parsedCount\n } else if (key === 'UNTIL') {\n const parsedUntil = parseUntil(value)\n if (!parsedUntil) return null\n until = parsedUntil\n } else {\n return null\n }\n }\n\n if (!freq) return null\n return { freq, byDay, count, until }\n}\n\nfunction parseRecurrenceEndTime(rawRecurrenceEnd: string | null | undefined): number | null {\n if (typeof rawRecurrenceEnd !== 'string' || rawRecurrenceEnd.length === 0) return null\n const parsed = new Date(rawRecurrenceEnd)\n if (Number.isNaN(parsed.getTime())) return null\n const endOfDayLocal = new Date(\n parsed.getUTCFullYear(),\n parsed.getUTCMonth(),\n parsed.getUTCDate(),\n 23,\n 59,\n 59,\n 999,\n )\n return endOfDayLocal.getTime()\n}\n\nfunction occursOn(date: Date, rule: ParsedRecurrenceRule, seriesStartWeekday: number): boolean {\n if (rule.freq === 'DAILY') return true\n const allowedWeekdays = [...new Set(rule.byDay ?? [seriesStartWeekday])]\n return allowedWeekdays.includes(date.getDay())\n}\n\nfunction countMatchingDays(startDay: number, endDay: number, rule: ParsedRecurrenceRule, seriesStartWeekday: number): number {\n const dayCount = Math.max(0, endDay - startDay)\n if (rule.freq === 'DAILY') return dayCount\n const allowedWeekdays = [...new Set(rule.byDay ?? [seriesStartWeekday])]\n const fullWeeks = Math.floor(dayCount / 7)\n let matches = fullWeeks * allowedWeekdays.length\n const remainder = dayCount % 7\n const startWeekday = new Date(startDay * DAY_MS).getUTCDay()\n for (let offset = 0; offset < remainder; offset += 1) {\n if (allowedWeekdays.includes((startWeekday + offset) % 7)) matches += 1\n }\n return matches\n}\n\nfunction utcDay(date: Date): number {\n return Math.floor(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()) / DAY_MS)\n}\n\nfunction expandZonedOccurrences(item: CalendarItem, range: CalendarRange, rule: ParsedRecurrenceRule, timezone: string): CalendarItem[] {\n const startWall = calendarInstantToWallTime(item.start, timezone)\n const cursor = new Date(`${startWall.date}T00:00:00Z`)\n const seriesStartDay = Math.floor(cursor.getTime() / DAY_MS)\n const earliestRelevant = new Date(range.from.getTime() - Math.max(0, item.end.getTime() - item.start.getTime()))\n const earliestWallDate = calendarInstantToWallTime(earliestRelevant, timezone).date\n const earliestDay = Math.floor(new Date(`${earliestWallDate}T00:00:00Z`).getTime() / DAY_MS)\n const finalDate = calendarInstantToWallTime(range.to, timezone).date\n const seriesWeekday = cursor.getUTCDay()\n const duration = item.end.getTime() - item.start.getTime()\n const recurrenceEnd = typeof item.raw.recurrenceEnd === 'string' ? new Date(item.raw.recurrenceEnd).getTime() : null\n const occurrences: CalendarItem[] = []\n let occurrenceIndex = 0\n if (earliestDay > seriesStartDay) {\n occurrenceIndex = countMatchingDays(seriesStartDay, earliestDay, rule, seriesWeekday)\n cursor.setUTCDate(cursor.getUTCDate() + earliestDay - seriesStartDay)\n }\n while (cursor.toISOString().slice(0, 10) <= finalDate) {\n const date = cursor.toISOString().slice(0, 10)\n const start = item.allDay ? calendarDayStartInstant(date, timezone) : calendarRecurrenceWallTimeToInstant(date, startWall.time, timezone)\n if (start && ((rule.until && start > rule.until) || (recurrenceEnd !== null && start.getTime() > recurrenceEnd))) break\n const matches = rule.freq === 'DAILY' || (rule.byDay ?? [seriesWeekday]).includes(cursor.getUTCDay())\n if (start && matches) {\n if (rule.count !== null && occurrenceIndex >= rule.count) break\n const end = item.allDay ? calendarDayEndInstant(date, timezone) : new Date(start.getTime() + duration)\n if (end && start <= range.to && end > range.from) {\n occurrences.push({ ...item, id: `${item.id}:${occurrenceIndex}`, start, end, isRecurringOccurrence: true })\n if (occurrences.length >= MAX_OCCURRENCES_PER_WINDOW) break\n }\n occurrenceIndex += 1\n }\n cursor.setUTCDate(cursor.getUTCDate() + 1)\n }\n return occurrences\n}\n\nexport function expandOccurrences(item: CalendarItem, range: CalendarRange): CalendarItem[] {\n const rawRule = item.raw.recurrenceRule\n if (typeof rawRule !== 'string' || rawRule.trim().length === 0) return [item]\n const rule = parseRecurrenceRule(rawRule)\n if (!rule) return [item]\n if (isCalendarTimezone(item.raw.timezone)) return expandZonedOccurrences(item, range, rule, item.raw.timezone)\n\n const durationMs = item.end.getTime() - item.start.getTime()\n const recurrenceEndTime = parseRecurrenceEndTime(item.raw.recurrenceEnd)\n const untilTime = rule.until ? rule.until.getTime() : null\n const seriesStartWeekday = item.start.getDay()\n\n const occurrences: CalendarItem[] = []\n let occurrenceIndex = 0\n let cursor = new Date(item.start)\n const seriesStartDay = utcDay(cursor)\n const earliestRelevant = new Date(range.from.getTime() - Math.max(0, durationMs))\n const earliestDay = utcDay(earliestRelevant)\n if (earliestDay > seriesStartDay) {\n occurrenceIndex = countMatchingDays(seriesStartDay, earliestDay, rule, seriesStartWeekday)\n cursor = addDays(cursor, earliestDay - seriesStartDay)\n }\n\n while (cursor.getTime() <= range.to.getTime()) {\n if (untilTime !== null && cursor.getTime() > untilTime) break\n if (recurrenceEndTime !== null && cursor.getTime() > recurrenceEndTime) break\n if (occursOn(cursor, rule, seriesStartWeekday)) {\n if (rule.count !== null && occurrenceIndex >= rule.count) break\n const occurrenceStart = new Date(cursor)\n const occurrenceEnd = new Date(occurrenceStart.getTime() + durationMs)\n if (occurrenceStart.getTime() <= range.to.getTime() && occurrenceEnd.getTime() > range.from.getTime()) {\n occurrences.push({\n ...item,\n id: `${item.id}:${occurrenceIndex}`,\n start: occurrenceStart,\n end: occurrenceEnd,\n isRecurringOccurrence: true,\n })\n if (occurrences.length >= MAX_OCCURRENCES_PER_WINDOW) break\n }\n occurrenceIndex += 1\n }\n cursor = addDays(cursor, 1)\n }\n\n return occurrences\n}\n"],
5
+ "mappings": "AAAA,SAAS,eAAe;AACxB,SAAS,uBAAuB,yBAAyB,2BAA2B,qCAAqC,0BAA0B;AAGnJ,MAAM,6BAA6B;AACnC,MAAM,SAAS,KAAK,KAAK,KAAK;AAE9B,MAAM,iBAAiB,CAAC,MAAM,MAAM,MAAM,MAAM,MAAM,MAAM,IAAI;AAEhE,MAAM,gBAAgB;AAStB,SAAS,WAAW,OAA4B;AAC9C,QAAM,QAAQ,cAAc,KAAK,KAAK;AACtC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,CAAC,EAAE,MAAM,OAAO,KAAK,OAAO,SAAS,OAAO,IAAI;AACtD,QAAM,SAAS,IAAI;AAAA,IACjB,KAAK,IAAI,OAAO,IAAI,GAAG,OAAO,KAAK,IAAI,GAAG,OAAO,GAAG,GAAG,OAAO,KAAK,GAAG,OAAO,OAAO,GAAG,OAAO,OAAO,CAAC;AAAA,EACxG;AACA,SAAO,OAAO,MAAM,OAAO,QAAQ,CAAC,IAAI,OAAO;AACjD;AAEO,SAAS,oBAAoB,MAA2C;AAC7E,QAAM,QAAQ,KACX,MAAM,GAAG,EACT,IAAI,CAAC,SAAS,KAAK,KAAK,CAAC,EACzB,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC;AACnC,MAAI,MAAM,WAA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,sBAAkB,kBAAkB,gBAAgB,aAAa,MAAM,kBAAkB;AACzF,aAAS,QAAQ,QAAQ,cAAc,cAAc;AAAA,EACvD;AAEA,SAAO,OAAO,QAAQ,KAAK,MAAM,GAAG,QAAQ,GAAG;AAC7C,QAAI,cAAc,QAAQ,OAAO,QAAQ,IAAI,UAAW;AACxD,QAAI,sBAAsB,QAAQ,OAAO,QAAQ,IAAI,kBAAmB;AACxE,QAAI,SAAS,QAAQ,MAAM,kBAAkB,GAAG;AAC9C,UAAI,KAAK,UAAU,QAAQ,mBAAmB,KAAK,MAAO;AAC1D,YAAM,kBAAkB,IAAI,KAAK,MAAM;AACvC,YAAM,gBAAgB,IAAI,KAAK,gBAAgB,QAAQ,IAAI,UAAU;AACrE,UAAI,gBAAgB,QAAQ,KAAK,MAAM,GAAG,QAAQ,KAAK,cAAc,QAAQ,IAAI,MAAM,KAAK,QAAQ,GAAG;AACrG,oBAAY,KAAK;AAAA,UACf,GAAG;AAAA,UACH,IAAI,GAAG,KAAK,EAAE,IAAI,eAAe;AAAA,UACjC,OAAO;AAAA,UACP,KAAK;AAAA,UACL,uBAAuB;AAAA,QACzB,CAAC;AACD,YAAI,YAAY,UAAU,2BAA4B;AAAA,MACxD;AACA,yBAAmB;AAAA,IACrB;AACA,aAAS,QAAQ,QAAQ,CAAC;AAAA,EAC5B;AAEA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,111 @@
1
+ const formatters = /* @__PURE__ */ new Map();
2
+ function parseWallTime(date, time) {
3
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(date) || !/^\d{2}:\d{2}$/.test(time)) return null;
4
+ const wall = /* @__PURE__ */ new Date(`${date}T${time}:00Z`);
5
+ if (!Number.isFinite(wall.getTime()) || wall.toISOString().slice(0, 16) !== `${date}T${time}`) return null;
6
+ return wall;
7
+ }
8
+ function calendarTimezoneOffsets(wall, timezone) {
9
+ const offsets = /* @__PURE__ */ new Set();
10
+ for (const hour of [-36, -12, 0, 12, 36]) {
11
+ const sample = new Date(wall.getTime() + hour * 36e5);
12
+ const local = calendarInstantToWallTime(sample, timezone);
13
+ offsets.add((/* @__PURE__ */ new Date(`${local.date}T${local.time}:00Z`)).getTime() - sample.getTime());
14
+ }
15
+ return [...offsets];
16
+ }
17
+ function isCalendarTimezone(value) {
18
+ if (typeof value !== "string" || !value.trim() || value.length > 120 || /^[+-]/.test(value)) return false;
19
+ try {
20
+ formatter(value).format();
21
+ return true;
22
+ } catch {
23
+ return false;
24
+ }
25
+ }
26
+ function canonicalCalendarTimezone(value) {
27
+ if (!isCalendarTimezone(value)) return null;
28
+ const resolved = formatter(value).resolvedOptions().timeZone;
29
+ return isCalendarTimezone(resolved) ? resolved : value;
30
+ }
31
+ function defaultCalendarTimezone() {
32
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
33
+ return isCalendarTimezone(timezone) ? timezone : "UTC";
34
+ }
35
+ function formatter(timezone) {
36
+ let result = formatters.get(timezone);
37
+ if (!result) {
38
+ result = new Intl.DateTimeFormat("en-CA", { timeZone: timezone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
39
+ if (formatters.size >= 64) formatters.delete(formatters.keys().next().value);
40
+ formatters.set(timezone, result);
41
+ }
42
+ return result;
43
+ }
44
+ function calendarInstantToWallTime(instant, timezone) {
45
+ const parts = formatter(timezone).formatToParts(instant);
46
+ const part = (name) => parts.find((entry) => entry.type === name).value;
47
+ return { date: `${part("year")}-${part("month")}-${part("day")}`, time: `${part("hour")}:${part("minute")}` };
48
+ }
49
+ function calendarWallTimeToInstant(date, time, timezone) {
50
+ if (!isCalendarTimezone(timezone)) return null;
51
+ const wall = parseWallTime(date, time);
52
+ if (!wall) return null;
53
+ const candidates = calendarTimezoneOffsets(wall, timezone).map((offset) => new Date(wall.getTime() - offset)).filter((instant) => {
54
+ const local = calendarInstantToWallTime(instant, timezone);
55
+ return local.date === date && local.time === time;
56
+ }).sort((left, right) => left.getTime() - right.getTime());
57
+ return candidates[0] ?? null;
58
+ }
59
+ function calendarRecurrenceWallTimeToInstant(date, time, timezone) {
60
+ const exact = calendarWallTimeToInstant(date, time, timezone);
61
+ if (exact) return exact;
62
+ if (!isCalendarTimezone(timezone) || !calendarDayStartInstant(date, timezone)) return null;
63
+ const wall = parseWallTime(date, time);
64
+ if (!wall) return null;
65
+ const offsets = calendarTimezoneOffsets(wall, timezone);
66
+ if (offsets.length < 2) return null;
67
+ return new Date(wall.getTime() - Math.min(...offsets));
68
+ }
69
+ function calendarDayStartInstant(date, timezone) {
70
+ if (!isCalendarTimezone(timezone) || !/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
71
+ const anchor = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
72
+ if (!Number.isFinite(anchor.getTime()) || anchor.toISOString().slice(0, 10) !== date) return null;
73
+ const midnight = calendarWallTimeToInstant(date, "00:00", timezone);
74
+ if (midnight) return midnight;
75
+ let lower = anchor.getTime() - 36 * 36e5;
76
+ let upper = anchor.getTime() + 36 * 36e5;
77
+ while (lower < upper) {
78
+ const middle = lower + Math.floor((upper - lower) / 2);
79
+ if (calendarInstantToWallTime(new Date(middle), timezone).date < date) lower = middle + 1;
80
+ else upper = middle;
81
+ }
82
+ const boundary = new Date(lower);
83
+ return calendarInstantToWallTime(boundary, timezone).date === date ? boundary : null;
84
+ }
85
+ function calendarDayEndInstant(date, timezone) {
86
+ if (!calendarDayStartInstant(date, timezone)) return null;
87
+ const nextDate = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
88
+ for (let skippedDays = 0; skippedDays < 3; skippedDays += 1) {
89
+ nextDate.setUTCDate(nextDate.getUTCDate() + 1);
90
+ const nextBoundary = calendarDayStartInstant(nextDate.toISOString().slice(0, 10), timezone);
91
+ if (nextBoundary) return new Date(nextBoundary.getTime() - 1);
92
+ }
93
+ return null;
94
+ }
95
+ function calendarTimezoneOptions(storedTimezone) {
96
+ const intl = Intl;
97
+ const stored = isCalendarTimezone(storedTimezone) ? [storedTimezone] : [];
98
+ return [.../* @__PURE__ */ new Set(["UTC", defaultCalendarTimezone(), ...stored, ...intl.supportedValuesOf?.("timeZone") ?? []])];
99
+ }
100
+ export {
101
+ calendarDayEndInstant,
102
+ calendarDayStartInstant,
103
+ calendarInstantToWallTime,
104
+ calendarRecurrenceWallTimeToInstant,
105
+ calendarTimezoneOptions,
106
+ calendarWallTimeToInstant,
107
+ canonicalCalendarTimezone,
108
+ defaultCalendarTimezone,
109
+ isCalendarTimezone
110
+ };
111
+ //# sourceMappingURL=timezone.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../src/modules/customers/lib/calendar/timezone.ts"],
4
+ "sourcesContent": ["const formatters = new Map<string, Intl.DateTimeFormat>()\n\nfunction parseWallTime(date: string, time: string): Date | null {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date) || !/^\\d{2}:\\d{2}$/.test(time)) return null\n const wall = new Date(`${date}T${time}:00Z`)\n if (!Number.isFinite(wall.getTime()) || wall.toISOString().slice(0, 16) !== `${date}T${time}`) return null\n return wall\n}\n\nfunction calendarTimezoneOffsets(wall: Date, timezone: string): number[] {\n const offsets = new Set<number>()\n for (const hour of [-36, -12, 0, 12, 36]) {\n const sample = new Date(wall.getTime() + hour * 3600000)\n const local = calendarInstantToWallTime(sample, timezone)\n offsets.add(new Date(`${local.date}T${local.time}:00Z`).getTime() - sample.getTime())\n }\n return [...offsets]\n}\n\nexport function isCalendarTimezone(value: unknown): value is string {\n if (typeof value !== 'string' || !value.trim() || value.length > 120 || /^[+-]/.test(value)) return false\n try {\n formatter(value).format()\n return true\n } catch {\n return false\n }\n}\n\n/**\n * IANA zone ids are case-insensitive, so `europe/warsaw` and `Europe/Warsaw` are\n * the same zone and would otherwise be stored \u2014 and listed \u2014 as two options.\n * Canonicalize on write so the stored value matches the catalog spelling.\n */\nexport function canonicalCalendarTimezone(value: unknown): string | null {\n if (!isCalendarTimezone(value)) return null\n const resolved = formatter(value).resolvedOptions().timeZone\n return isCalendarTimezone(resolved) ? resolved : value\n}\n\nexport function defaultCalendarTimezone(): string {\n const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone\n return isCalendarTimezone(timezone) ? timezone : 'UTC'\n}\n\nfunction formatter(timezone: string): Intl.DateTimeFormat {\n let result = formatters.get(timezone)\n if (!result) {\n result = new Intl.DateTimeFormat('en-CA', { timeZone: timezone, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hourCycle: 'h23' })\n if (formatters.size >= 64) formatters.delete(formatters.keys().next().value!)\n formatters.set(timezone, result)\n }\n return result\n}\n\nexport function calendarInstantToWallTime(instant: Date, timezone: string): { date: string; time: string } {\n const parts = formatter(timezone).formatToParts(instant)\n const part = (name: string) => parts.find((entry) => entry.type === name)!.value\n return { date: `${part('year')}-${part('month')}-${part('day')}`, time: `${part('hour')}:${part('minute')}` }\n}\n\nexport function calendarWallTimeToInstant(date: string, time: string, timezone: string): Date | null {\n if (!isCalendarTimezone(timezone)) return null\n const wall = parseWallTime(date, time)\n if (!wall) return null\n const candidates = calendarTimezoneOffsets(wall, timezone).map((offset) => new Date(wall.getTime() - offset))\n .filter((instant) => {\n const local = calendarInstantToWallTime(instant, timezone)\n return local.date === date && local.time === time\n }).sort((left, right) => left.getTime() - right.getTime())\n return candidates[0] ?? null\n}\n\nexport function calendarRecurrenceWallTimeToInstant(date: string, time: string, timezone: string): Date | null {\n const exact = calendarWallTimeToInstant(date, time, timezone)\n if (exact) return exact\n if (!isCalendarTimezone(timezone) || !calendarDayStartInstant(date, timezone)) return null\n const wall = parseWallTime(date, time)\n if (!wall) return null\n const offsets = calendarTimezoneOffsets(wall, timezone)\n if (offsets.length < 2) return null\n return new Date(wall.getTime() - Math.min(...offsets))\n}\n\nexport function calendarDayStartInstant(date: string, timezone: string): Date | null {\n if (!isCalendarTimezone(timezone) || !/^\\d{4}-\\d{2}-\\d{2}$/.test(date)) return null\n const anchor = new Date(`${date}T00:00:00Z`)\n if (!Number.isFinite(anchor.getTime()) || anchor.toISOString().slice(0, 10) !== date) return null\n const midnight = calendarWallTimeToInstant(date, '00:00', timezone)\n if (midnight) return midnight\n let lower = anchor.getTime() - 36 * 3600000\n let upper = anchor.getTime() + 36 * 3600000\n while (lower < upper) {\n const middle = lower + Math.floor((upper - lower) / 2)\n if (calendarInstantToWallTime(new Date(middle), timezone).date < date) lower = middle + 1\n else upper = middle\n }\n const boundary = new Date(lower)\n return calendarInstantToWallTime(boundary, timezone).date === date ? boundary : null\n}\n\nexport function calendarDayEndInstant(date: string, timezone: string): Date | null {\n if (!calendarDayStartInstant(date, timezone)) return null\n const nextDate = new Date(`${date}T00:00:00Z`)\n for (let skippedDays = 0; skippedDays < 3; skippedDays += 1) {\n nextDate.setUTCDate(nextDate.getUTCDate() + 1)\n const nextBoundary = calendarDayStartInstant(nextDate.toISOString().slice(0, 10), timezone)\n if (nextBoundary) return new Date(nextBoundary.getTime() - 1)\n }\n return null\n}\n\nexport function calendarTimezoneOptions(storedTimezone?: string | null): string[] {\n const intl = Intl as typeof Intl & { supportedValuesOf?: (key: 'timeZone') => string[] }\n const stored = isCalendarTimezone(storedTimezone) ? [storedTimezone] : []\n return [...new Set(['UTC', defaultCalendarTimezone(), ...stored, ...(intl.supportedValuesOf?.('timeZone') ?? [])])]\n}\n"],
5
+ "mappings": "AAAA,MAAM,aAAa,oBAAI,IAAiC;AAExD,SAAS,cAAc,MAAc,MAA2B;AAC9D,MAAI,CAAC,sBAAsB,KAAK,IAAI,KAAK,CAAC,gBAAgB,KAAK,IAAI,EAAG,QAAO;AAC7E,QAAM,OAAO,oBAAI,KAAK,GAAG,IAAI,IAAI,IAAI,MAAM;AAC3C,MAAI,CAAC,OAAO,SAAS,KAAK,QAAQ,CAAC,KAAK,KAAK,YAAY,EAAE,MAAM,GAAG,EAAE,MAAM,GAAG,IAAI,IAAI,IAAI,GAAI,QAAO;AACtG,SAAO;A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;AACb,QAAM,SAAS,mBAAmB,cAAc,IAAI,CAAC,cAAc,IAAI,CAAC;AACxE,SAAO,CAAC,GAAG,oBAAI,IAAI,CAAC,OAAO,wBAAwB,GAAG,GAAG,QAAQ,GAAI,KAAK,oBAAoB,UAAU,KAAK,CAAC,CAAE,CAAC,CAAC;AACpH;",
6
+ "names": []
7
+ }
@@ -122,6 +122,7 @@ async function hydrateCanonicalInteractions({
122
122
  appearanceColor: interaction.appearanceColor ?? null,
123
123
  source: interaction.source ?? null,
124
124
  duration: interaction.durationMinutes ?? null,
125
+ timezone: interaction.timezone ?? null,
125
126
  location: interaction.location ?? null,
126
127
  allDay: interaction.allDay ?? null,
127
128
  recurrenceRule: interaction.recurrenceRule ?? null,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/lib/interactionReadModel.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { applyResponseEnrichers } from '@open-mercato/shared/lib/crud/enricher-runner'\nimport { loadCustomFieldValues } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { normalizeCustomFieldResponse } from '@open-mercato/shared/lib/custom-fields/normalize'\nimport type { EnricherContext } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerDeal, CustomerEntity, CustomerInteraction } from '../data/entities'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport {\n CUSTOMER_INTERACTION_ENTITY_ID,\n type InteractionRecord,\n} from './interactionCompatibility'\n\ntype ContainerLike = {\n resolve: (name: string) => unknown\n}\n\ntype AuthLike = {\n tenantId: string | null\n orgId: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype RbacServiceLike = {\n getGrantedFeatures?: (\n userId: string,\n input: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n}\n\ntype HydrateCanonicalInteractionsInput = {\n em: EntityManager\n container: ContainerLike\n auth: AuthLike\n selectedOrganizationId: string | null\n interactions: CustomerInteraction[]\n enrich?: boolean\n}\n\ntype CustomerSummary = {\n id: string\n displayName: string | null\n kind: string | null\n}\n\nfunction resolveActorId(auth: AuthLike): string {\n if (typeof auth.sub === 'string' && auth.sub.trim().length > 0) return auth.sub\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId\n if (typeof auth.keyId === 'string' && auth.keyId.trim().length > 0) return auth.keyId\n return 'system'\n}\n\nfunction mergeAdditiveRecord<T extends Record<string, unknown>>(base: T, candidate: T | undefined): T {\n if (!candidate) return base\n const additions = Object.fromEntries(\n Object.entries(candidate).filter(([key]) => !(key in base)),\n ) as Partial<T>\n return {\n ...base,\n ...additions,\n }\n}\n\nfunction normalizeInteractionCustomValues(values: Record<string, unknown> | null | undefined): Record<string, unknown> | null {\n return normalizeCustomFieldResponse(values) ?? null\n}\n\nasync function resolveUserFeatures(\n container: ContainerLike,\n userId: string,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<string[] | undefined> {\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike | undefined\n if (!rbac?.getGrantedFeatures) return undefined\n return await rbac.getGrantedFeatures(userId, { tenantId, organizationId })\n } catch {\n return undefined\n }\n}\n\nexport async function buildCustomersInteractionEnricherContext(\n container: ContainerLike,\n auth: AuthLike,\n organizationId: string | null,\n): Promise<EnricherContext> {\n const userId = resolveActorId(auth)\n return {\n organizationId: organizationId ?? '',\n tenantId: auth.tenantId ?? '',\n userId,\n em: container.resolve('em'),\n container,\n userFeatures: await resolveUserFeatures(container, userId, auth.tenantId, organizationId),\n }\n}\n\nexport async function loadCustomerSummaries(\n em: EntityManager,\n entityIds: string[],\n tenantId?: string | null,\n organizationId?: string | null,\n): Promise<Map<string, CustomerSummary>> {\n if (!entityIds.length) return new Map()\n const entities = await findWithDecryption(em, CustomerEntity, { id: { $in: entityIds } }, undefined, { tenantId, organizationId })\n return new Map(\n entities.map((entity) => [\n entity.id,\n {\n id: entity.id,\n displayName: entity.displayName ?? null,\n kind: entity.kind ?? null,\n },\n ]),\n )\n}\n\nexport async function hydrateCanonicalInteractions({\n em,\n container,\n auth,\n selectedOrganizationId,\n interactions,\n enrich = false,\n}: HydrateCanonicalInteractionsInput): Promise<InteractionRecord[]> {\n if (interactions.length === 0) return []\n\n const authorIds = Array.from(\n new Set(\n interactions\n .map((interaction) =>\n typeof interaction.authorUserId === 'string' ? interaction.authorUserId : null)\n .filter((value): value is string => !!value),\n ),\n )\n const dealIds = Array.from(\n new Set(\n interactions\n .map((interaction) => (typeof interaction.dealId === 'string' ? interaction.dealId : null))\n .filter((value): value is string => !!value),\n ),\n )\n\n const tenantId = auth.tenantId ?? null\n const organizationId = selectedOrganizationId ?? null\n const [users, deals, customFieldValues] = await Promise.all([\n authorIds.length > 0 ? findWithDecryption(em, User, { id: { $in: authorIds } }, undefined, { tenantId, organizationId }) : Promise.resolve([]),\n dealIds.length > 0 ? findWithDecryption(em, CustomerDeal, { id: { $in: dealIds } }, undefined, { tenantId, organizationId }) : Promise.resolve([]),\n loadCustomFieldValues({\n em,\n entityId: CUSTOMER_INTERACTION_ENTITY_ID,\n recordIds: interactions.map((interaction) => interaction.id),\n tenantIdByRecord: Object.fromEntries(interactions.map((interaction) => [interaction.id, interaction.tenantId])),\n organizationIdByRecord: Object.fromEntries(interactions.map((interaction) => [interaction.id, interaction.organizationId])),\n tenantFallbacks: [auth.tenantId].filter((value): value is string => !!value),\n }),\n ])\n\n const userMap = new Map(\n users.map((user) => [\n user.id,\n {\n name: user.name ?? null,\n email: user.email ?? null,\n },\n ]),\n )\n const dealMap = new Map(deals.map((deal) => [deal.id, deal.title]))\n\n const baseItems: InteractionRecord[] = interactions.map((interaction) => {\n const entityId = typeof interaction.entity === 'string' ? interaction.entity : interaction.entity.id\n return {\n id: interaction.id,\n entityId,\n dealId: interaction.dealId ?? null,\n interactionType: interaction.interactionType,\n title: interaction.title ?? null,\n body: interaction.body ?? null,\n status: interaction.status,\n scheduledAt: interaction.scheduledAt ? interaction.scheduledAt.toISOString() : null,\n occurredAt: interaction.occurredAt ? interaction.occurredAt.toISOString() : null,\n priority: interaction.priority ?? null,\n authorUserId: interaction.authorUserId ?? null,\n ownerUserId: interaction.ownerUserId ?? null,\n appearanceIcon: interaction.appearanceIcon ?? null,\n appearanceColor: interaction.appearanceColor ?? null,\n source: interaction.source ?? null,\n duration: interaction.durationMinutes ?? null,\n location: interaction.location ?? null,\n allDay: interaction.allDay ?? null,\n recurrenceRule: interaction.recurrenceRule ?? null,\n recurrenceEnd: interaction.recurrenceEnd ? interaction.recurrenceEnd.toISOString() : null,\n participants: interaction.participants ?? null,\n reminderMinutes: interaction.reminderMinutes ?? null,\n visibility: interaction.visibility ?? null,\n linkedEntities: interaction.linkedEntities ?? null,\n guestPermissions: interaction.guestPermissions ?? null,\n organizationId: interaction.organizationId,\n tenantId: interaction.tenantId,\n createdAt: interaction.createdAt.toISOString(),\n updatedAt: interaction.updatedAt.toISOString(),\n authorName: interaction.authorUserId ? userMap.get(interaction.authorUserId)?.name ?? null : null,\n authorEmail: interaction.authorUserId ? userMap.get(interaction.authorUserId)?.email ?? null : null,\n dealTitle: interaction.dealId ? dealMap.get(interaction.dealId) ?? null : null,\n customValues: normalizeInteractionCustomValues(customFieldValues[interaction.id]),\n }\n })\n\n if (!enrich) return baseItems\n\n const enricherContext = await buildCustomersInteractionEnricherContext(\n container,\n auth,\n selectedOrganizationId,\n )\n const enriched = await applyResponseEnrichers(baseItems, 'customers.interaction', enricherContext)\n return baseItems.map((item, index) => mergeAdditiveRecord(item, enriched.items[index]))\n}\n"],
5
- "mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oCAAoC;AAE7C,SAAS,0BAA0B;AACnC,SAAS,cAAc,sBAA2C;AAClE,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,OAEK;AAoCP,SAAS,eAAe,MAAwB;AAC9C,MAAI,OAAO,KAAK,QAAQ,YAAY,KAAK,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,YAAY,kBAAkB;AAAA,MAC9C,iBAAiB,YAAY,mBAAmB;AAAA,MAChD,QAAQ,YAAY,UAAU;AAAA,MAC9B,UAAU,YAAY,mBAAmB;AAAA,MACzC,UAAU,YAAY,YAAY;AAAA,MAClC,QAAQ,YAAY,UAAU;AAAA,MAC9B,gBAAgB,YAAY,kBAAkB;AAAA,MAC9C,eAAe,YAAY,gBAAgB,YAAY,cAAc,YAAY,IAAI;AAAA,MACrF,cAAc,YAAY,gBAAgB;AAAA,MAC1C,iBAAiB,YAAY,mBAAmB;AAAA,MAChD,YAAY,YAAY,cAAc;AAAA,MACtC,gBAAgB,YAAY,kBAAkB;AAAA,MAC9C,kBAAkB,YAAY,oBAAoB;AAAA,MAClD,gBAAgB,YAAY;AAAA,MAC5B,UAAU,YAAY;AAAA,MACtB,WAAW,YAAY,UAAU,YAAY;AAAA,MAC7C,WAAW,YAAY,UAAU,YAAY;AAAA,MAC7C,YAAY,YAAY,eAAe,QAAQ,IAAI,YAAY,YAAY,GAAG,QAAQ,OAAO;AAAA,MAC7F,aAAa,YAAY,eAAe,QAAQ,IAAI,YAAY,YAAY,GAAG,SAAS,OAAO;AAAA,MAC/F,WAAW,YAAY,SAAS,QAAQ,IAAI,YAAY,MAAM,KAAK,OAAO;AAAA,MAC1E,cAAc,iCAAiC,kBAAkB,YAAY,EAAE,CAAC;AAAA,IAClF;AAAA,EACF,CAAC;AAED,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,kBAAkB,MAAM;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,WAAW,MAAM,uBAAuB,WAAW,yBAAyB,eAAe;AACjG,SAAO,UAAU,IAAI,CAAC,MAAM,UAAU,oBAAoB,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC;AACxF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport { applyResponseEnrichers } from '@open-mercato/shared/lib/crud/enricher-runner'\nimport { loadCustomFieldValues } from '@open-mercato/shared/lib/crud/custom-fields'\nimport { normalizeCustomFieldResponse } from '@open-mercato/shared/lib/custom-fields/normalize'\nimport type { EnricherContext } from '@open-mercato/shared/lib/crud/response-enricher'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport { CustomerDeal, CustomerEntity, CustomerInteraction } from '../data/entities'\nimport { User } from '@open-mercato/core/modules/auth/data/entities'\nimport {\n CUSTOMER_INTERACTION_ENTITY_ID,\n type InteractionRecord,\n} from './interactionCompatibility'\n\ntype ContainerLike = {\n resolve: (name: string) => unknown\n}\n\ntype AuthLike = {\n tenantId: string | null\n orgId: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype RbacServiceLike = {\n getGrantedFeatures?: (\n userId: string,\n input: { tenantId: string | null; organizationId: string | null },\n ) => Promise<string[]>\n}\n\ntype HydrateCanonicalInteractionsInput = {\n em: EntityManager\n container: ContainerLike\n auth: AuthLike\n selectedOrganizationId: string | null\n interactions: CustomerInteraction[]\n enrich?: boolean\n}\n\ntype CustomerSummary = {\n id: string\n displayName: string | null\n kind: string | null\n}\n\nfunction resolveActorId(auth: AuthLike): string {\n if (typeof auth.sub === 'string' && auth.sub.trim().length > 0) return auth.sub\n if (typeof auth.userId === 'string' && auth.userId.trim().length > 0) return auth.userId\n if (typeof auth.keyId === 'string' && auth.keyId.trim().length > 0) return auth.keyId\n return 'system'\n}\n\nfunction mergeAdditiveRecord<T extends Record<string, unknown>>(base: T, candidate: T | undefined): T {\n if (!candidate) return base\n const additions = Object.fromEntries(\n Object.entries(candidate).filter(([key]) => !(key in base)),\n ) as Partial<T>\n return {\n ...base,\n ...additions,\n }\n}\n\nfunction normalizeInteractionCustomValues(values: Record<string, unknown> | null | undefined): Record<string, unknown> | null {\n return normalizeCustomFieldResponse(values) ?? null\n}\n\nasync function resolveUserFeatures(\n container: ContainerLike,\n userId: string,\n tenantId: string | null,\n organizationId: string | null,\n): Promise<string[] | undefined> {\n try {\n const rbac = container.resolve('rbacService') as RbacServiceLike | undefined\n if (!rbac?.getGrantedFeatures) return undefined\n return await rbac.getGrantedFeatures(userId, { tenantId, organizationId })\n } catch {\n return undefined\n }\n}\n\nexport async function buildCustomersInteractionEnricherContext(\n container: ContainerLike,\n auth: AuthLike,\n organizationId: string | null,\n): Promise<EnricherContext> {\n const userId = resolveActorId(auth)\n return {\n organizationId: organizationId ?? '',\n tenantId: auth.tenantId ?? '',\n userId,\n em: container.resolve('em'),\n container,\n userFeatures: await resolveUserFeatures(container, userId, auth.tenantId, organizationId),\n }\n}\n\nexport async function loadCustomerSummaries(\n em: EntityManager,\n entityIds: string[],\n tenantId?: string | null,\n organizationId?: string | null,\n): Promise<Map<string, CustomerSummary>> {\n if (!entityIds.length) return new Map()\n const entities = await findWithDecryption(em, CustomerEntity, { id: { $in: entityIds } }, undefined, { tenantId, organizationId })\n return new Map(\n entities.map((entity) => [\n entity.id,\n {\n id: entity.id,\n displayName: entity.displayName ?? null,\n kind: entity.kind ?? null,\n },\n ]),\n )\n}\n\nexport async function hydrateCanonicalInteractions({\n em,\n container,\n auth,\n selectedOrganizationId,\n interactions,\n enrich = false,\n}: HydrateCanonicalInteractionsInput): Promise<InteractionRecord[]> {\n if (interactions.length === 0) return []\n\n const authorIds = Array.from(\n new Set(\n interactions\n .map((interaction) =>\n typeof interaction.authorUserId === 'string' ? interaction.authorUserId : null)\n .filter((value): value is string => !!value),\n ),\n )\n const dealIds = Array.from(\n new Set(\n interactions\n .map((interaction) => (typeof interaction.dealId === 'string' ? interaction.dealId : null))\n .filter((value): value is string => !!value),\n ),\n )\n\n const tenantId = auth.tenantId ?? null\n const organizationId = selectedOrganizationId ?? null\n const [users, deals, customFieldValues] = await Promise.all([\n authorIds.length > 0 ? findWithDecryption(em, User, { id: { $in: authorIds } }, undefined, { tenantId, organizationId }) : Promise.resolve([]),\n dealIds.length > 0 ? findWithDecryption(em, CustomerDeal, { id: { $in: dealIds } }, undefined, { tenantId, organizationId }) : Promise.resolve([]),\n loadCustomFieldValues({\n em,\n entityId: CUSTOMER_INTERACTION_ENTITY_ID,\n recordIds: interactions.map((interaction) => interaction.id),\n tenantIdByRecord: Object.fromEntries(interactions.map((interaction) => [interaction.id, interaction.tenantId])),\n organizationIdByRecord: Object.fromEntries(interactions.map((interaction) => [interaction.id, interaction.organizationId])),\n tenantFallbacks: [auth.tenantId].filter((value): value is string => !!value),\n }),\n ])\n\n const userMap = new Map(\n users.map((user) => [\n user.id,\n {\n name: user.name ?? null,\n email: user.email ?? null,\n },\n ]),\n )\n const dealMap = new Map(deals.map((deal) => [deal.id, deal.title]))\n\n const baseItems: InteractionRecord[] = interactions.map((interaction) => {\n const entityId = typeof interaction.entity === 'string' ? interaction.entity : interaction.entity.id\n return {\n id: interaction.id,\n entityId,\n dealId: interaction.dealId ?? null,\n interactionType: interaction.interactionType,\n title: interaction.title ?? null,\n body: interaction.body ?? null,\n status: interaction.status,\n scheduledAt: interaction.scheduledAt ? interaction.scheduledAt.toISOString() : null,\n occurredAt: interaction.occurredAt ? interaction.occurredAt.toISOString() : null,\n priority: interaction.priority ?? null,\n authorUserId: interaction.authorUserId ?? null,\n ownerUserId: interaction.ownerUserId ?? null,\n appearanceIcon: interaction.appearanceIcon ?? null,\n appearanceColor: interaction.appearanceColor ?? null,\n source: interaction.source ?? null,\n duration: interaction.durationMinutes ?? null,\n timezone: interaction.timezone ?? null,\n location: interaction.location ?? null,\n allDay: interaction.allDay ?? null,\n recurrenceRule: interaction.recurrenceRule ?? null,\n recurrenceEnd: interaction.recurrenceEnd ? interaction.recurrenceEnd.toISOString() : null,\n participants: interaction.participants ?? null,\n reminderMinutes: interaction.reminderMinutes ?? null,\n visibility: interaction.visibility ?? null,\n linkedEntities: interaction.linkedEntities ?? null,\n guestPermissions: interaction.guestPermissions ?? null,\n organizationId: interaction.organizationId,\n tenantId: interaction.tenantId,\n createdAt: interaction.createdAt.toISOString(),\n updatedAt: interaction.updatedAt.toISOString(),\n authorName: interaction.authorUserId ? userMap.get(interaction.authorUserId)?.name ?? null : null,\n authorEmail: interaction.authorUserId ? userMap.get(interaction.authorUserId)?.email ?? null : null,\n dealTitle: interaction.dealId ? dealMap.get(interaction.dealId) ?? null : null,\n customValues: normalizeInteractionCustomValues(customFieldValues[interaction.id]),\n }\n })\n\n if (!enrich) return baseItems\n\n const enricherContext = await buildCustomersInteractionEnricherContext(\n container,\n auth,\n selectedOrganizationId,\n )\n const enriched = await applyResponseEnrichers(baseItems, 'customers.interaction', enricherContext)\n return baseItems.map((item, index) => mergeAdditiveRecord(item, enriched.items[index]))\n}\n"],
5
+ "mappings": "AACA,SAAS,8BAA8B;AACvC,SAAS,6BAA6B;AACtC,SAAS,oCAAoC;AAE7C,SAAS,0BAA0B;AACnC,SAAS,cAAc,sBAA2C;AAClE,SAAS,YAAY;AACrB;AAAA,EACE;AAAA,OAEK;AAoCP,SAAS,eAAe,MAAwB;AAC9C,MAAI,OAAO,KAAK,QAAQ,YAAY,KAAK,IAAI,KAAK,EAAE,SAAS,EAAG,QAAO,KAAK;AAC5E,MAAI,OAAO,KAAK,WAAW,YAAY,KAAK,OAAO,KAAK,EAAE,SAAS,EAAG,QAAO,KAAK;AAClF,MAAI,OAAO,KAAK,UAAU,YAAY,KAAK,MAAM,KAAK,EAAE,SAAS,EAAG,QAAO,KAAK;AAChF,SAAO;AACT;AAEA,SAAS,oBAAuD,MAAS,WAA6B;AACpG,MAAI,CAAC,UAAW,QAAO;AACvB,QAAM,YAAY,OAAO;AAAA,IACvB,OAAO,QAAQ,SAAS,EAAE,OAAO,CAAC,CAAC,GAAG,MAAM,EAAE,OAAO,KAAK;AAAA,EAC5D;AACA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,EACL;AACF;AAEA,SAAS,iCAAiC,QAAoF;AAC5H,SAAO,6BAA6B,MAAM,KAAK;AACjD;AAEA,eAAe,oBACb,WACA,QACA,UACA,gBAC+B;AAC/B,MAAI;AACF,UAAM,OAAO,UAAU,QAAQ,aAAa;A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,IAAI,YAAY,YAAY,GAAG,QAAQ,OAAO;AAAA,MAC7F,aAAa,YAAY,eAAe,QAAQ,IAAI,YAAY,YAAY,GAAG,SAAS,OAAO;AAAA,MAC/F,WAAW,YAAY,SAAS,QAAQ,IAAI,YAAY,MAAM,KAAK,OAAO;AAAA,MAC1E,cAAc,iCAAiC,kBAAkB,YAAY,EAAE,CAAC;AAAA,IAClF;AAAA,EACF,CAAC;AAED,MAAI,CAAC,OAAQ,QAAO;AAEpB,QAAM,kBAAkB,MAAM;AAAA,IAC5B;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACA,QAAM,WAAW,MAAM,uBAAuB,WAAW,yBAAyB,eAAe;AACjG,SAAO,UAAU,IAAI,CAAC,MAAM,UAAU,oBAAoB,MAAM,SAAS,MAAM,KAAK,CAAC,CAAC;AACxF;",
6
6
  "names": []
7
7
  }
@@ -447,6 +447,7 @@ function mapInteractionRecordToTodoRow(interaction, customer, options) {
447
447
  todoSeverity: typeof customValues.severity === "string" && customValues.severity.trim().length > 0 ? customValues.severity.trim() : null,
448
448
  todoDescription: interaction.body ?? null,
449
449
  todoDueAt: interaction.scheduledAt ?? null,
450
+ todoTimezone: interaction.timezone ?? null,
450
451
  todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,
451
452
  todoOrganizationId: interaction.organizationId ?? null,
452
453
  todoUpdatedAt: interaction.updatedAt ?? null,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/lib/todoCompatibility.ts"],
4
- "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
- "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AA+DvC,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD;AAEA,SAAS,uCACP,iBACA,gBACS;AACT,SAAO,mBAAmB,SAAS,CAAC,mBAAmB,gBAAgB,WAAW;AACpF;AAIA,SAAS,wBAAwB,QAA2C;AAC1E,SAAO,OAAO,WAAW,YAAY,OAAO,KAAK,EAAE,SAAS,IACxD,SACA;AACN;AAEA,SAAS,iBAAiB,QAAgD;AAIxE,QAAM,aAAa,CAAC,SAAS,WAAW,QAAQ,aAAa,YAAY,WAAW,QAAQ,aAAa;AACzG,aAAW,OAAO,YAAY;AAC5B,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,GAAG;AACxD,aAAO,MAAM,KAAK;AAAA,IACpB;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,YAAY,OAA+B;AAClD,MAAI,OAAO,UAAU,YAAY,OAAO,SAAS,KAAK,EAAG,QAAO;AAChE,MAAI,OAAO,UAAU,UAAU;AAC7B,UAAM,UAAU,MAAM,KAAK;AAC3B,QAAI,CAAC,QAAQ,OAAQ,QAAO;AAC5B,UAAM,SAAS,OAAO,OAAO;AAC7B,QAAI,CAAC,OAAO,MAAM,MAAM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,UAAa,aAAa,aAAa,QAAW;AAC7E,iBAAa,WAAW,YAAY,YAAY;AAAA,EAClD;AACA,MAAI,YAAY,SAAS,UAAa,aAAa,gBAAgB,QAAW;AAC5E,iBAAa,cAAc,YAAY,QAAQ;AAAA,EACjD;AACA,MAAI,YAAY,gBAAgB,UAAa,aAAa,WAAW,QAAW;AAC9E,iBAAa,SAAS,YAAY,eAAe;AAAA,EACnD;AAEA,SAAO;AAAA,IACL,IACE,OAAO,SAAS,UAAU,YAAY,QAAQ,MAAM,KAAK,EAAE,SAAS,IAChE,QAAQ,QACR,YAAY;AAAA,IAClB,QAAQ,YAAY;AAAA,IACpB,YACE,OAAO,SAAS,eAAe,YAAY,QAAQ,WAAW,KAAK,EAAE,SAAS,IAC1E,QAAQ,aACR;AAAA,IACN,WAAW,YAAY,SAAS;AAAA,IAChC,YAAY,YAAY,WAAW;AAAA,IACnC,cAAc,YAAY,YAAY;AAAA,IACtC,cACE,OAAO,aAAa,aAAa,YAAY,aAAa,SAAS,KAAK,EAAE,SAAS,IAC/E,aAAa,SAAS,KAAK,IAC3B;AAAA,IACN,iBAAiB,YAAY,QAAQ;AAAA,IACrC,WAAW,YAAY,eAAe;AAAA,IACtC,kBAAkB,OAAO,KAAK,YAAY,EAAE,SAAS,IAAI,eAAe;AAAA,IACxE,oBAAoB,YAAY,kBAAkB;AAAA,IAClD,eAAe,YAAY,aAAa;AAAA,IACxC,gBAAgB,YAAY,kBAAkB;AAAA,IAC9C,UAAU,YAAY,YAAY;AAAA,IAClC,WAAW,YAAY;AAAA,IACvB,cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
4
+ "sourcesContent": ["import type { EntityManager } from '@mikro-orm/postgresql'\nimport type { QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { EntityId } from '@open-mercato/shared/modules/entities'\nimport { isValidEntityIdShape } from '@open-mercato/shared/lib/query/engine'\nimport { parseBooleanFromUnknown } from '@open-mercato/shared/lib/boolean'\nimport {\n CustomerInteraction,\n CustomerTodoLink,\n} from '../data/entities'\nimport type { InteractionRecord } from './interactionCompatibility'\nimport {\n CUSTOMER_INTERACTION_TASK_SOURCE,\n EXAMPLE_TODO_SOURCE,\n resolveExampleIntegrationHref,\n} from './interactionCompatibility'\nimport { hydrateCanonicalInteractions, loadCustomerSummaries } from './interactionReadModel'\nimport { createLogger } from '@open-mercato/shared/lib/logger'\n\nconst logger = createLogger('customers')\n\nexport type CustomerTodoRow = {\n id: string\n todoId: string\n todoSource: string\n todoTitle: string | null\n todoIsDone: boolean | null\n todoPriority?: number | null\n todoSeverity?: string | null\n todoDescription?: string | null\n todoDueAt?: string | null\n todoTimezone?: string | null\n todoCustomValues?: Record<string, unknown> | null\n todoOrganizationId: string | null\n todoUpdatedAt?: string | null\n organizationId: string\n tenantId: string\n createdAt: string\n externalHref?: string | null\n _integrations?: Record<string, unknown>\n customer: {\n id: string | null\n displayName: string | null\n kind: string | null\n }\n}\n\nexport type LegacyTodoDetail = {\n title: string | null\n isDone: boolean | null\n priority: number | null\n severity: string | null\n description: string | null\n dueAt: string | null\n organizationId: string | null\n updatedAt: string | null\n customValues: Record<string, unknown> | null\n}\n\ntype CustomerSummary = {\n id: string | null\n displayName: string | null\n kind: string | null\n}\n\ntype CustomersAuthLike = {\n tenantId: string | null\n orgId?: string | null\n sub?: string | null\n userId?: string | null\n keyId?: string | null\n}\n\ntype CustomersContainerLike = {\n resolve: (name: string) => unknown\n}\n\nexport type CanonicalTodoListResult = {\n items: CustomerTodoRow[]\n bridgeIds: Set<string>\n total: number\n}\n\nfunction emptyCanonicalTodoList(): CanonicalTodoListResult {\n return { items: [], bridgeIds: new Set(), total: 0 }\n}\n\nfunction isCollapsedRestrictedOrganizationScope(\n organizationIds: string[] | null | undefined,\n isUnrestricted: boolean | undefined,\n): boolean {\n return isUnrestricted !== true && (!organizationIds || organizationIds.length === 0)\n}\n\nexport type ListTodosPagination = { page: number; pageSize: number }\n\nfunction resolveLegacyTodoSource(source: string | null | undefined): string {\n return typeof source === 'string' && source.trim().length > 0\n ? source\n : EXAMPLE_TODO_SOURCE\n}\n\nfunction extractTodoTitle(record: Record<string, unknown>): string | null {\n // `task_name` / `taskName` carry a workflow user task's name; the query engine\n // returns the raw column on the ORM path and the camelCase property on the\n // indexed one, so both spellings are read.\n const candidates = ['title', 'subject', 'name', 'task_name', 'taskName', 'summary', 'text', 'description']\n for (const key of candidates) {\n const value = record[key]\n if (typeof value === 'string' && value.trim().length > 0) {\n return value.trim()\n }\n }\n return null\n}\n\nfunction parseNumber(value: unknown): number | null {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = Number(trimmed)\n if (!Number.isNaN(parsed)) return parsed\n }\n return null\n}\n\nfunction parseDateValue(value: unknown): string | null {\n if (value instanceof Date) {\n return Number.isNaN(value.getTime()) ? null : value.toISOString()\n }\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (!trimmed.length) return null\n const parsed = new Date(trimmed)\n return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString()\n }\n return null\n}\n\nfunction readCustomField(record: Record<string, unknown>, key: string): unknown {\n const custom = record.custom ?? record.customFields ?? record.cf\n if (custom && typeof custom === 'object') {\n const bucket = custom as Record<string, unknown>\n if (key in bucket) return bucket[key]\n }\n return undefined\n}\n\nexport function normalizeTodoSearch(value: string | undefined): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim().toLowerCase()\n return trimmed.length > 0 ? trimmed : null\n}\n\nexport function sortTodoRows(rows: CustomerTodoRow[]): CustomerTodoRow[] {\n return [...rows].sort((left, right) => {\n const leftTime = new Date(left.createdAt).getTime()\n const rightTime = new Date(right.createdAt).getTime()\n if (leftTime === rightTime) {\n return right.id.localeCompare(left.id)\n }\n return rightTime - leftTime\n })\n}\n\nexport function filterTodoRows(rows: CustomerTodoRow[], search: string | null): CustomerTodoRow[] {\n if (!search) return rows\n return rows.filter((row) => {\n const haystack = [\n row.customer.displayName,\n row.todoTitle,\n row.todoDescription,\n ]\n .filter((value): value is string => typeof value === 'string' && value.trim().length > 0)\n .join(' ')\n .toLowerCase()\n return haystack.includes(search)\n })\n}\n\nexport function paginateTodoRows(\n rows: CustomerTodoRow[],\n page: number,\n pageSize: number,\n exportAll: boolean,\n): { items: CustomerTodoRow[]; total: number; page: number; pageSize: number; totalPages: number } {\n const total = rows.length\n if (exportAll) {\n return {\n items: rows,\n total,\n page: 1,\n pageSize: total,\n totalPages: 1,\n }\n }\n const start = (page - 1) * pageSize\n return {\n items: rows.slice(start, start + pageSize),\n total,\n page,\n pageSize,\n totalPages: Math.max(1, Math.ceil(total / pageSize)),\n }\n}\n\nexport async function resolveLegacyTodoDetails(\n queryEngine: QueryEngine,\n links: CustomerTodoLink[],\n tenantId: string | null,\n organizationIds: Array<string | null>,\n): Promise<Map<string, LegacyTodoDetail>> {\n const details = new Map<string, LegacyTodoDetail>()\n if (!links.length || !tenantId) return details\n\n const scopedOrganizationIds = organizationIds.filter(\n (value): value is string => typeof value === 'string' && value.trim().length > 0,\n )\n\n const idsBySource = new Map<string, Set<string>>()\n for (const link of links) {\n const source = resolveLegacyTodoSource(link.todoSource)\n const id =\n typeof link.todoId === 'string' && link.todoId.trim().length > 0\n ? link.todoId\n : String(link.todoId ?? '')\n if (!id) continue\n if (!idsBySource.has(source)) idsBySource.set(source, new Set<string>())\n idsBySource.get(source)!.add(id)\n }\n\n for (const [source, idSet] of idsBySource.entries()) {\n const ids = Array.from(idSet)\n if (!ids.length) continue\n if (!isValidEntityIdShape(source)) {\n // A legacy/malformed `todoSource` (e.g. a bare module name written before\n // the value was required to be a `module:entity` id) does not resolve to\n // any real table. Querying it anyway surfaces a raw DB error (\"relation\n // ... does not exist\") as a dashboard-wide schema-mismatch banner instead\n // of just leaving that row's details unresolved.\n logger.warn('Skipping malformed legacy todo source', { component: 'todoCompatibility', source })\n continue\n }\n try {\n const result = await queryEngine.query<Record<string, unknown>>(source as EntityId, {\n tenantId,\n organizationIds: scopedOrganizationIds.length > 0 ? scopedOrganizationIds : undefined,\n filters: { id: { $in: ids } },\n includeCustomFields: ['priority', 'due_at', 'severity', 'description'],\n page: { page: 1, pageSize: Math.max(ids.length, 1) },\n })\n\n for (const item of result.items ?? []) {\n if (!item || typeof item !== 'object') continue\n const record = item as Record<string, unknown>\n const rawId =\n typeof record.id === 'string' && record.id.trim().length > 0\n ? record.id\n : String(record.id ?? '')\n if (!rawId) continue\n\n const isDone = (() => {\n const direct = parseBooleanFromUnknown(record.is_done)\n if (direct !== null) return direct\n const custom = parseBooleanFromUnknown(readCustomField(record, 'is_done'))\n if (custom !== null) return custom\n const generic = parseBooleanFromUnknown(record.isDone)\n if (generic !== null) return generic\n return parseBooleanFromUnknown(readCustomField(record, 'isDone'))\n })()\n\n const priority = (() => {\n const candidates = [\n record['cf:priority'],\n record['cf_priority'],\n record.priority,\n readCustomField(record, 'priority'),\n ]\n for (const candidate of candidates) {\n const parsed = parseNumber(candidate)\n if (parsed !== null) return parsed\n }\n return null\n })()\n\n const severity = (() => {\n const candidates = [\n record['cf:severity'],\n record['cf_severity'],\n record.severity,\n readCustomField(record, 'severity'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const description = (() => {\n const candidates = [\n record.description,\n record['cf:description'],\n record['cf_description'],\n readCustomField(record, 'description'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const dueAt = (() => {\n const candidates = [\n record.due_at,\n record.dueAt,\n record['cf:due_at'],\n record['cf_due_at'],\n readCustomField(record, 'due_at'),\n readCustomField(record, 'dueAt'),\n ]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n const organizationId = (() => {\n const candidates = [\n record.organization_id,\n record.organizationId,\n record['cf:organization_id'],\n record['cf_organization_id'],\n readCustomField(record, 'organization_id'),\n readCustomField(record, 'organizationId'),\n ]\n for (const candidate of candidates) {\n if (typeof candidate === 'string' && candidate.trim().length > 0) {\n return candidate.trim()\n }\n }\n return null\n })()\n\n const customValues: Record<string, unknown> = {}\n const assignCustomValue = (key: string, value: unknown) => {\n const trimmedKey = key.trim()\n if (!trimmedKey.length) return\n customValues[trimmedKey] = value === undefined ? null : value\n }\n for (const [rawKey, rawValue] of Object.entries(record)) {\n if (rawKey.startsWith('cf:')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n } else if (rawKey.startsWith('cf_')) {\n assignCustomValue(rawKey.slice(3), rawValue)\n }\n }\n const nestedCustom = record.custom ?? record.customFields ?? record.cf\n if (nestedCustom && typeof nestedCustom === 'object') {\n for (const [key, value] of Object.entries(nestedCustom as Record<string, unknown>)) {\n assignCustomValue(key, value)\n }\n }\n\n const updatedAt = (() => {\n const candidates = [record.updated_at, record.updatedAt]\n for (const candidate of candidates) {\n const parsed = parseDateValue(candidate)\n if (parsed) return parsed\n }\n return null\n })()\n\n details.set(`${source}:${rawId}`, {\n title: extractTodoTitle(record),\n isDone,\n priority,\n severity,\n description,\n dueAt,\n organizationId,\n updatedAt,\n customValues: Object.keys(customValues).length > 0 ? customValues : null,\n })\n }\n } catch (err) {\n logger.warn('Failed to resolve todo details', { component: 'todoCompatibility', source, err })\n continue\n }\n }\n\n return details\n}\n\nexport async function listLegacyTodoRows(\n em: EntityManager,\n queryEngine: QueryEngine,\n tenantId: string,\n organizationIds: string[] | null,\n entityId: string | undefined,\n options?: { limit?: number | null; isUnrestricted?: boolean },\n): Promise<CustomerTodoRow[]> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return []\n }\n const where: Record<string, unknown> = { tenantId }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (entityId) {\n where.entity = entityId\n }\n\n const findOptions: Record<string, unknown> = {\n populate: ['entity'],\n orderBy: { createdAt: 'desc' },\n }\n if (typeof options?.limit === 'number' && Number.isFinite(options.limit) && options.limit > 0) {\n findOptions.limit = options.limit\n }\n\n const links = await em.find(CustomerTodoLink, where, findOptions as any)\n const details = await resolveLegacyTodoDetails(\n queryEngine,\n links,\n tenantId,\n organizationIds ?? [],\n )\n\n return links.map((link) => {\n const source = resolveLegacyTodoSource(link.todoSource)\n return mapLegacyTodoLinkToRow(\n link,\n details.get(`${source}:${link.todoId}`) ?? null,\n )\n })\n}\n\nexport async function listCanonicalTodoRows(\n em: EntityManager,\n container: CustomersContainerLike,\n auth: CustomersAuthLike,\n selectedOrganizationId: string | null,\n organizationIds: string[] | null,\n options?: {\n entityId?: string\n includeDeleted?: boolean\n source?: string | string[] | null\n pagination?: ListTodosPagination | null\n searchText?: string | null\n limit?: number | null\n isUnrestricted?: boolean\n },\n): Promise<CanonicalTodoListResult> {\n if (isCollapsedRestrictedOrganizationScope(organizationIds, options?.isUnrestricted)) {\n return emptyCanonicalTodoList()\n }\n const where: Record<string, unknown> = {\n tenantId: auth.tenantId,\n interactionType: 'task',\n }\n if (!options?.includeDeleted) {\n where.deletedAt = null\n }\n if (organizationIds && organizationIds.length > 0) {\n where.organizationId = { $in: organizationIds }\n }\n if (options?.entityId) {\n where.entity = options.entityId\n }\n if (options?.source) {\n where.source = Array.isArray(options.source) ? { $in: options.source } : options.source\n }\n const trimmedSearch =\n typeof options?.searchText === 'string' ? options.searchText.trim() : ''\n if (trimmedSearch.length > 0) {\n const pattern = `%${trimmedSearch}%`\n where.$or = [\n { title: { $ilike: pattern } },\n { body: { $ilike: pattern } },\n ]\n }\n\n const findOptions: Record<string, unknown> = {\n orderBy: { createdAt: 'desc' },\n }\n const pagination = options?.pagination ?? null\n if (pagination) {\n findOptions.offset = Math.max(0, (pagination.page - 1) * pagination.pageSize)\n findOptions.limit = pagination.pageSize\n } else if (\n typeof options?.limit === 'number' &&\n Number.isFinite(options.limit) &&\n options.limit > 0\n ) {\n findOptions.limit = options.limit\n }\n\n let interactions: CustomerInteraction[]\n let total: number\n if (pagination) {\n const [rows, count] = await em.findAndCount(CustomerInteraction, where, findOptions as any)\n interactions = rows\n total = count\n } else {\n interactions = await em.find(CustomerInteraction, where, findOptions as any)\n total = interactions.filter((interaction) => !interaction.deletedAt).length\n }\n const activeInteractions = interactions.filter((interaction) => !interaction.deletedAt)\n const groups = new Map<string, CustomerInteraction[]>()\n\n for (const interaction of activeInteractions) {\n const organizationId =\n typeof interaction.organizationId === 'string' && interaction.organizationId.trim().length > 0\n ? interaction.organizationId\n : selectedOrganizationId ?? ''\n const bucket = groups.get(organizationId)\n if (bucket) {\n bucket.push(interaction)\n } else {\n groups.set(organizationId, [interaction])\n }\n }\n\n const rowByInteractionId = new Map<string, CustomerTodoRow>()\n\n for (const [groupOrganizationId, groupedInteractions] of groups.entries()) {\n const scopedOrganizationId = groupOrganizationId.length > 0 ? groupOrganizationId : null\n const hydrated = await hydrateCanonicalInteractions({\n em,\n container,\n auth: {\n ...auth,\n orgId: auth.orgId ?? null,\n },\n selectedOrganizationId: scopedOrganizationId,\n interactions: groupedInteractions,\n })\n const customerIds = Array.from(\n new Set(\n hydrated\n .map((interaction) => interaction.entityId ?? null)\n .filter((value): value is string => !!value),\n ),\n )\n const customerSummaries = await loadCustomerSummaries(\n em,\n customerIds,\n auth.tenantId,\n scopedOrganizationId,\n )\n\n for (const interaction of hydrated) {\n rowByInteractionId.set(\n interaction.id,\n mapInteractionRecordToTodoRow(\n interaction,\n interaction.entityId ? customerSummaries.get(interaction.entityId) ?? null : null,\n ),\n )\n }\n }\n\n return {\n items: activeInteractions\n .map((interaction) => rowByInteractionId.get(interaction.id) ?? null)\n .filter((row): row is CustomerTodoRow => !!row),\n bridgeIds: new Set(interactions.map((interaction) => interaction.id)),\n total,\n }\n}\n\nexport function mapLegacyTodoLinkToRow(\n link: CustomerTodoLink,\n detail: LegacyTodoDetail | null,\n customerOverride?: CustomerSummary | null,\n): CustomerTodoRow {\n const entity = customerOverride ?? {\n id: typeof link.entity === 'string' ? null : link.entity.id,\n displayName: typeof link.entity === 'string' ? null : link.entity.displayName ?? null,\n kind: typeof link.entity === 'string' ? null : link.entity.kind ?? null,\n }\n\n return {\n id: link.id,\n todoId: link.todoId,\n todoSource: resolveLegacyTodoSource(link.todoSource),\n todoTitle: detail?.title ?? null,\n todoIsDone: detail?.isDone ?? null,\n todoPriority: detail?.priority ?? null,\n todoSeverity: detail?.severity ?? null,\n todoDescription: detail?.description ?? null,\n todoDueAt: detail?.dueAt ?? null,\n todoCustomValues: detail?.customValues ?? null,\n todoOrganizationId: detail?.organizationId ?? link.organizationId ?? null,\n todoUpdatedAt: detail?.updatedAt ?? null,\n organizationId: link.organizationId,\n tenantId: link.tenantId,\n createdAt: link.createdAt.toISOString(),\n _integrations: undefined,\n customer: entity,\n }\n}\n\nexport function mapInteractionRecordToTodoRow(\n interaction: InteractionRecord,\n customer: CustomerSummary | null,\n options?: { rowId?: string | null; todoSource?: string | null },\n): CustomerTodoRow {\n const customValues: Record<string, unknown> = { ...(interaction.customValues ?? {}) }\n if (interaction.priority !== undefined && customValues.priority === undefined) {\n customValues.priority = interaction.priority ?? null\n }\n if (interaction.body !== undefined && customValues.description === undefined) {\n customValues.description = interaction.body ?? null\n }\n if (interaction.scheduledAt !== undefined && customValues.due_at === undefined) {\n customValues.due_at = interaction.scheduledAt ?? null\n }\n\n return {\n id:\n typeof options?.rowId === 'string' && options.rowId.trim().length > 0\n ? options.rowId\n : interaction.id,\n todoId: interaction.id,\n todoSource:\n typeof options?.todoSource === 'string' && options.todoSource.trim().length > 0\n ? options.todoSource\n : CUSTOMER_INTERACTION_TASK_SOURCE,\n todoTitle: interaction.title ?? null,\n todoIsDone: interaction.status === 'done',\n todoPriority: interaction.priority ?? null,\n todoSeverity:\n typeof customValues.severity === 'string' && customValues.severity.trim().length > 0\n ? customValues.severity.trim()\n : null,\n todoDescription: interaction.body ?? null,\n todoDueAt: interaction.scheduledAt ?? null,\n todoTimezone: interaction.timezone ?? null,\n todoCustomValues: Object.keys(customValues).length > 0 ? customValues : null,\n todoOrganizationId: interaction.organizationId ?? null,\n todoUpdatedAt: interaction.updatedAt ?? null,\n organizationId: interaction.organizationId ?? '',\n tenantId: interaction.tenantId ?? '',\n createdAt: interaction.createdAt,\n externalHref: resolveExampleIntegrationHref(interaction),\n _integrations: interaction._integrations ?? undefined,\n customer: customer ?? {\n id: interaction.entityId ?? null,\n displayName: null,\n kind: null,\n },\n }\n}\n"],
5
+ "mappings": "AAGA,SAAS,4BAA4B;AACrC,SAAS,+BAA+B;AACxC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,8BAA8B,6BAA6B;AACpE,SAAS,oBAAoB;AAE7B,MAAM,SAAS,aAAa,WAAW;AAgEvC,SAAS,yBAAkD;AACzD,SAAO,EAAE,OAAO,CAAC,GAAG,WAAW,oBAAI,IAAI,GAAG,OAAO,EAAE;AACrD;AAEA,SAAS,uCACP,iBACA,gBACS;AACT,SAAO,mBAAmB,SAAS,CAAC,mBAAmB,gBAAgB,WAAW;AACpF;AAIA,SAAS,wBAAwB,QAA2C;AAC1E,SAAO,OAAO,WAAW,YAAY,OAAO,KAAK,EAAE,SAAS,IACxD,SACA;AACN;AAEA,SAAS,iBAAiB,QAAgD;AAIxE,QAAM,aAAa,CAAC,SAAS,WAAW,QAAQ,aAAa,YAAY,WAAW,QAAQ,aAAa;AACzG,aAAW,OAAO,YAAY;AAC5B,UAAM,QAAQ,OAAO,GAAG;AACxB,QAAI,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,GAAG;AACxD,aAAO,MAAM,KAAK;AAAA,IACpB;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,YAAY,O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cAAc,8BAA8B,WAAW;AAAA,IACvD,eAAe,YAAY,iBAAiB;AAAA,IAC5C,UAAU,YAAY;AAAA,MACpB,IAAI,YAAY,YAAY;AAAA,MAC5B,aAAa;AAAA,MACb,MAAM;AAAA,IACR;AAAA,EACF;AACF;",
6
6
  "names": []
7
7
  }
@@ -0,0 +1,17 @@
1
+ import { Migration } from "@mikro-orm/migrations";
2
+ class Migration20260928175058_customers extends Migration {
3
+ constructor() {
4
+ super(...arguments);
5
+ this.name = "Migration20260928175058_customers";
6
+ }
7
+ up() {
8
+ this.addSql(`alter table "customer_dictionary_entries" add "activity_type_behavior" jsonb null;`);
9
+ }
10
+ down() {
11
+ this.addSql(`alter table "customer_dictionary_entries" drop column "activity_type_behavior";`);
12
+ }
13
+ }
14
+ export {
15
+ Migration20260928175058_customers
16
+ };
17
+ //# sourceMappingURL=Migration20260928175058_customers.js.map