@open-mercato/core 0.6.8-develop.7030.1.b84302d973 → 0.6.8-develop.7032.1.70d74d4bfe

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 (239) hide show
  1. package/dist/modules/api_keys/backend/api-keys/page.js +3 -1
  2. package/dist/modules/api_keys/backend/api-keys/page.js.map +2 -2
  3. package/dist/modules/attachments/components/AttachmentLibrary.js +2 -0
  4. package/dist/modules/attachments/components/AttachmentLibrary.js.map +2 -2
  5. package/dist/modules/audit_logs/backend/audit-logs/page.js +6 -0
  6. package/dist/modules/audit_logs/backend/audit-logs/page.js.map +2 -2
  7. package/dist/modules/auth/backend/roles/page.js +3 -1
  8. package/dist/modules/auth/backend/roles/page.js.map +2 -2
  9. package/dist/modules/auth/backend/users/page.js +2 -1
  10. package/dist/modules/auth/backend/users/page.js.map +2 -2
  11. package/dist/modules/business_rules/backend/logs/page.js +3 -1
  12. package/dist/modules/business_rules/backend/logs/page.js.map +2 -2
  13. package/dist/modules/business_rules/backend/rules/page.js +3 -1
  14. package/dist/modules/business_rules/backend/rules/page.js.map +2 -2
  15. package/dist/modules/business_rules/backend/sets/page.js +3 -1
  16. package/dist/modules/business_rules/backend/sets/page.js.map +2 -2
  17. package/dist/modules/business_rules/lib/expression-evaluator.js +9 -9
  18. package/dist/modules/business_rules/lib/expression-evaluator.js.map +2 -2
  19. package/dist/modules/business_rules/lib/rule-evaluator.js +10 -9
  20. package/dist/modules/business_rules/lib/rule-evaluator.js.map +2 -2
  21. package/dist/modules/catalog/ai-agents.js +1 -1
  22. package/dist/modules/catalog/ai-agents.js.map +1 -1
  23. package/dist/modules/catalog/ai-tools/merchandising-pack.js +2 -2
  24. package/dist/modules/catalog/ai-tools/merchandising-pack.js.map +2 -2
  25. package/dist/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.js +5 -2
  26. package/dist/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.js.map +2 -2
  27. package/dist/modules/catalog/components/categories/CategoriesDataTable.js +2 -0
  28. package/dist/modules/catalog/components/categories/CategoriesDataTable.js.map +2 -2
  29. package/dist/modules/catalog/components/products/ProductsDataTable.js +7 -1
  30. package/dist/modules/catalog/components/products/ProductsDataTable.js.map +2 -2
  31. package/dist/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.js +2 -0
  32. package/dist/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.js.map +2 -2
  33. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js +3 -0
  34. package/dist/modules/communication_channels/backend/communication_channels/channels/page.js.map +2 -2
  35. package/dist/modules/configs/lib/system-status.js +9 -0
  36. package/dist/modules/configs/lib/system-status.js.map +2 -2
  37. package/dist/modules/currencies/backend/currencies/page.js +3 -1
  38. package/dist/modules/currencies/backend/currencies/page.js.map +2 -2
  39. package/dist/modules/currencies/backend/exchange-rates/page.js +3 -1
  40. package/dist/modules/currencies/backend/exchange-rates/page.js.map +2 -2
  41. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js +3 -1
  42. package/dist/modules/customer_accounts/backend/customer_accounts/roles/page.js.map +2 -2
  43. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js +3 -1
  44. package/dist/modules/customer_accounts/backend/customer_accounts/users/page.js.map +2 -2
  45. package/dist/modules/customers/ai-tools/companies-pack.js +4 -1
  46. package/dist/modules/customers/ai-tools/companies-pack.js.map +2 -2
  47. package/dist/modules/customers/ai-tools/deals-pack.js +4 -1
  48. package/dist/modules/customers/ai-tools/deals-pack.js.map +2 -2
  49. package/dist/modules/customers/ai-tools/people-pack.js +4 -1
  50. package/dist/modules/customers/ai-tools/people-pack.js.map +2 -2
  51. package/dist/modules/customers/api/deals/map/route.js +2 -1
  52. package/dist/modules/customers/api/deals/map/route.js.map +2 -2
  53. package/dist/modules/customers/backend/customers/companies/page.js +3 -1
  54. package/dist/modules/customers/backend/customers/companies/page.js.map +2 -2
  55. package/dist/modules/customers/backend/customers/deals/page.js +5 -2
  56. package/dist/modules/customers/backend/customers/deals/page.js.map +2 -2
  57. package/dist/modules/customers/backend/customers/people/page.js +3 -1
  58. package/dist/modules/customers/backend/customers/people/page.js.map +2 -2
  59. package/dist/modules/customers/components/CustomerTodosTable.js +1 -0
  60. package/dist/modules/customers/components/CustomerTodosTable.js.map +2 -2
  61. package/dist/modules/data_sync/backend/data-sync/page.js +3 -1
  62. package/dist/modules/data_sync/backend/data-sync/page.js.map +2 -2
  63. package/dist/modules/devices/backend/devices/page.js +3 -1
  64. package/dist/modules/devices/backend/devices/page.js.map +2 -2
  65. package/dist/modules/directory/backend/directory/organizations/page.js +2 -1
  66. package/dist/modules/directory/backend/directory/organizations/page.js.map +2 -2
  67. package/dist/modules/directory/backend/directory/tenants/page.js +2 -1
  68. package/dist/modules/directory/backend/directory/tenants/page.js.map +2 -2
  69. package/dist/modules/entities/api/records.js +4 -2
  70. package/dist/modules/entities/api/records.js.map +2 -2
  71. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js +3 -1
  72. package/dist/modules/entities/backend/entities/user/[entityId]/records/page.js.map +2 -2
  73. package/dist/modules/eudr/backend/eudr/evidence-submissions/page.js +3 -0
  74. package/dist/modules/eudr/backend/eudr/evidence-submissions/page.js.map +2 -2
  75. package/dist/modules/eudr/backend/eudr/plots/page.js +3 -0
  76. package/dist/modules/eudr/backend/eudr/plots/page.js.map +2 -2
  77. package/dist/modules/eudr/backend/eudr/product-mappings/page.js +3 -0
  78. package/dist/modules/eudr/backend/eudr/product-mappings/page.js.map +2 -2
  79. package/dist/modules/eudr/backend/eudr/risk-assessments/page.js +3 -0
  80. package/dist/modules/eudr/backend/eudr/risk-assessments/page.js.map +2 -2
  81. package/dist/modules/eudr/backend/eudr/statements/page.js +3 -0
  82. package/dist/modules/eudr/backend/eudr/statements/page.js.map +2 -2
  83. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js +1 -0
  84. package/dist/modules/feature_toggles/components/FeatureTogglesTable.js.map +2 -2
  85. package/dist/modules/feature_toggles/components/OverridesTable.js +1 -0
  86. package/dist/modules/feature_toggles/components/OverridesTable.js.map +2 -2
  87. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js +3 -0
  88. package/dist/modules/inbox_ops/backend/inbox-ops/log/page.js.map +2 -2
  89. package/dist/modules/inbox_ops/backend/inbox-ops/page.js +3 -0
  90. package/dist/modules/inbox_ops/backend/inbox-ops/page.js.map +2 -2
  91. package/dist/modules/messages/components/MessagesInboxPageClient.js +4 -1
  92. package/dist/modules/messages/components/MessagesInboxPageClient.js.map +2 -2
  93. package/dist/modules/payment_gateways/backend/payment-gateways/page.js +3 -1
  94. package/dist/modules/payment_gateways/backend/payment-gateways/page.js.map +2 -2
  95. package/dist/modules/planner/backend/planner/availability-rulesets/page.js +3 -0
  96. package/dist/modules/planner/backend/planner/availability-rulesets/page.js.map +2 -2
  97. package/dist/modules/push_notifications/backend/push_notifications/page.js +3 -1
  98. package/dist/modules/push_notifications/backend/push_notifications/page.js.map +2 -2
  99. package/dist/modules/query_index/lib/engine.js +108 -48
  100. package/dist/modules/query_index/lib/engine.js.map +2 -2
  101. package/dist/modules/resources/backend/resources/resource-types/page.js +3 -1
  102. package/dist/modules/resources/backend/resources/resource-types/page.js.map +2 -2
  103. package/dist/modules/resources/backend/resources/resources/page.js +3 -1
  104. package/dist/modules/resources/backend/resources/resources/page.js.map +2 -2
  105. package/dist/modules/sales/backend/sales/channels/offers/page.js +3 -0
  106. package/dist/modules/sales/backend/sales/channels/offers/page.js.map +2 -2
  107. package/dist/modules/sales/backend/sales/channels/page.js +3 -0
  108. package/dist/modules/sales/backend/sales/channels/page.js.map +2 -2
  109. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js +3 -0
  110. package/dist/modules/sales/components/channels/SalesChannelOffersPanel.js.map +2 -2
  111. package/dist/modules/sales/components/documents/SalesDocumentsTable.js +4 -0
  112. package/dist/modules/sales/components/documents/SalesDocumentsTable.js.map +2 -2
  113. package/dist/modules/staff/backend/staff/leave-requests/page.js +3 -0
  114. package/dist/modules/staff/backend/staff/leave-requests/page.js.map +2 -2
  115. package/dist/modules/staff/backend/staff/my-leave-requests/page.js +3 -0
  116. package/dist/modules/staff/backend/staff/my-leave-requests/page.js.map +2 -2
  117. package/dist/modules/staff/backend/staff/team-members/page.js +3 -0
  118. package/dist/modules/staff/backend/staff/team-members/page.js.map +2 -2
  119. package/dist/modules/staff/backend/staff/team-roles/page.js +3 -0
  120. package/dist/modules/staff/backend/staff/team-roles/page.js.map +2 -2
  121. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js +3 -0
  122. package/dist/modules/staff/backend/staff/teams/[id]/edit/page.js.map +2 -2
  123. package/dist/modules/staff/backend/staff/teams/page.js +3 -0
  124. package/dist/modules/staff/backend/staff/teams/page.js.map +2 -2
  125. package/dist/modules/staff/backend/staff/timesheets/projects/page.js +3 -0
  126. package/dist/modules/staff/backend/staff/timesheets/projects/page.js.map +2 -2
  127. package/dist/modules/warranty_claims/backend/page.js +3 -0
  128. package/dist/modules/warranty_claims/backend/page.js.map +2 -2
  129. package/dist/modules/warranty_claims/backend/warranty_claims/registrations/page.js +3 -0
  130. package/dist/modules/warranty_claims/backend/warranty_claims/registrations/page.js.map +2 -2
  131. package/dist/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.js +3 -0
  132. package/dist/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.js.map +2 -2
  133. package/dist/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.js +3 -0
  134. package/dist/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.js.map +2 -2
  135. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.js +3 -0
  136. package/dist/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.js.map +2 -2
  137. package/dist/modules/wms/components/backend/WmsConfigurationPage.js +4 -0
  138. package/dist/modules/wms/components/backend/WmsConfigurationPage.js.map +2 -2
  139. package/dist/modules/wms/components/backend/WmsInventoryConsolePage.js +1 -0
  140. package/dist/modules/wms/components/backend/WmsInventoryConsolePage.js.map +2 -2
  141. package/dist/modules/wms/components/backend/WmsLotsListPage.js +1 -0
  142. package/dist/modules/wms/components/backend/WmsLotsListPage.js.map +2 -2
  143. package/dist/modules/wms/components/backend/inventoryMutationLoaders.js +27 -20
  144. package/dist/modules/wms/components/backend/inventoryMutationLoaders.js.map +2 -2
  145. package/dist/modules/workflows/backend/definitions/page.js +3 -1
  146. package/dist/modules/workflows/backend/definitions/page.js.map +2 -2
  147. package/dist/modules/workflows/backend/events/page.js +3 -1
  148. package/dist/modules/workflows/backend/events/page.js.map +2 -2
  149. package/dist/modules/workflows/backend/instances/page.js +3 -1
  150. package/dist/modules/workflows/backend/instances/page.js.map +2 -2
  151. package/dist/modules/workflows/backend/tasks/page.js +3 -1
  152. package/dist/modules/workflows/backend/tasks/page.js.map +2 -2
  153. package/package.json +7 -7
  154. package/src/modules/api_keys/backend/api-keys/page.tsx +4 -1
  155. package/src/modules/attachments/components/AttachmentLibrary.tsx +3 -0
  156. package/src/modules/audit_logs/backend/audit-logs/page.tsx +8 -0
  157. package/src/modules/auth/backend/roles/page.tsx +4 -2
  158. package/src/modules/auth/backend/users/page.tsx +3 -2
  159. package/src/modules/business_rules/backend/logs/page.tsx +4 -1
  160. package/src/modules/business_rules/backend/rules/page.tsx +4 -1
  161. package/src/modules/business_rules/backend/sets/page.tsx +4 -1
  162. package/src/modules/business_rules/lib/expression-evaluator.ts +9 -9
  163. package/src/modules/business_rules/lib/rule-evaluator.ts +10 -9
  164. package/src/modules/catalog/ai-agents.ts +1 -1
  165. package/src/modules/catalog/ai-tools/merchandising-pack.ts +2 -2
  166. package/src/modules/catalog/backend/catalog/products/MerchandisingAssistantSheet.tsx +12 -5
  167. package/src/modules/catalog/components/categories/CategoriesDataTable.tsx +3 -0
  168. package/src/modules/catalog/components/products/ProductsDataTable.tsx +7 -0
  169. package/src/modules/catalog/i18n/de.json +1 -0
  170. package/src/modules/catalog/i18n/en.json +1 -0
  171. package/src/modules/catalog/i18n/es.json +1 -0
  172. package/src/modules/catalog/i18n/ko.json +1 -0
  173. package/src/modules/catalog/i18n/pl.json +1 -0
  174. package/src/modules/catalog/widgets/injection/merchandising-assistant-trigger/widget.client.tsx +4 -0
  175. package/src/modules/communication_channels/backend/communication_channels/channels/page.tsx +4 -0
  176. package/src/modules/configs/i18n/de.json +2 -0
  177. package/src/modules/configs/i18n/en.json +2 -0
  178. package/src/modules/configs/i18n/es.json +2 -0
  179. package/src/modules/configs/i18n/ko.json +2 -0
  180. package/src/modules/configs/i18n/pl.json +2 -0
  181. package/src/modules/configs/lib/system-status.ts +9 -0
  182. package/src/modules/currencies/backend/currencies/page.tsx +4 -1
  183. package/src/modules/currencies/backend/exchange-rates/page.tsx +4 -1
  184. package/src/modules/customer_accounts/backend/customer_accounts/roles/page.tsx +4 -1
  185. package/src/modules/customer_accounts/backend/customer_accounts/users/page.tsx +4 -1
  186. package/src/modules/customers/ai-tools/companies-pack.ts +4 -1
  187. package/src/modules/customers/ai-tools/deals-pack.ts +4 -1
  188. package/src/modules/customers/ai-tools/people-pack.ts +4 -1
  189. package/src/modules/customers/api/deals/map/route.ts +1 -0
  190. package/src/modules/customers/backend/customers/companies/page.tsx +4 -1
  191. package/src/modules/customers/backend/customers/deals/page.tsx +8 -2
  192. package/src/modules/customers/backend/customers/people/page.tsx +4 -1
  193. package/src/modules/customers/components/CustomerTodosTable.tsx +2 -0
  194. package/src/modules/data_sync/backend/data-sync/page.tsx +4 -1
  195. package/src/modules/devices/backend/devices/page.tsx +4 -1
  196. package/src/modules/directory/backend/directory/organizations/page.tsx +3 -1
  197. package/src/modules/directory/backend/directory/tenants/page.tsx +3 -1
  198. package/src/modules/entities/api/records.ts +2 -0
  199. package/src/modules/entities/backend/entities/user/[entityId]/records/page.tsx +4 -1
  200. package/src/modules/eudr/backend/eudr/evidence-submissions/page.tsx +4 -0
  201. package/src/modules/eudr/backend/eudr/plots/page.tsx +4 -0
  202. package/src/modules/eudr/backend/eudr/product-mappings/page.tsx +4 -0
  203. package/src/modules/eudr/backend/eudr/risk-assessments/page.tsx +4 -0
  204. package/src/modules/eudr/backend/eudr/statements/page.tsx +4 -0
  205. package/src/modules/feature_toggles/components/FeatureTogglesTable.tsx +2 -1
  206. package/src/modules/feature_toggles/components/OverridesTable.tsx +2 -1
  207. package/src/modules/inbox_ops/backend/inbox-ops/log/page.tsx +4 -0
  208. package/src/modules/inbox_ops/backend/inbox-ops/page.tsx +4 -0
  209. package/src/modules/messages/components/MessagesInboxPageClient.tsx +4 -0
  210. package/src/modules/payment_gateways/backend/payment-gateways/page.tsx +4 -1
  211. package/src/modules/planner/backend/planner/availability-rulesets/page.tsx +4 -0
  212. package/src/modules/push_notifications/backend/push_notifications/page.tsx +4 -1
  213. package/src/modules/query_index/lib/engine.ts +156 -53
  214. package/src/modules/resources/backend/resources/resource-types/page.tsx +4 -1
  215. package/src/modules/resources/backend/resources/resources/page.tsx +4 -1
  216. package/src/modules/sales/backend/sales/channels/offers/page.tsx +4 -0
  217. package/src/modules/sales/backend/sales/channels/page.tsx +4 -0
  218. package/src/modules/sales/components/channels/SalesChannelOffersPanel.tsx +4 -0
  219. package/src/modules/sales/components/documents/SalesDocumentsTable.tsx +5 -0
  220. package/src/modules/staff/backend/staff/leave-requests/page.tsx +4 -0
  221. package/src/modules/staff/backend/staff/my-leave-requests/page.tsx +4 -0
  222. package/src/modules/staff/backend/staff/team-members/page.tsx +6 -0
  223. package/src/modules/staff/backend/staff/team-roles/page.tsx +4 -0
  224. package/src/modules/staff/backend/staff/teams/[id]/edit/page.tsx +4 -0
  225. package/src/modules/staff/backend/staff/teams/page.tsx +4 -0
  226. package/src/modules/staff/backend/staff/timesheets/projects/page.tsx +4 -0
  227. package/src/modules/warranty_claims/backend/page.tsx +4 -0
  228. package/src/modules/warranty_claims/backend/warranty_claims/registrations/page.tsx +4 -0
  229. package/src/modules/warranty_claims/backend/warranty_claims/troubleshooting-guides/page.tsx +4 -0
  230. package/src/modules/warranty_claims/backend/warranty_claims/vendor-policies/page.tsx +4 -0
  231. package/src/modules/warranty_claims/frontend/[orgSlug]/portal/claims/page.tsx +4 -0
  232. package/src/modules/wms/components/backend/WmsConfigurationPage.tsx +5 -0
  233. package/src/modules/wms/components/backend/WmsInventoryConsolePage.tsx +2 -0
  234. package/src/modules/wms/components/backend/WmsLotsListPage.tsx +2 -0
  235. package/src/modules/wms/components/backend/inventoryMutationLoaders.ts +36 -20
  236. package/src/modules/workflows/backend/definitions/page.tsx +4 -1
  237. package/src/modules/workflows/backend/events/page.tsx +4 -1
  238. package/src/modules/workflows/backend/instances/page.tsx +4 -1
  239. package/src/modules/workflows/backend/tasks/page.tsx +4 -1
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/ai-tools/companies-pack.ts"],
4
- "sourcesContent": ["/**\n * `customers.list_companies` + `customers.get_company` (Phase 1 WS-C, Step 3.9).\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_companies` is now an API-backed wrapper over\n * `GET /api/customers/companies`. Tool name, schema, requiredFeatures, and\n * output shape are unchanged.\n *\n * Phase 3c of the same spec migrates `customers.get_company` to a single\n * in-process call to `GET /api/customers/companies/<id>?include=...` over the\n * documented aggregate detail route. Tool name, schema, requiredFeatures, and\n * output shape are unchanged.\n */\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\nimport {\n buildRelatedRecords,\n toCustomerListSummary,\n toIso,\n type CustomerRelatedRecords,\n} from './_shared'\n\nconst listCompaniesInput = z\n .object({\n q: z.string().trim().optional().describe('Search text matched against display name / email / domain. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n tags: z.array(z.string().uuid()).optional().describe('Restrict to companies carrying at least one of these tag ids.'),\n })\n .passthrough()\n\ntype ListCompaniesInput = z.infer<typeof listCompaniesInput>\n\ntype ListCompaniesApiItem = {\n id?: string\n display_name?: string | null\n displayName?: string | null\n primary_email?: string | null\n primaryEmail?: string | null\n primary_phone?: string | null\n primaryPhone?: string | null\n status?: string | null\n lifecycle_stage?: string | null\n lifecycleStage?: string | null\n source?: string | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n domain?: string | null\n website_url?: string | null\n websiteUrl?: string | null\n industry?: string | null\n size_bucket?: string | null\n sizeBucket?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListCompaniesApiResponse = {\n items?: ListCompaniesApiItem[]\n total?: number\n}\n\ntype ListCompaniesOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listCompaniesTool = defineApiBackedAiTool<\n ListCompaniesInput,\n ListCompaniesApiResponse,\n ListCompaniesOutput\n>({\n name: 'customers.list_companies',\n displayName: 'List companies',\n description:\n 'Search / list companies for the caller tenant + organization. Returns { items, total, limit, offset }.',\n inputSchema: listCompaniesInput,\n requiredFeatures: ['customers.companies.view'],\n toOperation: (input, ctx) => {\n assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.tags && input.tags.length > 0) query.tagIds = input.tags.join(',')\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/companies',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListCompaniesApiResponse\n const rawItems: ListCompaniesApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => ({\n ...toCustomerListSummary(row),\n domain: row.domain ?? null,\n websiteUrl: row.website_url ?? row.websiteUrl ?? null,\n industry: row.industry ?? null,\n sizeBucket: row.size_bucket ?? row.sizeBucket ?? null,\n })),\n total: typeof data.total === 'number' ? data.total : 0,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getCompanyInput = z.object({\n companyId: z.string().uuid().describe('Company entity id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, deals, people, addresses, tasks, and tags (each capped at 100).'),\n})\n\ntype GetCompanyInput = z.infer<typeof getCompanyInput>\n\nconst getCompanyTool: CustomersAiToolDefinition = {\n name: 'customers.get_company',\n displayName: 'Get company',\n description:\n 'Fetch a company customer record by id with profile fields and (optionally) notes, activities, deals, people, addresses, tasks, tags, and custom fields. Returns { found: false } when outside tenant/org scope.',\n inputSchema: getCompanyInput,\n requiredFeatures: ['customers.companies.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId: _tenantId } = assertTenantScope(ctx)\n void _tenantId\n const input: GetCompanyInput = getCompanyInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: `/customers/companies/${input.companyId}`,\n }\n if (includeRelated) {\n operation.query = {\n include: 'addresses,comments,activities,interactions,deals,todos,people',\n }\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run<Record<string, unknown>>(operation)\n if (!response.success) {\n if (response.statusCode === 404 || response.statusCode === 403) {\n return { found: false as const, companyId: input.companyId }\n }\n throw new Error(response.error ?? `Failed to fetch company ${input.companyId}`)\n }\n const data = (response.data ?? {}) as Record<string, unknown>\n const companyRow = (data.company ?? null) as Record<string, unknown> | null\n if (!companyRow) {\n return { found: false as const, companyId: input.companyId }\n }\n const profileRow = (data.profile ?? null) as Record<string, unknown> | null\n const customFields = (data.customFields ?? {}) as Record<string, unknown>\n\n let related: CustomerRelatedRecords | null = null\n if (includeRelated) {\n related = buildRelatedRecords(data, { includePeople: true })\n }\n return {\n found: true as const,\n company: {\n id: companyRow.id,\n displayName: companyRow.displayName ?? null,\n description: companyRow.description ?? null,\n primaryEmail: companyRow.primaryEmail ?? null,\n primaryPhone: companyRow.primaryPhone ?? null,\n status: companyRow.status ?? null,\n lifecycleStage: companyRow.lifecycleStage ?? null,\n source: companyRow.source ?? null,\n ownerUserId: companyRow.ownerUserId ?? null,\n organizationId: companyRow.organizationId ?? null,\n tenantId: companyRow.tenantId ?? null,\n createdAt: toIso(companyRow.createdAt),\n updatedAt: toIso(companyRow.updatedAt),\n },\n profile: profileRow\n ? {\n id: profileRow.id,\n legalName: profileRow.legalName ?? null,\n brandName: profileRow.brandName ?? null,\n domain: profileRow.domain ?? null,\n websiteUrl: profileRow.websiteUrl ?? null,\n industry: profileRow.industry ?? null,\n sizeBucket: profileRow.sizeBucket ?? null,\n annualRevenue: profileRow.annualRevenue ?? null,\n }\n : null,\n customFields,\n related,\n }\n },\n}\n\nexport const companiesAiTools: CustomersAiToolDefinition[] = [listCompaniesTool, getCompanyTool]\n\nexport default companiesAiTools\n"],
5
- "mappings": "AAaA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,yBAAoF;AAC7F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,qBAAqB,EACxB,OAAO;AAAA,EACN,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,6FAA6F;AAAA,EACtI,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,S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C,YAAY;AACf,aAAO,EAAE,OAAO,OAAgB,WAAW,MAAM,UAAU;AAAA,IAC7D;AACA,UAAM,aAAc,KAAK,WAAW;AACpC,UAAM,eAAgB,KAAK,gBAAgB,CAAC;AAE5C,QAAI,UAAyC;AAC7C,QAAI,gBAAgB;AAClB,gBAAU,oBAAoB,MAAM,EAAE,eAAe,KAAK,CAAC;AAAA,IAC7D;AACA,WAAO;AAAA,MACL,OAAO;AAAA,MACP,SAAS;AAAA,QACP,IAAI,WAAW;AAAA,QACf,aAAa,WAAW,eAAe;AAAA,QACvC,aAAa,WAAW,eAAe;AAAA,QACvC,cAAc,WAAW,gBAAgB;AAAA,QACzC,cAAc,WAAW,gBAAgB;AAAA,QACzC,QAAQ,WAAW,UAAU;AAAA,QAC7B,gBAAgB,WAAW,kBAAkB;AAAA,QAC7C,QAAQ,WAAW,UAAU;AAAA,QAC7B,aAAa,WAAW,eAAe;AAAA,QACvC,gBAAgB,WAAW,kBAAkB;AAAA,QAC7C,UAAU,WAAW,YAAY;AAAA,QACjC,WAAW,MAAM,WAAW,SAAS;AAAA,QACrC,WAAW,MAAM,WAAW,SAAS;AAAA,MACvC;AAAA,MACA,SAAS,aACL;AAAA,QACE,IAAI,WAAW;AAAA,QACf,WAAW,WAAW,aAAa;AAAA,QACnC,WAAW,WAAW,aAAa;AAAA,QACnC,QAAQ,WAAW,UAAU;AAAA,QAC7B,YAAY,WAAW,cAAc;AAAA,QACrC,UAAU,WAAW,YAAY;AAAA,QACjC,YAAY,WAAW,cAAc;AAAA,QACrC,eAAe,WAAW,iBAAiB;AAAA,MAC7C,IACA;AAAA,MACJ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,mBAAgD,CAAC,mBAAmB,cAAc;AAE/F,IAAO,yBAAQ;",
4
+ "sourcesContent": ["/**\n * `customers.list_companies` + `customers.get_company` (Phase 1 WS-C, Step 3.9).\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_companies` is now an API-backed wrapper over\n * `GET /api/customers/companies`. Tool name, schema, requiredFeatures, and\n * output shape are unchanged.\n *\n * Phase 3c of the same spec migrates `customers.get_company` to a single\n * in-process call to `GET /api/customers/companies/<id>?include=...` over the\n * documented aggregate detail route. Tool name, schema, requiredFeatures, and\n * output shape are unchanged.\n */\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\nimport {\n buildRelatedRecords,\n toCustomerListSummary,\n toIso,\n type CustomerRelatedRecords,\n} from './_shared'\n\nconst listCompaniesInput = z\n .object({\n q: z.string().trim().optional().describe('Search text matched against display name / email / domain. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n tags: z.array(z.string().uuid()).optional().describe('Restrict to companies carrying at least one of these tag ids.'),\n })\n .passthrough()\n\ntype ListCompaniesInput = z.infer<typeof listCompaniesInput>\n\ntype ListCompaniesApiItem = {\n id?: string\n display_name?: string | null\n displayName?: string | null\n primary_email?: string | null\n primaryEmail?: string | null\n primary_phone?: string | null\n primaryPhone?: string | null\n status?: string | null\n lifecycle_stage?: string | null\n lifecycleStage?: string | null\n source?: string | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n domain?: string | null\n website_url?: string | null\n websiteUrl?: string | null\n industry?: string | null\n size_bucket?: string | null\n sizeBucket?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListCompaniesApiResponse = {\n items?: ListCompaniesApiItem[]\n total?: number\n}\n\ntype ListCompaniesOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listCompaniesTool = defineApiBackedAiTool<\n ListCompaniesInput,\n ListCompaniesApiResponse,\n ListCompaniesOutput\n>({\n name: 'customers.list_companies',\n displayName: 'List companies',\n description:\n 'Search / list companies for the caller tenant + organization. Returns { items, total, totalIsCapped, limit, offset }. When totalIsCapped is true, total is a floor (\"at least N\", render it as \"N+\"), and pagination is exhausted only when a page returns fewer than limit items \u2014 never when offset reaches total.',\n inputSchema: listCompaniesInput,\n requiredFeatures: ['customers.companies.view'],\n toOperation: (input, ctx) => {\n assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.tags && input.tags.length > 0) query.tagIds = input.tags.join(',')\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/companies',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListCompaniesApiResponse\n const rawItems: ListCompaniesApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => ({\n ...toCustomerListSummary(row),\n domain: row.domain ?? null,\n websiteUrl: row.website_url ?? row.websiteUrl ?? null,\n industry: row.industry ?? null,\n sizeBucket: row.size_bucket ?? row.sizeBucket ?? null,\n })),\n total: typeof data.total === 'number' ? data.total : 0,\n // A capped count reports a floor: phrase the total as \"at least N\" and\n // never treat it as proof that pagination is exhausted.\n totalIsCapped: (data as { totalIsCapped?: boolean }).totalIsCapped === true,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getCompanyInput = z.object({\n companyId: z.string().uuid().describe('Company entity id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, deals, people, addresses, tasks, and tags (each capped at 100).'),\n})\n\ntype GetCompanyInput = z.infer<typeof getCompanyInput>\n\nconst getCompanyTool: CustomersAiToolDefinition = {\n name: 'customers.get_company',\n displayName: 'Get company',\n description:\n 'Fetch a company customer record by id with profile fields and (optionally) notes, activities, deals, people, addresses, tasks, tags, and custom fields. Returns { found: false } when outside tenant/org scope.',\n inputSchema: getCompanyInput,\n requiredFeatures: ['customers.companies.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId: _tenantId } = assertTenantScope(ctx)\n void _tenantId\n const input: GetCompanyInput = getCompanyInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: `/customers/companies/${input.companyId}`,\n }\n if (includeRelated) {\n operation.query = {\n include: 'addresses,comments,activities,interactions,deals,todos,people',\n }\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run<Record<string, unknown>>(operation)\n if (!response.success) {\n if (response.statusCode === 404 || response.statusCode === 403) {\n return { found: false as const, companyId: input.companyId }\n }\n throw new Error(response.error ?? `Failed to fetch company ${input.companyId}`)\n }\n const data = (response.data ?? {}) as Record<string, unknown>\n const companyRow = (data.company ?? null) as Record<string, unknown> | null\n if (!companyRow) {\n return { found: false as const, companyId: input.companyId }\n }\n const profileRow = (data.profile ?? null) as Record<string, unknown> | null\n const customFields = (data.customFields ?? {}) as Record<string, unknown>\n\n let related: CustomerRelatedRecords | null = null\n if (includeRelated) {\n related = buildRelatedRecords(data, { includePeople: true })\n }\n return {\n found: true as const,\n company: {\n id: companyRow.id,\n displayName: companyRow.displayName ?? null,\n description: companyRow.description ?? null,\n primaryEmail: companyRow.primaryEmail ?? null,\n primaryPhone: companyRow.primaryPhone ?? null,\n status: companyRow.status ?? null,\n lifecycleStage: companyRow.lifecycleStage ?? null,\n source: companyRow.source ?? null,\n ownerUserId: companyRow.ownerUserId ?? null,\n organizationId: companyRow.organizationId ?? null,\n tenantId: companyRow.tenantId ?? null,\n createdAt: toIso(companyRow.createdAt),\n updatedAt: toIso(companyRow.updatedAt),\n },\n profile: profileRow\n ? {\n id: profileRow.id,\n legalName: profileRow.legalName ?? null,\n brandName: profileRow.brandName ?? null,\n domain: profileRow.domain ?? null,\n websiteUrl: profileRow.websiteUrl ?? null,\n industry: profileRow.industry ?? null,\n sizeBucket: profileRow.sizeBucket ?? null,\n annualRevenue: profileRow.annualRevenue ?? null,\n }\n : null,\n customFields,\n related,\n }\n },\n}\n\nexport const companiesAiTools: CustomersAiToolDefinition[] = [listCompaniesTool, getCompanyTool]\n\nexport default companiesAiTools\n"],
5
+ "mappings": "AAaA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,yBAAoF;AAC7F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,qBAAqB,EACxB,OAAO;AAAA,EACN,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,6FAA6F;AAAA,EACtI,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,SAAS,+CAA+C;AAAA,EAC3G,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,qCAAqC;AAAA,EACzF,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,SAAS,EAAE,SAAS,+DAA+D;AACtH,CAAC,EACA,YAAY;AA4Cf,MAAM,oBAAoB,sBAIxB;AAAA,EACA,MAAM;AAAA,EACN,aAAa;AAAA,EACb,aACE;AAAA,EACF,aAAa;AAAA,EACb,kBAAkB,CAAC,0BAA0B;AAAA,EAC7C,aAAa,CAAC,OAAO,QAAQ;AAC3B,sBAAkB,GAAsC;AACxD,UAAM,QAAQ,MAAM,SAAS;AAC7B,U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A,QACzC,cAAc,WAAW,gBAAgB;AAAA,QACzC,QAAQ,WAAW,UAAU;AAAA,QAC7B,gBAAgB,WAAW,kBAAkB;AAAA,QAC7C,QAAQ,WAAW,UAAU;AAAA,QAC7B,aAAa,WAAW,eAAe;AAAA,QACvC,gBAAgB,WAAW,kBAAkB;AAAA,QAC7C,UAAU,WAAW,YAAY;AAAA,QACjC,WAAW,MAAM,WAAW,SAAS;AAAA,QACrC,WAAW,MAAM,WAAW,SAAS;AAAA,MACvC;AAAA,MACA,SAAS,aACL;AAAA,QACE,IAAI,WAAW;AAAA,QACf,WAAW,WAAW,aAAa;AAAA,QACnC,WAAW,WAAW,aAAa;AAAA,QACnC,QAAQ,WAAW,UAAU;AAAA,QAC7B,YAAY,WAAW,cAAc;AAAA,QACrC,UAAU,WAAW,YAAY;AAAA,QACjC,YAAY,WAAW,cAAc;AAAA,QACrC,eAAe,WAAW,iBAAiB;AAAA,MAC7C,IACA;AAAA,MACJ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,mBAAgD,CAAC,mBAAmB,cAAc;AAE/F,IAAO,yBAAQ;",
6
6
  "names": []
7
7
  }
@@ -29,7 +29,7 @@ const listDealsInput = z.object({
29
29
  const listDealsTool = defineApiBackedAiTool({
30
30
  name: "customers.list_deals",
31
31
  displayName: "List deals",
32
- description: "Search / list deals for the caller tenant + organization. Optional filters include linked person / company / pipeline stage.",
32
+ description: 'Search / list deals for the caller tenant + organization. Optional filters include linked person / company / pipeline stage. Returns { items, total, totalIsCapped, limit, offset }. When totalIsCapped is true, total is a floor ("at least N", render it as "N+"), and pagination is exhausted only when a page returns fewer than limit items \u2014 never when offset reaches total.',
33
33
  inputSchema: listDealsInput,
34
34
  requiredFeatures: ["customers.deals.view"],
35
35
  toOperation: (input, ctx) => {
@@ -83,6 +83,9 @@ const listDealsTool = defineApiBackedAiTool({
83
83
  };
84
84
  }),
85
85
  total: typeof data.total === "number" ? data.total : 0,
86
+ // A capped count reports a floor: phrase the total as "at least N" and
87
+ // never treat it as proof that pagination is exhausted.
88
+ totalIsCapped: data.totalIsCapped === true,
86
89
  limit,
87
90
  offset
88
91
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/ai-tools/deals-pack.ts"],
4
- "sourcesContent": ["/**\n * `customers.list_deals` + `customers.get_deal` (Phase 1 WS-C, Step 3.9).\n * `customers.update_deal_stage` mutation tool (Phase 3 WS-C, Step 5.13).\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_deals` is now an API-backed wrapper over\n * `GET /api/customers/deals`. Tool name, schema, requiredFeatures, and output\n * shape are unchanged.\n *\n * Phase 3c of the same spec migrates `customers.get_deal` to the documented\n * aggregate detail route. The handler issues 1 call without `includeRelated`\n * (`GET /customers/deals/<id>`) and 3 bounded calls with `includeRelated`\n * (deal detail + activities + comments by `dealId`). The 3-call cap matches\n * the spec's residual N+1 budget; deeper aggregation can earn a first-class\n * API later without touching the AI surface.\n */\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerDeal,\n CustomerPipelineStage,\n} from '../data/entities'\nimport {\n assertTenantScope,\n type CustomersAiToolDefinition,\n type CustomersToolContext,\n type CustomersToolLoadBeforeSingleRecord,\n} from './types'\n\nfunction resolveEm(ctx: CustomersToolContext | AiToolExecutionContext): EntityManager {\n return ctx.container.resolve<EntityManager>('em')\n}\n\nfunction buildScope(ctx: CustomersToolContext | AiToolExecutionContext, tenantId: string) {\n return { tenantId, organizationId: ctx.organizationId }\n}\n\nconst listDealsInput = z\n .object({\n q: z.string().trim().optional().describe('Search text matched against deal title / description. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n personId: z.string().uuid().optional().describe('Return only deals linked to this person entity id.'),\n companyId: z.string().uuid().optional().describe('Return only deals linked to this company entity id.'),\n pipelineStageId: z.string().uuid().optional().describe('Return only deals at this pipeline stage.'),\n status: z.string().optional().describe('Filter by deal status (e.g. \"open\", \"won\", \"lost\").'),\n })\n .passthrough()\n\ntype ListDealsInput = z.infer<typeof listDealsInput>\n\ntype ListDealsApiItem = {\n id?: string\n title?: string | null\n description?: string | null\n status?: string | null\n pipeline_id?: string | null\n pipelineId?: string | null\n pipeline_stage_id?: string | null\n pipelineStageId?: string | null\n value_amount?: string | number | null\n valueAmount?: string | number | null\n value_currency?: string | null\n valueCurrency?: string | null\n probability?: number | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n expected_close_at?: string | null\n expectedCloseAt?: string | null\n source?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListDealsApiResponse = {\n items?: ListDealsApiItem[]\n total?: number\n}\n\ntype ListDealsOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listDealsTool = defineApiBackedAiTool<ListDealsInput, ListDealsApiResponse, ListDealsOutput>({\n name: 'customers.list_deals',\n displayName: 'List deals',\n description:\n 'Search / list deals for the caller tenant + organization. Optional filters include linked person / company / pipeline stage.',\n inputSchema: listDealsInput,\n requiredFeatures: ['customers.deals.view'],\n toOperation: (input, ctx) => {\n assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.personId) query.personId = input.personId\n if (input.companyId) query.companyId = input.companyId\n if (input.pipelineStageId) query.pipelineStageId = input.pipelineStageId\n if (input.status) query.status = input.status\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/deals',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListDealsApiResponse\n const rawItems: ListDealsApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => {\n const expectedCloseRaw = row.expected_close_at ?? row.expectedCloseAt ?? null\n const expectedCloseAt = expectedCloseRaw ? new Date(String(expectedCloseRaw)).toISOString() : null\n const createdAtRaw = row.created_at ?? row.createdAt ?? null\n const createdAt = createdAtRaw ? new Date(String(createdAtRaw)).toISOString() : null\n return {\n id: row.id,\n title: row.title ?? null,\n description: row.description ?? null,\n status: row.status ?? null,\n pipelineId: row.pipeline_id ?? row.pipelineId ?? null,\n pipelineStageId: row.pipeline_stage_id ?? row.pipelineStageId ?? null,\n valueAmount: row.value_amount ?? row.valueAmount ?? null,\n valueCurrency: row.value_currency ?? row.valueCurrency ?? null,\n probability: row.probability ?? null,\n ownerUserId: row.owner_user_id ?? row.ownerUserId ?? null,\n expectedCloseAt,\n source: row.source ?? null,\n organizationId: row.organization_id ?? row.organizationId ?? null,\n tenantId: row.tenant_id ?? row.tenantId ?? null,\n createdAt,\n }\n }),\n total: typeof data.total === 'number' ? data.total : 0,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getDealInput = z.object({\n dealId: z.string().uuid().describe('Deal id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, linked people and companies (each capped at 100).'),\n})\n\ntype GetDealInput = z.infer<typeof getDealInput>\n\nfunction toIsoDeal(value: unknown): string | null {\n if (!value) return null\n const dt = value instanceof Date ? value : new Date(String(value))\n if (Number.isNaN(dt.getTime())) return null\n return dt.toISOString()\n}\n\nconst getDealTool: CustomersAiToolDefinition = {\n name: 'customers.get_deal',\n displayName: 'Get deal',\n description:\n 'Fetch a deal by id with fields and (optionally) notes, activities, linked people, and linked companies. Returns { found: false } when outside tenant/org scope.',\n inputSchema: getDealInput,\n requiredFeatures: ['customers.deals.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId: _tenantId } = assertTenantScope(ctx)\n void _tenantId\n const input: GetDealInput = getDealInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n\n const detailResponse = await runner.run<Record<string, unknown>>({\n method: 'GET',\n path: `/customers/deals/${input.dealId}`,\n })\n if (!detailResponse.success) {\n if (detailResponse.statusCode === 404 || detailResponse.statusCode === 403) {\n return { found: false as const, dealId: input.dealId }\n }\n throw new Error(detailResponse.error ?? `Failed to fetch deal ${input.dealId}`)\n }\n const detail = (detailResponse.data ?? {}) as Record<string, unknown>\n const dealRow = (detail.deal ?? null) as Record<string, unknown> | null\n if (!dealRow) {\n return { found: false as const, dealId: input.dealId }\n }\n const customFields = (detail.customFields ?? {}) as Record<string, unknown>\n const peopleRows = Array.isArray(detail.people) ? (detail.people as Array<Record<string, unknown>>) : []\n const companiesRows = Array.isArray(detail.companies)\n ? (detail.companies as Array<Record<string, unknown>>)\n : []\n\n let related: Record<string, unknown> | null = null\n if (includeRelated) {\n const [activitiesResponse, commentsResponse] = await Promise.all([\n runner.run<{ items?: Array<Record<string, unknown>>; total?: number }>({\n method: 'GET',\n path: '/customers/activities',\n query: { dealId: input.dealId, page: 1, pageSize: 100, sortField: 'occurredAt', sortDir: 'desc' },\n }),\n runner.run<{ items?: Array<Record<string, unknown>>; total?: number }>({\n method: 'GET',\n path: '/customers/comments',\n query: { dealId: input.dealId, page: 1, pageSize: 100 },\n }),\n ])\n const activities =\n activitiesResponse.success && Array.isArray(activitiesResponse.data?.items)\n ? (activitiesResponse.data!.items as Array<Record<string, unknown>>)\n : []\n const comments =\n commentsResponse.success && Array.isArray(commentsResponse.data?.items)\n ? (commentsResponse.data!.items as Array<Record<string, unknown>>)\n : []\n\n related = {\n activities: activities.map((activity) => ({\n id: activity.id,\n activityType: activity.activityType ?? activity.activity_type ?? null,\n subject: activity.subject ?? null,\n body: activity.body ?? null,\n occurredAt: toIsoDeal(activity.occurredAt ?? activity.occurred_at),\n createdAt: toIsoDeal(activity.createdAt ?? activity.created_at),\n })),\n notes: comments.map((comment) => ({\n id: comment.id,\n body: comment.body,\n authorUserId: comment.authorUserId ?? comment.author_user_id ?? null,\n createdAt: toIsoDeal(comment.createdAt ?? comment.created_at),\n })),\n people: peopleRows\n .map((person) => {\n if (!person || typeof person !== 'object') return null\n const id = typeof person.id === 'string' ? person.id : null\n if (!id) return null\n const subtitle = typeof person.subtitle === 'string' ? person.subtitle : null\n const label = typeof person.label === 'string' ? person.label : ''\n const entry: {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n participantRole: string | null\n } = {\n id,\n displayName: label,\n primaryEmail: subtitle && subtitle.includes('@') ? subtitle : null,\n primaryPhone: subtitle && !subtitle.includes('@') ? subtitle : null,\n participantRole: null as string | null,\n }\n return entry\n })\n .filter(\n (value): value is {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n participantRole: string | null\n } => value !== null,\n ),\n companies: companiesRows\n .map((company) => {\n if (!company || typeof company !== 'object') return null\n const id = typeof company.id === 'string' ? company.id : null\n if (!id) return null\n const label = typeof company.label === 'string' ? company.label : ''\n const entry: {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n } = {\n id,\n displayName: label,\n primaryEmail: null as string | null,\n primaryPhone: null as string | null,\n }\n return entry\n })\n .filter(\n (value): value is {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n } => value !== null,\n ),\n }\n }\n\n return {\n found: true as const,\n deal: {\n id: dealRow.id,\n title: typeof dealRow.title === 'string' ? dealRow.title : '',\n description: dealRow.description ?? null,\n status: dealRow.status ?? null,\n pipelineId: dealRow.pipelineId ?? null,\n pipelineStageId: dealRow.pipelineStageId ?? null,\n valueAmount: dealRow.valueAmount ?? null,\n valueCurrency: dealRow.valueCurrency ?? null,\n probability: dealRow.probability ?? null,\n ownerUserId: dealRow.ownerUserId ?? null,\n expectedCloseAt: toIsoDeal(dealRow.expectedCloseAt),\n source: dealRow.source ?? null,\n organizationId: dealRow.organizationId ?? null,\n tenantId: dealRow.tenantId ?? null,\n createdAt: toIsoDeal(dealRow.createdAt),\n updatedAt: toIsoDeal(dealRow.updatedAt),\n },\n customFields,\n related,\n }\n },\n}\n\n/**\n * Mutation tool: move a deal to a different pipeline stage. Step 5.13 \u2014 first\n * mutation-capable flow on the pending-action contract.\n *\n * Accepts either `toPipelineStageId` (UUID \u2014 preferred, tenant-scoped stage\n * record) or `toStage` (free-form string that maps to `CustomerDeal.status`\n * for pipeline roots like `open`/`won`/`lost`). Exactly one must be provided.\n *\n * The handler delegates to the existing `customers.deals.update` command so\n * all side effects (audit log, `customers.deal.updated` event, query index\n * refresh, notifications) stay identical to a direct API write.\n */\n// LLMs frequently emit `\"\"` for \"not provided\" \u2014 coerce blanks (and surrounding\n// whitespace) to `undefined` BEFORE the per-field validators run so the\n// `.uuid()` check on `toPipelineStageId` does not blow up on an empty string\n// the caller actually meant as \"skip this field\".\nconst blankToUndefined = (value: unknown): unknown => {\n if (typeof value !== 'string') return value\n const trimmed = value.trim()\n return trimmed.length === 0 ? undefined : trimmed\n}\n\nconst updateDealStageInput = z\n .object({\n dealId: z.string().uuid().describe('Deal id (UUID) to update.'),\n toPipelineStageId: z\n .preprocess(blankToUndefined, z.string().uuid().optional())\n .describe('Target pipeline stage id (UUID). Preferred \u2014 tenant-scoped stage record.'),\n toStage: z\n .preprocess(blankToUndefined, z.string().min(1).max(50).optional())\n .describe(\n 'Target status slug (e.g. \"open\", \"won\", \"lost\"). Used when the deal does not belong to a managed pipeline.',\n ),\n })\n .refine(\n (value) => Boolean(value.toPipelineStageId) !== Boolean(value.toStage),\n {\n message: 'Provide exactly one of toPipelineStageId or toStage.',\n path: ['toPipelineStageId'],\n },\n )\n\ntype UpdateDealStageInput = z.infer<typeof updateDealStageInput>\n\nfunction recordVersionFromUpdatedAt(updatedAt: Date | null | undefined): string | null {\n if (!updatedAt) return null\n const value = updatedAt instanceof Date ? updatedAt : new Date(updatedAt)\n if (Number.isNaN(value.getTime())) return null\n return value.toISOString()\n}\n\nfunction titleStatus(value: string | null | undefined): string | undefined {\n if (!value) return undefined\n return value\n .split(/[_\\s-]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(' ')\n}\n\nasync function loadDealWithStage(\n em: EntityManager,\n ctx: CustomersToolContext,\n tenantId: string,\n dealId: string,\n): Promise<CustomerDeal | null> {\n const where: Record<string, unknown> = { id: dealId, tenantId, deletedAt: null }\n if (ctx.organizationId) where.organizationId = ctx.organizationId\n const deal = await findOneWithDecryption<CustomerDeal>(\n em,\n CustomerDeal,\n where as FilterQuery<CustomerDeal>,\n undefined,\n buildScope(ctx, tenantId),\n )\n if (!deal || deal.tenantId !== tenantId) return null\n if (ctx.organizationId && deal.organizationId !== ctx.organizationId) return null\n return deal\n}\n\nasync function loadPipelineStage(\n em: EntityManager,\n ctx: CustomersToolContext,\n tenantId: string,\n stageId: string,\n organizationId: string,\n): Promise<CustomerPipelineStage | null> {\n return findOneWithDecryption<CustomerPipelineStage>(\n em,\n CustomerPipelineStage,\n {\n id: stageId,\n tenantId,\n organizationId,\n },\n undefined,\n buildScope(ctx, tenantId),\n )\n}\n\nconst updateDealStageTool: CustomersAiToolDefinition = {\n name: 'customers.update_deal_stage',\n displayName: 'Update deal stage',\n description:\n 'Move a deal to a different pipeline stage (by stage id) or change its top-level status (e.g. \"open\", \"won\", \"lost\"). Mutation tool \u2014 flows through the AI pending-action approval gate.',\n inputSchema: updateDealStageInput as z.ZodType<unknown>,\n requiredFeatures: ['customers.deals.manage'],\n tags: ['write', 'customers'],\n isMutation: true,\n loadBeforeRecord: async (rawInput, ctx): Promise<CustomersToolLoadBeforeSingleRecord | null> => {\n const { tenantId } = assertTenantScope(ctx)\n const input: UpdateDealStageInput = updateDealStageInput.parse(rawInput)\n const em = resolveEm(ctx)\n const deal = await loadDealWithStage(em, ctx, tenantId, input.dealId)\n if (!deal) return null\n let afterStatus = deal.status ?? null\n let afterPipelineStageId = deal.pipelineStageId ?? null\n let afterPipelineStageLabel = deal.pipelineStage ?? null\n if (input.toPipelineStageId) {\n const organizationId = deal.organizationId ?? ctx.organizationId ?? null\n const stage = organizationId\n ? await loadPipelineStage(em, ctx, tenantId, input.toPipelineStageId, organizationId)\n : null\n afterPipelineStageId = input.toPipelineStageId\n afterPipelineStageLabel = stage?.label ?? input.toPipelineStageId\n } else if (input.toStage) {\n afterStatus = input.toStage\n }\n const beforeStatus = deal.status ?? null\n const beforePipelineStageId = deal.pipelineStageId ?? null\n const beforePipelineStageLabel = deal.pipelineStage ?? beforePipelineStageId\n return {\n recordId: deal.id,\n entityType: 'customers.deal',\n recordVersion: recordVersionFromUpdatedAt(deal.updatedAt),\n before: {\n status: beforeStatus,\n pipelineStageId: beforePipelineStageId,\n },\n after: {\n status: afterStatus,\n pipelineStageId: afterPipelineStageId,\n },\n display: {\n fieldLabels: {\n status: 'Status',\n pipelineStageId: 'Pipeline stage',\n },\n before: {\n ...(beforeStatus ? { status: titleStatus(beforeStatus) } : {}),\n ...(beforePipelineStageLabel ? { pipelineStageId: beforePipelineStageLabel } : {}),\n },\n after: {\n ...(afterStatus ? { status: titleStatus(afterStatus) } : {}),\n ...(afterPipelineStageLabel ? { pipelineStageId: afterPipelineStageLabel } : {}),\n },\n },\n }\n },\n handler: async (rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const input: UpdateDealStageInput = updateDealStageInput.parse(rawInput)\n const em = resolveEm(ctx)\n const deal = await loadDealWithStage(em, ctx, tenantId, input.dealId)\n if (!deal) {\n throw new Error(`Deal \"${input.dealId}\" is not accessible to the caller.`)\n }\n const organizationId = deal.organizationId\n if (!organizationId) {\n throw new Error(`Deal \"${input.dealId}\" has no organization scope.`)\n }\n\n const before = {\n status: deal.status ?? null,\n pipelineStage: deal.pipelineStage ?? null,\n pipelineStageId: deal.pipelineStageId ?? null,\n }\n\n const body: Record<string, unknown> = {\n id: deal.id,\n tenantId,\n organizationId,\n }\n if (input.toPipelineStageId) {\n const stage = await loadPipelineStage(em, ctx, tenantId, input.toPipelineStageId, organizationId)\n if (!stage) {\n throw new Error('Pipeline stage not found.')\n }\n body.pipelineStageId = input.toPipelineStageId\n } else if (input.toStage) {\n body.status = input.toStage\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run({\n method: 'PUT',\n path: '/customers/deals',\n body,\n })\n if (!response.success) {\n throw new Error(response.error ?? `Failed to update deal \"${deal.id}\"`)\n }\n\n const after = await loadDealWithStage(em, ctx, tenantId, deal.id)\n return {\n recordId: deal.id,\n commandName: 'customers.deals.update',\n before,\n after: after\n ? {\n status: after.status ?? null,\n pipelineStage: after.pipelineStage ?? null,\n pipelineStageId: after.pipelineStageId ?? null,\n }\n : null,\n }\n },\n}\n\nexport const dealsAiTools: CustomersAiToolDefinition[] = [listDealsTool, getDealTool, updateDealStageTool]\n\nexport default dealsAiTools\n"],
5
- "mappings": "AAiBA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,OAIK;AAEP,SAAS,UAAU,KAAmE;AACpF,SAAO,IAAI,UAAU,QAAuB,IAAI;AAClD;AAEA,SAAS,WAAW,KAAoD,UAAkB;AACxF,SAAO,EAAE,UAAU,gBAAgB,IAAI,eAAe;AACxD;AAEA,MAAM,iBAAiB,EACpB,OAAO;AAAA,EACN,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AAA,MACf,aAAa;AAAA,MACb;AAAA,MACA,OAAO,QACH;AAAA,QACE,QAAQ,MAAM,UAAU;AAAA,QACxB,eAAe,MAAM,iBAAiB;AAAA,QACtC,iBAAiB,MAAM,mBAAmB;AAAA,MAC5C,IACA;AAAA,IACN;AAAA,EACF;AACF;AAEO,MAAM,eAA4C,CAAC,eAAe,aAAa,mBAAmB;AAEzG,IAAO,qBAAQ;",
4
+ "sourcesContent": ["/**\n * `customers.list_deals` + `customers.get_deal` (Phase 1 WS-C, Step 3.9).\n * `customers.update_deal_stage` mutation tool (Phase 3 WS-C, Step 5.13).\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_deals` is now an API-backed wrapper over\n * `GET /api/customers/deals`. Tool name, schema, requiredFeatures, and output\n * shape are unchanged.\n *\n * Phase 3c of the same spec migrates `customers.get_deal` to the documented\n * aggregate detail route. The handler issues 1 call without `includeRelated`\n * (`GET /customers/deals/<id>`) and 3 bounded calls with `includeRelated`\n * (deal detail + activities + comments by `dealId`). The 3-call cap matches\n * the spec's residual N+1 budget; deeper aggregation can earn a first-class\n * API later without touching the AI surface.\n */\nimport type { EntityManager, FilterQuery } from '@mikro-orm/postgresql'\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { findOneWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerDeal,\n CustomerPipelineStage,\n} from '../data/entities'\nimport {\n assertTenantScope,\n type CustomersAiToolDefinition,\n type CustomersToolContext,\n type CustomersToolLoadBeforeSingleRecord,\n} from './types'\n\nfunction resolveEm(ctx: CustomersToolContext | AiToolExecutionContext): EntityManager {\n return ctx.container.resolve<EntityManager>('em')\n}\n\nfunction buildScope(ctx: CustomersToolContext | AiToolExecutionContext, tenantId: string) {\n return { tenantId, organizationId: ctx.organizationId }\n}\n\nconst listDealsInput = z\n .object({\n q: z.string().trim().optional().describe('Search text matched against deal title / description. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n personId: z.string().uuid().optional().describe('Return only deals linked to this person entity id.'),\n companyId: z.string().uuid().optional().describe('Return only deals linked to this company entity id.'),\n pipelineStageId: z.string().uuid().optional().describe('Return only deals at this pipeline stage.'),\n status: z.string().optional().describe('Filter by deal status (e.g. \"open\", \"won\", \"lost\").'),\n })\n .passthrough()\n\ntype ListDealsInput = z.infer<typeof listDealsInput>\n\ntype ListDealsApiItem = {\n id?: string\n title?: string | null\n description?: string | null\n status?: string | null\n pipeline_id?: string | null\n pipelineId?: string | null\n pipeline_stage_id?: string | null\n pipelineStageId?: string | null\n value_amount?: string | number | null\n valueAmount?: string | number | null\n value_currency?: string | null\n valueCurrency?: string | null\n probability?: number | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n expected_close_at?: string | null\n expectedCloseAt?: string | null\n source?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListDealsApiResponse = {\n items?: ListDealsApiItem[]\n total?: number\n}\n\ntype ListDealsOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listDealsTool = defineApiBackedAiTool<ListDealsInput, ListDealsApiResponse, ListDealsOutput>({\n name: 'customers.list_deals',\n displayName: 'List deals',\n description:\n 'Search / list deals for the caller tenant + organization. Optional filters include linked person / company / pipeline stage. Returns { items, total, totalIsCapped, limit, offset }. When totalIsCapped is true, total is a floor (\"at least N\", render it as \"N+\"), and pagination is exhausted only when a page returns fewer than limit items \u2014 never when offset reaches total.',\n inputSchema: listDealsInput,\n requiredFeatures: ['customers.deals.view'],\n toOperation: (input, ctx) => {\n assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.personId) query.personId = input.personId\n if (input.companyId) query.companyId = input.companyId\n if (input.pipelineStageId) query.pipelineStageId = input.pipelineStageId\n if (input.status) query.status = input.status\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/deals',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListDealsApiResponse\n const rawItems: ListDealsApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => {\n const expectedCloseRaw = row.expected_close_at ?? row.expectedCloseAt ?? null\n const expectedCloseAt = expectedCloseRaw ? new Date(String(expectedCloseRaw)).toISOString() : null\n const createdAtRaw = row.created_at ?? row.createdAt ?? null\n const createdAt = createdAtRaw ? new Date(String(createdAtRaw)).toISOString() : null\n return {\n id: row.id,\n title: row.title ?? null,\n description: row.description ?? null,\n status: row.status ?? null,\n pipelineId: row.pipeline_id ?? row.pipelineId ?? null,\n pipelineStageId: row.pipeline_stage_id ?? row.pipelineStageId ?? null,\n valueAmount: row.value_amount ?? row.valueAmount ?? null,\n valueCurrency: row.value_currency ?? row.valueCurrency ?? null,\n probability: row.probability ?? null,\n ownerUserId: row.owner_user_id ?? row.ownerUserId ?? null,\n expectedCloseAt,\n source: row.source ?? null,\n organizationId: row.organization_id ?? row.organizationId ?? null,\n tenantId: row.tenant_id ?? row.tenantId ?? null,\n createdAt,\n }\n }),\n total: typeof data.total === 'number' ? data.total : 0,\n // A capped count reports a floor: phrase the total as \"at least N\" and\n // never treat it as proof that pagination is exhausted.\n totalIsCapped: (data as { totalIsCapped?: boolean }).totalIsCapped === true,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getDealInput = z.object({\n dealId: z.string().uuid().describe('Deal id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, linked people and companies (each capped at 100).'),\n})\n\ntype GetDealInput = z.infer<typeof getDealInput>\n\nfunction toIsoDeal(value: unknown): string | null {\n if (!value) return null\n const dt = value instanceof Date ? value : new Date(String(value))\n if (Number.isNaN(dt.getTime())) return null\n return dt.toISOString()\n}\n\nconst getDealTool: CustomersAiToolDefinition = {\n name: 'customers.get_deal',\n displayName: 'Get deal',\n description:\n 'Fetch a deal by id with fields and (optionally) notes, activities, linked people, and linked companies. Returns { found: false } when outside tenant/org scope.',\n inputSchema: getDealInput,\n requiredFeatures: ['customers.deals.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId: _tenantId } = assertTenantScope(ctx)\n void _tenantId\n const input: GetDealInput = getDealInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n\n const detailResponse = await runner.run<Record<string, unknown>>({\n method: 'GET',\n path: `/customers/deals/${input.dealId}`,\n })\n if (!detailResponse.success) {\n if (detailResponse.statusCode === 404 || detailResponse.statusCode === 403) {\n return { found: false as const, dealId: input.dealId }\n }\n throw new Error(detailResponse.error ?? `Failed to fetch deal ${input.dealId}`)\n }\n const detail = (detailResponse.data ?? {}) as Record<string, unknown>\n const dealRow = (detail.deal ?? null) as Record<string, unknown> | null\n if (!dealRow) {\n return { found: false as const, dealId: input.dealId }\n }\n const customFields = (detail.customFields ?? {}) as Record<string, unknown>\n const peopleRows = Array.isArray(detail.people) ? (detail.people as Array<Record<string, unknown>>) : []\n const companiesRows = Array.isArray(detail.companies)\n ? (detail.companies as Array<Record<string, unknown>>)\n : []\n\n let related: Record<string, unknown> | null = null\n if (includeRelated) {\n const [activitiesResponse, commentsResponse] = await Promise.all([\n runner.run<{ items?: Array<Record<string, unknown>>; total?: number }>({\n method: 'GET',\n path: '/customers/activities',\n query: { dealId: input.dealId, page: 1, pageSize: 100, sortField: 'occurredAt', sortDir: 'desc' },\n }),\n runner.run<{ items?: Array<Record<string, unknown>>; total?: number }>({\n method: 'GET',\n path: '/customers/comments',\n query: { dealId: input.dealId, page: 1, pageSize: 100 },\n }),\n ])\n const activities =\n activitiesResponse.success && Array.isArray(activitiesResponse.data?.items)\n ? (activitiesResponse.data!.items as Array<Record<string, unknown>>)\n : []\n const comments =\n commentsResponse.success && Array.isArray(commentsResponse.data?.items)\n ? (commentsResponse.data!.items as Array<Record<string, unknown>>)\n : []\n\n related = {\n activities: activities.map((activity) => ({\n id: activity.id,\n activityType: activity.activityType ?? activity.activity_type ?? null,\n subject: activity.subject ?? null,\n body: activity.body ?? null,\n occurredAt: toIsoDeal(activity.occurredAt ?? activity.occurred_at),\n createdAt: toIsoDeal(activity.createdAt ?? activity.created_at),\n })),\n notes: comments.map((comment) => ({\n id: comment.id,\n body: comment.body,\n authorUserId: comment.authorUserId ?? comment.author_user_id ?? null,\n createdAt: toIsoDeal(comment.createdAt ?? comment.created_at),\n })),\n people: peopleRows\n .map((person) => {\n if (!person || typeof person !== 'object') return null\n const id = typeof person.id === 'string' ? person.id : null\n if (!id) return null\n const subtitle = typeof person.subtitle === 'string' ? person.subtitle : null\n const label = typeof person.label === 'string' ? person.label : ''\n const entry: {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n participantRole: string | null\n } = {\n id,\n displayName: label,\n primaryEmail: subtitle && subtitle.includes('@') ? subtitle : null,\n primaryPhone: subtitle && !subtitle.includes('@') ? subtitle : null,\n participantRole: null as string | null,\n }\n return entry\n })\n .filter(\n (value): value is {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n participantRole: string | null\n } => value !== null,\n ),\n companies: companiesRows\n .map((company) => {\n if (!company || typeof company !== 'object') return null\n const id = typeof company.id === 'string' ? company.id : null\n if (!id) return null\n const label = typeof company.label === 'string' ? company.label : ''\n const entry: {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n } = {\n id,\n displayName: label,\n primaryEmail: null as string | null,\n primaryPhone: null as string | null,\n }\n return entry\n })\n .filter(\n (value): value is {\n id: string\n displayName: string\n primaryEmail: string | null\n primaryPhone: string | null\n } => value !== null,\n ),\n }\n }\n\n return {\n found: true as const,\n deal: {\n id: dealRow.id,\n title: typeof dealRow.title === 'string' ? dealRow.title : '',\n description: dealRow.description ?? null,\n status: dealRow.status ?? null,\n pipelineId: dealRow.pipelineId ?? null,\n pipelineStageId: dealRow.pipelineStageId ?? null,\n valueAmount: dealRow.valueAmount ?? null,\n valueCurrency: dealRow.valueCurrency ?? null,\n probability: dealRow.probability ?? null,\n ownerUserId: dealRow.ownerUserId ?? null,\n expectedCloseAt: toIsoDeal(dealRow.expectedCloseAt),\n source: dealRow.source ?? null,\n organizationId: dealRow.organizationId ?? null,\n tenantId: dealRow.tenantId ?? null,\n createdAt: toIsoDeal(dealRow.createdAt),\n updatedAt: toIsoDeal(dealRow.updatedAt),\n },\n customFields,\n related,\n }\n },\n}\n\n/**\n * Mutation tool: move a deal to a different pipeline stage. Step 5.13 \u2014 first\n * mutation-capable flow on the pending-action contract.\n *\n * Accepts either `toPipelineStageId` (UUID \u2014 preferred, tenant-scoped stage\n * record) or `toStage` (free-form string that maps to `CustomerDeal.status`\n * for pipeline roots like `open`/`won`/`lost`). Exactly one must be provided.\n *\n * The handler delegates to the existing `customers.deals.update` command so\n * all side effects (audit log, `customers.deal.updated` event, query index\n * refresh, notifications) stay identical to a direct API write.\n */\n// LLMs frequently emit `\"\"` for \"not provided\" \u2014 coerce blanks (and surrounding\n// whitespace) to `undefined` BEFORE the per-field validators run so the\n// `.uuid()` check on `toPipelineStageId` does not blow up on an empty string\n// the caller actually meant as \"skip this field\".\nconst blankToUndefined = (value: unknown): unknown => {\n if (typeof value !== 'string') return value\n const trimmed = value.trim()\n return trimmed.length === 0 ? undefined : trimmed\n}\n\nconst updateDealStageInput = z\n .object({\n dealId: z.string().uuid().describe('Deal id (UUID) to update.'),\n toPipelineStageId: z\n .preprocess(blankToUndefined, z.string().uuid().optional())\n .describe('Target pipeline stage id (UUID). Preferred \u2014 tenant-scoped stage record.'),\n toStage: z\n .preprocess(blankToUndefined, z.string().min(1).max(50).optional())\n .describe(\n 'Target status slug (e.g. \"open\", \"won\", \"lost\"). Used when the deal does not belong to a managed pipeline.',\n ),\n })\n .refine(\n (value) => Boolean(value.toPipelineStageId) !== Boolean(value.toStage),\n {\n message: 'Provide exactly one of toPipelineStageId or toStage.',\n path: ['toPipelineStageId'],\n },\n )\n\ntype UpdateDealStageInput = z.infer<typeof updateDealStageInput>\n\nfunction recordVersionFromUpdatedAt(updatedAt: Date | null | undefined): string | null {\n if (!updatedAt) return null\n const value = updatedAt instanceof Date ? updatedAt : new Date(updatedAt)\n if (Number.isNaN(value.getTime())) return null\n return value.toISOString()\n}\n\nfunction titleStatus(value: string | null | undefined): string | undefined {\n if (!value) return undefined\n return value\n .split(/[_\\s-]+/)\n .filter(Boolean)\n .map((part) => part.charAt(0).toUpperCase() + part.slice(1))\n .join(' ')\n}\n\nasync function loadDealWithStage(\n em: EntityManager,\n ctx: CustomersToolContext,\n tenantId: string,\n dealId: string,\n): Promise<CustomerDeal | null> {\n const where: Record<string, unknown> = { id: dealId, tenantId, deletedAt: null }\n if (ctx.organizationId) where.organizationId = ctx.organizationId\n const deal = await findOneWithDecryption<CustomerDeal>(\n em,\n CustomerDeal,\n where as FilterQuery<CustomerDeal>,\n undefined,\n buildScope(ctx, tenantId),\n )\n if (!deal || deal.tenantId !== tenantId) return null\n if (ctx.organizationId && deal.organizationId !== ctx.organizationId) return null\n return deal\n}\n\nasync function loadPipelineStage(\n em: EntityManager,\n ctx: CustomersToolContext,\n tenantId: string,\n stageId: string,\n organizationId: string,\n): Promise<CustomerPipelineStage | null> {\n return findOneWithDecryption<CustomerPipelineStage>(\n em,\n CustomerPipelineStage,\n {\n id: stageId,\n tenantId,\n organizationId,\n },\n undefined,\n buildScope(ctx, tenantId),\n )\n}\n\nconst updateDealStageTool: CustomersAiToolDefinition = {\n name: 'customers.update_deal_stage',\n displayName: 'Update deal stage',\n description:\n 'Move a deal to a different pipeline stage (by stage id) or change its top-level status (e.g. \"open\", \"won\", \"lost\"). Mutation tool \u2014 flows through the AI pending-action approval gate.',\n inputSchema: updateDealStageInput as z.ZodType<unknown>,\n requiredFeatures: ['customers.deals.manage'],\n tags: ['write', 'customers'],\n isMutation: true,\n loadBeforeRecord: async (rawInput, ctx): Promise<CustomersToolLoadBeforeSingleRecord | null> => {\n const { tenantId } = assertTenantScope(ctx)\n const input: UpdateDealStageInput = updateDealStageInput.parse(rawInput)\n const em = resolveEm(ctx)\n const deal = await loadDealWithStage(em, ctx, tenantId, input.dealId)\n if (!deal) return null\n let afterStatus = deal.status ?? null\n let afterPipelineStageId = deal.pipelineStageId ?? null\n let afterPipelineStageLabel = deal.pipelineStage ?? null\n if (input.toPipelineStageId) {\n const organizationId = deal.organizationId ?? ctx.organizationId ?? null\n const stage = organizationId\n ? await loadPipelineStage(em, ctx, tenantId, input.toPipelineStageId, organizationId)\n : null\n afterPipelineStageId = input.toPipelineStageId\n afterPipelineStageLabel = stage?.label ?? input.toPipelineStageId\n } else if (input.toStage) {\n afterStatus = input.toStage\n }\n const beforeStatus = deal.status ?? null\n const beforePipelineStageId = deal.pipelineStageId ?? null\n const beforePipelineStageLabel = deal.pipelineStage ?? beforePipelineStageId\n return {\n recordId: deal.id,\n entityType: 'customers.deal',\n recordVersion: recordVersionFromUpdatedAt(deal.updatedAt),\n before: {\n status: beforeStatus,\n pipelineStageId: beforePipelineStageId,\n },\n after: {\n status: afterStatus,\n pipelineStageId: afterPipelineStageId,\n },\n display: {\n fieldLabels: {\n status: 'Status',\n pipelineStageId: 'Pipeline stage',\n },\n before: {\n ...(beforeStatus ? { status: titleStatus(beforeStatus) } : {}),\n ...(beforePipelineStageLabel ? { pipelineStageId: beforePipelineStageLabel } : {}),\n },\n after: {\n ...(afterStatus ? { status: titleStatus(afterStatus) } : {}),\n ...(afterPipelineStageLabel ? { pipelineStageId: afterPipelineStageLabel } : {}),\n },\n },\n }\n },\n handler: async (rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const input: UpdateDealStageInput = updateDealStageInput.parse(rawInput)\n const em = resolveEm(ctx)\n const deal = await loadDealWithStage(em, ctx, tenantId, input.dealId)\n if (!deal) {\n throw new Error(`Deal \"${input.dealId}\" is not accessible to the caller.`)\n }\n const organizationId = deal.organizationId\n if (!organizationId) {\n throw new Error(`Deal \"${input.dealId}\" has no organization scope.`)\n }\n\n const before = {\n status: deal.status ?? null,\n pipelineStage: deal.pipelineStage ?? null,\n pipelineStageId: deal.pipelineStageId ?? null,\n }\n\n const body: Record<string, unknown> = {\n id: deal.id,\n tenantId,\n organizationId,\n }\n if (input.toPipelineStageId) {\n const stage = await loadPipelineStage(em, ctx, tenantId, input.toPipelineStageId, organizationId)\n if (!stage) {\n throw new Error('Pipeline stage not found.')\n }\n body.pipelineStageId = input.toPipelineStageId\n } else if (input.toStage) {\n body.status = input.toStage\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run({\n method: 'PUT',\n path: '/customers/deals',\n body,\n })\n if (!response.success) {\n throw new Error(response.error ?? `Failed to update deal \"${deal.id}\"`)\n }\n\n const after = await loadDealWithStage(em, ctx, tenantId, deal.id)\n return {\n recordId: deal.id,\n commandName: 'customers.deals.update',\n before,\n after: after\n ? {\n status: after.status ?? null,\n pipelineStage: after.pipelineStage ?? null,\n pipelineStageId: after.pipelineStageId ?? null,\n }\n : null,\n }\n },\n}\n\nexport const dealsAiTools: CustomersAiToolDefinition[] = [listDealsTool, getDealTool, updateDealStageTool]\n\nexport default dealsAiTools\n"],
5
+ "mappings": "AAiBA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OA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,UAAM,SAAS,2BAA2B,GAAwC;AAClF,UAAM,WAAW,MAAM,OAAO,IAAI;AAAA,MAChC,QAAQ;AAAA,MACR,MAAM;AAAA,MACN;AAAA,IACF,CAAC;AACD,QAAI,CAAC,SAAS,SAAS;AACrB,YAAM,IAAI,MAAM,SAAS,SAAS,0BAA0B,KAAK,EAAE,GAAG;AAAA,IACxE;AAEA,UAAM,QAAQ,MAAM,kBAAkB,IAAI,KAAK,UAAU,KAAK,EAAE;AAChE,WAAO;AAAA,MACL,UAAU,KAAK;AAAA,MACf,aAAa;AAAA,MACb;AAAA,MACA,OAAO,QACH;AAAA,QACE,QAAQ,MAAM,UAAU;AAAA,QACxB,eAAe,MAAM,iBAAiB;AAAA,QACtC,iBAAiB,MAAM,mBAAmB;AAAA,MAC5C,IACA;AAAA,IACN;AAAA,EACF;AACF;AAEO,MAAM,eAA4C,CAAC,eAAe,aAAa,mBAAmB;AAEzG,IAAO,qBAAQ;",
6
6
  "names": []
7
7
  }
@@ -26,7 +26,7 @@ const listPeopleInput = z.object({
26
26
  const listPeopleTool = defineApiBackedAiTool({
27
27
  name: "customers.list_people",
28
28
  displayName: "List people",
29
- description: "Search / list people (CRM persons) for the caller tenant + organization. Returns { items, total, limit, offset }.",
29
+ description: 'Search / list people (CRM persons) for the caller tenant + organization. Returns { items, total, totalIsCapped, limit, offset }. When totalIsCapped is true, total is a floor ("at least N", render it as "N+"), and pagination is exhausted only when a page returns fewer than limit items \u2014 never when offset reaches total.',
30
30
  inputSchema: listPeopleInput,
31
31
  requiredFeatures: ["customers.people.view"],
32
32
  toOperation: async (input, ctx) => {
@@ -73,6 +73,9 @@ const listPeopleTool = defineApiBackedAiTool({
73
73
  return {
74
74
  items: rawItems.map((row) => toCustomerListSummary(row)),
75
75
  total: typeof data.total === "number" ? data.total : 0,
76
+ // A capped count reports a floor: phrase the total as "at least N" and
77
+ // never treat it as proof that pagination is exhausted.
78
+ totalIsCapped: data.totalIsCapped === true,
76
79
  limit,
77
80
  offset
78
81
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../src/modules/customers/ai-tools/people-pack.ts"],
4
- "sourcesContent": ["/**\n * `customers.list_people` + `customers.get_person` (Phase 1 WS-C, Step 3.9).\n *\n * Read-only tools scoped to `ctx.tenantId` / `ctx.organizationId` that wrap\n * the existing customers query engine + encryption helpers. Mutation tools\n * are deferred to Step 5.13+ under the pending-action contract.\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_people` is now an API-backed wrapper over\n * `GET /api/customers/people`. The `companyId` AI input has no inclusion\n * equivalent on the route (the route exposes `excludeLinkedCompanyId` only)\n * so it is pre-resolved against `CustomerPersonProfile.company` and threaded\n * through the route's `ids` filter.\n *\n * Phase 3c of the same spec migrates `customers.get_person` to a single\n * in-process call to `GET /api/customers/people/<id>?include=...` (the\n * documented aggregate detail route). Tool name, schema, requiredFeatures,\n * and output shape are unchanged.\n */\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerPersonProfile,\n} from '../data/entities'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\nimport {\n buildRelatedRecords,\n buildScope,\n resolveEm,\n toCustomerListSummary,\n toIso,\n type CustomerRelatedRecords,\n} from './_shared'\n\nconst NIL_UUID = '00000000-0000-0000-0000-000000000000'\n\nconst listPeopleInput = z\n .object({\n q: z.string().trim().optional().describe('Optional search text matched against display name / email / phone. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n tags: z.array(z.string().uuid()).optional().describe('Restrict to persons carrying at least one of these tag ids.'),\n companyId: z.string().uuid().optional().describe('Restrict to persons linked to the given company entity.'),\n })\n .passthrough()\n\ntype ListPeopleInput = z.infer<typeof listPeopleInput>\n\ntype ListPeopleApiItem = {\n id?: string\n display_name?: string | null\n displayName?: string | null\n primary_email?: string | null\n primaryEmail?: string | null\n primary_phone?: string | null\n primaryPhone?: string | null\n status?: string | null\n lifecycle_stage?: string | null\n lifecycleStage?: string | null\n source?: string | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListPeopleApiResponse = {\n items?: ListPeopleApiItem[]\n total?: number\n}\n\ntype ListPeopleOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listPeopleTool = defineApiBackedAiTool<ListPeopleInput, ListPeopleApiResponse, ListPeopleOutput>({\n name: 'customers.list_people',\n displayName: 'List people',\n description:\n 'Search / list people (CRM persons) for the caller tenant + organization. Returns { items, total, limit, offset }.',\n inputSchema: listPeopleInput,\n requiredFeatures: ['customers.people.view'],\n toOperation: async (input, ctx) => {\n const { tenantId } = assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.tags && input.tags.length > 0) query.tagIds = input.tags.join(',')\n\n if (input.companyId) {\n const em = resolveEm(ctx)\n const profiles = await findWithDecryption<CustomerPersonProfile>(\n em,\n CustomerPersonProfile,\n { tenantId, company: input.companyId } as never,\n undefined,\n buildScope(ctx, tenantId),\n )\n const ids = profiles\n .map((profile) => {\n const entity = (profile as { entity?: unknown }).entity\n if (!entity) return null\n if (typeof entity === 'string') return entity\n const candidate = (entity as { id?: unknown }).id\n return typeof candidate === 'string' ? candidate : null\n })\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n // Empty match \u2014 feed a non-existent uuid so the route returns\n // { items: [], total: 0 } without us bypassing the API.\n query.ids = ids.length ? ids.join(',') : NIL_UUID\n }\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/people',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListPeopleApiResponse\n const rawItems: ListPeopleApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => toCustomerListSummary(row)),\n total: typeof data.total === 'number' ? data.total : 0,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getPersonInput = z.object({\n personId: z.string().uuid().describe('Person entity id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, deals, addresses, tasks, and tags (each capped at 100).'),\n})\n\ntype GetPersonInput = z.infer<typeof getPersonInput>\n\ntype ApiPersonDetailRow = Record<string, unknown> | null | undefined\n\nconst getPersonTool: CustomersAiToolDefinition = {\n name: 'customers.get_person',\n displayName: 'Get person',\n description:\n 'Fetch a person customer record by id with profile fields and (optionally) notes, activities, deals, addresses, tasks, tags, and custom fields. Returns { found: false } when the record is outside tenant/org scope or missing.',\n inputSchema: getPersonInput,\n requiredFeatures: ['customers.people.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const input: GetPersonInput = getPersonInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: `/customers/people/${input.personId}`,\n }\n if (includeRelated) {\n operation.query = { include: 'addresses,comments,activities,interactions,deals,todos' }\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run<Record<string, unknown>>(operation)\n if (!response.success) {\n if (response.statusCode === 404 || response.statusCode === 403) {\n return { found: false as const, personId: input.personId }\n }\n throw new Error(response.error ?? `Failed to fetch person ${input.personId}`)\n }\n const data = (response.data ?? {}) as Record<string, unknown>\n const personRow = (data.person ?? null) as ApiPersonDetailRow\n if (!personRow) {\n return { found: false as const, personId: input.personId }\n }\n const profileRow = (data.profile ?? null) as ApiPersonDetailRow\n const customFields = (data.customFields ?? {}) as Record<string, unknown>\n\n let related: CustomerRelatedRecords | null = null\n if (includeRelated) {\n related = buildRelatedRecords(data)\n }\n\n return {\n found: true as const,\n person: {\n id: personRow.id,\n displayName: personRow.displayName ?? null,\n description: personRow.description ?? null,\n primaryEmail: personRow.primaryEmail ?? null,\n primaryPhone: personRow.primaryPhone ?? null,\n status: personRow.status ?? null,\n lifecycleStage: personRow.lifecycleStage ?? null,\n source: personRow.source ?? null,\n ownerUserId: personRow.ownerUserId ?? null,\n organizationId: personRow.organizationId ?? null,\n tenantId: personRow.tenantId ?? null,\n createdAt: toIso(personRow.createdAt),\n updatedAt: toIso(personRow.updatedAt),\n },\n profile: profileRow\n ? {\n id: profileRow.id,\n firstName: profileRow.firstName ?? null,\n lastName: profileRow.lastName ?? null,\n preferredName: profileRow.preferredName ?? null,\n jobTitle: profileRow.jobTitle ?? null,\n department: profileRow.department ?? null,\n seniority: profileRow.seniority ?? null,\n timezone: profileRow.timezone ?? null,\n linkedInUrl: profileRow.linkedInUrl ?? null,\n twitterUrl: profileRow.twitterUrl ?? null,\n companyEntityId: profileRow.companyEntityId ?? null,\n }\n : null,\n customFields,\n related,\n }\n },\n}\n\nexport const peopleAiTools: CustomersAiToolDefinition[] = [listPeopleTool, getPersonTool]\n\nexport default peopleAiTools\n"],
5
- "mappings": "AAmBA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,OACK;AACP,SAAS,yBAAoF;AAC7F;AAAA,EACE;AAAA,EACA;A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QAC5B,aAAa,UAAU,eAAe;AAAA,QACtC,gBAAgB,UAAU,kBAAkB;AAAA,QAC5C,UAAU,UAAU,YAAY;AAAA,QAChC,WAAW,MAAM,UAAU,SAAS;AAAA,QACpC,WAAW,MAAM,UAAU,SAAS;AAAA,MACtC;AAAA,MACA,SAAS,aACL;AAAA,QACE,IAAI,WAAW;AAAA,QACf,WAAW,WAAW,aAAa;AAAA,QACnC,UAAU,WAAW,YAAY;AAAA,QACjC,eAAe,WAAW,iBAAiB;AAAA,QAC3C,UAAU,WAAW,YAAY;AAAA,QACjC,YAAY,WAAW,cAAc;AAAA,QACrC,WAAW,WAAW,aAAa;AAAA,QACnC,UAAU,WAAW,YAAY;AAAA,QACjC,aAAa,WAAW,eAAe;AAAA,QACvC,YAAY,WAAW,cAAc;AAAA,QACrC,iBAAiB,WAAW,mBAAmB;AAAA,MACjD,IACA;AAAA,MACJ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,gBAA6C,CAAC,gBAAgB,aAAa;AAExF,IAAO,sBAAQ;",
4
+ "sourcesContent": ["/**\n * `customers.list_people` + `customers.get_person` (Phase 1 WS-C, Step 3.9).\n *\n * Read-only tools scoped to `ctx.tenantId` / `ctx.organizationId` that wrap\n * the existing customers query engine + encryption helpers. Mutation tools\n * are deferred to Step 5.13+ under the pending-action contract.\n *\n * Phase 3a of `.ai/specs/implemented/2026-04-27-ai-tools-api-backed-dry-refactor.md`:\n * `customers.list_people` is now an API-backed wrapper over\n * `GET /api/customers/people`. The `companyId` AI input has no inclusion\n * equivalent on the route (the route exposes `excludeLinkedCompanyId` only)\n * so it is pre-resolved against `CustomerPersonProfile.company` and threaded\n * through the route's `ids` filter.\n *\n * Phase 3c of the same spec migrates `customers.get_person` to a single\n * in-process call to `GET /api/customers/people/<id>?include=...` (the\n * documented aggregate detail route). Tool name, schema, requiredFeatures,\n * and output shape are unchanged.\n */\nimport { z } from 'zod'\nimport { defineApiBackedAiTool } from '@open-mercato/ai-assistant/modules/ai_assistant/lib/api-backed-tool'\nimport {\n createAiApiOperationRunner,\n type AiApiOperationRequest,\n type AiToolExecutionContext,\n} from '@open-mercato/ai-assistant/modules/ai_assistant/lib/ai-api-operation-runner'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerPersonProfile,\n} from '../data/entities'\nimport { assertTenantScope, type CustomersAiToolDefinition, type CustomersToolContext } from './types'\nimport {\n buildRelatedRecords,\n buildScope,\n resolveEm,\n toCustomerListSummary,\n toIso,\n type CustomerRelatedRecords,\n} from './_shared'\n\nconst NIL_UUID = '00000000-0000-0000-0000-000000000000'\n\nconst listPeopleInput = z\n .object({\n q: z.string().trim().optional().describe('Optional search text matched against display name / email / phone. Omit or leave empty to list all.'),\n limit: z.number().int().min(1).max(100).optional().describe('Maximum rows to return (default 50, max 100).'),\n offset: z.number().int().min(0).optional().describe('Number of rows to skip (default 0).'),\n tags: z.array(z.string().uuid()).optional().describe('Restrict to persons carrying at least one of these tag ids.'),\n companyId: z.string().uuid().optional().describe('Restrict to persons linked to the given company entity.'),\n })\n .passthrough()\n\ntype ListPeopleInput = z.infer<typeof listPeopleInput>\n\ntype ListPeopleApiItem = {\n id?: string\n display_name?: string | null\n displayName?: string | null\n primary_email?: string | null\n primaryEmail?: string | null\n primary_phone?: string | null\n primaryPhone?: string | null\n status?: string | null\n lifecycle_stage?: string | null\n lifecycleStage?: string | null\n source?: string | null\n owner_user_id?: string | null\n ownerUserId?: string | null\n organization_id?: string | null\n organizationId?: string | null\n tenant_id?: string | null\n tenantId?: string | null\n created_at?: string | null\n createdAt?: string | null\n}\n\ntype ListPeopleApiResponse = {\n items?: ListPeopleApiItem[]\n total?: number\n}\n\ntype ListPeopleOutput = {\n items: Array<Record<string, unknown>>\n total: number\n limit: number\n offset: number\n}\n\nconst listPeopleTool = defineApiBackedAiTool<ListPeopleInput, ListPeopleApiResponse, ListPeopleOutput>({\n name: 'customers.list_people',\n displayName: 'List people',\n description:\n 'Search / list people (CRM persons) for the caller tenant + organization. Returns { items, total, totalIsCapped, limit, offset }. When totalIsCapped is true, total is a floor (\"at least N\", render it as \"N+\"), and pagination is exhausted only when a page returns fewer than limit items \u2014 never when offset reaches total.',\n inputSchema: listPeopleInput,\n requiredFeatures: ['customers.people.view'],\n toOperation: async (input, ctx) => {\n const { tenantId } = assertTenantScope(ctx as unknown as CustomersToolContext)\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const page = Math.floor(offset / limit) + 1\n\n const query: Record<string, string | number | boolean | null | undefined> = {\n page,\n pageSize: limit,\n }\n if (input.q?.trim()) query.search = input.q.trim()\n if (input.tags && input.tags.length > 0) query.tagIds = input.tags.join(',')\n\n if (input.companyId) {\n const em = resolveEm(ctx)\n const profiles = await findWithDecryption<CustomerPersonProfile>(\n em,\n CustomerPersonProfile,\n { tenantId, company: input.companyId } as never,\n undefined,\n buildScope(ctx, tenantId),\n )\n const ids = profiles\n .map((profile) => {\n const entity = (profile as { entity?: unknown }).entity\n if (!entity) return null\n if (typeof entity === 'string') return entity\n const candidate = (entity as { id?: unknown }).id\n return typeof candidate === 'string' ? candidate : null\n })\n .filter((value): value is string => typeof value === 'string' && value.length > 0)\n // Empty match \u2014 feed a non-existent uuid so the route returns\n // { items: [], total: 0 } without us bypassing the API.\n query.ids = ids.length ? ids.join(',') : NIL_UUID\n }\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: '/customers/people',\n query,\n }\n return operation\n },\n mapResponse: (response, input) => {\n const limit = input.limit ?? 50\n const offset = input.offset ?? 0\n const data = (response.data ?? {}) as ListPeopleApiResponse\n const rawItems: ListPeopleApiItem[] = Array.isArray(data.items) ? data.items : []\n return {\n items: rawItems.map((row) => toCustomerListSummary(row)),\n total: typeof data.total === 'number' ? data.total : 0,\n // A capped count reports a floor: phrase the total as \"at least N\" and\n // never treat it as proof that pagination is exhausted.\n totalIsCapped: (data as { totalIsCapped?: boolean }).totalIsCapped === true,\n limit,\n offset,\n }\n },\n}) as unknown as CustomersAiToolDefinition\n\nconst getPersonInput = z.object({\n personId: z.string().uuid().describe('Person entity id (UUID).'),\n includeRelated: z\n .boolean()\n .optional()\n .describe('When true, include notes, activities, deals, addresses, tasks, and tags (each capped at 100).'),\n})\n\ntype GetPersonInput = z.infer<typeof getPersonInput>\n\ntype ApiPersonDetailRow = Record<string, unknown> | null | undefined\n\nconst getPersonTool: CustomersAiToolDefinition = {\n name: 'customers.get_person',\n displayName: 'Get person',\n description:\n 'Fetch a person customer record by id with profile fields and (optionally) notes, activities, deals, addresses, tasks, tags, and custom fields. Returns { found: false } when the record is outside tenant/org scope or missing.',\n inputSchema: getPersonInput,\n requiredFeatures: ['customers.people.view'],\n tags: ['read', 'customers'],\n handler: async (rawInput, ctx) => {\n const { tenantId } = assertTenantScope(ctx)\n const input: GetPersonInput = getPersonInput.parse(rawInput)\n const includeRelated = !!input.includeRelated\n\n const operation: AiApiOperationRequest = {\n method: 'GET',\n path: `/customers/people/${input.personId}`,\n }\n if (includeRelated) {\n operation.query = { include: 'addresses,comments,activities,interactions,deals,todos' }\n }\n\n const runner = createAiApiOperationRunner(ctx as unknown as AiToolExecutionContext)\n const response = await runner.run<Record<string, unknown>>(operation)\n if (!response.success) {\n if (response.statusCode === 404 || response.statusCode === 403) {\n return { found: false as const, personId: input.personId }\n }\n throw new Error(response.error ?? `Failed to fetch person ${input.personId}`)\n }\n const data = (response.data ?? {}) as Record<string, unknown>\n const personRow = (data.person ?? null) as ApiPersonDetailRow\n if (!personRow) {\n return { found: false as const, personId: input.personId }\n }\n const profileRow = (data.profile ?? null) as ApiPersonDetailRow\n const customFields = (data.customFields ?? {}) as Record<string, unknown>\n\n let related: CustomerRelatedRecords | null = null\n if (includeRelated) {\n related = buildRelatedRecords(data)\n }\n\n return {\n found: true as const,\n person: {\n id: personRow.id,\n displayName: personRow.displayName ?? null,\n description: personRow.description ?? null,\n primaryEmail: personRow.primaryEmail ?? null,\n primaryPhone: personRow.primaryPhone ?? null,\n status: personRow.status ?? null,\n lifecycleStage: personRow.lifecycleStage ?? null,\n source: personRow.source ?? null,\n ownerUserId: personRow.ownerUserId ?? null,\n organizationId: personRow.organizationId ?? null,\n tenantId: personRow.tenantId ?? null,\n createdAt: toIso(personRow.createdAt),\n updatedAt: toIso(personRow.updatedAt),\n },\n profile: profileRow\n ? {\n id: profileRow.id,\n firstName: profileRow.firstName ?? null,\n lastName: profileRow.lastName ?? null,\n preferredName: profileRow.preferredName ?? null,\n jobTitle: profileRow.jobTitle ?? null,\n department: profileRow.department ?? null,\n seniority: profileRow.seniority ?? null,\n timezone: profileRow.timezone ?? null,\n linkedInUrl: profileRow.linkedInUrl ?? null,\n twitterUrl: profileRow.twitterUrl ?? null,\n companyEntityId: profileRow.companyEntityId ?? null,\n }\n : null,\n customFields,\n related,\n }\n },\n}\n\nexport const peopleAiTools: CustomersAiToolDefinition[] = [listPeopleTool, getPersonTool]\n\nexport default peopleAiTools\n"],
5
+ "mappings": "AAmBA,SAAS,SAAS;AAClB,SAAS,6BAA6B;AACtC;AAAA,EACE;AAAA,OAGK;AACP,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,OACK;AACP,SAAS,yBAAoF;AAC7F;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AAEP,MAAM,WAAW;AAEjB,MAAM,kBAAkB,EACrB,OAAO;AAAA,EACN,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,SAAS,qGAAqG;AAAA,EAC9I,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,GAAG,EAAE,SAAS,EAAE,SAAS,+CAA+C;AAAA,EAC3G,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,SAAS,EAAE,SAAS,qCAAqC;AAAA,EACzF,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,KAAK,CAAC,EAAE,SAAS,EAAE,SAAS,6DAA6D;AAAA,E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YAAY;AAAA,QACjC,aAAa,WAAW,eAAe;AAAA,QACvC,YAAY,WAAW,cAAc;AAAA,QACrC,iBAAiB,WAAW,mBAAmB;AAAA,MACjD,IACA;AAAA,MACJ;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEO,MAAM,gBAA6C,CAAC,gBAAgB,aAAa;AAExF,IAAO,sBAAQ;",
6
6
  "names": []
7
7
  }
@@ -422,7 +422,8 @@ async function GET(req) {
422
422
  total: res.total,
423
423
  page: query.page,
424
424
  pageSize: query.pageSize,
425
- totalPages: Math.ceil(res.total / (query.pageSize || 1))
425
+ totalPages: Math.ceil(res.total / (query.pageSize || 1)),
426
+ ...res.meta?.listCountCapWarning ? { totalIsCapped: true } : {}
426
427
  });
427
428
  }
428
429
  export {
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/modules/customers/api/deals/map/route.ts"],
4
- "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport { SortDir, type QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerAddress,\n CustomerDealCompanyLink,\n CustomerDealPersonLink,\n} from '../../../data/entities'\nimport { buildDealListFilters, dealListQuerySchema } from '../route'\nimport { applyEntityIdRestriction, findMatchingEntityIdsBySearchTokensAcrossSources } from '../../utils'\nimport { createPagedListResponseSchema } from '../../openapi'\nimport {\n resolveDealLocations,\n type DealMapAddress,\n type DealMapLink,\n type DealMapLocation,\n} from '../../../lib/dealsMapLocation'\nimport { E } from '#generated/entities.ids.generated'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view', 'customers.activities.view'] },\n}\n\nconst mapSortFields = ['createdAt', 'updatedAt', 'title', 'value', 'probability', 'expectedCloseAt'] as const\n\nconst sortFieldMap: Record<(typeof mapSortFields)[number], string> = {\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n title: 'title',\n value: 'value_amount',\n probability: 'probability',\n expectedCloseAt: 'expected_close_at',\n}\n\nconst querySchema = dealListQuerySchema.extend({\n pageSize: z.coerce.number().min(1).max(100).default(100),\n sortField: z.enum(mapSortFields).optional(),\n})\n\nconst dealMapAssociationSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n})\n\nconst dealMapLocationSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n city: z.string().nullable(),\n region: z.string().nullable(),\n country: z.string().nullable(),\n source: z.enum(['company', 'person']),\n entityId: z.string().uuid(),\n addressId: z.string().uuid(),\n})\n\nconst dealMapItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string().nullable(),\n status: z.string().nullable(),\n pipelineId: z.string().uuid().nullable(),\n pipelineStageId: z.string().uuid().nullable(),\n pipelineStage: z.string().nullable(),\n valueAmount: z.number().nullable(),\n valueCurrency: z.string().nullable(),\n probability: z.number().nullable(),\n expectedCloseAt: z.string().nullable(),\n ownerUserId: z.string().uuid().nullable(),\n updatedAt: z.string().nullable(),\n companies: z.array(dealMapAssociationSchema),\n people: z.array(dealMapAssociationSchema),\n location: dealMapLocationSchema.nullable(),\n})\n\nconst mapErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Deals map listing with resolved locations',\n methods: {\n GET: {\n summary: 'Paginated deals that have a resolvable map location',\n description:\n 'Returns a page of deals that have a coordinate-bearing linked company/person address, each enriched with one resolved location (company primary first, then earliest created; person addresses as fallback). Deals with no coordinate-bearing address are excluded entirely, so every item carries a non-null location in normal operation; the schema keeps location nullable only for the rare case where the address is deleted between the located-deal resolution and the page fetch.',\n query: querySchema,\n responses: [\n { status: 200, description: 'Paged located deals', schema: createPagedListResponseSchema(dealMapItemSchema) },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters', schema: mapErrorSchema },\n { status: 401, description: 'Unauthorized', schema: mapErrorSchema },\n { status: 403, description: 'Missing required features', schema: mapErrorSchema },\n ],\n },\n },\n}\n\ntype DealMapAssociation = z.infer<typeof dealMapAssociationSchema>\n\ntype LinkRow = {\n dealId: string\n entityId: string\n label: string\n createdAt: Date | string | null\n}\n\nfunction readEntityRef(ref: unknown): { id: string | null; record: Record<string, unknown> | null } {\n if (typeof ref === 'string') return { id: ref, record: null }\n if (ref && typeof ref === 'object') {\n const record = ref as Record<string, unknown>\n return { id: typeof record.id === 'string' ? record.id : null, record }\n }\n return { id: null, record: null }\n}\n\nfunction readLinkRow(link: { deal: unknown; createdAt?: Date | string | null }, linkedRef: unknown): LinkRow | null {\n const { id: dealId } = readEntityRef(link.deal)\n if (!dealId) return null\n const { id: entityId, record } = readEntityRef(linkedRef)\n if (!entityId) return null\n const label = record && typeof record.displayName === 'string' ? record.displayName : ''\n return { dealId, entityId, label, createdAt: link.createdAt ?? null }\n}\n\nfunction groupAssociations(rows: LinkRow[]): Map<string, DealMapAssociation[]> {\n const byDeal = new Map<string, DealMapAssociation[]>()\n for (const row of rows) {\n const bucket = byDeal.get(row.dealId) ?? []\n if (!bucket.some((entry) => entry.id === row.entityId)) {\n bucket.push({ id: row.entityId, label: row.label })\n byDeal.set(row.dealId, bucket)\n }\n }\n return byDeal\n}\n\nfunction toStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction toFiniteNumberOrNull(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim().length > 0) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\nfunction toIsoStringOrNull(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString()\n return toStringOrNull(value)\n}\n\nfunction readArrayParam(searchParams: URLSearchParams, key: string): string[] | null {\n const all = searchParams.getAll(key)\n if (!all.length) return null\n const trimmed = all.flatMap((value) => value.split(',')).map((value) => value.trim()).filter(Boolean)\n return trimmed.length ? trimmed : null\n}\n\nfunction collectRefIds(rows: unknown[], key: string): string[] {\n const ids = new Set<string>()\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue\n const { id } = readEntityRef((row as Record<string, unknown>)[key])\n if (id) ids.add(id)\n }\n return Array.from(ids)\n}\n\n// The deal-list filter builder may already restrict `id` (search, association, stuck, or advanced\n// filters). `applyEntityIdRestriction` overwrites an existing `$in`, so intersect the located-deal\n// set with whatever allow-list is already present before re-applying it.\nfunction readFilterIdAllowlist(filters: Record<string, unknown>): string[] | null {\n const idFilter = filters.id\n if (!idFilter || typeof idFilter !== 'object' || Array.isArray(idFilter)) return null\n const record = idFilter as { $eq?: unknown; $in?: unknown }\n if (typeof record.$eq === 'string') return [record.$eq]\n if (Array.isArray(record.$in)) return record.$in.filter((value): value is string => typeof value === 'string')\n return null\n}\n\nfunction emptyMapResponse(page: number, pageSize: number) {\n return NextResponse.json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const params = url.searchParams\n const parsed = querySchema.safeParse({\n page: params.get('page') ?? undefined,\n pageSize: params.get('pageSize') ?? undefined,\n search: params.get('search') ?? undefined,\n status: readArrayParam(params, 'status') ?? undefined,\n pipelineId: readArrayParam(params, 'pipelineId') ?? undefined,\n pipelineStageId: params.get('pipelineStageId') ?? undefined,\n ownerUserId: readArrayParam(params, 'ownerUserId') ?? undefined,\n personId: readArrayParam(params, 'personId') ?? undefined,\n companyId: readArrayParam(params, 'companyId') ?? undefined,\n valueCurrency: readArrayParam(params, 'valueCurrency') ?? undefined,\n expectedCloseAtFrom: params.get('expectedCloseAtFrom') ?? undefined,\n expectedCloseAtTo: params.get('expectedCloseAtTo') ?? undefined,\n isStuck: params.get('isStuck') ?? undefined,\n isOverdue: params.get('isOverdue') ?? undefined,\n sortField: params.get('sortField') ?? undefined,\n sortDir: params.get('sortDir') ?? undefined,\n })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid query parameters' }, { status: 400 })\n }\n const query = parsed.data\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const queryEngine = container.resolve<QueryEngine>('queryEngine')\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const effectiveTenantId = scope.tenantId ?? auth.tenantId\n // `null` = unrestricted access (superadmin or an \"all organizations\" grant): aggregate tenant-wide,\n // exactly like the deals List route (`makeCrudRoute`) and the query_index status route. A populated\n // array bounds the query to the caller's visible orgs; an empty array means no org visibility \u2192 401.\n // The previous guard hard-required `auth.orgId`, which is empty under the header \"All organizations\"\n // scope, so the map 401'd (and hung on the loading spinner) while List/Kanban aggregated fine (#3481).\n const orgScopeIds: string[] | null =\n scope.filterIds === null\n ? null\n : Array.isArray(scope.filterIds) && scope.filterIds.length > 0\n ? Array.from(new Set(scope.filterIds.filter((id) => typeof id === 'string' && id.length > 0)))\n : auth.orgId\n ? [auth.orgId]\n : []\n if (!effectiveTenantId || (Array.isArray(orgScopeIds) && orgScopeIds.length === 0)) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n // Bounded `$in` when the caller is org-restricted; omitted entirely under unrestricted access so\n // every query stays tenant-scoped only. `fallbackOrgId` is undefined when unrestricted.\n const orgScopeFilter = orgScopeIds ? { organizationId: { $in: orgScopeIds } } : {}\n const fallbackOrgId = orgScopeIds && orgScopeIds.length > 0 ? orgScopeIds[0] : undefined\n\n // `findWithDecryption` decrypts each row with the row's OWN tenant/organization (the encryption\n // subscriber's resolveScope(target) wins); this scope is only a fallback for rows that carry no\n // scope columns. CustomerAddress always carries organization_id, so every org's rows still decrypt\n // correctly under a multi-org / unrestricted scope even though `fallbackOrgId` may be undefined.\n const decryptionScope = { tenantId: effectiveTenantId, organizationId: fallbackOrgId }\n\n // Located-only, resolved in two stages so the per-request cost stays page-bounded:\n // 1) LIGHT id-only queries (FK columns only, no decryption) determine which deals have a\n // coordinate-bearing linked company/person, so pagination + `total` operate on located deals.\n // 2) The HEAVY decrypted/populated fetch (labels + address coordinates) runs only for the deals\n // that actually land on the requested page \u2014 never the whole located universe.\n const coordinateEntityRows = await findWithDecryption(\n em,\n CustomerAddress,\n {\n latitude: { $ne: null },\n longitude: { $ne: null },\n tenantId: effectiveTenantId,\n ...orgScopeFilter,\n },\n { fields: ['entity'] },\n decryptionScope,\n )\n const locatedEntityIds = collectRefIds(coordinateEntityRows, 'entity')\n if (locatedEntityIds.length === 0) {\n return emptyMapResponse(query.page, query.pageSize)\n }\n\n const [locatedCompanyLinkRows, locatedPersonLinkRows] = await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { company: { $in: locatedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { person: { $in: locatedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n ])\n const locatedDealIds = Array.from(\n new Set([\n ...collectRefIds(locatedCompanyLinkRows, 'deal'),\n ...collectRefIds(locatedPersonLinkRows, 'deal'),\n ]),\n )\n if (locatedDealIds.length === 0) {\n return emptyMapResponse(query.page, query.pageSize)\n }\n\n const ctx: CrudCtx = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: fallbackOrgId ?? null,\n organizationIds: orgScopeIds,\n request: req,\n }\n\n const filters = await buildDealListFilters(query, ctx)\n const existingAllowlist = readFilterIdAllowlist(filters)\n\n // The map card headline is the linked company/person name, which the deal-field token search\n // (title/description/status/\u2026) used by `buildDealListFilters` does NOT cover \u2014 so searching a\n // company/person name a user can plainly see on a card would otherwise return nothing. When a\n // search term is present, also resolve located deals whose linked company/person ENTITY name\n // matches, and union them with the deal-field matches. The sentinel \"no match\" id from the\n // deal-field search drops out naturally at the located intersection below, so no special-casing.\n let searchAllowlist = existingAllowlist\n if (query.search && locatedEntityIds.length > 0) {\n const nameMatchedEntityIds = await findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query: query.search,\n sources: [\n {\n entityType: E.customers.customer_entity,\n fields: ['display_name', 'primary_email', 'primary_phone', 'description'],\n },\n ],\n })\n const locatedEntitySet = new Set(locatedEntityIds)\n const locatedMatchedEntityIds = (nameMatchedEntityIds ?? []).filter((id) => locatedEntitySet.has(id))\n if (locatedMatchedEntityIds.length > 0) {\n const [companyNameLinkRows, personNameLinkRows] = await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { company: { $in: locatedMatchedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { person: { $in: locatedMatchedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n ])\n let nameMatchedDealIds = [\n ...collectRefIds(companyNameLinkRows, 'deal'),\n ...collectRefIds(personNameLinkRows, 'deal'),\n ]\n if (nameMatchedDealIds.length > 0) {\n // The deal-field search in `buildDealListFilters` is intersected with the People/Companies\n // association (and stuck/`?id`) filters \u2014 they all land together in `filters.id`. The name\n // matches above carry NO such constraint, so unioning them raw would let a co-active\n // People/Companies filter be bypassed (over-broad results). Recover exactly the non-search id\n // allowlist by rebuilding the deal filters WITHOUT the search term, and intersect the name\n // matches with it so the active filter is honored: located \u2229 nonSearch \u2229 (dealField \u222A name).\n // (The map's query carries no advanced `filter[...]` params, so the consume-mutation in\n // buildDealListFilters does not affect this second build.)\n const nonSearchAllowlist = readFilterIdAllowlist(\n await buildDealListFilters({ ...query, search: undefined }, ctx),\n )\n if (nonSearchAllowlist) {\n const nonSearchLookup = new Set(nonSearchAllowlist)\n nameMatchedDealIds = nameMatchedDealIds.filter((id) => nonSearchLookup.has(id))\n }\n }\n if (nameMatchedDealIds.length > 0) {\n searchAllowlist = Array.from(new Set([...(existingAllowlist ?? []), ...nameMatchedDealIds]))\n }\n }\n }\n\n const allowlistLookup = searchAllowlist ? new Set(searchAllowlist) : null\n const restrictedDealIds = allowlistLookup\n ? locatedDealIds.filter((id) => allowlistLookup.has(id))\n : locatedDealIds\n // `restrictedDealIds` is the final located \u2229 (deal-field \u222A company/person-name) set \u2014 it already\n // captures every id constraint `buildDealListFilters` expressed (read back via\n // `readFilterIdAllowlist`). Clear the stale `filters.id` first so `applyEntityIdRestriction` does\n // not re-intersect against the deal-field \"no match\" sentinel and drop the name-matched deals.\n delete (filters as Record<string, unknown>).id\n applyEntityIdRestriction(filters, restrictedDealIds)\n\n const sortColumn = query.sortField ? sortFieldMap[query.sortField] : 'id'\n const sortDir = query.sortDir === 'desc' ? SortDir.Desc : SortDir.Asc\n // Always append `id` as a stable tiebreaker \u2014 non-unique sort columns (title, value,\n // probability, stage, or colliding timestamps) otherwise reorder between OFFSET pages and the\n // client's multi-page accumulation would skip or duplicate deals at page boundaries.\n const sort = sortColumn === 'id'\n ? [{ field: 'id', dir: sortDir }]\n : [{ field: sortColumn, dir: sortDir }, { field: 'id', dir: SortDir.Asc }]\n\n const res = await queryEngine.query(E.customers.customer_deal, {\n fields: [\n 'id',\n // `organization_id` is projected (never exposed in the response) so the query engine can decrypt\n // each row's encrypted fields (e.g. `title`) with the row's OWN org. Without it, an unrestricted\n // \"All organizations\" scope has no single fallback org to decrypt with and titles come back as\n // ciphertext \u2014 the List route projects it for the same reason (#3481).\n 'organization_id',\n 'title',\n 'status',\n 'pipeline_id',\n 'pipeline_stage_id',\n 'pipeline_stage',\n 'value_amount',\n 'value_currency',\n 'probability',\n 'expected_close_at',\n 'owner_user_id',\n 'updated_at',\n ],\n sort,\n page: { page: query.page, pageSize: query.pageSize },\n filters,\n tenantId: effectiveTenantId,\n organizationId: fallbackOrgId,\n organizationIds: orgScopeIds ?? undefined,\n })\n\n const rows = (Array.isArray(res.items) ? res.items : []).filter(\n (row): row is Record<string, unknown> => !!row && typeof row === 'object',\n )\n const dealIds = rows\n .map((row) => (typeof row.id === 'string' && row.id.trim().length ? row.id : null))\n .filter((value): value is string => value !== null)\n\n // Heavy fetch, page-bounded: pull decrypted links (for labels) and coordinate-bearing addresses\n // only for the deals on this page.\n const [companyLinks, personLinks] = dealIds.length\n ? await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: { $in: dealIds } },\n { populate: ['company'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: { $in: dealIds } },\n { populate: ['person'] },\n decryptionScope,\n ),\n ])\n : [[], []]\n\n const companyRows = companyLinks\n .map((link) => readLinkRow(link, link.company))\n .filter((row): row is LinkRow => row !== null)\n const personRows = personLinks\n .map((link) => readLinkRow(link, link.person))\n .filter((row): row is LinkRow => row !== null)\n const companiesByDeal = groupAssociations(companyRows)\n const peopleByDeal = groupAssociations(personRows)\n\n const linkedEntityIds = Array.from(\n new Set([...companyRows, ...personRows].map((row) => row.entityId)),\n )\n const addresses = linkedEntityIds.length\n ? await findWithDecryption(\n em,\n CustomerAddress,\n {\n entity: { $in: linkedEntityIds },\n latitude: { $ne: null },\n longitude: { $ne: null },\n tenantId: effectiveTenantId,\n ...orgScopeFilter,\n },\n {},\n decryptionScope,\n )\n : []\n\n const addressRows: DealMapAddress[] = []\n for (const address of addresses) {\n const { id: entityId } = readEntityRef(address.entity)\n if (!entityId) continue\n addressRows.push({\n id: address.id,\n entityId,\n isPrimary: address.isPrimary === true,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n country: address.country ?? null,\n createdAt: address.createdAt ?? null,\n })\n }\n\n const toLink = (row: LinkRow): DealMapLink => ({\n dealId: row.dealId,\n entityId: row.entityId,\n createdAt: row.createdAt,\n })\n const locationByDeal: Map<string, DealMapLocation | null> = resolveDealLocations(\n dealIds,\n companyRows.map(toLink),\n personRows.map(toLink),\n addressRows,\n )\n\n const items = rows\n .map((row) => {\n const id = typeof row.id === 'string' && row.id.trim().length ? row.id : null\n if (!id) return null\n return {\n id,\n title: toStringOrNull(row.title),\n status: toStringOrNull(row.status),\n pipelineId: toStringOrNull(row.pipeline_id),\n pipelineStageId: toStringOrNull(row.pipeline_stage_id),\n pipelineStage: toStringOrNull(row.pipeline_stage),\n valueAmount: toFiniteNumberOrNull(row.value_amount),\n valueCurrency: toStringOrNull(row.value_currency),\n probability: toFiniteNumberOrNull(row.probability),\n expectedCloseAt: toIsoStringOrNull(row.expected_close_at),\n ownerUserId: toStringOrNull(row.owner_user_id),\n updatedAt: toIsoStringOrNull(row.updated_at),\n companies: companiesByDeal.get(id) ?? [],\n people: peopleByDeal.get(id) ?? [],\n location: locationByDeal.get(id) ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null)\n\n return NextResponse.json({\n items,\n total: res.total,\n page: query.page,\n pageSize: query.pageSize,\n totalPages: Math.ceil(res.total / (query.pageSize || 1)),\n })\n}\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AAEnD,SAAS,eAAiC;AAE1C,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB,2BAA2B;AAC1D,SAAS,0BAA0B,wDAAwD;AAC3F,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,OAIK;AACP,SAAS,SAAS;AAEX,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM,iBAAiB,CAAC,wBAAwB,2BAA2B,EAAE;AACnG;AAEA,MAAM,gBAAgB,CAAC,aAAa,aAAa,SAAS,SAAS,eAAe,iBAAiB;AAEnG,MAAM,eAA+D;AAAA,EACnE,WAAW;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B;AAAA,MACrD,eAAe,eAAe,IAAI,cAAc;AAAA,MAChD,aAAa,qBAAqB,IAAI,YAAY;AAAA,MAClD,eAAe,eAAe,IAAI,cAAc;AAAA,MAChD,aAAa,qBAAqB,IAAI,WAAW;AAAA,MACjD,iBAAiB,kBAAkB,IAAI,iBAAiB;AAAA,MACxD,aAAa,eAAe,IAAI,aAAa;AAAA,MAC7C,WAAW,kBAAkB,IAAI,UAAU;AAAA,MAC3C,WAAW,gBAAgB,IAAI,EAAE,KAAK,CAAC;AAAA,MACvC,QAAQ,aAAa,IAAI,EAAE,KAAK,CAAC;AAAA,MACjC,UAAU,eAAe,IAAI,EAAE,KAAK;AAAA,IACtC;AAAA,EACF,CAAC,EACA,OAAO,CAAC,SAA2C,SAAS,IAAI;AAEnE,SAAO,aAAa,KAAK;AAAA,IACvB;AAAA,IACA,OAAO,IAAI;AAAA,IACX,MAAM,MAAM;AAAA,IACZ,UAAU,MAAM;AAAA,IAChB,YAAY,KAAK,KAAK,IAAI,SAAS,MAAM,YAAY,EAAE;AAAA,EACzD,CAAC;AACH;",
4
+ "sourcesContent": ["import { NextResponse } from 'next/server'\nimport { z } from 'zod'\nimport type { EntityManager } from '@mikro-orm/postgresql'\nimport { getAuthFromRequest } from '@open-mercato/shared/lib/auth/server'\nimport { createRequestContainer } from '@open-mercato/shared/lib/di/container'\nimport { resolveOrganizationScopeForRequest } from '@open-mercato/core/modules/directory/utils/organizationScope'\nimport type { CrudCtx } from '@open-mercato/shared/lib/crud/factory'\nimport { SortDir, type QueryEngine } from '@open-mercato/shared/lib/query/types'\nimport type { OpenApiRouteDoc } from '@open-mercato/shared/lib/openapi'\nimport { findWithDecryption } from '@open-mercato/shared/lib/encryption/find'\nimport {\n CustomerAddress,\n CustomerDealCompanyLink,\n CustomerDealPersonLink,\n} from '../../../data/entities'\nimport { buildDealListFilters, dealListQuerySchema } from '../route'\nimport { applyEntityIdRestriction, findMatchingEntityIdsBySearchTokensAcrossSources } from '../../utils'\nimport { createPagedListResponseSchema } from '../../openapi'\nimport {\n resolveDealLocations,\n type DealMapAddress,\n type DealMapLink,\n type DealMapLocation,\n} from '../../../lib/dealsMapLocation'\nimport { E } from '#generated/entities.ids.generated'\n\nexport const metadata = {\n GET: { requireAuth: true, requireFeatures: ['customers.deals.view', 'customers.activities.view'] },\n}\n\nconst mapSortFields = ['createdAt', 'updatedAt', 'title', 'value', 'probability', 'expectedCloseAt'] as const\n\nconst sortFieldMap: Record<(typeof mapSortFields)[number], string> = {\n createdAt: 'created_at',\n updatedAt: 'updated_at',\n title: 'title',\n value: 'value_amount',\n probability: 'probability',\n expectedCloseAt: 'expected_close_at',\n}\n\nconst querySchema = dealListQuerySchema.extend({\n pageSize: z.coerce.number().min(1).max(100).default(100),\n sortField: z.enum(mapSortFields).optional(),\n})\n\nconst dealMapAssociationSchema = z.object({\n id: z.string().uuid(),\n label: z.string().nullable(),\n})\n\nconst dealMapLocationSchema = z.object({\n latitude: z.number(),\n longitude: z.number(),\n city: z.string().nullable(),\n region: z.string().nullable(),\n country: z.string().nullable(),\n source: z.enum(['company', 'person']),\n entityId: z.string().uuid(),\n addressId: z.string().uuid(),\n})\n\nconst dealMapItemSchema = z.object({\n id: z.string().uuid(),\n title: z.string().nullable(),\n status: z.string().nullable(),\n pipelineId: z.string().uuid().nullable(),\n pipelineStageId: z.string().uuid().nullable(),\n pipelineStage: z.string().nullable(),\n valueAmount: z.number().nullable(),\n valueCurrency: z.string().nullable(),\n probability: z.number().nullable(),\n expectedCloseAt: z.string().nullable(),\n ownerUserId: z.string().uuid().nullable(),\n updatedAt: z.string().nullable(),\n companies: z.array(dealMapAssociationSchema),\n people: z.array(dealMapAssociationSchema),\n location: dealMapLocationSchema.nullable(),\n})\n\nconst mapErrorSchema = z.object({\n error: z.string(),\n})\n\nexport const openApi: OpenApiRouteDoc = {\n tag: 'Customers',\n summary: 'Deals map listing with resolved locations',\n methods: {\n GET: {\n summary: 'Paginated deals that have a resolvable map location',\n description:\n 'Returns a page of deals that have a coordinate-bearing linked company/person address, each enriched with one resolved location (company primary first, then earliest created; person addresses as fallback). Deals with no coordinate-bearing address are excluded entirely, so every item carries a non-null location in normal operation; the schema keeps location nullable only for the rare case where the address is deleted between the located-deal resolution and the page fetch.',\n query: querySchema,\n responses: [\n { status: 200, description: 'Paged located deals', schema: createPagedListResponseSchema(dealMapItemSchema) },\n ],\n errors: [\n { status: 400, description: 'Invalid query parameters', schema: mapErrorSchema },\n { status: 401, description: 'Unauthorized', schema: mapErrorSchema },\n { status: 403, description: 'Missing required features', schema: mapErrorSchema },\n ],\n },\n },\n}\n\ntype DealMapAssociation = z.infer<typeof dealMapAssociationSchema>\n\ntype LinkRow = {\n dealId: string\n entityId: string\n label: string\n createdAt: Date | string | null\n}\n\nfunction readEntityRef(ref: unknown): { id: string | null; record: Record<string, unknown> | null } {\n if (typeof ref === 'string') return { id: ref, record: null }\n if (ref && typeof ref === 'object') {\n const record = ref as Record<string, unknown>\n return { id: typeof record.id === 'string' ? record.id : null, record }\n }\n return { id: null, record: null }\n}\n\nfunction readLinkRow(link: { deal: unknown; createdAt?: Date | string | null }, linkedRef: unknown): LinkRow | null {\n const { id: dealId } = readEntityRef(link.deal)\n if (!dealId) return null\n const { id: entityId, record } = readEntityRef(linkedRef)\n if (!entityId) return null\n const label = record && typeof record.displayName === 'string' ? record.displayName : ''\n return { dealId, entityId, label, createdAt: link.createdAt ?? null }\n}\n\nfunction groupAssociations(rows: LinkRow[]): Map<string, DealMapAssociation[]> {\n const byDeal = new Map<string, DealMapAssociation[]>()\n for (const row of rows) {\n const bucket = byDeal.get(row.dealId) ?? []\n if (!bucket.some((entry) => entry.id === row.entityId)) {\n bucket.push({ id: row.entityId, label: row.label })\n byDeal.set(row.dealId, bucket)\n }\n }\n return byDeal\n}\n\nfunction toStringOrNull(value: unknown): string | null {\n return typeof value === 'string' && value.length > 0 ? value : null\n}\n\nfunction toFiniteNumberOrNull(value: unknown): number | null {\n if (typeof value === 'number') return Number.isFinite(value) ? value : null\n if (typeof value === 'string' && value.trim().length > 0) {\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : null\n }\n return null\n}\n\nfunction toIsoStringOrNull(value: unknown): string | null {\n if (value instanceof Date) return value.toISOString()\n return toStringOrNull(value)\n}\n\nfunction readArrayParam(searchParams: URLSearchParams, key: string): string[] | null {\n const all = searchParams.getAll(key)\n if (!all.length) return null\n const trimmed = all.flatMap((value) => value.split(',')).map((value) => value.trim()).filter(Boolean)\n return trimmed.length ? trimmed : null\n}\n\nfunction collectRefIds(rows: unknown[], key: string): string[] {\n const ids = new Set<string>()\n for (const row of rows) {\n if (!row || typeof row !== 'object') continue\n const { id } = readEntityRef((row as Record<string, unknown>)[key])\n if (id) ids.add(id)\n }\n return Array.from(ids)\n}\n\n// The deal-list filter builder may already restrict `id` (search, association, stuck, or advanced\n// filters). `applyEntityIdRestriction` overwrites an existing `$in`, so intersect the located-deal\n// set with whatever allow-list is already present before re-applying it.\nfunction readFilterIdAllowlist(filters: Record<string, unknown>): string[] | null {\n const idFilter = filters.id\n if (!idFilter || typeof idFilter !== 'object' || Array.isArray(idFilter)) return null\n const record = idFilter as { $eq?: unknown; $in?: unknown }\n if (typeof record.$eq === 'string') return [record.$eq]\n if (Array.isArray(record.$in)) return record.$in.filter((value): value is string => typeof value === 'string')\n return null\n}\n\nfunction emptyMapResponse(page: number, pageSize: number) {\n return NextResponse.json({ items: [], total: 0, page, pageSize, totalPages: 0 })\n}\n\nexport async function GET(req: Request) {\n const auth = await getAuthFromRequest(req)\n if (!auth?.tenantId) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n const url = new URL(req.url)\n const params = url.searchParams\n const parsed = querySchema.safeParse({\n page: params.get('page') ?? undefined,\n pageSize: params.get('pageSize') ?? undefined,\n search: params.get('search') ?? undefined,\n status: readArrayParam(params, 'status') ?? undefined,\n pipelineId: readArrayParam(params, 'pipelineId') ?? undefined,\n pipelineStageId: params.get('pipelineStageId') ?? undefined,\n ownerUserId: readArrayParam(params, 'ownerUserId') ?? undefined,\n personId: readArrayParam(params, 'personId') ?? undefined,\n companyId: readArrayParam(params, 'companyId') ?? undefined,\n valueCurrency: readArrayParam(params, 'valueCurrency') ?? undefined,\n expectedCloseAtFrom: params.get('expectedCloseAtFrom') ?? undefined,\n expectedCloseAtTo: params.get('expectedCloseAtTo') ?? undefined,\n isStuck: params.get('isStuck') ?? undefined,\n isOverdue: params.get('isOverdue') ?? undefined,\n sortField: params.get('sortField') ?? undefined,\n sortDir: params.get('sortDir') ?? undefined,\n })\n if (!parsed.success) {\n return NextResponse.json({ error: 'Invalid query parameters' }, { status: 400 })\n }\n const query = parsed.data\n\n const container = await createRequestContainer()\n const em = container.resolve<EntityManager>('em')\n const queryEngine = container.resolve<QueryEngine>('queryEngine')\n\n const scope = await resolveOrganizationScopeForRequest({ container, auth, request: req })\n const effectiveTenantId = scope.tenantId ?? auth.tenantId\n // `null` = unrestricted access (superadmin or an \"all organizations\" grant): aggregate tenant-wide,\n // exactly like the deals List route (`makeCrudRoute`) and the query_index status route. A populated\n // array bounds the query to the caller's visible orgs; an empty array means no org visibility \u2192 401.\n // The previous guard hard-required `auth.orgId`, which is empty under the header \"All organizations\"\n // scope, so the map 401'd (and hung on the loading spinner) while List/Kanban aggregated fine (#3481).\n const orgScopeIds: string[] | null =\n scope.filterIds === null\n ? null\n : Array.isArray(scope.filterIds) && scope.filterIds.length > 0\n ? Array.from(new Set(scope.filterIds.filter((id) => typeof id === 'string' && id.length > 0)))\n : auth.orgId\n ? [auth.orgId]\n : []\n if (!effectiveTenantId || (Array.isArray(orgScopeIds) && orgScopeIds.length === 0)) {\n return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })\n }\n\n // Bounded `$in` when the caller is org-restricted; omitted entirely under unrestricted access so\n // every query stays tenant-scoped only. `fallbackOrgId` is undefined when unrestricted.\n const orgScopeFilter = orgScopeIds ? { organizationId: { $in: orgScopeIds } } : {}\n const fallbackOrgId = orgScopeIds && orgScopeIds.length > 0 ? orgScopeIds[0] : undefined\n\n // `findWithDecryption` decrypts each row with the row's OWN tenant/organization (the encryption\n // subscriber's resolveScope(target) wins); this scope is only a fallback for rows that carry no\n // scope columns. CustomerAddress always carries organization_id, so every org's rows still decrypt\n // correctly under a multi-org / unrestricted scope even though `fallbackOrgId` may be undefined.\n const decryptionScope = { tenantId: effectiveTenantId, organizationId: fallbackOrgId }\n\n // Located-only, resolved in two stages so the per-request cost stays page-bounded:\n // 1) LIGHT id-only queries (FK columns only, no decryption) determine which deals have a\n // coordinate-bearing linked company/person, so pagination + `total` operate on located deals.\n // 2) The HEAVY decrypted/populated fetch (labels + address coordinates) runs only for the deals\n // that actually land on the requested page \u2014 never the whole located universe.\n const coordinateEntityRows = await findWithDecryption(\n em,\n CustomerAddress,\n {\n latitude: { $ne: null },\n longitude: { $ne: null },\n tenantId: effectiveTenantId,\n ...orgScopeFilter,\n },\n { fields: ['entity'] },\n decryptionScope,\n )\n const locatedEntityIds = collectRefIds(coordinateEntityRows, 'entity')\n if (locatedEntityIds.length === 0) {\n return emptyMapResponse(query.page, query.pageSize)\n }\n\n const [locatedCompanyLinkRows, locatedPersonLinkRows] = await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { company: { $in: locatedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { person: { $in: locatedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n ])\n const locatedDealIds = Array.from(\n new Set([\n ...collectRefIds(locatedCompanyLinkRows, 'deal'),\n ...collectRefIds(locatedPersonLinkRows, 'deal'),\n ]),\n )\n if (locatedDealIds.length === 0) {\n return emptyMapResponse(query.page, query.pageSize)\n }\n\n const ctx: CrudCtx = {\n container,\n auth,\n organizationScope: scope,\n selectedOrganizationId: fallbackOrgId ?? null,\n organizationIds: orgScopeIds,\n request: req,\n }\n\n const filters = await buildDealListFilters(query, ctx)\n const existingAllowlist = readFilterIdAllowlist(filters)\n\n // The map card headline is the linked company/person name, which the deal-field token search\n // (title/description/status/\u2026) used by `buildDealListFilters` does NOT cover \u2014 so searching a\n // company/person name a user can plainly see on a card would otherwise return nothing. When a\n // search term is present, also resolve located deals whose linked company/person ENTITY name\n // matches, and union them with the deal-field matches. The sentinel \"no match\" id from the\n // deal-field search drops out naturally at the located intersection below, so no special-casing.\n let searchAllowlist = existingAllowlist\n if (query.search && locatedEntityIds.length > 0) {\n const nameMatchedEntityIds = await findMatchingEntityIdsBySearchTokensAcrossSources({\n ctx,\n query: query.search,\n sources: [\n {\n entityType: E.customers.customer_entity,\n fields: ['display_name', 'primary_email', 'primary_phone', 'description'],\n },\n ],\n })\n const locatedEntitySet = new Set(locatedEntityIds)\n const locatedMatchedEntityIds = (nameMatchedEntityIds ?? []).filter((id) => locatedEntitySet.has(id))\n if (locatedMatchedEntityIds.length > 0) {\n const [companyNameLinkRows, personNameLinkRows] = await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { company: { $in: locatedMatchedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { person: { $in: locatedMatchedEntityIds } },\n { fields: ['deal'] },\n decryptionScope,\n ),\n ])\n let nameMatchedDealIds = [\n ...collectRefIds(companyNameLinkRows, 'deal'),\n ...collectRefIds(personNameLinkRows, 'deal'),\n ]\n if (nameMatchedDealIds.length > 0) {\n // The deal-field search in `buildDealListFilters` is intersected with the People/Companies\n // association (and stuck/`?id`) filters \u2014 they all land together in `filters.id`. The name\n // matches above carry NO such constraint, so unioning them raw would let a co-active\n // People/Companies filter be bypassed (over-broad results). Recover exactly the non-search id\n // allowlist by rebuilding the deal filters WITHOUT the search term, and intersect the name\n // matches with it so the active filter is honored: located \u2229 nonSearch \u2229 (dealField \u222A name).\n // (The map's query carries no advanced `filter[...]` params, so the consume-mutation in\n // buildDealListFilters does not affect this second build.)\n const nonSearchAllowlist = readFilterIdAllowlist(\n await buildDealListFilters({ ...query, search: undefined }, ctx),\n )\n if (nonSearchAllowlist) {\n const nonSearchLookup = new Set(nonSearchAllowlist)\n nameMatchedDealIds = nameMatchedDealIds.filter((id) => nonSearchLookup.has(id))\n }\n }\n if (nameMatchedDealIds.length > 0) {\n searchAllowlist = Array.from(new Set([...(existingAllowlist ?? []), ...nameMatchedDealIds]))\n }\n }\n }\n\n const allowlistLookup = searchAllowlist ? new Set(searchAllowlist) : null\n const restrictedDealIds = allowlistLookup\n ? locatedDealIds.filter((id) => allowlistLookup.has(id))\n : locatedDealIds\n // `restrictedDealIds` is the final located \u2229 (deal-field \u222A company/person-name) set \u2014 it already\n // captures every id constraint `buildDealListFilters` expressed (read back via\n // `readFilterIdAllowlist`). Clear the stale `filters.id` first so `applyEntityIdRestriction` does\n // not re-intersect against the deal-field \"no match\" sentinel and drop the name-matched deals.\n delete (filters as Record<string, unknown>).id\n applyEntityIdRestriction(filters, restrictedDealIds)\n\n const sortColumn = query.sortField ? sortFieldMap[query.sortField] : 'id'\n const sortDir = query.sortDir === 'desc' ? SortDir.Desc : SortDir.Asc\n // Always append `id` as a stable tiebreaker \u2014 non-unique sort columns (title, value,\n // probability, stage, or colliding timestamps) otherwise reorder between OFFSET pages and the\n // client's multi-page accumulation would skip or duplicate deals at page boundaries.\n const sort = sortColumn === 'id'\n ? [{ field: 'id', dir: sortDir }]\n : [{ field: sortColumn, dir: sortDir }, { field: 'id', dir: SortDir.Asc }]\n\n const res = await queryEngine.query(E.customers.customer_deal, {\n fields: [\n 'id',\n // `organization_id` is projected (never exposed in the response) so the query engine can decrypt\n // each row's encrypted fields (e.g. `title`) with the row's OWN org. Without it, an unrestricted\n // \"All organizations\" scope has no single fallback org to decrypt with and titles come back as\n // ciphertext \u2014 the List route projects it for the same reason (#3481).\n 'organization_id',\n 'title',\n 'status',\n 'pipeline_id',\n 'pipeline_stage_id',\n 'pipeline_stage',\n 'value_amount',\n 'value_currency',\n 'probability',\n 'expected_close_at',\n 'owner_user_id',\n 'updated_at',\n ],\n sort,\n page: { page: query.page, pageSize: query.pageSize },\n filters,\n tenantId: effectiveTenantId,\n organizationId: fallbackOrgId,\n organizationIds: orgScopeIds ?? undefined,\n })\n\n const rows = (Array.isArray(res.items) ? res.items : []).filter(\n (row): row is Record<string, unknown> => !!row && typeof row === 'object',\n )\n const dealIds = rows\n .map((row) => (typeof row.id === 'string' && row.id.trim().length ? row.id : null))\n .filter((value): value is string => value !== null)\n\n // Heavy fetch, page-bounded: pull decrypted links (for labels) and coordinate-bearing addresses\n // only for the deals on this page.\n const [companyLinks, personLinks] = dealIds.length\n ? await Promise.all([\n findWithDecryption(\n em,\n CustomerDealCompanyLink,\n { deal: { $in: dealIds } },\n { populate: ['company'] },\n decryptionScope,\n ),\n findWithDecryption(\n em,\n CustomerDealPersonLink,\n { deal: { $in: dealIds } },\n { populate: ['person'] },\n decryptionScope,\n ),\n ])\n : [[], []]\n\n const companyRows = companyLinks\n .map((link) => readLinkRow(link, link.company))\n .filter((row): row is LinkRow => row !== null)\n const personRows = personLinks\n .map((link) => readLinkRow(link, link.person))\n .filter((row): row is LinkRow => row !== null)\n const companiesByDeal = groupAssociations(companyRows)\n const peopleByDeal = groupAssociations(personRows)\n\n const linkedEntityIds = Array.from(\n new Set([...companyRows, ...personRows].map((row) => row.entityId)),\n )\n const addresses = linkedEntityIds.length\n ? await findWithDecryption(\n em,\n CustomerAddress,\n {\n entity: { $in: linkedEntityIds },\n latitude: { $ne: null },\n longitude: { $ne: null },\n tenantId: effectiveTenantId,\n ...orgScopeFilter,\n },\n {},\n decryptionScope,\n )\n : []\n\n const addressRows: DealMapAddress[] = []\n for (const address of addresses) {\n const { id: entityId } = readEntityRef(address.entity)\n if (!entityId) continue\n addressRows.push({\n id: address.id,\n entityId,\n isPrimary: address.isPrimary === true,\n latitude: address.latitude ?? null,\n longitude: address.longitude ?? null,\n city: address.city ?? null,\n region: address.region ?? null,\n country: address.country ?? null,\n createdAt: address.createdAt ?? null,\n })\n }\n\n const toLink = (row: LinkRow): DealMapLink => ({\n dealId: row.dealId,\n entityId: row.entityId,\n createdAt: row.createdAt,\n })\n const locationByDeal: Map<string, DealMapLocation | null> = resolveDealLocations(\n dealIds,\n companyRows.map(toLink),\n personRows.map(toLink),\n addressRows,\n )\n\n const items = rows\n .map((row) => {\n const id = typeof row.id === 'string' && row.id.trim().length ? row.id : null\n if (!id) return null\n return {\n id,\n title: toStringOrNull(row.title),\n status: toStringOrNull(row.status),\n pipelineId: toStringOrNull(row.pipeline_id),\n pipelineStageId: toStringOrNull(row.pipeline_stage_id),\n pipelineStage: toStringOrNull(row.pipeline_stage),\n valueAmount: toFiniteNumberOrNull(row.value_amount),\n valueCurrency: toStringOrNull(row.value_currency),\n probability: toFiniteNumberOrNull(row.probability),\n expectedCloseAt: toIsoStringOrNull(row.expected_close_at),\n ownerUserId: toStringOrNull(row.owner_user_id),\n updatedAt: toIsoStringOrNull(row.updated_at),\n companies: companiesByDeal.get(id) ?? [],\n people: peopleByDeal.get(id) ?? [],\n location: locationByDeal.get(id) ?? null,\n }\n })\n .filter((item): item is NonNullable<typeof item> => item !== null)\n\n return NextResponse.json({\n items,\n total: res.total,\n page: query.page,\n pageSize: query.pageSize,\n totalPages: Math.ceil(res.total / (query.pageSize || 1)),\n ...(res.meta?.listCountCapWarning ? { totalIsCapped: true } : {}),\n })\n}\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB;AAC7B,SAAS,SAAS;AAElB,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AACvC,SAAS,0CAA0C;AAEnD,SAAS,eAAiC;AAE1C,SAAS,0BAA0B;AACnC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB,2BAA2B;AAC1D,SAAS,0BAA0B,wDAAwD;AAC3F,SAAS,qCAAqC;AAC9C;AAAA,EACE;AAAA,OAIK;AACP,SAAS,SAAS;AAEX,MAAM,WAAW;AAAA,EACtB,KAAK,EAAE,aAAa,MAAM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AAA,MACA,OAAO,eAAe,IAAI,KAAK;AAAA,MAC/B,QAAQ,eAAe,IAAI,MAAM;AAAA,MACjC,YAAY,eAAe,IAAI,WAAW;AAAA,MAC1C,iBAAiB,eAAe,IAAI,iBAAiB;AAAA,MACrD,eAAe,eAAe,IAAI,cAAc;AAAA,MAChD,aAAa,qBAAqB,IAAI,YAAY;AAAA,MAClD,eAAe,eAAe,IAAI,cAAc;AAAA,MAChD,aAAa,qBAAqB,IAAI,WAAW;AAAA,MACjD,iBAAiB,kBAAkB,IAAI,iBAAiB;AAAA,MACxD,aAAa,eAAe,IAAI,aAAa;AAAA,MAC7C,WAAW,kBAAkB,IAAI,UAAU;AAAA,MAC3C,WAAW,gBAAgB,IAAI,EAAE,KAAK,CAAC;AAAA,MACvC,QAAQ,aAAa,IAAI,EAAE,KAAK,CAAC;AAAA,MACjC,UAAU,eAAe,IAAI,EAAE,KAAK;AAAA,IACtC;AAAA,EACF,CAAC,EACA,OAAO,CAAC,SAA2C,SAAS,IAAI;AAEnE,SAAO,aAAa,KAAK;AAAA,IACvB;AAAA,IACA,OAAO,IAAI;AAAA,IACX,MAAM,MAAM;AAAA,IACZ,UAAU,MAAM;AAAA,IAChB,YAAY,KAAK,KAAK,IAAI,SAAS,MAAM,YAAY,EAAE;AAAA,IACvD,GAAI,IAAI,MAAM,sBAAsB,EAAE,eAAe,KAAK,IAAI,CAAC;AAAA,EACjE,CAAC;AACH;",
6
6
  "names": []
7
7
  }
@@ -144,6 +144,7 @@ function CustomersCompaniesPage() {
144
144
  const [sorting, setSorting] = React.useState([]);
145
145
  const [total, setTotal] = React.useState(0);
146
146
  const [totalPages, setTotalPages] = React.useState(1);
147
+ const [totalIsCapped, setTotalIsCapped] = React.useState(false);
147
148
  const [search, setSearch] = React.useState("");
148
149
  const pathname = usePathname();
149
150
  const searchParams = useSearchParams();
@@ -329,6 +330,7 @@ function CustomersCompaniesPage() {
329
330
  setRows(items.map((item) => mapApiItem(item)).filter((row) => !!row));
330
331
  setTotal(typeof payload.total === "number" ? payload.total : items.length);
331
332
  setTotalPages(typeof payload.totalPages === "number" ? payload.totalPages : 1);
333
+ setTotalIsCapped(payload?.totalIsCapped === true);
332
334
  } catch (err) {
333
335
  if (!cancelled) {
334
336
  setCacheStatus(null);
@@ -829,7 +831,7 @@ function CustomersCompaniesPage() {
829
831
  }
830
832
  ),
831
833
  virtualized: true,
832
- pagination: { page, pageSize, total, totalPages, onPageChange: setPage, pageSizeOptions: [10, 25, 50, 100], onPageSizeChange: handlePageSizeChange, cacheStatus },
834
+ pagination: { page, pageSize, total, totalPages, totalIsCapped, onPageChange: setPage, pageSizeOptions: [10, 25, 50, 100], onPageSizeChange: handlePageSizeChange, cacheStatus },
833
835
  isLoading
834
836
  }
835
837
  ),