@open-mercato/core 0.5.1-develop.2663.2c29774b5b → 0.5.1-develop.2681.c559bb2bc3

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 (687) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/generated/entities/action_log/index.js +8 -0
  3. package/dist/generated/entities/action_log/index.js.map +2 -2
  4. package/dist/generated/entities/customer_company_billing/index.js +23 -0
  5. package/dist/generated/entities/customer_company_billing/index.js.map +7 -0
  6. package/dist/generated/entities/customer_deal/index.js +8 -0
  7. package/dist/generated/entities/customer_deal/index.js.map +2 -2
  8. package/dist/generated/entities/customer_deal_stage_transition/index.js +31 -0
  9. package/dist/generated/entities/customer_deal_stage_transition/index.js.map +7 -0
  10. package/dist/generated/entities/customer_dictionary_kind_setting/index.js +21 -0
  11. package/dist/generated/entities/customer_dictionary_kind_setting/index.js.map +7 -0
  12. package/dist/generated/entities/customer_entity/index.js +8 -0
  13. package/dist/generated/entities/customer_entity/index.js.map +2 -2
  14. package/dist/generated/entities/customer_entity_role/index.js +23 -0
  15. package/dist/generated/entities/customer_entity_role/index.js.map +7 -0
  16. package/dist/generated/entities/customer_interaction/index.js +23 -1
  17. package/dist/generated/entities/customer_interaction/index.js.map +2 -2
  18. package/dist/generated/entities/customer_label/index.js +19 -0
  19. package/dist/generated/entities/customer_label/index.js.map +7 -0
  20. package/dist/generated/entities/customer_label_assignment/index.js +17 -0
  21. package/dist/generated/entities/customer_label_assignment/index.js.map +7 -0
  22. package/dist/generated/entities/customer_person_company_link/index.js +21 -0
  23. package/dist/generated/entities/customer_person_company_link/index.js.map +7 -0
  24. package/dist/generated/entities/customer_person_company_role/index.js +17 -0
  25. package/dist/generated/entities/customer_person_company_role/index.js.map +7 -0
  26. package/dist/generated/entities/dictionary_entry/index.js +4 -0
  27. package/dist/generated/entities/dictionary_entry/index.js.map +2 -2
  28. package/dist/generated/entities.ids.generated.js +9 -1
  29. package/dist/generated/entities.ids.generated.js.map +2 -2
  30. package/dist/generated/entity-fields-registry.js +116 -1
  31. package/dist/generated/entity-fields-registry.js.map +2 -2
  32. package/dist/modules/attachments/api/route.js +46 -8
  33. package/dist/modules/attachments/api/route.js.map +2 -2
  34. package/dist/modules/audit_logs/api/audit-logs/actions/export/route.js +208 -0
  35. package/dist/modules/audit_logs/api/audit-logs/actions/export/route.js.map +7 -0
  36. package/dist/modules/audit_logs/api/audit-logs/actions/route.js +52 -6
  37. package/dist/modules/audit_logs/api/audit-logs/actions/route.js.map +2 -2
  38. package/dist/modules/audit_logs/cli.js +62 -0
  39. package/dist/modules/audit_logs/cli.js.map +7 -0
  40. package/dist/modules/audit_logs/data/entities.js +21 -1
  41. package/dist/modules/audit_logs/data/entities.js.map +2 -2
  42. package/dist/modules/audit_logs/data/validators.js +9 -1
  43. package/dist/modules/audit_logs/data/validators.js.map +2 -2
  44. package/dist/modules/audit_logs/lib/changeRows.js +34 -0
  45. package/dist/modules/audit_logs/lib/changeRows.js.map +7 -0
  46. package/dist/modules/audit_logs/lib/display-helpers.js +2 -20
  47. package/dist/modules/audit_logs/lib/display-helpers.js.map +3 -3
  48. package/dist/modules/audit_logs/lib/projections.js +58 -0
  49. package/dist/modules/audit_logs/lib/projections.js.map +7 -0
  50. package/dist/modules/audit_logs/migrations/Migration20260412160533.js +21 -0
  51. package/dist/modules/audit_logs/migrations/Migration20260412160533.js.map +7 -0
  52. package/dist/modules/audit_logs/services/actionLogService.js +313 -79
  53. package/dist/modules/audit_logs/services/actionLogService.js.map +2 -2
  54. package/dist/modules/customers/acl.js +3 -1
  55. package/dist/modules/customers/acl.js.map +2 -2
  56. package/dist/modules/customers/api/activities/route.js +4 -0
  57. package/dist/modules/customers/api/activities/route.js.map +2 -2
  58. package/dist/modules/customers/api/assignable-staff/route.js +208 -0
  59. package/dist/modules/customers/api/assignable-staff/route.js.map +7 -0
  60. package/dist/modules/customers/api/companies/[id]/people/route.js +205 -0
  61. package/dist/modules/customers/api/companies/[id]/people/route.js.map +7 -0
  62. package/dist/modules/customers/api/companies/[id]/roles/route.js +22 -0
  63. package/dist/modules/customers/api/companies/[id]/roles/route.js.map +7 -0
  64. package/dist/modules/customers/api/companies/[id]/route.js +374 -32
  65. package/dist/modules/customers/api/companies/[id]/route.js.map +2 -2
  66. package/dist/modules/customers/api/companies/route.js +82 -7
  67. package/dist/modules/customers/api/companies/route.js.map +2 -2
  68. package/dist/modules/customers/api/deals/[id]/companies/route.js +172 -0
  69. package/dist/modules/customers/api/deals/[id]/companies/route.js.map +7 -0
  70. package/dist/modules/customers/api/deals/[id]/people/route.js +156 -0
  71. package/dist/modules/customers/api/deals/[id]/people/route.js.map +7 -0
  72. package/dist/modules/customers/api/deals/[id]/route.js +459 -53
  73. package/dist/modules/customers/api/deals/[id]/route.js.map +2 -2
  74. package/dist/modules/customers/api/deals/[id]/stats/route.js +195 -0
  75. package/dist/modules/customers/api/deals/[id]/stats/route.js.map +7 -0
  76. package/dist/modules/customers/api/deals/route.js +20 -10
  77. package/dist/modules/customers/api/deals/route.js.map +3 -3
  78. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js +105 -4
  79. package/dist/modules/customers/api/dictionaries/[kind]/[id]/route.js.map +2 -2
  80. package/dist/modules/customers/api/dictionaries/[kind]/route.js +118 -42
  81. package/dist/modules/customers/api/dictionaries/[kind]/route.js.map +2 -2
  82. package/dist/modules/customers/api/dictionaries/context.js +30 -6
  83. package/dist/modules/customers/api/dictionaries/context.js.map +2 -2
  84. package/dist/modules/customers/api/dictionaries/kind-settings/route.js +207 -0
  85. package/dist/modules/customers/api/dictionaries/kind-settings/route.js.map +7 -0
  86. package/dist/modules/customers/api/entity-roles-factory.js +471 -0
  87. package/dist/modules/customers/api/entity-roles-factory.js.map +7 -0
  88. package/dist/modules/customers/api/interactions/conflicts/route.js +158 -0
  89. package/dist/modules/customers/api/interactions/conflicts/route.js.map +7 -0
  90. package/dist/modules/customers/api/interactions/counts/route.js +92 -0
  91. package/dist/modules/customers/api/interactions/counts/route.js.map +7 -0
  92. package/dist/modules/customers/api/interactions/route.js +83 -4
  93. package/dist/modules/customers/api/interactions/route.js.map +2 -2
  94. package/dist/modules/customers/api/labels/assign/route.js +189 -0
  95. package/dist/modules/customers/api/labels/assign/route.js.map +7 -0
  96. package/dist/modules/customers/api/labels/auth.js +17 -0
  97. package/dist/modules/customers/api/labels/auth.js.map +7 -0
  98. package/dist/modules/customers/api/labels/route.js +281 -0
  99. package/dist/modules/customers/api/labels/route.js.map +7 -0
  100. package/dist/modules/customers/api/labels/table-errors.js +38 -0
  101. package/dist/modules/customers/api/labels/table-errors.js.map +7 -0
  102. package/dist/modules/customers/api/labels/unassign/route.js +184 -0
  103. package/dist/modules/customers/api/labels/unassign/route.js.map +7 -0
  104. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js +292 -0
  105. package/dist/modules/customers/api/people/[id]/companies/[linkId]/route.js.map +7 -0
  106. package/dist/modules/customers/api/people/[id]/companies/context.js +66 -0
  107. package/dist/modules/customers/api/people/[id]/companies/context.js.map +7 -0
  108. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js +334 -0
  109. package/dist/modules/customers/api/people/[id]/companies/enriched/route.js.map +7 -0
  110. package/dist/modules/customers/api/people/[id]/companies/route.js +205 -0
  111. package/dist/modules/customers/api/people/[id]/companies/route.js.map +7 -0
  112. package/dist/modules/customers/api/people/[id]/roles/route.js +22 -0
  113. package/dist/modules/customers/api/people/[id]/roles/route.js.map +7 -0
  114. package/dist/modules/customers/api/people/[id]/route.js +134 -21
  115. package/dist/modules/customers/api/people/[id]/route.js.map +2 -2
  116. package/dist/modules/customers/api/people/route.js +122 -23
  117. package/dist/modules/customers/api/people/route.js.map +2 -2
  118. package/dist/modules/customers/api/todos/route.js +4 -0
  119. package/dist/modules/customers/api/todos/route.js.map +2 -2
  120. package/dist/modules/customers/api/utils.js +22 -0
  121. package/dist/modules/customers/api/utils.js.map +2 -2
  122. package/dist/modules/customers/backend/config/customers/page.js +2 -6
  123. package/dist/modules/customers/backend/config/customers/page.js.map +2 -2
  124. package/dist/modules/customers/backend/customers/companies/page.js +37 -26
  125. package/dist/modules/customers/backend/customers/companies/page.js.map +2 -2
  126. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js +265 -262
  127. package/dist/modules/customers/backend/customers/companies-v2/[id]/page.js.map +3 -3
  128. package/dist/modules/customers/backend/customers/deals/[id]/hooks/formatters.js +23 -0
  129. package/dist/modules/customers/backend/customers/deals/[id]/hooks/formatters.js.map +7 -0
  130. package/dist/modules/customers/backend/customers/deals/[id]/hooks/types.js +1 -0
  131. package/dist/modules/customers/backend/customers/deals/[id]/hooks/types.js.map +7 -0
  132. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.js +43 -0
  133. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.js.map +7 -0
  134. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js +264 -0
  135. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.js.map +7 -0
  136. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js +88 -0
  137. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.js.map +7 -0
  138. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealData.js +41 -0
  139. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealData.js.map +7 -0
  140. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.js +66 -0
  141. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.js.map +7 -0
  142. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealInjectedTabs.js +39 -0
  143. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealInjectedTabs.js.map +7 -0
  144. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealMutationContext.js +49 -0
  145. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealMutationContext.js.map +7 -0
  146. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealPipeline.js +43 -0
  147. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useDealPipeline.js.map +7 -0
  148. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useScheduleDialog.js +28 -0
  149. package/dist/modules/customers/backend/customers/deals/[id]/hooks/useScheduleDialog.js.map +7 -0
  150. package/dist/modules/customers/backend/customers/deals/[id]/page.js +556 -503
  151. package/dist/modules/customers/backend/customers/deals/[id]/page.js.map +3 -3
  152. package/dist/modules/customers/backend/customers/deals/page.js +66 -21
  153. package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
  154. package/dist/modules/customers/backend/customers/people/page.js +36 -28
  155. package/dist/modules/customers/backend/customers/people/page.js.map +2 -2
  156. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js +318 -203
  157. package/dist/modules/customers/backend/customers/people-v2/[id]/page.js.map +3 -3
  158. package/dist/modules/customers/cli.js +105 -13
  159. package/dist/modules/customers/cli.js.map +2 -2
  160. package/dist/modules/customers/commands/activities.js +6 -0
  161. package/dist/modules/customers/commands/activities.js.map +2 -2
  162. package/dist/modules/customers/commands/deals.js +315 -107
  163. package/dist/modules/customers/commands/deals.js.map +2 -2
  164. package/dist/modules/customers/commands/dictionaries.js +166 -32
  165. package/dist/modules/customers/commands/dictionaries.js.map +2 -2
  166. package/dist/modules/customers/commands/dictionaryKindSettings.js +208 -0
  167. package/dist/modules/customers/commands/dictionaryKindSettings.js.map +7 -0
  168. package/dist/modules/customers/commands/entity-roles.js +415 -0
  169. package/dist/modules/customers/commands/entity-roles.js.map +7 -0
  170. package/dist/modules/customers/commands/index.js +4 -0
  171. package/dist/modules/customers/commands/index.js.map +2 -2
  172. package/dist/modules/customers/commands/interactions.js +108 -21
  173. package/dist/modules/customers/commands/interactions.js.map +2 -2
  174. package/dist/modules/customers/commands/labels.js +539 -0
  175. package/dist/modules/customers/commands/labels.js.map +7 -0
  176. package/dist/modules/customers/commands/people.js +560 -463
  177. package/dist/modules/customers/commands/people.js.map +3 -3
  178. package/dist/modules/customers/commands/personCompanyLinks.js +568 -0
  179. package/dist/modules/customers/commands/personCompanyLinks.js.map +7 -0
  180. package/dist/modules/customers/commands/shared.js +12 -4
  181. package/dist/modules/customers/commands/shared.js.map +2 -2
  182. package/dist/modules/customers/commands/todos.js +10 -1
  183. package/dist/modules/customers/commands/todos.js.map +2 -2
  184. package/dist/modules/customers/components/AddressEditor.js +1 -1
  185. package/dist/modules/customers/components/AddressEditor.js.map +2 -2
  186. package/dist/modules/customers/components/CustomersConfigurationSections.js +31 -0
  187. package/dist/modules/customers/components/CustomersConfigurationSections.js.map +7 -0
  188. package/dist/modules/customers/components/DictionarySettings.js +37 -2
  189. package/dist/modules/customers/components/DictionarySettings.js.map +2 -2
  190. package/dist/modules/customers/components/detail/ActiveDealCard.js +121 -0
  191. package/dist/modules/customers/components/detail/ActiveDealCard.js.map +7 -0
  192. package/dist/modules/customers/components/detail/ActivitiesSection.js +222 -331
  193. package/dist/modules/customers/components/detail/ActivitiesSection.js.map +3 -3
  194. package/dist/modules/customers/components/detail/ActivityAiActions.js +36 -0
  195. package/dist/modules/customers/components/detail/ActivityAiActions.js.map +7 -0
  196. package/dist/modules/customers/components/detail/ActivityCard.js +126 -0
  197. package/dist/modules/customers/components/detail/ActivityCard.js.map +7 -0
  198. package/dist/modules/customers/components/detail/ActivityHistorySection.js +340 -0
  199. package/dist/modules/customers/components/detail/ActivityHistorySection.js.map +7 -0
  200. package/dist/modules/customers/components/detail/ActivityLogTab.js +56 -0
  201. package/dist/modules/customers/components/detail/ActivityLogTab.js.map +7 -0
  202. package/dist/modules/customers/components/detail/ActivityTimeline.js +108 -0
  203. package/dist/modules/customers/components/detail/ActivityTimeline.js.map +7 -0
  204. package/dist/modules/customers/components/detail/ActivityTimelineFilters.js +139 -0
  205. package/dist/modules/customers/components/detail/ActivityTimelineFilters.js.map +7 -0
  206. package/dist/modules/customers/components/detail/ActivityTypeSelector.js +42 -0
  207. package/dist/modules/customers/components/detail/ActivityTypeSelector.js.map +7 -0
  208. package/dist/modules/customers/components/detail/AiActionChips.js +38 -0
  209. package/dist/modules/customers/components/detail/AiActionChips.js.map +7 -0
  210. package/dist/modules/customers/components/detail/AssignRoleDialog.js +534 -0
  211. package/dist/modules/customers/components/detail/AssignRoleDialog.js.map +7 -0
  212. package/dist/modules/customers/components/detail/ChangelogEntryRow.js +79 -0
  213. package/dist/modules/customers/components/detail/ChangelogEntryRow.js.map +7 -0
  214. package/dist/modules/customers/components/detail/ChangelogFilters.js +176 -0
  215. package/dist/modules/customers/components/detail/ChangelogFilters.js.map +7 -0
  216. package/dist/modules/customers/components/detail/ChangelogKpiCards.js +88 -0
  217. package/dist/modules/customers/components/detail/ChangelogKpiCards.js.map +7 -0
  218. package/dist/modules/customers/components/detail/ChangelogTab.js +470 -0
  219. package/dist/modules/customers/components/detail/ChangelogTab.js.map +7 -0
  220. package/dist/modules/customers/components/detail/ComingSoonPlaceholder.js +16 -0
  221. package/dist/modules/customers/components/detail/ComingSoonPlaceholder.js.map +7 -0
  222. package/dist/modules/customers/components/detail/CompanyCard.js +283 -0
  223. package/dist/modules/customers/components/detail/CompanyCard.js.map +7 -0
  224. package/dist/modules/customers/components/detail/CompanyDashboardTab.js +133 -0
  225. package/dist/modules/customers/components/detail/CompanyDashboardTab.js.map +7 -0
  226. package/dist/modules/customers/components/detail/CompanyDetailHeader.js +191 -0
  227. package/dist/modules/customers/components/detail/CompanyDetailHeader.js.map +7 -0
  228. package/dist/modules/customers/components/detail/CompanyDetailTabs.js +123 -0
  229. package/dist/modules/customers/components/detail/CompanyDetailTabs.js.map +7 -0
  230. package/dist/modules/customers/components/detail/CompanyKpiBar.js +174 -0
  231. package/dist/modules/customers/components/detail/CompanyKpiBar.js.map +7 -0
  232. package/dist/modules/customers/components/detail/CompanyPeopleSection.js +514 -230
  233. package/dist/modules/customers/components/detail/CompanyPeopleSection.js.map +2 -2
  234. package/dist/modules/customers/components/detail/CompanyTagsDialog.js +22 -0
  235. package/dist/modules/customers/components/detail/CompanyTagsDialog.js.map +7 -0
  236. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js +159 -0
  237. package/dist/modules/customers/components/detail/ConfirmDealLostDialog.js.map +7 -0
  238. package/dist/modules/customers/components/detail/CreatePersonDialog.js +135 -0
  239. package/dist/modules/customers/components/detail/CreatePersonDialog.js.map +7 -0
  240. package/dist/modules/customers/components/detail/DealClosureActionBar.js +59 -0
  241. package/dist/modules/customers/components/detail/DealClosureActionBar.js.map +7 -0
  242. package/dist/modules/customers/components/detail/DealDetailHeader.js +237 -0
  243. package/dist/modules/customers/components/detail/DealDetailHeader.js.map +7 -0
  244. package/dist/modules/customers/components/detail/DealDetailTabs.js +109 -0
  245. package/dist/modules/customers/components/detail/DealDetailTabs.js.map +7 -0
  246. package/dist/modules/customers/components/detail/DealForm.js +219 -92
  247. package/dist/modules/customers/components/detail/DealForm.js.map +2 -2
  248. package/dist/modules/customers/components/detail/DealLinkedEntitiesTab.js +295 -0
  249. package/dist/modules/customers/components/detail/DealLinkedEntitiesTab.js.map +7 -0
  250. package/dist/modules/customers/components/detail/DealLostSummaryDialog.js +107 -0
  251. package/dist/modules/customers/components/detail/DealLostSummaryDialog.js.map +7 -0
  252. package/dist/modules/customers/components/detail/DealWonPopup.js +113 -0
  253. package/dist/modules/customers/components/detail/DealWonPopup.js.map +7 -0
  254. package/dist/modules/customers/components/detail/DealsSection.js +206 -193
  255. package/dist/modules/customers/components/detail/DealsSection.js.map +2 -2
  256. package/dist/modules/customers/components/detail/DecisionMakersFooter.js +39 -0
  257. package/dist/modules/customers/components/detail/DecisionMakersFooter.js.map +7 -0
  258. package/dist/modules/customers/components/detail/EntityTagsDialog.js +1096 -0
  259. package/dist/modules/customers/components/detail/EntityTagsDialog.js.map +7 -0
  260. package/dist/modules/customers/components/detail/InlineActivityComposer.js +197 -0
  261. package/dist/modules/customers/components/detail/InlineActivityComposer.js.map +7 -0
  262. package/dist/modules/customers/components/detail/ManageTagsDialog.js +1091 -0
  263. package/dist/modules/customers/components/detail/ManageTagsDialog.js.map +7 -0
  264. package/dist/modules/customers/components/detail/MiniWeekCalendar.js +272 -0
  265. package/dist/modules/customers/components/detail/MiniWeekCalendar.js.map +7 -0
  266. package/dist/modules/customers/components/detail/MobilePersonDetail.js +106 -0
  267. package/dist/modules/customers/components/detail/MobilePersonDetail.js.map +7 -0
  268. package/dist/modules/customers/components/detail/NextStepCard.js +72 -0
  269. package/dist/modules/customers/components/detail/NextStepCard.js.map +7 -0
  270. package/dist/modules/customers/components/detail/PersonCard.js +192 -0
  271. package/dist/modules/customers/components/detail/PersonCard.js.map +7 -0
  272. package/dist/modules/customers/components/detail/PersonCompaniesSection.js +345 -0
  273. package/dist/modules/customers/components/detail/PersonCompaniesSection.js.map +7 -0
  274. package/dist/modules/customers/components/detail/PersonDetailHeader.js +220 -0
  275. package/dist/modules/customers/components/detail/PersonDetailHeader.js.map +7 -0
  276. package/dist/modules/customers/components/detail/PersonDetailTabs.js +122 -0
  277. package/dist/modules/customers/components/detail/PersonDetailTabs.js.map +7 -0
  278. package/dist/modules/customers/components/detail/PersonTagsDialog.js +24 -0
  279. package/dist/modules/customers/components/detail/PersonTagsDialog.js.map +7 -0
  280. package/dist/modules/customers/components/detail/PipelineStepper.js +191 -0
  281. package/dist/modules/customers/components/detail/PipelineStepper.js.map +7 -0
  282. package/dist/modules/customers/components/detail/PlannedActivitiesSection.js +222 -0
  283. package/dist/modules/customers/components/detail/PlannedActivitiesSection.js.map +7 -0
  284. package/dist/modules/customers/components/detail/RelationshipHealthCard.js +49 -0
  285. package/dist/modules/customers/components/detail/RelationshipHealthCard.js.map +7 -0
  286. package/dist/modules/customers/components/detail/RoleAssignmentRow.js +189 -0
  287. package/dist/modules/customers/components/detail/RoleAssignmentRow.js.map +7 -0
  288. package/dist/modules/customers/components/detail/RolesSection.js +234 -0
  289. package/dist/modules/customers/components/detail/RolesSection.js.map +7 -0
  290. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js +410 -0
  291. package/dist/modules/customers/components/detail/ScheduleActivityDialog.js.map +7 -0
  292. package/dist/modules/customers/components/detail/aiActionCatalog.js +41 -0
  293. package/dist/modules/customers/components/detail/aiActionCatalog.js.map +7 -0
  294. package/dist/modules/customers/components/detail/assignableStaff.js +48 -0
  295. package/dist/modules/customers/components/detail/assignableStaff.js.map +7 -0
  296. package/dist/modules/customers/components/detail/dashboard/ActiveDealWidget.js +48 -0
  297. package/dist/modules/customers/components/detail/dashboard/ActiveDealWidget.js.map +7 -0
  298. package/dist/modules/customers/components/detail/dashboard/OpenTasksWidget.js +86 -0
  299. package/dist/modules/customers/components/detail/dashboard/OpenTasksWidget.js.map +7 -0
  300. package/dist/modules/customers/components/detail/dashboard/RecentActivityWidget.js +53 -0
  301. package/dist/modules/customers/components/detail/dashboard/RecentActivityWidget.js.map +7 -0
  302. package/dist/modules/customers/components/detail/dashboard/RelationshipHealthWidget.js +30 -0
  303. package/dist/modules/customers/components/detail/dashboard/RelationshipHealthWidget.js.map +7 -0
  304. package/dist/modules/customers/components/detail/dashboard/UpcomingMeetingsWidget.js +43 -0
  305. package/dist/modules/customers/components/detail/dashboard/UpcomingMeetingsWidget.js.map +7 -0
  306. package/dist/modules/customers/components/detail/dashboard/helpers.js +71 -0
  307. package/dist/modules/customers/components/detail/dashboard/helpers.js.map +7 -0
  308. package/dist/modules/customers/components/detail/healthScoreUtils.js +69 -0
  309. package/dist/modules/customers/components/detail/healthScoreUtils.js.map +7 -0
  310. package/dist/modules/customers/components/detail/hooks/useCurrencyDictionary.js +5 -5
  311. package/dist/modules/customers/components/detail/hooks/useCurrencyDictionary.js.map +2 -2
  312. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js +9 -8
  313. package/dist/modules/customers/components/detail/hooks/useCustomerDictionary.js.map +3 -3
  314. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js +65 -0
  315. package/dist/modules/customers/components/detail/hooks/useInteractionMutations.js.map +7 -0
  316. package/dist/modules/customers/components/detail/notesAdapter.js +70 -30
  317. package/dist/modules/customers/components/detail/notesAdapter.js.map +2 -2
  318. package/dist/modules/customers/components/detail/pipelineStageUtils.js +26 -0
  319. package/dist/modules/customers/components/detail/pipelineStageUtils.js.map +7 -0
  320. package/dist/modules/customers/components/detail/schedule/DateTimeFields.js +144 -0
  321. package/dist/modules/customers/components/detail/schedule/DateTimeFields.js.map +7 -0
  322. package/dist/modules/customers/components/detail/schedule/FooterFields.js +60 -0
  323. package/dist/modules/customers/components/detail/schedule/FooterFields.js.map +7 -0
  324. package/dist/modules/customers/components/detail/schedule/LinkedEntitiesField.js +216 -0
  325. package/dist/modules/customers/components/detail/schedule/LinkedEntitiesField.js.map +7 -0
  326. package/dist/modules/customers/components/detail/schedule/LocationField.js +34 -0
  327. package/dist/modules/customers/components/detail/schedule/LocationField.js.map +7 -0
  328. package/dist/modules/customers/components/detail/schedule/ParticipantsField.js +226 -0
  329. package/dist/modules/customers/components/detail/schedule/ParticipantsField.js.map +7 -0
  330. package/dist/modules/customers/components/detail/schedule/fieldConfig.js +69 -0
  331. package/dist/modules/customers/components/detail/schedule/fieldConfig.js.map +7 -0
  332. package/dist/modules/customers/components/detail/schedule/index.js +21 -0
  333. package/dist/modules/customers/components/detail/schedule/index.js.map +7 -0
  334. package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js +172 -0
  335. package/dist/modules/customers/components/detail/schedule/useScheduleFormState.js.map +7 -0
  336. package/dist/modules/customers/components/detail/utils.js +23 -0
  337. package/dist/modules/customers/components/detail/utils.js.map +2 -2
  338. package/dist/modules/customers/components/formConfig.js +144 -22
  339. package/dist/modules/customers/components/formConfig.js.map +2 -2
  340. package/dist/modules/customers/components/linking/LinkEntityDialog.js +661 -0
  341. package/dist/modules/customers/components/linking/LinkEntityDialog.js.map +7 -0
  342. package/dist/modules/customers/components/linking/adapters/companyAdapter.js +252 -0
  343. package/dist/modules/customers/components/linking/adapters/companyAdapter.js.map +7 -0
  344. package/dist/modules/customers/components/linking/adapters/dealAdapter.js +384 -0
  345. package/dist/modules/customers/components/linking/adapters/dealAdapter.js.map +7 -0
  346. package/dist/modules/customers/components/linking/adapters/personAdapter.js +324 -0
  347. package/dist/modules/customers/components/linking/adapters/personAdapter.js.map +7 -0
  348. package/dist/modules/customers/components/list/CollectionPreviewCell.js +53 -0
  349. package/dist/modules/customers/components/list/CollectionPreviewCell.js.map +7 -0
  350. package/dist/modules/customers/data/entities.js +407 -1
  351. package/dist/modules/customers/data/entities.js.map +2 -2
  352. package/dist/modules/customers/data/validators.js +139 -21
  353. package/dist/modules/customers/data/validators.js.map +2 -2
  354. package/dist/modules/customers/events.js +19 -1
  355. package/dist/modules/customers/events.js.map +2 -2
  356. package/dist/modules/customers/lib/customerRoleTypes.js +19 -0
  357. package/dist/modules/customers/lib/customerRoleTypes.js.map +7 -0
  358. package/dist/modules/customers/lib/dealClosureNotification.js +39 -0
  359. package/dist/modules/customers/lib/dealClosureNotification.js.map +7 -0
  360. package/dist/modules/customers/lib/dealStageTransitionTable.js +29 -0
  361. package/dist/modules/customers/lib/dealStageTransitionTable.js.map +7 -0
  362. package/dist/modules/customers/lib/dictionaries.js +25 -0
  363. package/dist/modules/customers/lib/dictionaries.js.map +2 -2
  364. package/dist/modules/customers/lib/interactionReadModel.js +10 -0
  365. package/dist/modules/customers/lib/interactionReadModel.js.map +2 -2
  366. package/dist/modules/customers/lib/personCompanies.js +235 -0
  367. package/dist/modules/customers/lib/personCompanies.js.map +7 -0
  368. package/dist/modules/customers/lib/personCompanyLinkTable.js +42 -0
  369. package/dist/modules/customers/lib/personCompanyLinkTable.js.map +7 -0
  370. package/dist/modules/customers/lib/roleTypeUsage.js +104 -0
  371. package/dist/modules/customers/lib/roleTypeUsage.js.map +7 -0
  372. package/dist/modules/customers/migrations/Migration20260406214502.js +18 -0
  373. package/dist/modules/customers/migrations/Migration20260406214502.js.map +7 -0
  374. package/dist/modules/customers/migrations/Migration20260408135736.js +17 -0
  375. package/dist/modules/customers/migrations/Migration20260408135736.js.map +7 -0
  376. package/dist/modules/customers/migrations/Migration20260408225345.js +21 -0
  377. package/dist/modules/customers/migrations/Migration20260408225345.js.map +7 -0
  378. package/dist/modules/customers/migrations/Migration20260411075533.js +27 -0
  379. package/dist/modules/customers/migrations/Migration20260411075533.js.map +7 -0
  380. package/dist/modules/customers/migrations/Migration20260411103551.js +13 -0
  381. package/dist/modules/customers/migrations/Migration20260411103551.js.map +7 -0
  382. package/dist/modules/customers/migrations/Migration20260411130944.js +26 -0
  383. package/dist/modules/customers/migrations/Migration20260411130944.js.map +7 -0
  384. package/dist/modules/customers/migrations/Migration20260415095203.js +13 -0
  385. package/dist/modules/customers/migrations/Migration20260415095203.js.map +7 -0
  386. package/dist/modules/customers/migrations/Migration20260415135056.js +20 -0
  387. package/dist/modules/customers/migrations/Migration20260415135056.js.map +7 -0
  388. package/dist/modules/customers/migrations/Migration20260417140000.js +15 -0
  389. package/dist/modules/customers/migrations/Migration20260417140000.js.map +7 -0
  390. package/dist/modules/customers/migrations/Migration20260417160000.js +17 -0
  391. package/dist/modules/customers/migrations/Migration20260417160000.js.map +7 -0
  392. package/dist/modules/customers/migrations/Migration20260417235407.js +13 -0
  393. package/dist/modules/customers/migrations/Migration20260417235407.js.map +7 -0
  394. package/dist/modules/customers/setup.js +16 -1
  395. package/dist/modules/customers/setup.js.map +2 -2
  396. package/dist/modules/customers/subscribers/deal-closure-notification.js +16 -0
  397. package/dist/modules/customers/subscribers/deal-closure-notification.js.map +7 -0
  398. package/dist/modules/customers/subscribers/deal-lost-notification.js +16 -0
  399. package/dist/modules/customers/subscribers/deal-lost-notification.js.map +7 -0
  400. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js +2 -0
  401. package/dist/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.js.map +2 -2
  402. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js +154 -0
  403. package/dist/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.js.map +7 -0
  404. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js +6 -2
  405. package/dist/modules/dictionaries/api/[dictionaryId]/entries/route.js.map +2 -2
  406. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js +154 -0
  407. package/dist/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.js.map +7 -0
  408. package/dist/modules/dictionaries/api/context.js +8 -1
  409. package/dist/modules/dictionaries/api/context.js.map +2 -2
  410. package/dist/modules/dictionaries/api/openapi.js +18 -1
  411. package/dist/modules/dictionaries/api/openapi.js.map +2 -2
  412. package/dist/modules/dictionaries/commands/entry-operations.js +388 -0
  413. package/dist/modules/dictionaries/commands/entry-operations.js.map +7 -0
  414. package/dist/modules/dictionaries/commands/factory.js +24 -3
  415. package/dist/modules/dictionaries/commands/factory.js.map +2 -2
  416. package/dist/modules/dictionaries/commands/index.js +1 -0
  417. package/dist/modules/dictionaries/commands/index.js.map +2 -2
  418. package/dist/modules/dictionaries/components/DictionaryTable.js +6 -3
  419. package/dist/modules/dictionaries/components/DictionaryTable.js.map +2 -2
  420. package/dist/modules/dictionaries/data/entities.js +11 -1
  421. package/dist/modules/dictionaries/data/entities.js.map +2 -2
  422. package/dist/modules/dictionaries/data/validators.js +28 -2
  423. package/dist/modules/dictionaries/data/validators.js.map +2 -2
  424. package/dist/modules/dictionaries/events.js +18 -0
  425. package/dist/modules/dictionaries/events.js.map +7 -0
  426. package/dist/modules/dictionaries/lib/clientEntries.js +43 -0
  427. package/dist/modules/dictionaries/lib/clientEntries.js.map +7 -0
  428. package/dist/modules/dictionaries/migrations/Migration20260410171544.js +45 -0
  429. package/dist/modules/dictionaries/migrations/Migration20260410171544.js.map +7 -0
  430. package/dist/modules/inbox_ops/api/proposals/[id]/route.js +4 -1
  431. package/dist/modules/inbox_ops/api/proposals/[id]/route.js.map +2 -2
  432. package/dist/modules/query_index/lib/engine.js +1 -1
  433. package/dist/modules/query_index/lib/engine.js.map +2 -2
  434. package/dist/modules/sales/components/documents/AddressesSection.js +82 -42
  435. package/dist/modules/sales/components/documents/AddressesSection.js.map +2 -2
  436. package/dist/modules/sales/lib/dictionaries.js +16 -0
  437. package/dist/modules/sales/lib/dictionaries.js.map +2 -2
  438. package/dist/modules/sales/widgets/injection-table.js +5 -1
  439. package/dist/modules/sales/widgets/injection-table.js.map +2 -2
  440. package/generated/entities/action_log/index.ts +4 -0
  441. package/generated/entities/customer_company_billing/index.ts +10 -0
  442. package/generated/entities/customer_deal/index.ts +4 -0
  443. package/generated/entities/customer_deal_stage_transition/index.ts +14 -0
  444. package/generated/entities/customer_dictionary_kind_setting/index.ts +9 -0
  445. package/generated/entities/customer_entity/index.ts +4 -0
  446. package/generated/entities/customer_entity_role/index.ts +10 -0
  447. package/generated/entities/customer_interaction/index.ts +11 -0
  448. package/generated/entities/customer_label/index.ts +8 -0
  449. package/generated/entities/customer_label_assignment/index.ts +7 -0
  450. package/generated/entities/customer_person_company_link/index.ts +9 -0
  451. package/generated/entities/customer_person_company_role/index.ts +7 -0
  452. package/generated/entities/dictionary_entry/index.ts +2 -0
  453. package/generated/entities.ids.generated.ts +9 -1
  454. package/generated/entity-fields-registry.ts +116 -1
  455. package/package.json +3 -3
  456. package/src/modules/attachments/api/route.ts +48 -6
  457. package/src/modules/attachments/i18n/de.json +4 -0
  458. package/src/modules/attachments/i18n/en.json +4 -0
  459. package/src/modules/attachments/i18n/es.json +4 -0
  460. package/src/modules/attachments/i18n/pl.json +4 -0
  461. package/src/modules/audit_logs/api/audit-logs/actions/export/route.ts +260 -0
  462. package/src/modules/audit_logs/api/audit-logs/actions/route.ts +81 -6
  463. package/src/modules/audit_logs/cli.ts +79 -0
  464. package/src/modules/audit_logs/data/entities.ts +17 -0
  465. package/src/modules/audit_logs/data/validators.ts +9 -1
  466. package/src/modules/audit_logs/lib/changeRows.ts +47 -0
  467. package/src/modules/audit_logs/lib/display-helpers.tsx +4 -30
  468. package/src/modules/audit_logs/lib/projections.ts +110 -0
  469. package/src/modules/audit_logs/migrations/.snapshot-open-mercato.json +325 -2
  470. package/src/modules/audit_logs/migrations/Migration20260412160533.ts +21 -0
  471. package/src/modules/audit_logs/services/actionLogService.ts +455 -85
  472. package/src/modules/catalog/i18n/de.json +1 -0
  473. package/src/modules/catalog/i18n/en.json +1 -0
  474. package/src/modules/catalog/i18n/es.json +1 -0
  475. package/src/modules/catalog/i18n/pl.json +1 -0
  476. package/src/modules/customer_accounts/i18n/de.json +2 -0
  477. package/src/modules/customer_accounts/i18n/en.json +2 -0
  478. package/src/modules/customer_accounts/i18n/es.json +2 -0
  479. package/src/modules/customer_accounts/i18n/pl.json +2 -0
  480. package/src/modules/customers/acl.ts +2 -0
  481. package/src/modules/customers/api/activities/route.ts +4 -0
  482. package/src/modules/customers/api/assignable-staff/route.ts +250 -0
  483. package/src/modules/customers/api/companies/[id]/people/route.ts +244 -0
  484. package/src/modules/customers/api/companies/[id]/roles/route.ts +15 -0
  485. package/src/modules/customers/api/companies/[id]/route.ts +458 -40
  486. package/src/modules/customers/api/companies/route.ts +93 -15
  487. package/src/modules/customers/api/deals/[id]/companies/route.ts +203 -0
  488. package/src/modules/customers/api/deals/[id]/people/route.ts +182 -0
  489. package/src/modules/customers/api/deals/[id]/route.ts +554 -57
  490. package/src/modules/customers/api/deals/[id]/stats/route.ts +221 -0
  491. package/src/modules/customers/api/deals/route.ts +35 -46
  492. package/src/modules/customers/api/dictionaries/[kind]/[id]/route.ts +105 -3
  493. package/src/modules/customers/api/dictionaries/[kind]/route.ts +143 -44
  494. package/src/modules/customers/api/dictionaries/context.ts +45 -16
  495. package/src/modules/customers/api/dictionaries/kind-settings/route.ts +232 -0
  496. package/src/modules/customers/api/entity-roles-factory.ts +520 -0
  497. package/src/modules/customers/api/interactions/conflicts/route.ts +196 -0
  498. package/src/modules/customers/api/interactions/counts/route.ts +112 -0
  499. package/src/modules/customers/api/interactions/route.ts +95 -2
  500. package/src/modules/customers/api/labels/assign/route.ts +202 -0
  501. package/src/modules/customers/api/labels/auth.ts +19 -0
  502. package/src/modules/customers/api/labels/route.ts +310 -0
  503. package/src/modules/customers/api/labels/table-errors.ts +36 -0
  504. package/src/modules/customers/api/labels/unassign/route.ts +197 -0
  505. package/src/modules/customers/api/people/[id]/companies/[linkId]/route.ts +331 -0
  506. package/src/modules/customers/api/people/[id]/companies/context.ts +70 -0
  507. package/src/modules/customers/api/people/[id]/companies/enriched/route.ts +384 -0
  508. package/src/modules/customers/api/people/[id]/companies/route.ts +215 -0
  509. package/src/modules/customers/api/people/[id]/roles/route.ts +15 -0
  510. package/src/modules/customers/api/people/[id]/route.ts +153 -26
  511. package/src/modules/customers/api/people/route.ts +134 -31
  512. package/src/modules/customers/api/todos/route.ts +4 -0
  513. package/src/modules/customers/api/utils.ts +36 -0
  514. package/src/modules/customers/backend/config/customers/page.tsx +2 -6
  515. package/src/modules/customers/backend/customers/companies/page.tsx +36 -26
  516. package/src/modules/customers/backend/customers/companies-v2/[id]/page.tsx +277 -262
  517. package/src/modules/customers/backend/customers/deals/[id]/hooks/formatters.ts +19 -0
  518. package/src/modules/customers/backend/customers/deals/[id]/hooks/types.ts +104 -0
  519. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealActivities.ts +60 -0
  520. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealAssociations.ts +362 -0
  521. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealClosure.ts +113 -0
  522. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealData.ts +52 -0
  523. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealFormHandlers.ts +86 -0
  524. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealInjectedTabs.tsx +60 -0
  525. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealMutationContext.ts +76 -0
  526. package/src/modules/customers/backend/customers/deals/[id]/hooks/useDealPipeline.ts +56 -0
  527. package/src/modules/customers/backend/customers/deals/[id]/hooks/useScheduleDialog.ts +38 -0
  528. package/src/modules/customers/backend/customers/deals/[id]/page.tsx +587 -624
  529. package/src/modules/customers/backend/customers/deals/page.tsx +71 -28
  530. package/src/modules/customers/backend/customers/people/page.tsx +35 -29
  531. package/src/modules/customers/backend/customers/people-v2/[id]/page.tsx +343 -209
  532. package/src/modules/customers/cli.ts +107 -12
  533. package/src/modules/customers/commands/activities.ts +13 -0
  534. package/src/modules/customers/commands/deals.ts +386 -114
  535. package/src/modules/customers/commands/dictionaries.ts +175 -32
  536. package/src/modules/customers/commands/dictionaryKindSettings.ts +268 -0
  537. package/src/modules/customers/commands/entity-roles.ts +494 -0
  538. package/src/modules/customers/commands/index.ts +4 -0
  539. package/src/modules/customers/commands/interactions.ts +125 -21
  540. package/src/modules/customers/commands/labels.ts +626 -0
  541. package/src/modules/customers/commands/people.ts +373 -259
  542. package/src/modules/customers/commands/personCompanyLinks.ts +654 -0
  543. package/src/modules/customers/commands/shared.ts +16 -15
  544. package/src/modules/customers/commands/todos.ts +17 -1
  545. package/src/modules/customers/components/AddressEditor.tsx +1 -1
  546. package/src/modules/customers/components/CustomersConfigurationSections.tsx +36 -0
  547. package/src/modules/customers/components/DictionarySettings.tsx +43 -2
  548. package/src/modules/customers/components/detail/ActiveDealCard.tsx +175 -0
  549. package/src/modules/customers/components/detail/ActivitiesSection.tsx +267 -361
  550. package/src/modules/customers/components/detail/ActivityAiActions.tsx +49 -0
  551. package/src/modules/customers/components/detail/ActivityCard.tsx +154 -0
  552. package/src/modules/customers/components/detail/ActivityHistorySection.tsx +412 -0
  553. package/src/modules/customers/components/detail/ActivityLogTab.tsx +67 -0
  554. package/src/modules/customers/components/detail/ActivityTimeline.tsx +158 -0
  555. package/src/modules/customers/components/detail/ActivityTimelineFilters.tsx +163 -0
  556. package/src/modules/customers/components/detail/ActivityTypeSelector.tsx +53 -0
  557. package/src/modules/customers/components/detail/AiActionChips.tsx +48 -0
  558. package/src/modules/customers/components/detail/AssignRoleDialog.tsx +672 -0
  559. package/src/modules/customers/components/detail/ChangelogEntryRow.tsx +132 -0
  560. package/src/modules/customers/components/detail/ChangelogFilters.tsx +193 -0
  561. package/src/modules/customers/components/detail/ChangelogKpiCards.tsx +107 -0
  562. package/src/modules/customers/components/detail/ChangelogTab.tsx +629 -0
  563. package/src/modules/customers/components/detail/ComingSoonPlaceholder.tsx +21 -0
  564. package/src/modules/customers/components/detail/CompanyCard.tsx +419 -0
  565. package/src/modules/customers/components/detail/CompanyDashboardTab.tsx +161 -0
  566. package/src/modules/customers/components/detail/CompanyDetailHeader.tsx +243 -0
  567. package/src/modules/customers/components/detail/CompanyDetailTabs.tsx +172 -0
  568. package/src/modules/customers/components/detail/CompanyKpiBar.tsx +206 -0
  569. package/src/modules/customers/components/detail/CompanyPeopleSection.tsx +582 -288
  570. package/src/modules/customers/components/detail/CompanyTagsDialog.tsx +23 -0
  571. package/src/modules/customers/components/detail/ConfirmDealLostDialog.tsx +210 -0
  572. package/src/modules/customers/components/detail/CreatePersonDialog.tsx +178 -0
  573. package/src/modules/customers/components/detail/DealClosureActionBar.tsx +63 -0
  574. package/src/modules/customers/components/detail/DealDetailHeader.tsx +335 -0
  575. package/src/modules/customers/components/detail/DealDetailTabs.tsx +154 -0
  576. package/src/modules/customers/components/detail/DealForm.tsx +253 -101
  577. package/src/modules/customers/components/detail/DealLinkedEntitiesTab.tsx +349 -0
  578. package/src/modules/customers/components/detail/DealLostSummaryDialog.tsx +156 -0
  579. package/src/modules/customers/components/detail/DealWonPopup.tsx +164 -0
  580. package/src/modules/customers/components/detail/DealsSection.tsx +276 -221
  581. package/src/modules/customers/components/detail/DecisionMakersFooter.tsx +56 -0
  582. package/src/modules/customers/components/detail/EntityTagsDialog.tsx +1372 -0
  583. package/src/modules/customers/components/detail/InlineActivityComposer.tsx +239 -0
  584. package/src/modules/customers/components/detail/ManageTagsDialog.tsx +1331 -0
  585. package/src/modules/customers/components/detail/MiniWeekCalendar.tsx +338 -0
  586. package/src/modules/customers/components/detail/MobilePersonDetail.tsx +124 -0
  587. package/src/modules/customers/components/detail/NextStepCard.tsx +104 -0
  588. package/src/modules/customers/components/detail/PersonCard.tsx +238 -0
  589. package/src/modules/customers/components/detail/PersonCompaniesSection.tsx +426 -0
  590. package/src/modules/customers/components/detail/PersonDetailHeader.tsx +294 -0
  591. package/src/modules/customers/components/detail/PersonDetailTabs.tsx +172 -0
  592. package/src/modules/customers/components/detail/PersonTagsDialog.tsx +26 -0
  593. package/src/modules/customers/components/detail/PipelineStepper.tsx +245 -0
  594. package/src/modules/customers/components/detail/PlannedActivitiesSection.tsx +255 -0
  595. package/src/modules/customers/components/detail/RelationshipHealthCard.tsx +63 -0
  596. package/src/modules/customers/components/detail/RoleAssignmentRow.tsx +248 -0
  597. package/src/modules/customers/components/detail/RolesSection.tsx +311 -0
  598. package/src/modules/customers/components/detail/ScheduleActivityDialog.tsx +481 -0
  599. package/src/modules/customers/components/detail/aiActionCatalog.ts +77 -0
  600. package/src/modules/customers/components/detail/assignableStaff.ts +124 -0
  601. package/src/modules/customers/components/detail/dashboard/ActiveDealWidget.tsx +63 -0
  602. package/src/modules/customers/components/detail/dashboard/OpenTasksWidget.tsx +114 -0
  603. package/src/modules/customers/components/detail/dashboard/RecentActivityWidget.tsx +69 -0
  604. package/src/modules/customers/components/detail/dashboard/RelationshipHealthWidget.tsx +40 -0
  605. package/src/modules/customers/components/detail/dashboard/UpcomingMeetingsWidget.tsx +64 -0
  606. package/src/modules/customers/components/detail/dashboard/helpers.ts +78 -0
  607. package/src/modules/customers/components/detail/healthScoreUtils.ts +91 -0
  608. package/src/modules/customers/components/detail/hooks/useCurrencyDictionary.ts +8 -8
  609. package/src/modules/customers/components/detail/hooks/useCustomerDictionary.ts +10 -6
  610. package/src/modules/customers/components/detail/hooks/useInteractionMutations.ts +91 -0
  611. package/src/modules/customers/components/detail/notesAdapter.ts +91 -30
  612. package/src/modules/customers/components/detail/pipelineStageUtils.ts +29 -0
  613. package/src/modules/customers/components/detail/schedule/DateTimeFields.tsx +187 -0
  614. package/src/modules/customers/components/detail/schedule/FooterFields.tsx +79 -0
  615. package/src/modules/customers/components/detail/schedule/LinkedEntitiesField.tsx +277 -0
  616. package/src/modules/customers/components/detail/schedule/LocationField.tsx +42 -0
  617. package/src/modules/customers/components/detail/schedule/ParticipantsField.tsx +255 -0
  618. package/src/modules/customers/components/detail/schedule/fieldConfig.ts +70 -0
  619. package/src/modules/customers/components/detail/schedule/index.ts +9 -0
  620. package/src/modules/customers/components/detail/schedule/useScheduleFormState.ts +221 -0
  621. package/src/modules/customers/components/detail/types.ts +16 -0
  622. package/src/modules/customers/components/detail/utils.ts +25 -0
  623. package/src/modules/customers/components/formConfig.tsx +223 -28
  624. package/src/modules/customers/components/linking/LinkEntityDialog.tsx +920 -0
  625. package/src/modules/customers/components/linking/adapters/companyAdapter.tsx +398 -0
  626. package/src/modules/customers/components/linking/adapters/dealAdapter.tsx +578 -0
  627. package/src/modules/customers/components/linking/adapters/personAdapter.tsx +512 -0
  628. package/src/modules/customers/components/list/CollectionPreviewCell.tsx +66 -0
  629. package/src/modules/customers/data/entities.ts +353 -1
  630. package/src/modules/customers/data/validators.ts +170 -19
  631. package/src/modules/customers/events.ts +22 -0
  632. package/src/modules/customers/i18n/de.json +841 -2
  633. package/src/modules/customers/i18n/en.json +841 -2
  634. package/src/modules/customers/i18n/es.json +840 -1
  635. package/src/modules/customers/i18n/pl.json +841 -2
  636. package/src/modules/customers/lib/customerRoleTypes.ts +24 -0
  637. package/src/modules/customers/lib/dealClosureNotification.ts +64 -0
  638. package/src/modules/customers/lib/dealStageTransitionTable.ts +32 -0
  639. package/src/modules/customers/lib/dictionaries.ts +26 -10
  640. package/src/modules/customers/lib/interactionReadModel.ts +10 -0
  641. package/src/modules/customers/lib/personCompanies.ts +317 -0
  642. package/src/modules/customers/lib/personCompanyLinkTable.ts +58 -0
  643. package/src/modules/customers/lib/roleTypeUsage.ts +146 -0
  644. package/src/modules/customers/migrations/.snapshot-open-mercato.json +2747 -798
  645. package/src/modules/customers/migrations/Migration20260406214502.ts +19 -0
  646. package/src/modules/customers/migrations/Migration20260408135736.ts +15 -0
  647. package/src/modules/customers/migrations/Migration20260408225345.ts +23 -0
  648. package/src/modules/customers/migrations/Migration20260411075533.ts +30 -0
  649. package/src/modules/customers/migrations/Migration20260411103551.ts +13 -0
  650. package/src/modules/customers/migrations/Migration20260411130944.ts +30 -0
  651. package/src/modules/customers/migrations/Migration20260415095203.ts +13 -0
  652. package/src/modules/customers/migrations/Migration20260415135056.ts +22 -0
  653. package/src/modules/customers/migrations/Migration20260417140000.ts +15 -0
  654. package/src/modules/customers/migrations/Migration20260417160000.ts +17 -0
  655. package/src/modules/customers/migrations/Migration20260417235407.ts +13 -0
  656. package/src/modules/customers/setup.ts +15 -0
  657. package/src/modules/customers/subscribers/deal-closure-notification.ts +22 -0
  658. package/src/modules/customers/subscribers/deal-lost-notification.ts +22 -0
  659. package/src/modules/dictionaries/api/[dictionaryId]/entries/[entryId]/route.ts +2 -0
  660. package/src/modules/dictionaries/api/[dictionaryId]/entries/reorder/route.ts +162 -0
  661. package/src/modules/dictionaries/api/[dictionaryId]/entries/route.ts +6 -2
  662. package/src/modules/dictionaries/api/[dictionaryId]/entries/set-default/route.ts +162 -0
  663. package/src/modules/dictionaries/api/context.ts +9 -0
  664. package/src/modules/dictionaries/api/openapi.ts +17 -0
  665. package/src/modules/dictionaries/commands/entry-operations.ts +457 -0
  666. package/src/modules/dictionaries/commands/factory.ts +31 -3
  667. package/src/modules/dictionaries/commands/index.ts +1 -0
  668. package/src/modules/dictionaries/components/DictionaryTable.tsx +15 -6
  669. package/src/modules/dictionaries/data/entities.ts +9 -0
  670. package/src/modules/dictionaries/data/validators.ts +34 -0
  671. package/src/modules/dictionaries/events.ts +20 -0
  672. package/src/modules/dictionaries/i18n/de.json +2 -0
  673. package/src/modules/dictionaries/i18n/en.json +2 -0
  674. package/src/modules/dictionaries/i18n/es.json +2 -0
  675. package/src/modules/dictionaries/i18n/pl.json +2 -0
  676. package/src/modules/dictionaries/lib/clientEntries.ts +66 -0
  677. package/src/modules/dictionaries/migrations/.snapshot-open-mercato.json +185 -3
  678. package/src/modules/dictionaries/migrations/Migration20260410171544.ts +49 -0
  679. package/src/modules/inbox_ops/api/proposals/[id]/route.ts +4 -1
  680. package/src/modules/query_index/lib/engine.ts +9 -1
  681. package/src/modules/sales/components/documents/AddressesSection.tsx +92 -42
  682. package/src/modules/sales/i18n/de.json +28 -0
  683. package/src/modules/sales/i18n/en.json +28 -0
  684. package/src/modules/sales/i18n/es.json +28 -0
  685. package/src/modules/sales/i18n/pl.json +28 -0
  686. package/src/modules/sales/lib/dictionaries.ts +18 -0
  687. package/src/modules/sales/widgets/injection-table.ts +4 -0
@@ -0,0 +1,334 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
4
+ import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
5
+ import { getAuthFromRequest } from "@open-mercato/shared/lib/auth/server";
6
+ import { resolveOrganizationScopeForRequest } from "@open-mercato/core/modules/directory/utils/organizationScope";
7
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
8
+ import { findWithDecryption, findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
9
+ import {
10
+ CustomerEntity,
11
+ CustomerCompanyProfile,
12
+ CustomerPersonCompanyLink,
13
+ CustomerAddress,
14
+ CustomerCompanyBilling,
15
+ CustomerPersonCompanyRole,
16
+ CustomerTagAssignment,
17
+ CustomerDealCompanyLink,
18
+ CustomerInteraction
19
+ } from "../../../../../data/entities.js";
20
+ import { withActiveCustomerPersonCompanyLinkFilter } from "../../../../../lib/personCompanyLinkTable.js";
21
+ const paramsSchema = z.object({
22
+ id: z.string().uuid()
23
+ });
24
+ const querySchema = z.object({
25
+ page: z.coerce.number().min(1).default(1),
26
+ pageSize: z.coerce.number().min(1).max(100).default(20),
27
+ search: z.string().optional(),
28
+ sort: z.enum(["name-asc", "name-desc", "recent"]).default("name-asc")
29
+ });
30
+ const metadata = {
31
+ GET: { requireAuth: true, requireFeatures: ["customers.people.view"] }
32
+ };
33
+ const openApi = {
34
+ tag: "Customers",
35
+ methods: {
36
+ GET: {
37
+ summary: "Get enriched company data for a person's linked companies",
38
+ query: querySchema,
39
+ responses: [
40
+ {
41
+ status: 200,
42
+ description: "Enriched company rows with profile, billing, tags, deals and more",
43
+ schema: z.object({
44
+ items: z.array(
45
+ z.object({
46
+ linkId: z.string().uuid(),
47
+ companyId: z.string().uuid(),
48
+ displayName: z.string(),
49
+ isPrimary: z.boolean(),
50
+ subtitle: z.string().nullable(),
51
+ profile: z.object({
52
+ industry: z.string().nullable(),
53
+ sizeBucket: z.string().nullable(),
54
+ legalName: z.string().nullable(),
55
+ domain: z.string().nullable(),
56
+ websiteUrl: z.string().nullable()
57
+ }).nullable(),
58
+ billing: z.object({
59
+ bankName: z.string().nullable(),
60
+ bankAccountMasked: z.string().nullable(),
61
+ paymentTerms: z.string().nullable(),
62
+ preferredCurrency: z.string().nullable()
63
+ }).nullable(),
64
+ primaryAddress: z.object({ formatted: z.string() }).nullable(),
65
+ tags: z.array(
66
+ z.object({
67
+ id: z.string().uuid(),
68
+ label: z.string(),
69
+ color: z.string().nullable()
70
+ })
71
+ ),
72
+ roles: z.array(
73
+ z.object({
74
+ id: z.string().uuid(),
75
+ roleValue: z.string()
76
+ })
77
+ ),
78
+ activeDeal: z.object({
79
+ title: z.string(),
80
+ valueAmount: z.string().nullable(),
81
+ valueCurrency: z.string().nullable()
82
+ }).nullable(),
83
+ lastContactAt: z.string().nullable(),
84
+ clv: z.object({ amount: z.number(), currency: z.string() }).nullable(),
85
+ status: z.string().nullable(),
86
+ lifecycleStage: z.string().nullable(),
87
+ temperature: z.string().nullable(),
88
+ renewalQuarter: z.string().nullable()
89
+ })
90
+ ),
91
+ total: z.number().int().nonnegative(),
92
+ page: z.number().int().min(1),
93
+ pageSize: z.number().int().min(1),
94
+ totalPages: z.number().int().min(1)
95
+ })
96
+ }
97
+ ]
98
+ }
99
+ }
100
+ };
101
+ function formatAddress(address) {
102
+ return [address.addressLine1, address.city, address.region, address.postalCode].filter(Boolean).join(", ");
103
+ }
104
+ function buildSubtitle(industry, address) {
105
+ const parts = [];
106
+ if (industry) parts.push(industry);
107
+ if (address) {
108
+ const locationParts = [address.city, address.region].filter(Boolean);
109
+ if (locationParts.length > 0) parts.push(locationParts.join(", "));
110
+ }
111
+ return parts.length > 0 ? parts.join(" \xB7 ") : null;
112
+ }
113
+ function matchesSearch(item, query) {
114
+ const normalized = query.trim().toLowerCase();
115
+ if (!normalized.length) return true;
116
+ return [
117
+ typeof item.displayName === "string" ? item.displayName : null,
118
+ typeof item.subtitle === "string" ? item.subtitle : null,
119
+ typeof item.status === "string" ? item.status : null,
120
+ typeof item.lifecycleStage === "string" ? item.lifecycleStage : null,
121
+ typeof item.temperature === "string" ? item.temperature : null,
122
+ typeof item.renewalQuarter === "string" ? item.renewalQuarter : null
123
+ ].filter((value) => typeof value === "string" && value.length > 0).some((value) => value.toLowerCase().includes(normalized));
124
+ }
125
+ async function GET(req, ctx) {
126
+ const { translate } = await resolveTranslations();
127
+ try {
128
+ const { id } = paramsSchema.parse({ id: ctx.params?.id });
129
+ const auth = await getAuthFromRequest(req);
130
+ if (!auth?.tenantId) {
131
+ throw new CrudHttpError(401, { error: translate("customers.errors.unauthorized", "Unauthorized") });
132
+ }
133
+ const url = new URL(req.url);
134
+ const query = querySchema.parse({
135
+ page: url.searchParams.get("page") ?? void 0,
136
+ pageSize: url.searchParams.get("pageSize") ?? void 0,
137
+ search: url.searchParams.get("search") ?? void 0,
138
+ sort: url.searchParams.get("sort") ?? void 0
139
+ });
140
+ const container = await createRequestContainer();
141
+ const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req });
142
+ const em = container.resolve("em").fork();
143
+ const decryptionScope = { tenantId: auth.tenantId, organizationId: auth.orgId ?? null };
144
+ const person = await findOneWithDecryption(em, CustomerEntity, { id, kind: "person", tenantId: auth.tenantId, deletedAt: null }, {}, decryptionScope);
145
+ if (!person) {
146
+ throw new CrudHttpError(404, { error: translate("customers.errors.person_not_found", "Person not found") });
147
+ }
148
+ const allowedOrgIds = /* @__PURE__ */ new Set();
149
+ if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry));
150
+ else if (auth.orgId) allowedOrgIds.add(auth.orgId);
151
+ if (allowedOrgIds.size > 0 && !allowedOrgIds.has(person.organizationId)) {
152
+ throw new CrudHttpError(403, { error: translate("customers.errors.access_denied", "Access denied") });
153
+ }
154
+ const entityScope = { tenantId: auth.tenantId, organizationId: person.organizationId };
155
+ const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(
156
+ em,
157
+ {
158
+ person,
159
+ tenantId: auth.tenantId
160
+ },
161
+ "customers.people.companiesEnriched.GET"
162
+ );
163
+ const links = await findWithDecryption(
164
+ em,
165
+ CustomerPersonCompanyLink,
166
+ linkWhere,
167
+ { populate: ["company"] },
168
+ entityScope
169
+ );
170
+ const companyIds = links.map((link) => link.company.id);
171
+ if (companyIds.length === 0) {
172
+ return NextResponse.json({
173
+ items: [],
174
+ total: 0,
175
+ page: 1,
176
+ pageSize: query.pageSize,
177
+ totalPages: 1
178
+ });
179
+ }
180
+ const tenantScope = { tenantId: auth.tenantId, organizationId: person.organizationId };
181
+ const [allProfiles, allAddresses, allBillings, allTagAssignments, allRoles, allDealLinks, allInteractions] = await Promise.all([
182
+ findWithDecryption(em, CustomerCompanyProfile, { entity: { $in: companyIds }, ...tenantScope }, {}, entityScope),
183
+ findWithDecryption(em, CustomerAddress, { entity: { $in: companyIds }, isPrimary: true, ...tenantScope }, {}, entityScope),
184
+ findWithDecryption(em, CustomerCompanyBilling, { entity: { $in: companyIds }, ...tenantScope }, {}, entityScope),
185
+ findWithDecryption(em, CustomerTagAssignment, { entity: { $in: companyIds }, ...tenantScope }, { populate: ["tag"] }, entityScope),
186
+ findWithDecryption(em, CustomerPersonCompanyRole, { personEntity: person, companyEntity: { $in: companyIds }, ...tenantScope }, {}, entityScope),
187
+ // CustomerDealCompanyLink is a pure junction table without tenantId/organizationId columns;
188
+ // scoping flows transitively through the already-tenant-scoped `company` filter.
189
+ findWithDecryption(em, CustomerDealCompanyLink, { company: { $in: companyIds } }, { populate: ["deal"] }, entityScope),
190
+ findWithDecryption(em, CustomerInteraction, {
191
+ entity: { $in: companyIds },
192
+ occurredAt: { $ne: null },
193
+ deletedAt: null,
194
+ ...tenantScope
195
+ }, { orderBy: { occurredAt: "DESC" } }, entityScope)
196
+ ]);
197
+ const profileByCompany = new Map(allProfiles.map((p) => [p.entity.id, p]));
198
+ const addressByCompany = new Map(allAddresses.map((a) => [a.entity.id, a]));
199
+ const billingByCompany = new Map(allBillings.map((b) => [b.entity.id, b]));
200
+ const tagsByCompany = /* @__PURE__ */ new Map();
201
+ for (const ta of allTagAssignments) {
202
+ const entityId = ta.entity.id;
203
+ const existing = tagsByCompany.get(entityId) ?? [];
204
+ existing.push(ta);
205
+ tagsByCompany.set(entityId, existing);
206
+ }
207
+ const rolesByCompany = /* @__PURE__ */ new Map();
208
+ for (const role of allRoles) {
209
+ const entityId = role.companyEntity.id;
210
+ const existing = rolesByCompany.get(entityId) ?? [];
211
+ existing.push(role);
212
+ rolesByCompany.set(entityId, existing);
213
+ }
214
+ const dealLinksByCompany = /* @__PURE__ */ new Map();
215
+ for (const dcl of allDealLinks) {
216
+ const entityId = dcl.company.id;
217
+ const existing = dealLinksByCompany.get(entityId) ?? [];
218
+ existing.push(dcl);
219
+ dealLinksByCompany.set(entityId, existing);
220
+ }
221
+ const lastInteractionByCompany = /* @__PURE__ */ new Map();
222
+ for (const interaction of allInteractions) {
223
+ const entityId = interaction.entity.id;
224
+ if (!lastInteractionByCompany.has(entityId)) {
225
+ lastInteractionByCompany.set(entityId, interaction);
226
+ }
227
+ }
228
+ const items = links.map((link) => {
229
+ const company = link.company;
230
+ const companyId = company.id;
231
+ const profile = profileByCompany.get(companyId) ?? null;
232
+ const primaryAddress = addressByCompany.get(companyId) ?? null;
233
+ const billing = billingByCompany.get(companyId) ?? null;
234
+ const tagAssignments = tagsByCompany.get(companyId) ?? [];
235
+ const roles = rolesByCompany.get(companyId) ?? [];
236
+ const companyDealLinks = dealLinksByCompany.get(companyId) ?? [];
237
+ const lastInteraction = lastInteractionByCompany.get(companyId) ?? null;
238
+ const activeDeals = companyDealLinks.map((dcl) => dcl.deal).filter((deal) => deal.status !== "win" && deal.status !== "loose" && !deal.deletedAt).sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
239
+ const activeDeal = activeDeals.length > 0 ? activeDeals[0] : null;
240
+ const wonDeals = companyDealLinks.map((dcl) => dcl.deal).filter((deal) => deal.status === "win" && !deal.deletedAt);
241
+ let clv = null;
242
+ if (wonDeals.length > 0) {
243
+ const currencies = /* @__PURE__ */ new Map();
244
+ for (const deal of wonDeals) {
245
+ if (deal.valueAmount) {
246
+ const currency = deal.valueCurrency ?? "USD";
247
+ currencies.set(currency, (currencies.get(currency) ?? 0) + parseFloat(deal.valueAmount));
248
+ }
249
+ }
250
+ if (currencies.size > 0) {
251
+ const [currency, amount] = currencies.entries().next().value;
252
+ clv = { amount, currency };
253
+ }
254
+ }
255
+ return {
256
+ linkId: link.id,
257
+ companyId,
258
+ displayName: company.displayName,
259
+ isPrimary: Boolean(link.isPrimary),
260
+ subtitle: buildSubtitle(profile?.industry, primaryAddress),
261
+ profile: profile ? {
262
+ industry: profile.industry ?? null,
263
+ sizeBucket: profile.sizeBucket ?? null,
264
+ legalName: profile.legalName ?? null,
265
+ domain: profile.domain ?? null,
266
+ websiteUrl: profile.websiteUrl ?? null
267
+ } : null,
268
+ billing: billing ? {
269
+ bankName: billing.bankName ?? null,
270
+ bankAccountMasked: billing.bankAccountMasked ?? null,
271
+ paymentTerms: billing.paymentTerms ?? null,
272
+ preferredCurrency: billing.preferredCurrency ?? null
273
+ } : null,
274
+ primaryAddress: primaryAddress ? { formatted: formatAddress(primaryAddress) } : null,
275
+ tags: tagAssignments.map((ta) => {
276
+ const tag = ta.tag;
277
+ return {
278
+ id: tag.id,
279
+ label: tag.label,
280
+ color: tag.color ?? null
281
+ };
282
+ }),
283
+ roles: roles.map((r) => ({ id: r.id, roleValue: r.roleValue })),
284
+ activeDeal: activeDeal ? {
285
+ title: activeDeal.title,
286
+ valueAmount: activeDeal.valueAmount ?? null,
287
+ valueCurrency: activeDeal.valueCurrency ?? null
288
+ } : null,
289
+ lastContactAt: lastInteraction?.occurredAt?.toISOString() ?? null,
290
+ clv,
291
+ status: company.status ?? null,
292
+ lifecycleStage: company.lifecycleStage ?? null,
293
+ temperature: company.temperature ?? null,
294
+ renewalQuarter: company.renewalQuarter ?? null
295
+ };
296
+ });
297
+ const filteredItems = query.search?.trim().length ? items.filter((item) => matchesSearch(item, query.search ?? "")) : items;
298
+ const sortedItems = [...filteredItems].sort((left, right) => {
299
+ if (query.sort === "recent") {
300
+ const leftTimestamp = left.lastContactAt ? new Date(left.lastContactAt).getTime() : 0;
301
+ const rightTimestamp = right.lastContactAt ? new Date(right.lastContactAt).getTime() : 0;
302
+ if (leftTimestamp === rightTimestamp) {
303
+ return left.displayName.localeCompare(right.displayName, void 0, { sensitivity: "base" });
304
+ }
305
+ return rightTimestamp - leftTimestamp;
306
+ }
307
+ const compare = left.displayName.localeCompare(right.displayName, void 0, { sensitivity: "base" });
308
+ return query.sort === "name-asc" ? compare : -compare;
309
+ });
310
+ const total = sortedItems.length;
311
+ const totalPages = Math.max(1, Math.ceil(total / query.pageSize));
312
+ const page = Math.min(query.page, totalPages);
313
+ const start = (page - 1) * query.pageSize;
314
+ return NextResponse.json({
315
+ items: sortedItems.slice(start, start + query.pageSize),
316
+ total,
317
+ page,
318
+ pageSize: query.pageSize,
319
+ totalPages
320
+ });
321
+ } catch (err) {
322
+ if (err instanceof CrudHttpError) {
323
+ return NextResponse.json(err.body, { status: err.status });
324
+ }
325
+ console.error("[customers/people/[id]/companies/enriched] GET failed", err);
326
+ return NextResponse.json({ error: translate("customers.errors.internal", "Internal server error") }, { status: 500 });
327
+ }
328
+ }
329
+ export {
330
+ GET,
331
+ metadata,
332
+ openApi
333
+ };
334
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../../src/modules/customers/api/people/%5Bid%5D/companies/enriched/route.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption, findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerEntity,\n CustomerCompanyProfile,\n CustomerPersonCompanyLink,\n CustomerAddress,\n CustomerCompanyBilling,\n CustomerPersonCompanyRole,\n CustomerTagAssignment,\n CustomerDealCompanyLink,\n CustomerDeal,\n CustomerInteraction,\n} from '../../../../../data/entities'\nimport { withActiveCustomerPersonCompanyLinkFilter } from '../../../../../lib/personCompanyLinkTable'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst querySchema = z.object({\n page: z.coerce.number().min(1).default(1),\n pageSize: z.coerce.number().min(1).max(100).default(20),\n search: z.string().optional(),\n sort: z.enum(['name-asc', 'name-desc', 'recent']).default('name-asc'),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'Get enriched company data for a person\\'s linked companies',\n query: querySchema,\n responses: [\n {\n status: 200,\n description: 'Enriched company rows with profile, billing, tags, deals and more',\n schema: z.object({\n items: z.array(\n z.object({\n linkId: z.string().uuid(),\n companyId: z.string().uuid(),\n displayName: z.string(),\n isPrimary: z.boolean(),\n subtitle: z.string().nullable(),\n profile: z\n .object({\n industry: z.string().nullable(),\n sizeBucket: z.string().nullable(),\n legalName: z.string().nullable(),\n domain: z.string().nullable(),\n websiteUrl: z.string().nullable(),\n })\n .nullable(),\n billing: z\n .object({\n bankName: z.string().nullable(),\n bankAccountMasked: z.string().nullable(),\n paymentTerms: z.string().nullable(),\n preferredCurrency: z.string().nullable(),\n })\n .nullable(),\n primaryAddress: z.object({ formatted: z.string() }).nullable(),\n tags: z.array(\n z.object({\n id: z.string().uuid(),\n label: z.string(),\n color: z.string().nullable(),\n }),\n ),\n roles: z.array(\n z.object({\n id: z.string().uuid(),\n roleValue: z.string(),\n }),\n ),\n activeDeal: z\n .object({\n title: z.string(),\n valueAmount: z.string().nullable(),\n valueCurrency: z.string().nullable(),\n })\n .nullable(),\n lastContactAt: z.string().nullable(),\n clv: z.object({ amount: z.number(), currency: z.string() }).nullable(),\n status: z.string().nullable(),\n lifecycleStage: z.string().nullable(),\n temperature: z.string().nullable(),\n renewalQuarter: z.string().nullable(),\n }),\n ),\n total: z.number().int().nonnegative(),\n page: z.number().int().min(1),\n pageSize: z.number().int().min(1),\n totalPages: z.number().int().min(1),\n }),\n },\n ],\n },\n },\n}\n\nfunction formatAddress(address: CustomerAddress): string {\n return [address.addressLine1, address.city, address.region, address.postalCode]\n .filter(Boolean)\n .join(', ')\n}\n\nfunction buildSubtitle(industry: string | null | undefined, address: CustomerAddress | null): string | null {\n const parts: string[] = []\n if (industry) parts.push(industry)\n if (address) {\n const locationParts = [address.city, address.region].filter(Boolean)\n if (locationParts.length > 0) parts.push(locationParts.join(', '))\n }\n return parts.length > 0 ? parts.join(' \u00B7 ') : null\n}\n\nfunction matchesSearch(item: Record<string, unknown>, query: string): boolean {\n const normalized = query.trim().toLowerCase()\n if (!normalized.length) return true\n return [\n typeof item.displayName === 'string' ? item.displayName : null,\n typeof item.subtitle === 'string' ? item.subtitle : null,\n typeof item.status === 'string' ? item.status : null,\n typeof item.lifecycleStage === 'string' ? item.lifecycleStage : null,\n typeof item.temperature === 'string' ? item.temperature : null,\n typeof item.renewalQuarter === 'string' ? item.renewalQuarter : null,\n ]\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n .some((value) => value.toLowerCase().includes(normalized))\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) {\n throw new CrudHttpError(401, { error: translate('customers.errors.unauthorized', 'Unauthorized') })\n }\n const url = new URL(req.url)\n const query = querySchema.parse({\n page: url.searchParams.get('page') ?? undefined,\n pageSize: url.searchParams.get('pageSize') ?? undefined,\n search: url.searchParams.get('search') ?? undefined,\n sort: url.searchParams.get('sort') ?? undefined,\n })\n\n const container = await createRequestContainer()\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const em = (container.resolve('em') as EntityManager).fork()\n\n const decryptionScope = { tenantId: auth.tenantId, organizationId: auth.orgId ?? null }\n const person = await findOneWithDecryption(em, CustomerEntity, { id, kind: 'person', tenantId: auth.tenantId, deletedAt: null }, {}, decryptionScope)\n if (!person) {\n throw new CrudHttpError(404, { error: translate('customers.errors.person_not_found', 'Person not found') })\n }\n\n const allowedOrgIds = new Set<string>()\n if (scope?.filterIds?.length) scope.filterIds.forEach((entry) => allowedOrgIds.add(entry))\n else if (auth.orgId) allowedOrgIds.add(auth.orgId)\n\n if (allowedOrgIds.size > 0 && !allowedOrgIds.has(person.organizationId)) {\n throw new CrudHttpError(403, { error: translate('customers.errors.access_denied', 'Access denied') })\n }\n\n const entityScope = { tenantId: auth.tenantId, organizationId: person.organizationId }\n const linkWhere = await withActiveCustomerPersonCompanyLinkFilter(\n em,\n {\n person,\n tenantId: auth.tenantId,\n },\n 'customers.people.companiesEnriched.GET',\n )\n const links = await findWithDecryption(\n em,\n CustomerPersonCompanyLink,\n linkWhere,\n { populate: ['company'] },\n entityScope,\n )\n\n const companyIds = links.map((link) => (link.company as CustomerEntity).id)\n\n if (companyIds.length === 0) {\n return NextResponse.json({\n items: [],\n total: 0,\n page: 1,\n pageSize: query.pageSize,\n totalPages: 1,\n })\n }\n\n const tenantScope = { tenantId: auth.tenantId, organizationId: person.organizationId }\n const [allProfiles, allAddresses, allBillings, allTagAssignments, allRoles, allDealLinks, allInteractions] =\n await Promise.all([\n findWithDecryption(em, CustomerCompanyProfile, { entity: { $in: companyIds }, ...tenantScope }, {}, entityScope),\n findWithDecryption(em, CustomerAddress, { entity: { $in: companyIds }, isPrimary: true, ...tenantScope }, {}, entityScope),\n findWithDecryption(em, CustomerCompanyBilling, { entity: { $in: companyIds }, ...tenantScope }, {}, entityScope),\n findWithDecryption(em, CustomerTagAssignment, { entity: { $in: companyIds }, ...tenantScope }, { populate: ['tag'] }, entityScope),\n findWithDecryption(em, CustomerPersonCompanyRole, { personEntity: person, companyEntity: { $in: companyIds }, ...tenantScope }, {}, entityScope),\n // CustomerDealCompanyLink is a pure junction table without tenantId/organizationId columns;\n // scoping flows transitively through the already-tenant-scoped `company` filter.\n findWithDecryption(em, CustomerDealCompanyLink, { company: { $in: companyIds } }, { populate: ['deal'] }, entityScope),\n findWithDecryption(em, CustomerInteraction, {\n entity: { $in: companyIds },\n occurredAt: { $ne: null },\n deletedAt: null,\n ...tenantScope,\n }, { orderBy: { occurredAt: 'DESC' } }, entityScope),\n ])\n\n const profileByCompany = new Map(allProfiles.map((p) => [(p.entity as { id: string }).id, p]))\n const addressByCompany = new Map(allAddresses.map((a) => [(a.entity as { id: string }).id, a]))\n const billingByCompany = new Map(allBillings.map((b) => [(b.entity as { id: string }).id, b]))\n\n const tagsByCompany = new Map<string, typeof allTagAssignments>()\n for (const ta of allTagAssignments) {\n const entityId = (ta.entity as { id: string }).id\n const existing = tagsByCompany.get(entityId) ?? []\n existing.push(ta)\n tagsByCompany.set(entityId, existing)\n }\n\n const rolesByCompany = new Map<string, typeof allRoles>()\n for (const role of allRoles) {\n const entityId = (role.companyEntity as { id: string }).id\n const existing = rolesByCompany.get(entityId) ?? []\n existing.push(role)\n rolesByCompany.set(entityId, existing)\n }\n\n const dealLinksByCompany = new Map<string, typeof allDealLinks>()\n for (const dcl of allDealLinks) {\n const entityId = (dcl.company as { id: string }).id\n const existing = dealLinksByCompany.get(entityId) ?? []\n existing.push(dcl)\n dealLinksByCompany.set(entityId, existing)\n }\n\n const lastInteractionByCompany = new Map<string, CustomerInteraction>()\n for (const interaction of allInteractions) {\n const entityId = (interaction.entity as { id: string }).id\n if (!lastInteractionByCompany.has(entityId)) {\n lastInteractionByCompany.set(entityId, interaction)\n }\n }\n\n const items = links.map((link) => {\n const company = link.company as CustomerEntity\n const companyId = company.id\n const profile = profileByCompany.get(companyId) ?? null\n const primaryAddress = addressByCompany.get(companyId) ?? null\n const billing = billingByCompany.get(companyId) ?? null\n const tagAssignments = tagsByCompany.get(companyId) ?? []\n const roles = rolesByCompany.get(companyId) ?? []\n const companyDealLinks = dealLinksByCompany.get(companyId) ?? []\n const lastInteraction = lastInteractionByCompany.get(companyId) ?? null\n\n const activeDeals = companyDealLinks\n .map((dcl) => dcl.deal as CustomerDeal)\n .filter((deal) => deal.status !== 'win' && deal.status !== 'loose' && !deal.deletedAt)\n .sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())\n const activeDeal = activeDeals.length > 0 ? activeDeals[0] : null\n\n const wonDeals = companyDealLinks\n .map((dcl) => dcl.deal as CustomerDeal)\n .filter((deal) => deal.status === 'win' && !deal.deletedAt)\n let clv: { amount: number; currency: string } | null = null\n if (wonDeals.length > 0) {\n const currencies = new Map<string, number>()\n for (const deal of wonDeals) {\n if (deal.valueAmount) {\n const currency = deal.valueCurrency ?? 'USD'\n currencies.set(currency, (currencies.get(currency) ?? 0) + parseFloat(deal.valueAmount))\n }\n }\n if (currencies.size > 0) {\n const [currency, amount] = currencies.entries().next().value!\n clv = { amount, currency }\n }\n }\n\n return {\n linkId: link.id,\n companyId,\n displayName: company.displayName,\n isPrimary: Boolean(link.isPrimary),\n subtitle: buildSubtitle(profile?.industry, primaryAddress),\n profile: profile\n ? {\n industry: profile.industry ?? null,\n sizeBucket: profile.sizeBucket ?? null,\n legalName: profile.legalName ?? null,\n domain: profile.domain ?? null,\n websiteUrl: profile.websiteUrl ?? null,\n }\n : null,\n billing: billing\n ? {\n bankName: billing.bankName ?? null,\n bankAccountMasked: billing.bankAccountMasked ?? null,\n paymentTerms: billing.paymentTerms ?? null,\n preferredCurrency: billing.preferredCurrency ?? null,\n }\n : null,\n primaryAddress: primaryAddress ? { formatted: formatAddress(primaryAddress) } : null,\n tags: tagAssignments.map((ta) => {\n const tag = ta.tag as { id: string; label: string; color?: string | null }\n return {\n id: tag.id,\n label: tag.label,\n color: tag.color ?? null,\n }\n }),\n roles: roles.map((r) => ({ id: r.id, roleValue: r.roleValue })),\n activeDeal: activeDeal\n ? {\n title: activeDeal.title,\n valueAmount: activeDeal.valueAmount ?? null,\n valueCurrency: activeDeal.valueCurrency ?? null,\n }\n : null,\n lastContactAt: lastInteraction?.occurredAt?.toISOString() ?? null,\n clv,\n status: company.status ?? null,\n lifecycleStage: company.lifecycleStage ?? null,\n temperature: company.temperature ?? null,\n renewalQuarter: company.renewalQuarter ?? null,\n }\n })\n\n const filteredItems = query.search?.trim().length\n ? items.filter((item) => matchesSearch(item as Record<string, unknown>, query.search ?? ''))\n : items\n const sortedItems = [...filteredItems].sort((left, right) => {\n if (query.sort === 'recent') {\n const leftTimestamp = left.lastContactAt ? new Date(left.lastContactAt).getTime() : 0\n const rightTimestamp = right.lastContactAt ? new Date(right.lastContactAt).getTime() : 0\n if (leftTimestamp === rightTimestamp) {\n return left.displayName.localeCompare(right.displayName, undefined, { sensitivity: 'base' })\n }\n return rightTimestamp - leftTimestamp\n }\n const compare = left.displayName.localeCompare(right.displayName, undefined, { sensitivity: 'base' })\n return query.sort === 'name-asc' ? compare : -compare\n })\n\n const total = sortedItems.length\n const totalPages = Math.max(1, Math.ceil(total / query.pageSize))\n const page = Math.min(query.page, totalPages)\n const start = (page - 1) * query.pageSize\n\n return NextResponse.json({\n items: sortedItems.slice(start, start + query.pageSize),\n total,\n page,\n pageSize: query.pageSize,\n totalPages,\n })\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n console.error('[customers/people/[id]/companies/enriched] GET failed', err)\n return NextResponse.json({ error: translate('customers.errors.internal', 'Internal server error') }, { status: 500 })\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,qBAAqB;AAC9B,SAAS,8BAA8B;AACvC,SAAS,0BAA0B;AACnC,SAAS,0CAA0C;AACnD,SAAS,2BAA2B;AAEpC,SAAS,oBAAoB,6BAA6B;AAC1D;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA;AAAA,OACK;AACP,SAAS,iDAAiD;AAE1D,MAAM,eAAe,EAAE,OAAO;AAAA,EAC5B,IAAI,EAAE,OAAO,EAAE,KAAK;AACtB,CAAC;AAED,MAAM,cAAc,EAAE,OAAO;AAAA,EAC3B,MAAM,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,QAAQ,CAAC;AAAA,EACxC,UAAU,EAAE,OAAO,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,QAAQ,EAAE;AAAA,EACtD,QAAQ,EAAE,OAAO,EAAE,SAAS;AAAA,EAC5B,MAAM,EAAE,KAAK,CAAC,YAAY,aAAa,QAAQ,CAAC,EAAE,QAAQ,UAAU;AACtE,CAAC;AAEM,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,uBAAuB,EAAE;AACvE;AAEO,MAAM,UAA2B;AAAA,EACtC,KAAK;AA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E,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACtH;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,205 @@
1
+ import { NextResponse } from "next/server";
2
+ import { z } from "zod";
3
+ import { CrudHttpError } from "@open-mercato/shared/lib/crud/errors";
4
+ import {
5
+ runCrudMutationGuardAfterSuccess,
6
+ validateCrudMutationGuard
7
+ } from "@open-mercato/shared/lib/crud/mutation-guard";
8
+ import {
9
+ loadPersonCompanyLinks,
10
+ summarizePersonCompanies
11
+ } from "@open-mercato/core/modules/customers/lib/personCompanies";
12
+ import { serializeOperationMetadata } from "@open-mercato/shared/lib/commands/operationMetadata";
13
+ import { readJsonSafe } from "@open-mercato/shared/lib/http/readJsonSafe";
14
+ import { resolveAuthActorId } from "@open-mercato/core/modules/customers/lib/interactionRequestContext";
15
+ import { findOneWithDecryption } from "@open-mercato/shared/lib/encryption/find";
16
+ import {
17
+ CustomerEntity,
18
+ CustomerPersonCompanyLink
19
+ } from "@open-mercato/core/modules/customers/data/entities";
20
+ import {
21
+ personCompanyLinkCreateSchema
22
+ } from "@open-mercato/core/modules/customers/data/validators";
23
+ import { loadPersonContext } from "./context.js";
24
+ import { resolveTranslations } from "@open-mercato/shared/lib/i18n/server";
25
+ const paramsSchema = z.object({
26
+ id: z.string().uuid()
27
+ });
28
+ const createSchema = z.object({
29
+ companyId: z.string().uuid(),
30
+ isPrimary: z.boolean().optional()
31
+ });
32
+ const listResponseSchema = z.object({
33
+ items: z.array(
34
+ z.object({
35
+ id: z.string().uuid(),
36
+ companyId: z.string().uuid(),
37
+ displayName: z.string(),
38
+ isPrimary: z.boolean()
39
+ })
40
+ )
41
+ });
42
+ const createResponseSchema = z.object({
43
+ ok: z.literal(true),
44
+ result: z.object({
45
+ id: z.string().uuid(),
46
+ companyId: z.string().uuid(),
47
+ displayName: z.string(),
48
+ isPrimary: z.boolean()
49
+ })
50
+ });
51
+ const metadata = {
52
+ GET: { requireAuth: true, requireFeatures: ["customers.people.view"] },
53
+ POST: { requireAuth: true, requireFeatures: ["customers.people.manage"] }
54
+ };
55
+ const openApi = {
56
+ tag: "Customers",
57
+ methods: {
58
+ GET: {
59
+ summary: "List linked companies for a person",
60
+ responses: [{ status: 200, description: "Linked company rows", schema: listResponseSchema }]
61
+ },
62
+ POST: {
63
+ summary: "Link a company to a person",
64
+ requestBody: { schema: createSchema },
65
+ responses: [{ status: 200, description: "Linked company row", schema: createResponseSchema }]
66
+ }
67
+ }
68
+ };
69
+ async function GET(req, ctx) {
70
+ const { translate } = await resolveTranslations();
71
+ try {
72
+ const { id } = paramsSchema.parse({ id: ctx.params?.id });
73
+ const { em, person, profile } = await loadPersonContext(req, id);
74
+ const links = await loadPersonCompanyLinks(em, person);
75
+ const items = summarizePersonCompanies(profile, links).map((entry) => ({
76
+ id: entry.linkId ?? entry.companyId,
77
+ companyId: entry.companyId,
78
+ displayName: entry.displayName,
79
+ isPrimary: entry.isPrimary
80
+ }));
81
+ return NextResponse.json({ items });
82
+ } catch (err) {
83
+ if (err instanceof CrudHttpError) {
84
+ return NextResponse.json(err.body, { status: err.status });
85
+ }
86
+ return NextResponse.json({ error: translate("customers.errors.internal", "Internal server error") }, { status: 500 });
87
+ }
88
+ }
89
+ async function POST(req, ctx) {
90
+ const { translate } = await resolveTranslations();
91
+ try {
92
+ const { id } = paramsSchema.parse({ id: ctx.params?.id });
93
+ const payload = createSchema.parse(await readJsonSafe(req, {}));
94
+ const { container, auth, selectedOrganizationId, em, person } = await loadPersonContext(req, id);
95
+ if (!selectedOrganizationId) {
96
+ throw new CrudHttpError(400, { error: translate("customers.errors.organization_required", "Organization context is required") });
97
+ }
98
+ const guardUserId = resolveAuthActorId(auth);
99
+ const guardResult = await validateCrudMutationGuard(container, {
100
+ tenantId: auth.tenantId,
101
+ organizationId: selectedOrganizationId,
102
+ userId: guardUserId,
103
+ resourceKind: "customers.person",
104
+ resourceId: person.id,
105
+ operation: "custom",
106
+ requestMethod: req.method,
107
+ requestHeaders: req.headers,
108
+ mutationPayload: payload
109
+ });
110
+ if (guardResult && !guardResult.ok) {
111
+ return NextResponse.json(guardResult.body, { status: guardResult.status });
112
+ }
113
+ const commandInput = personCompanyLinkCreateSchema.parse({
114
+ personEntityId: person.id,
115
+ companyEntityId: payload.companyId,
116
+ isPrimary: payload.isPrimary,
117
+ tenantId: auth.tenantId,
118
+ organizationId: selectedOrganizationId
119
+ });
120
+ const commandBus = container.resolve("commandBus");
121
+ const { result, logEntry } = await commandBus.execute(
122
+ "customers.personCompanyLinks.create",
123
+ {
124
+ input: commandInput,
125
+ ctx: {
126
+ container,
127
+ auth,
128
+ organizationScope: null,
129
+ selectedOrganizationId,
130
+ organizationIds: [selectedOrganizationId],
131
+ request: req
132
+ }
133
+ }
134
+ );
135
+ if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {
136
+ await runCrudMutationGuardAfterSuccess(container, {
137
+ tenantId: auth.tenantId,
138
+ organizationId: selectedOrganizationId,
139
+ userId: guardUserId,
140
+ resourceKind: "customers.person",
141
+ resourceId: person.id,
142
+ operation: "custom",
143
+ requestMethod: req.method,
144
+ requestHeaders: req.headers,
145
+ metadata: guardResult.metadata ?? null
146
+ });
147
+ }
148
+ const freshEm = container.resolve("em").fork();
149
+ const linkRecord = await findOneWithDecryption(
150
+ freshEm,
151
+ CustomerPersonCompanyLink,
152
+ { id: result.linkId, tenantId: auth.tenantId, organizationId: selectedOrganizationId },
153
+ { populate: ["company"] },
154
+ { tenantId: auth.tenantId, organizationId: selectedOrganizationId }
155
+ );
156
+ const company = linkRecord && typeof linkRecord.company !== "string" ? linkRecord.company : null;
157
+ let displayName = company?.displayName ?? "";
158
+ if (!displayName && !company) {
159
+ const fallbackCompany = await findOneWithDecryption(
160
+ freshEm,
161
+ CustomerEntity,
162
+ { id: payload.companyId, tenantId: auth.tenantId, organizationId: selectedOrganizationId, deletedAt: null },
163
+ void 0,
164
+ { tenantId: auth.tenantId, organizationId: selectedOrganizationId }
165
+ );
166
+ displayName = fallbackCompany?.displayName ?? "";
167
+ }
168
+ const response = NextResponse.json({
169
+ ok: true,
170
+ result: {
171
+ id: result.linkId,
172
+ companyId: company?.id ?? payload.companyId,
173
+ displayName,
174
+ isPrimary: linkRecord ? Boolean(linkRecord.isPrimary) : Boolean(payload.isPrimary)
175
+ }
176
+ });
177
+ if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {
178
+ response.headers.set(
179
+ "x-om-operation",
180
+ serializeOperationMetadata({
181
+ id: logEntry.id,
182
+ undoToken: logEntry.undoToken,
183
+ commandId: logEntry.commandId,
184
+ actionLabel: logEntry.actionLabel ?? null,
185
+ resourceKind: logEntry.resourceKind ?? "customers.personCompanyLink",
186
+ resourceId: logEntry.resourceId ?? result.linkId,
187
+ executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : (/* @__PURE__ */ new Date()).toISOString()
188
+ })
189
+ );
190
+ }
191
+ return response;
192
+ } catch (err) {
193
+ if (err instanceof CrudHttpError) {
194
+ return NextResponse.json(err.body, { status: err.status });
195
+ }
196
+ return NextResponse.json({ error: translate("customers.errors.internal", "Internal server error") }, { status: 500 });
197
+ }
198
+ }
199
+ export {
200
+ GET,
201
+ POST,
202
+ metadata,
203
+ openApi
204
+ };
205
+ //# sourceMappingURL=route.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../../src/modules/customers/api/people/%5Bid%5D/companies/route.ts"],
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport { CrudHttpError } from '@open-mercato/shared/lib/crud/errors'\nimport {\n runCrudMutationGuardAfterSuccess,\n validateCrudMutationGuard,\n} from '@open-mercato/shared/lib/crud/mutation-guard'\nimport {\n loadPersonCompanyLinks,\n summarizePersonCompanies,\n} from '@open-mercato/core/modules/customers/lib/personCompanies'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport type { CommandBus } from '@open-mercato/shared/lib/commands'\nimport { serializeOperationMetadata } from '@open-mercato/shared/lib/commands/operationMetadata'\nimport { readJsonSafe } from '@open-mercato/shared/lib/http/readJsonSafe'\nimport { resolveAuthActorId } from '@open-mercato/core/modules/customers/lib/interactionRequestContext'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerEntity,\n CustomerPersonCompanyLink,\n} from '@open-mercato/core/modules/customers/data/entities'\nimport {\n personCompanyLinkCreateSchema,\n type PersonCompanyLinkCreateInput,\n} from '@open-mercato/core/modules/customers/data/validators'\nimport { loadPersonContext } from './context'\nimport { resolveTranslations } from '@open-mercato/shared/lib/i18n/server'\nimport type { EntityManager } from '@mikro-orm/postgresql'\n\nconst paramsSchema = z.object({\n id: z.string().uuid(),\n})\n\nconst createSchema = z.object({\n companyId: z.string().uuid(),\n isPrimary: z.boolean().optional(),\n})\n\nconst listResponseSchema = z.object({\n items: z.array(\n z.object({\n id: z.string().uuid(),\n companyId: z.string().uuid(),\n displayName: z.string(),\n isPrimary: z.boolean(),\n }),\n ),\n})\n\nconst createResponseSchema = z.object({\n ok: z.literal(true),\n result: z.object({\n id: z.string().uuid(),\n companyId: z.string().uuid(),\n displayName: z.string(),\n isPrimary: z.boolean(),\n }),\n})\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.people.view'] },\n POST: { requireAuth: true, requireFeatures: ['customers.people.manage'] },\n}\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n methods: {\n GET: {\n summary: 'List linked companies for a person',\n responses: [{ status: 200, description: 'Linked company rows', schema: listResponseSchema }],\n },\n POST: {\n summary: 'Link a company to a person',\n requestBody: { schema: createSchema },\n responses: [{ status: 200, description: 'Linked company row', schema: createResponseSchema }],\n },\n },\n}\n\nexport async function GET(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const { em, person, profile } = await loadPersonContext(req, id)\n const links = await loadPersonCompanyLinks(em, person)\n const items = summarizePersonCompanies(profile, links).map((entry) => ({\n id: entry.linkId ?? entry.companyId,\n companyId: entry.companyId,\n displayName: entry.displayName,\n isPrimary: entry.isPrimary,\n }))\n return NextResponse.json({ items })\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n return NextResponse.json({ error: translate('customers.errors.internal', 'Internal server error') }, { status: 500 })\n }\n}\n\nexport async function POST(req: Request, ctx: { params?: { id?: string } }) {\n const { translate } = await resolveTranslations()\n try {\n const { id } = paramsSchema.parse({ id: ctx.params?.id })\n const payload = createSchema.parse(await readJsonSafe(req, {}))\n const { container, auth, selectedOrganizationId, em, person } = await loadPersonContext(req, id)\n if (!selectedOrganizationId) {\n throw new CrudHttpError(400, { error: translate('customers.errors.organization_required', 'Organization context is required') })\n }\n const guardUserId = resolveAuthActorId(auth)\n const guardResult = await validateCrudMutationGuard(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.person',\n resourceId: person.id,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n mutationPayload: payload,\n })\n if (guardResult && !guardResult.ok) {\n return NextResponse.json(guardResult.body, { status: guardResult.status })\n }\n\n const commandInput = personCompanyLinkCreateSchema.parse({\n personEntityId: person.id,\n companyEntityId: payload.companyId,\n isPrimary: payload.isPrimary,\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n } satisfies PersonCompanyLinkCreateInput)\n\n const commandBus = container.resolve('commandBus') as CommandBus\n const { result, logEntry } = await commandBus.execute<PersonCompanyLinkCreateInput, { linkId: string; created: boolean; undeleted: boolean }>(\n 'customers.personCompanyLinks.create',\n {\n input: commandInput,\n ctx: {\n container,\n auth,\n organizationScope: null,\n selectedOrganizationId,\n organizationIds: [selectedOrganizationId],\n request: req,\n },\n },\n )\n\n if (guardResult?.ok && guardResult.shouldRunAfterSuccess) {\n await runCrudMutationGuardAfterSuccess(container, {\n tenantId: auth.tenantId,\n organizationId: selectedOrganizationId,\n userId: guardUserId,\n resourceKind: 'customers.person',\n resourceId: person.id,\n operation: 'custom',\n requestMethod: req.method,\n requestHeaders: req.headers,\n metadata: guardResult.metadata ?? null,\n })\n }\n\n const freshEm = (container.resolve('em') as EntityManager).fork()\n const linkRecord = await findOneWithDecryption(\n freshEm,\n CustomerPersonCompanyLink,\n { id: result.linkId, tenantId: auth.tenantId, organizationId: selectedOrganizationId },\n { populate: ['company'] },\n { tenantId: auth.tenantId, organizationId: selectedOrganizationId },\n )\n const company = linkRecord && typeof linkRecord.company !== 'string' ? linkRecord.company : null\n let displayName = company?.displayName ?? ''\n if (!displayName && !company) {\n const fallbackCompany = await findOneWithDecryption(\n freshEm,\n CustomerEntity,\n { id: payload.companyId, tenantId: auth.tenantId, organizationId: selectedOrganizationId, deletedAt: null },\n undefined,\n { tenantId: auth.tenantId, organizationId: selectedOrganizationId },\n )\n displayName = fallbackCompany?.displayName ?? ''\n }\n\n const response = NextResponse.json({\n ok: true as const,\n result: {\n id: result.linkId,\n companyId: company?.id ?? payload.companyId,\n displayName,\n isPrimary: linkRecord ? Boolean(linkRecord.isPrimary) : Boolean(payload.isPrimary),\n },\n })\n if (logEntry?.undoToken && logEntry.id && logEntry.commandId) {\n response.headers.set(\n 'x-om-operation',\n serializeOperationMetadata({\n id: logEntry.id,\n undoToken: logEntry.undoToken,\n commandId: logEntry.commandId,\n actionLabel: logEntry.actionLabel ?? null,\n resourceKind: logEntry.resourceKind ?? 'customers.personCompanyLink',\n resourceId: logEntry.resourceId ?? result.linkId,\n executedAt: logEntry.createdAt instanceof Date ? logEntry.createdAt.toISOString() : new Date().toISOString(),\n }),\n )\n }\n return response\n } catch (err) {\n if (err instanceof CrudHttpError) {\n return NextResponse.json(err.body, { status: err.status })\n }\n return NextResponse.json({ error: translate('customers.errors.internal', 'Internal server error') }, { status: 500 })\n }\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAClB,SAAS,qBAAqB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AAS;AAAA,UACpB,aAAa,SAAS,eAAe;AAAA,UACrC,cAAc,SAAS,gBAAgB;AAAA,UACvC,YAAY,SAAS,cAAc,OAAO;AAAA,UAC1C,YAAY,SAAS,qBAAqB,OAAO,SAAS,UAAU,YAAY,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,QAC7G,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO;AAAA,EACT,SAAS,KAAK;AACZ,QAAI,eAAe,eAAe;AAChC,aAAO,aAAa,KAAK,IAAI,MAAM,EAAE,QAAQ,IAAI,OAAO,CAAC;AAAA,IAC3D;AACA,WAAO,aAAa,KAAK,EAAE,OAAO,UAAU,6BAA6B,uBAAuB,EAAE,GAAG,EAAE,QAAQ,IAAI,CAAC;AAAA,EACtH;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,22 @@
1
+ import { buildEntityRolesOpenApi, createEntityRolesHandlers } from "../../../../api/entity-roles-factory.js";
2
+ const metadata = {
3
+ GET: { requireAuth: true, requireFeatures: ["customers.roles.view"] },
4
+ POST: { requireAuth: true, requireFeatures: ["customers.roles.manage"] },
5
+ PUT: { requireAuth: true, requireFeatures: ["customers.roles.manage"] },
6
+ DELETE: { requireAuth: true, requireFeatures: ["customers.roles.manage"] }
7
+ };
8
+ const openApi = buildEntityRolesOpenApi("person");
9
+ const handlers = createEntityRolesHandlers("person");
10
+ const GET = handlers.GET;
11
+ const POST = handlers.POST;
12
+ const PUT = handlers.PUT;
13
+ const DELETE = handlers.DELETE;
14
+ export {
15
+ DELETE,
16
+ GET,
17
+ POST,
18
+ PUT,
19
+ metadata,
20
+ openApi
21
+ };
22
+ //# sourceMappingURL=route.js.map