@elevasis/core 0.15.0 → 0.16.0

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 (88) hide show
  1. package/dist/index.d.ts +1718 -19
  2. package/dist/index.js +369 -25
  3. package/dist/organization-model/index.d.ts +1718 -19
  4. package/dist/organization-model/index.js +369 -25
  5. package/dist/test-utils/index.d.ts +1108 -371
  6. package/dist/test-utils/index.js +357 -17
  7. package/package.json +5 -1
  8. package/src/__tests__/publish.test.ts +14 -13
  9. package/src/__tests__/template-core-compatibility.test.ts +4 -4
  10. package/src/_gen/__tests__/__snapshots__/contracts.md.snap +1109 -882
  11. package/src/auth/multi-tenancy/index.ts +3 -0
  12. package/src/auth/multi-tenancy/theme-presets.ts +45 -0
  13. package/src/auth/multi-tenancy/types.ts +57 -83
  14. package/src/auth/multi-tenancy/users/api-schemas.ts +165 -194
  15. package/src/business/acquisition/activity-events.ts +13 -4
  16. package/src/business/acquisition/api-schemas.test.ts +315 -4
  17. package/src/business/acquisition/api-schemas.ts +122 -8
  18. package/src/business/acquisition/build-templates.ts +44 -0
  19. package/src/business/acquisition/crm-next-action.test.ts +262 -0
  20. package/src/business/acquisition/crm-next-action.ts +220 -0
  21. package/src/business/acquisition/crm-priority.test.ts +216 -0
  22. package/src/business/acquisition/crm-priority.ts +349 -0
  23. package/src/business/acquisition/crm-state-actions.test.ts +151 -160
  24. package/src/business/acquisition/deal-ownership.test.ts +351 -0
  25. package/src/business/acquisition/deal-ownership.ts +120 -0
  26. package/src/business/acquisition/derive-actions.test.ts +101 -37
  27. package/src/business/acquisition/derive-actions.ts +102 -87
  28. package/src/business/acquisition/index.ts +10 -0
  29. package/src/business/acquisition/types.ts +400 -366
  30. package/src/business/crm/api-schemas.ts +40 -0
  31. package/src/business/crm/index.ts +1 -0
  32. package/src/business/deals/api-schemas.ts +79 -0
  33. package/src/business/deals/index.ts +1 -0
  34. package/src/business/projects/types.ts +124 -88
  35. package/src/execution/core/runner-types.ts +61 -80
  36. package/src/execution/engine/index.ts +4 -3
  37. package/src/execution/engine/tools/integration/server/adapters/gmail/gmail-tools.ts +105 -104
  38. package/src/execution/engine/tools/integration/server/adapters/instantly/instantly-tools.ts +1474 -1473
  39. package/src/execution/engine/tools/integration/server/adapters/millionverifier/millionverifier-tools.ts +103 -102
  40. package/src/execution/engine/tools/integration/server/adapters/signature-api/signature-api-tools.ts +182 -179
  41. package/src/execution/engine/tools/integration/server/adapters/stripe/stripe-tools.ts +310 -309
  42. package/src/execution/engine/tools/integration/tool.ts +255 -253
  43. package/src/execution/engine/tools/lead-service-types.ts +939 -924
  44. package/src/execution/engine/tools/messages.ts +43 -0
  45. package/src/execution/engine/tools/platform/acquisition/list-tools.ts +6 -5
  46. package/src/execution/engine/tools/platform/acquisition/types.ts +5 -2
  47. package/src/execution/engine/tools/platform/email/types.ts +97 -96
  48. package/src/execution/engine/tools/registry.ts +4 -3
  49. package/src/execution/engine/tools/tool-maps.ts +3 -1
  50. package/src/execution/engine/tools/types.ts +234 -233
  51. package/src/execution/engine/workflow/types.ts +195 -193
  52. package/src/execution/external/api-schemas.ts +40 -0
  53. package/src/execution/external/index.ts +1 -0
  54. package/src/knowledge/README.md +32 -0
  55. package/src/knowledge/__tests__/queries.test.ts +504 -0
  56. package/src/knowledge/format.ts +99 -0
  57. package/src/knowledge/index.ts +5 -0
  58. package/src/knowledge/queries.ts +256 -0
  59. package/src/organization-model/__tests__/defaults.test.ts +172 -172
  60. package/src/organization-model/__tests__/foundation.test.ts +7 -7
  61. package/src/organization-model/__tests__/icons.test.ts +27 -0
  62. package/src/organization-model/__tests__/knowledge.test.ts +214 -0
  63. package/src/organization-model/contracts.ts +17 -15
  64. package/src/organization-model/defaults.ts +74 -19
  65. package/src/organization-model/domains/knowledge.ts +53 -0
  66. package/src/organization-model/domains/navigation.ts +416 -399
  67. package/src/organization-model/domains/prospecting.ts +204 -1
  68. package/src/organization-model/domains/sales.test.ts +29 -0
  69. package/src/organization-model/domains/sales.ts +102 -0
  70. package/src/organization-model/domains/shared.ts +6 -5
  71. package/src/organization-model/foundation.ts +10 -6
  72. package/src/organization-model/graph/build.ts +209 -182
  73. package/src/organization-model/graph/schema.ts +37 -34
  74. package/src/organization-model/graph/types.ts +47 -31
  75. package/src/organization-model/icons.ts +81 -0
  76. package/src/organization-model/index.ts +8 -3
  77. package/src/organization-model/organization-model.mdx +1 -1
  78. package/src/organization-model/published.ts +103 -86
  79. package/src/organization-model/schema.ts +90 -85
  80. package/src/organization-model/types.ts +42 -35
  81. package/src/platform/constants/versions.ts +1 -1
  82. package/src/platform/index.ts +23 -27
  83. package/src/platform/registry/index.ts +0 -4
  84. package/src/platform/registry/resource-registry.ts +0 -77
  85. package/src/platform/registry/serialized-types.ts +148 -219
  86. package/src/platform/registry/stats-types.ts +60 -60
  87. package/src/reference/_generated/contracts.md +829 -595
  88. package/src/supabase/database.types.ts +2978 -2958
@@ -1,507 +1,520 @@
1
- /**
2
- * Lead Service Types
3
- * CRUD operation types for the acquisition platform (lists, companies, contacts, deals)
4
- *
5
- * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
6
- */
7
-
8
- import type { Json } from '../../../supabase'
9
-
10
- // Re-export acquisition domain types from the authoritative source
11
- import type {
12
- AcqList,
13
- AcqCompany,
14
- AcqContact,
15
- AcqDealTask,
16
- AcqDealTaskKind,
17
- ListStatus,
18
- ScrapingConfig,
19
- IcpRubric,
20
- PipelineConfig,
1
+ /**
2
+ * Lead Service Types
3
+ * CRUD operation types for the acquisition platform (lists, companies, contacts, deals)
4
+ *
5
+ * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
6
+ */
7
+
8
+ import type { Json } from '../../../supabase'
9
+
10
+ // Re-export acquisition domain types from the authoritative source
11
+ import type {
12
+ AcqList,
13
+ AcqCompany,
14
+ AcqContact,
15
+ AcqDealTask,
16
+ AcqDealTaskKind,
17
+ ListStatus,
18
+ ScrapingConfig,
19
+ IcpRubric,
20
+ PipelineConfig,
21
21
  ListTelemetry,
22
22
  DealDetail
23
23
  } from '../../../business/acquisition/types'
24
24
  import type { ListProgress, ProcessingStageStatus } from '../../../business/acquisition/api-schemas'
25
-
26
- export type {
27
- AcqList,
28
- AcqCompany,
29
- AcqContact,
30
- AcqDealTask,
31
- AcqDealTaskKind,
32
- ListStatus,
33
- ScrapingConfig,
34
- IcpRubric,
25
+
26
+ export type {
27
+ AcqList,
28
+ AcqCompany,
29
+ AcqContact,
30
+ AcqDealTask,
31
+ AcqDealTaskKind,
32
+ ListStatus,
33
+ ScrapingConfig,
34
+ IcpRubric,
35
35
  PipelineConfig,
36
36
  ProcessingStageStatus,
37
37
  ListTelemetry,
38
- DealDetail,
39
- ListProgress
40
- }
41
-
42
- // Pagination types
43
- export interface PaginationParams {
44
- limit: number
45
- offset: number
46
- }
47
-
48
- export interface PaginatedResult<T> {
49
- data: T[]
50
- total: number
51
- limit: number
52
- offset: number
53
- }
54
-
55
- // List params
56
- export interface CreateListParams {
57
- organizationId: string
58
- name: string
59
- description?: string
60
- type?: string
61
- batchIds?: string[]
62
- instantlyCampaignId?: string
63
- status?: ListStatus
64
- metadata?: Record<string, unknown>
65
- scrapingConfig?: ScrapingConfig
66
- icp?: IcpRubric
67
- pipelineConfig?: PipelineConfig
68
- }
69
-
70
- export interface UpdateListParams {
71
- name?: string
72
- description?: string
73
- batchIds?: string[]
74
- }
75
-
76
- export interface UpdateListStatusParams {
77
- organizationId: string
78
- listId: string
79
- status: ListStatus
80
- }
81
-
82
- // Company params
83
- export interface CreateCompanyParams {
84
- organizationId: string
85
- name: string
86
- domain?: string
87
- linkedinUrl?: string
88
- website?: string
89
- numEmployees?: number
90
- foundedYear?: number
91
- locationCity?: string
92
- locationState?: string
93
- category?: string
94
- source?: string
95
- batchId?: string
96
- verticalResearch?: string
97
- }
98
-
99
- export interface UpdateCompanyParams {
100
- name?: string
101
- domain?: string
102
- linkedinUrl?: string
103
- website?: string
104
- numEmployees?: number
105
- foundedYear?: number
106
- locationCity?: string
107
- locationState?: string
108
- category?: string
109
- segment?: string
110
- pipelineStatus?: Record<string, unknown>
111
- enrichmentData?: Record<string, unknown>
112
- source?: string
113
- batchId?: string
114
- status?: 'active' | 'invalid'
115
- verticalResearch?: string | null
116
- /** Track A: flat qualification score column (null until a scoring rubric is defined) */
117
- qualificationScore?: number | null
118
- /** Track A: flat qualification signals jsonb — mirrors the former pipeline_status.qualification shape */
119
- qualificationSignals?: Record<string, unknown> | null
120
- /** Track A: key identifying the rubric used for qualification */
121
- qualificationRubricKey?: string | null
122
- }
123
-
124
- export type UpsertCompanyParams = CreateCompanyParams
125
- // Upsert by domain - uses same fields as create
126
-
127
- export interface CompanyFilters {
128
- listId?: string // Filter to companies in a specific list (via acq_list_companies)
129
- search?: string
130
- domain?: string
131
- website?: string
132
- segment?: string
133
- category?: string
134
- pipelineStatus?: Record<string, unknown>
135
- /** Exclude companies whose pipeline_status contains this value (PostgREST NOT contains) */
136
- pipelineStatusNot?: Record<string, unknown>
137
- batchId?: string
138
- status?: 'active' | 'invalid'
139
- includeAll?: boolean
140
- excludeColumns?: Array<'enrichmentData' | 'pipelineStatus'>
141
- }
142
-
143
- // Contact params
144
- export interface CreateContactParams {
145
- organizationId: string
146
- email: string
147
- companyId?: string
148
- firstName?: string
149
- lastName?: string
150
- linkedinUrl?: string
151
- title?: string
152
- source?: string
153
- sourceId?: string
154
- batchId?: string
155
- }
156
-
157
- export interface UpdateContactParams {
158
- companyId?: string
159
- emailValid?: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN'
160
- firstName?: string
161
- lastName?: string
162
- linkedinUrl?: string
163
- title?: string
164
- headline?: string
165
- filterReason?: string
166
- openingLine?: string
167
- pipelineStatus?: Record<string, unknown>
168
- enrichmentData?: Record<string, unknown>
169
- status?: 'active' | 'invalid'
170
- }
171
-
172
- export type UpsertContactParams = CreateContactParams
173
- // Upsert by email - uses same fields as create
174
-
175
- export interface ContactFilters {
176
- listId?: string // Filter to contacts in a specific list (via acq_list_members)
177
- search?: string
178
- openingLineIsNull?: boolean // Filter to contacts without personalization
179
- pipelineStatus?: Record<string, unknown>
180
- batchId?: string
181
- contactStatus?: 'active' | 'invalid' // Filter by contact status (soft-delete flag)
182
- }
183
-
184
- // Deal params (for acq_deals table)
185
- export interface UpsertDealParams {
186
- organizationId: string
187
- /** Contact email — dedupe key together with organization_id */
188
- contactEmail: string
189
- /** Optional contact ID for foreign key join */
190
- contactId?: string
191
- /** Campaign list that generated this deal (FK to acq_lists) */
192
- sourceListId?: string
193
- /** Deal origin: 'instantly', 'referral', 'inbound', 'manual' */
194
- sourceType?: 'instantly' | 'referral' | 'inbound' | 'manual'
195
- /** Optional discovery data JSONB to set on upsert */
196
- discoveryData?: unknown
197
- /** Optional proposal data JSONB to set on upsert */
198
- proposalData?: unknown
199
- }
200
-
201
- export interface UpdateDiscoveryDataParams {
202
- organizationId: string
203
- contactEmail: string
204
- discoveryData: unknown
205
- submittedBy?: string
206
- }
207
-
208
- export interface UpdateProposalDataParams {
209
- organizationId: string
210
- contactEmail: string
211
- proposalData: unknown
212
- proposalPdfUrl?: string
213
- }
214
-
215
- export interface MarkProposalSentParams {
216
- organizationId: string
217
- contactEmail: string
218
- }
219
-
220
- export interface MarkProposalReviewedParams {
221
- organizationId: string
222
- contactEmail: string
223
- reviewedBy: string
224
- proposalData?: unknown
225
- }
226
-
227
- export interface UpdateCloseLostReasonParams {
228
- organizationId: string
229
- dealId: string
230
- reason: string
231
- }
232
-
233
- export interface UpdateFeesParams {
234
- organizationId: string
235
- contactEmail?: string
236
- dealId?: string
237
- initialFee?: number
238
- monthlyFee?: number
239
- }
240
-
241
- export interface TransitionItemParams {
242
- organizationId: string
243
- dealId: string
244
- pipelineKey: string
245
- stageKey: string
246
- stateKey?: string | null
247
- reason?: string
248
- expectedUpdatedAt?: string
249
- }
250
-
251
- export interface SetContactNurtureParams {
252
- organizationId: string
253
- contactEmail: string
254
- nurture?: boolean
255
- }
256
-
257
- export interface DeactivateContactsByCompanyParams {
258
- organizationId: string
259
- companyId: string
260
- }
261
-
262
- export interface DeactivateContactsByCompanyResult {
263
- deactivated: number
264
- }
265
-
266
- export interface CancelSchedulesAndHitlByEmailParams {
267
- organizationId: string
268
- email: string
269
- }
270
-
271
- export interface CancelHitlByDealIdParams {
272
- organizationId: string
273
- dealId: string
274
- }
275
-
276
- export interface ClearDealFieldsParams {
277
- organizationId: string
278
- contactEmail?: string
279
- dealId?: string
280
- fields: (
281
- | 'proposalPdfUrl'
282
- | 'proposalGeneratedAt'
283
- | 'initialFee'
284
- | 'monthlyFee'
285
- | 'closedLostReason'
286
- | 'closedLostAt'
287
- | 'discoveryData'
288
- | 'discoverySubmittedAt'
289
- )[]
290
- }
291
-
292
- export interface DeleteDealParams {
293
- organizationId: string
294
- dealId: string
295
- }
296
-
297
- export interface GetDealByIdParams {
298
- dealId: string
299
- organizationId: string
300
- }
301
-
302
- export interface GetContactByIdParams {
303
- contactId: string
304
- organizationId: string
305
- }
306
-
307
- export interface GetCompanyByIdParams {
308
- companyId: string
309
- organizationId: string
310
- }
311
-
312
- // Social monitoring params (acq_social_posts table)
313
- export interface UpsertSocialPostParams {
314
- organizationId: string
315
- platform: string
316
- platformPostId: string
317
- authorName: string
318
- authorUrl?: string | null
319
- postTitle: string
320
- postText: string
321
- postUrl: string
322
- engagementCount?: number
323
- commentsCount?: number
324
- postedAt: string
325
- metadata?: Record<string, unknown>
326
- relevanceScore?: number
327
- matchedKeywords?: string[]
328
- matchedQuery?: string | null
329
- initialDraft?: string | null
330
- finalResponse?: string | null
331
- sourceCategory?: string | null
332
- }
333
-
334
- export interface UpsertSocialPostsParams {
335
- organizationId: string
336
- posts: Omit<UpsertSocialPostParams, 'organizationId'>[]
337
- }
338
-
339
- export interface UpsertSocialPostsResult {
340
- inserted: number
341
- duplicatesSkipped: number
342
- }
343
-
344
- export interface AcqDeal {
345
- id: string
346
- organizationId: string
347
- contactEmail: string
348
- pipelineKey: string
349
- stageKey?: string | null
350
- stateKey?: string | null
351
- discoveryData?: Json | null
352
- proposalData?: Json | null
353
- proposalSentAt?: string | null
354
- proposalPdfUrl?: string | null
355
- signatureEnvelopeId?: string | null
356
- sourceListId?: string | null
357
- sourceType?: string | null
358
- activityLog: DealActivityEntry[]
359
- createdAt: Date
360
- updatedAt: Date
361
- }
362
-
363
- export interface DealActivityEntry {
364
- type: string
365
- title: string
366
- description?: string
367
- payload?: Record<string, unknown>
368
- occurredAt: string
369
- }
370
-
371
- export interface AcqDealNote {
372
- id: string
373
- dealId: string
374
- organizationId: string
375
- authorUserId: string | null
376
- body: string
377
- createdAt: string
378
- updatedAt: string
379
- }
380
-
381
- export interface CreateDealNoteParams {
382
- organizationId: string
383
- dealId: string
384
- body: string
385
- authorUserId?: string
386
- }
387
-
388
- export interface ListDealNotesParams {
389
- organizationId: string
390
- dealId: string
391
- }
392
-
393
- export interface CreateDealTaskParams {
394
- organizationId: string
395
- dealId: string
396
- title: string
397
- description?: string | null
398
- kind?: AcqDealTaskKind
399
- dueAt?: string | null
400
- assigneeUserId?: string | null
401
- createdByUserId?: string | null
402
- }
403
-
404
- export interface ListDealTasksParams {
405
- organizationId: string
406
- dealId: string
407
- }
408
-
409
- export interface ListDealTasksDueParams {
410
- organizationId: string
411
- assigneeUserId?: string | null
412
- /** Window filter: 'overdue' = past due, 'today' = due today only, 'today_and_overdue' (default) = both, 'upcoming' = future */
413
- window?: 'overdue' | 'today' | 'today_and_overdue' | 'upcoming'
414
- }
415
-
416
- export interface CompleteDealTaskParams {
417
- organizationId: string
418
- taskId: string
419
- completedByUserId: string | null
420
- }
421
-
422
- export interface RecordDealActivityParams {
423
- organizationId: string
424
- dealId: string
425
- type: string
426
- title: string
427
- description?: string
428
- payload?: Record<string, unknown>
429
- }
430
-
431
- export interface SetDealStateKeyParams {
432
- organizationId: string
433
- dealId: string
434
- stateKey: string
435
- }
436
-
437
- export interface TransitionDealParams {
438
- organizationId: string
439
- dealId: string
440
- toStage: string
441
- toState?: string
442
- }
443
-
444
- export interface LoadDealParams {
445
- organizationId: string
446
- dealId: string
447
- }
448
-
449
- // Deal analytics types (for /meta status and platform-status workflow)
450
-
451
- export interface DealStageSummary {
452
- stage: string
453
- count: number
454
- oldestUpdatedAt: string | null
455
- newestUpdatedAt: string | null
456
- }
457
-
458
- export interface StaleDeal {
459
- id: string
460
- contactEmail: string
461
- stageKey: string
462
- updatedAt: string
463
- daysStale: number
464
- }
465
-
466
- export interface DealPipelineAnalytics {
467
- totalDeals: number
468
- stageSummary: DealStageSummary[]
469
- staleDeals: StaleDeal[]
470
- recentActivity: AcqDeal[]
471
- }
472
-
473
- export interface DealAnalyticsParams {
474
- organizationId: string
475
- recentLimit?: number
476
- }
477
-
478
- export interface DealFilters {
479
- stage?: string
480
- search?: string
481
- limit?: number
482
- offset?: number
483
- }
484
-
485
- export interface AddContactsToListParams {
486
- organizationId: string
487
- listId: string
488
- contactIds: string[]
489
- }
490
-
491
- export interface AddContactsToListResult {
492
- added: number
493
- alreadyExisted: number
494
- }
495
-
496
- // List config/progress/executions params
497
- export interface UpdateListConfigParams {
498
- organizationId: string
499
- listId: string
500
- scrapingConfig?: ScrapingConfig
501
- icp?: IcpRubric
502
- pipelineConfig?: PipelineConfig
503
- }
504
-
38
+ DealDetail,
39
+ ListProgress
40
+ }
41
+
42
+ // Pagination types
43
+ export interface PaginationParams {
44
+ limit: number
45
+ offset: number
46
+ }
47
+
48
+ export interface PaginatedResult<T> {
49
+ data: T[]
50
+ total: number
51
+ limit: number
52
+ offset: number
53
+ }
54
+
55
+ // List params
56
+ export interface CreateListParams {
57
+ organizationId: string
58
+ name: string
59
+ description?: string
60
+ type?: string
61
+ batchIds?: string[]
62
+ instantlyCampaignId?: string
63
+ status?: ListStatus
64
+ buildTemplateId?: string
65
+ metadata?: Record<string, unknown>
66
+ scrapingConfig?: ScrapingConfig
67
+ icp?: IcpRubric
68
+ pipelineConfig?: PipelineConfig
69
+ }
70
+
71
+ export interface UpdateListParams {
72
+ name?: string
73
+ description?: string
74
+ batchIds?: string[]
75
+ }
76
+
77
+ export interface UpdateListStatusParams {
78
+ organizationId: string
79
+ listId: string
80
+ status: ListStatus
81
+ }
82
+
83
+ // Company params
84
+ export interface CreateCompanyParams {
85
+ organizationId: string
86
+ name: string
87
+ domain?: string
88
+ linkedinUrl?: string
89
+ website?: string
90
+ numEmployees?: number
91
+ foundedYear?: number
92
+ locationCity?: string
93
+ locationState?: string
94
+ category?: string
95
+ source?: string
96
+ batchId?: string
97
+ verticalResearch?: string
98
+ }
99
+
100
+ export interface UpdateCompanyParams {
101
+ name?: string
102
+ domain?: string
103
+ linkedinUrl?: string
104
+ website?: string
105
+ numEmployees?: number
106
+ foundedYear?: number
107
+ locationCity?: string
108
+ locationState?: string
109
+ category?: string
110
+ segment?: string
111
+ pipelineStatus?: Record<string, unknown>
112
+ enrichmentData?: Record<string, unknown>
113
+ source?: string
114
+ batchId?: string
115
+ status?: 'active' | 'invalid'
116
+ verticalResearch?: string | null
117
+ /** Track A: flat qualification score column (null until a scoring rubric is defined) */
118
+ qualificationScore?: number | null
119
+ /** Track A: flat qualification signals jsonb — mirrors the former pipeline_status.qualification shape */
120
+ qualificationSignals?: Record<string, unknown> | null
121
+ /** Track A: key identifying the rubric used for qualification */
122
+ qualificationRubricKey?: string | null
123
+ }
124
+
125
+ export type UpsertCompanyParams = CreateCompanyParams
126
+ // Upsert by domain - uses same fields as create
127
+
128
+ export interface CompanyFilters {
129
+ listId?: string // Filter to companies in a specific list (via acq_list_companies)
130
+ search?: string
131
+ domain?: string
132
+ website?: string
133
+ segment?: string
134
+ category?: string
135
+ pipelineStatus?: Record<string, unknown>
136
+ /** Exclude companies whose pipeline_status contains this value (PostgREST NOT contains) */
137
+ pipelineStatusNot?: Record<string, unknown>
138
+ batchId?: string
139
+ status?: 'active' | 'invalid'
140
+ includeAll?: boolean
141
+ excludeColumns?: Array<'enrichmentData' | 'pipelineStatus'>
142
+ limit?: number
143
+ }
144
+
145
+ // Contact params
146
+ export interface CreateContactParams {
147
+ organizationId: string
148
+ email: string
149
+ companyId?: string
150
+ firstName?: string
151
+ lastName?: string
152
+ linkedinUrl?: string
153
+ title?: string
154
+ source?: string
155
+ sourceId?: string
156
+ batchId?: string
157
+ }
158
+
159
+ export interface UpdateContactParams {
160
+ companyId?: string
161
+ emailValid?: 'VALID' | 'INVALID' | 'RISKY' | 'UNKNOWN'
162
+ firstName?: string
163
+ lastName?: string
164
+ linkedinUrl?: string
165
+ title?: string
166
+ headline?: string
167
+ filterReason?: string
168
+ openingLine?: string
169
+ pipelineStatus?: Record<string, unknown>
170
+ enrichmentData?: Record<string, unknown>
171
+ status?: 'active' | 'invalid'
172
+ }
173
+
174
+ export type UpsertContactParams = CreateContactParams
175
+ // Upsert by email - uses same fields as create
176
+
177
+ export interface ContactFilters {
178
+ listId?: string // Filter to contacts in a specific list (via acq_list_members)
179
+ search?: string
180
+ openingLineIsNull?: boolean // Filter to contacts without personalization
181
+ pipelineStatus?: Record<string, unknown>
182
+ batchId?: string
183
+ contactStatus?: 'active' | 'invalid' // Filter by contact status (soft-delete flag)
184
+ }
185
+
186
+ // Deal params (for acq_deals table)
187
+ export interface UpsertDealParams {
188
+ organizationId: string
189
+ /** Contact email dedupe key together with organization_id */
190
+ contactEmail: string
191
+ /** Optional contact ID for foreign key join */
192
+ contactId?: string
193
+ /** Campaign list that generated this deal (FK to acq_lists) */
194
+ sourceListId?: string
195
+ /** Deal origin: 'instantly', 'referral', 'inbound', 'manual' */
196
+ sourceType?: 'instantly' | 'referral' | 'inbound' | 'manual'
197
+ /** Optional discovery data JSONB to set on upsert */
198
+ discoveryData?: unknown
199
+ /** Optional proposal data JSONB to set on upsert */
200
+ proposalData?: unknown
201
+ /** Instantly email UUID used to hydrate the reply thread */
202
+ instantlyThreadUuid?: string
203
+ /** Instantly sender account for direction detection */
204
+ instantlyEmailAccount?: string
205
+ }
206
+
207
+ export interface UpdateDiscoveryDataParams {
208
+ organizationId: string
209
+ contactEmail: string
210
+ discoveryData: unknown
211
+ submittedBy?: string
212
+ }
213
+
214
+ export interface UpdateProposalDataParams {
215
+ organizationId: string
216
+ contactEmail: string
217
+ proposalData: unknown
218
+ proposalPdfUrl?: string
219
+ }
220
+
221
+ export interface MarkProposalSentParams {
222
+ organizationId: string
223
+ contactEmail: string
224
+ }
225
+
226
+ export interface MarkProposalReviewedParams {
227
+ organizationId: string
228
+ contactEmail: string
229
+ reviewedBy: string
230
+ proposalData?: unknown
231
+ }
232
+
233
+ export interface UpdateCloseLostReasonParams {
234
+ organizationId: string
235
+ dealId: string
236
+ reason: string
237
+ }
238
+
239
+ export interface UpdateFeesParams {
240
+ organizationId: string
241
+ contactEmail?: string
242
+ dealId?: string
243
+ initialFee?: number
244
+ monthlyFee?: number
245
+ }
246
+
247
+ export interface CacheInstantlyThreadIdsParams {
248
+ organizationId: string
249
+ dealId: string
250
+ instantlyThreadUuid: string
251
+ instantlyEmailAccount: string
252
+ }
253
+
254
+ export interface TransitionItemParams {
255
+ organizationId: string
256
+ dealId: string
257
+ pipelineKey: string
258
+ stageKey: string
259
+ stateKey?: string | null
260
+ reason?: string
261
+ expectedUpdatedAt?: string
262
+ }
263
+
264
+ export interface SetContactNurtureParams {
265
+ organizationId: string
266
+ contactEmail: string
267
+ nurture?: boolean
268
+ }
269
+
270
+ export interface DeactivateContactsByCompanyParams {
271
+ organizationId: string
272
+ companyId: string
273
+ }
274
+
275
+ export interface DeactivateContactsByCompanyResult {
276
+ deactivated: number
277
+ }
278
+
279
+ export interface CancelSchedulesAndHitlByEmailParams {
280
+ organizationId: string
281
+ email: string
282
+ }
283
+
284
+ export interface CancelHitlByDealIdParams {
285
+ organizationId: string
286
+ dealId: string
287
+ }
288
+
289
+ export interface ClearDealFieldsParams {
290
+ organizationId: string
291
+ contactEmail?: string
292
+ dealId?: string
293
+ fields: (
294
+ | 'proposalPdfUrl'
295
+ | 'proposalGeneratedAt'
296
+ | 'initialFee'
297
+ | 'monthlyFee'
298
+ | 'closedLostReason'
299
+ | 'closedLostAt'
300
+ | 'discoveryData'
301
+ | 'discoverySubmittedAt'
302
+ )[]
303
+ }
304
+
305
+ export interface DeleteDealParams {
306
+ organizationId: string
307
+ dealId: string
308
+ }
309
+
310
+ export interface GetDealByIdParams {
311
+ dealId: string
312
+ organizationId: string
313
+ }
314
+
315
+ export interface GetContactByIdParams {
316
+ contactId: string
317
+ organizationId: string
318
+ }
319
+
320
+ export interface GetCompanyByIdParams {
321
+ companyId: string
322
+ organizationId: string
323
+ }
324
+
325
+ // Social monitoring params (acq_social_posts table)
326
+ export interface UpsertSocialPostParams {
327
+ organizationId: string
328
+ platform: string
329
+ platformPostId: string
330
+ authorName: string
331
+ authorUrl?: string | null
332
+ postTitle: string
333
+ postText: string
334
+ postUrl: string
335
+ engagementCount?: number
336
+ commentsCount?: number
337
+ postedAt: string
338
+ metadata?: Record<string, unknown>
339
+ relevanceScore?: number
340
+ matchedKeywords?: string[]
341
+ matchedQuery?: string | null
342
+ initialDraft?: string | null
343
+ finalResponse?: string | null
344
+ sourceCategory?: string | null
345
+ }
346
+
347
+ export interface UpsertSocialPostsParams {
348
+ organizationId: string
349
+ posts: Omit<UpsertSocialPostParams, 'organizationId'>[]
350
+ }
351
+
352
+ export interface UpsertSocialPostsResult {
353
+ inserted: number
354
+ duplicatesSkipped: number
355
+ }
356
+
357
+ export interface AcqDeal {
358
+ id: string
359
+ organizationId: string
360
+ contactEmail: string
361
+ pipelineKey: string
362
+ stageKey?: string | null
363
+ stateKey?: string | null
364
+ discoveryData?: Json | null
365
+ proposalData?: Json | null
366
+ proposalSentAt?: string | null
367
+ proposalPdfUrl?: string | null
368
+ signatureEnvelopeId?: string | null
369
+ sourceListId?: string | null
370
+ sourceType?: string | null
371
+ activityLog: DealActivityEntry[]
372
+ createdAt: Date
373
+ updatedAt: Date
374
+ }
375
+
376
+ export interface DealActivityEntry {
377
+ type: string
378
+ title: string
379
+ description?: string
380
+ payload?: Record<string, unknown>
381
+ occurredAt: string
382
+ }
383
+
384
+ export interface AcqDealNote {
385
+ id: string
386
+ dealId: string
387
+ organizationId: string
388
+ authorUserId: string | null
389
+ body: string
390
+ createdAt: string
391
+ updatedAt: string
392
+ }
393
+
394
+ export interface CreateDealNoteParams {
395
+ organizationId: string
396
+ dealId: string
397
+ body: string
398
+ authorUserId?: string
399
+ }
400
+
401
+ export interface ListDealNotesParams {
402
+ organizationId: string
403
+ dealId: string
404
+ }
405
+
406
+ export interface CreateDealTaskParams {
407
+ organizationId: string
408
+ dealId: string
409
+ title: string
410
+ description?: string | null
411
+ kind?: AcqDealTaskKind
412
+ dueAt?: string | null
413
+ assigneeUserId?: string | null
414
+ createdByUserId?: string | null
415
+ }
416
+
417
+ export interface ListDealTasksParams {
418
+ organizationId: string
419
+ dealId: string
420
+ }
421
+
422
+ export interface ListDealTasksDueParams {
423
+ organizationId: string
424
+ assigneeUserId?: string | null
425
+ /** Window filter: 'overdue' = past due, 'today' = due today only, 'today_and_overdue' (default) = both, 'upcoming' = future */
426
+ window?: 'overdue' | 'today' | 'today_and_overdue' | 'upcoming'
427
+ }
428
+
429
+ export interface CompleteDealTaskParams {
430
+ organizationId: string
431
+ taskId: string
432
+ completedByUserId: string | null
433
+ }
434
+
435
+ export interface RecordDealActivityParams {
436
+ organizationId: string
437
+ dealId: string
438
+ type: string
439
+ title: string
440
+ description?: string
441
+ payload?: Record<string, unknown>
442
+ }
443
+
444
+ export interface SetDealStateKeyParams {
445
+ organizationId: string
446
+ dealId: string
447
+ stateKey: string
448
+ }
449
+
450
+ export interface TransitionDealParams {
451
+ organizationId: string
452
+ dealId: string
453
+ toStage: string
454
+ toState?: string
455
+ }
456
+
457
+ export interface LoadDealParams {
458
+ organizationId: string
459
+ dealId: string
460
+ }
461
+
462
+ // Deal analytics types (for /meta status and platform-status workflow)
463
+
464
+ export interface DealStageSummary {
465
+ stage: string
466
+ count: number
467
+ oldestUpdatedAt: string | null
468
+ newestUpdatedAt: string | null
469
+ }
470
+
471
+ export interface StaleDeal {
472
+ id: string
473
+ contactEmail: string
474
+ stageKey: string
475
+ updatedAt: string
476
+ daysStale: number
477
+ }
478
+
479
+ export interface DealPipelineAnalytics {
480
+ totalDeals: number
481
+ stageSummary: DealStageSummary[]
482
+ staleDeals: StaleDeal[]
483
+ recentActivity: AcqDeal[]
484
+ }
485
+
486
+ export interface DealAnalyticsParams {
487
+ organizationId: string
488
+ recentLimit?: number
489
+ }
490
+
491
+ export interface DealFilters {
492
+ stage?: string
493
+ search?: string
494
+ limit?: number
495
+ offset?: number
496
+ }
497
+
498
+ export interface AddContactsToListParams {
499
+ organizationId: string
500
+ listId: string
501
+ contactIds: string[]
502
+ }
503
+
504
+ export interface AddContactsToListResult {
505
+ added: number
506
+ alreadyExisted: number
507
+ }
508
+
509
+ // List config/progress/executions params
510
+ export interface UpdateListConfigParams {
511
+ organizationId: string
512
+ listId: string
513
+ scrapingConfig?: ScrapingConfig
514
+ icp?: IcpRubric
515
+ pipelineConfig?: PipelineConfig
516
+ }
517
+
505
518
  export interface UpdateCompanyStageParams {
506
519
  organizationId: string
507
520
  listId: string
@@ -519,430 +532,432 @@ export interface UpdateContactStageParams {
519
532
  status?: ProcessingStageStatus
520
533
  executionId?: string
521
534
  }
522
-
523
- export interface AddCompaniesToListParams {
524
- organizationId: string
525
- listId: string
526
- companyIds: string[]
527
- }
528
-
529
- export interface AddCompaniesToListResult {
530
- added: number
531
- alreadyExisted: number
532
- }
533
-
534
- export interface RemoveCompaniesFromListParams {
535
- organizationId: string
536
- listId: string
537
- companyIds: string[]
538
- }
539
-
540
- export interface RemoveCompaniesFromListResult {
541
- removed: number
542
- }
543
-
544
- export interface RecordListExecutionParams {
545
- organizationId: string
546
- listId: string
547
- executionId: string
548
- configSnapshot?: Record<string, unknown>
549
- }
550
-
551
- export interface ListExecutionSummary {
552
- executionId: string
553
- resourceId: string
554
- status: string
555
- createdAt: string
556
- completedAt: string | null
557
- durationMs: number | null
558
- }
559
-
560
- // Bulk import (contacts)
561
- export interface BulkImportParams {
562
- organizationId: string
563
- contacts: CreateContactParams[]
564
- listId?: string
565
- }
566
-
567
- export interface BulkImportResult {
568
- created: number
569
- updated: number
570
- errors: Array<{ email: string; error: string }>
571
- }
572
-
573
- // Bulk import (companies)
574
- export interface BulkImportCompanyEntry {
575
- name: string
576
- domain: string
577
- website?: string
578
- locationCity?: string
579
- locationState?: string
580
- category?: string
581
- source?: string
582
- enrichmentData?: Record<string, unknown>
583
- pipelineStatus?: Record<string, unknown>
584
- }
585
-
586
- export interface BulkImportCompaniesParams {
587
- organizationId: string
588
- batchId: string
589
- companies: BulkImportCompanyEntry[]
590
- }
591
-
592
- export interface BulkImportCompaniesResult {
593
- created: number
594
- skipped: number
595
- errors: Array<{ companyName: string; error: string }>
596
- }
597
-
598
- /**
599
- * Lead Service interface for acquisition platform tools.
600
- * Provides CRUD operations for lists, companies, and contacts.
601
- *
602
- * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
603
- *
604
- * Multi-tenancy: All operations require organizationId for tenant isolation.
605
- * All queries are filtered by organizationId via RLS policies.
606
- */
607
- export interface ILeadService {
608
- // List operations
609
- /**
610
- * Create a new list
611
- * @see LeadService.createList (apps/api/src/acquisition/lead-service.ts)
612
- */
613
- createList(params: CreateListParams): Promise<AcqList>
614
-
615
- /**
616
- * Update an existing list
617
- * @see LeadService.updateList (apps/api/src/acquisition/lead-service.ts)
618
- */
619
- updateList(id: string, params: UpdateListParams): Promise<AcqList>
620
-
621
- /**
622
- * Delete a list
623
- * @see LeadService.deleteList (apps/api/src/acquisition/lead-service.ts)
624
- */
625
- deleteList(id: string, organizationId: string): Promise<void>
626
-
627
- /**
628
- * Add contacts to a list (upsert — idempotent on re-runs)
629
- * @see LeadService.addContactsToList (apps/api/src/business/acquisition/lead-service.ts)
630
- */
631
- addContactsToList(params: AddContactsToListParams): Promise<AddContactsToListResult>
632
-
633
- /**
634
- * List all lists for an organization
635
- * @see LeadService.listLists (apps/api/src/acquisition/lead-service.ts)
636
- */
637
- listLists(organizationId: string): Promise<AcqList[]>
638
-
639
- /**
640
- * Get a single list by ID.
641
- */
642
- getList(id: string, organizationId: string): Promise<AcqList | null>
643
-
644
- /**
645
- * Deep-merge patch the jsonb `config` column. Patch keys at any depth
646
- * replace the corresponding subtree.
647
- */
648
- updateListConfig(params: UpdateListConfigParams): Promise<AcqList>
649
-
650
- /**
651
- * Add companies to a list via the acq_list_companies junction.
652
- * Idempotent on (list_id, company_id).
653
- */
654
- addCompaniesToList(params: AddCompaniesToListParams): Promise<AddCompaniesToListResult>
655
-
656
- /**
657
- * Remove companies from a list (delete junction rows only — company rows untouched).
658
- */
659
- removeCompaniesFromList(params: RemoveCompaniesFromListParams): Promise<RemoveCompaniesFromListResult>
660
-
661
- /**
662
- * Live org-wide list telemetry — computed on demand from acq_companies
663
- * and acq_contacts joined through the acq_list_companies / acq_list_members
664
- * junctions. Replaces the batch-scoped getBatchTelemetry.
665
- */
666
- getListsTelemetry(organizationId: string): Promise<ListTelemetry[]>
667
-
668
- /**
669
- * On-demand progress aggregation: COUNT(*) FILTER over processing_state flags,
670
- * keyed by the list's pipeline_config.stages[].key (Decision #4 + #7).
671
- */
672
- getListProgress(listId: string, organizationId: string): Promise<ListProgress | null>
673
-
674
- /**
675
- * Advance a company row within a list's explicit stage journey.
676
- */
677
- updateCompanyStage(params: UpdateCompanyStageParams): Promise<void>
678
-
679
- /**
680
- * Advance a contact row within a list's explicit stage journey.
681
- */
682
- updateContactStage(params: UpdateContactStageParams): Promise<void>
683
-
684
- /**
685
- * Per-list execution history — reads via the feature-owned
686
- * acq_list_executions junction, joined to execution_logs for details.
687
- */
688
- getListExecutions(listId: string, organizationId: string): Promise<ListExecutionSummary[]>
689
-
690
- /**
691
- * Write a junction row linking (listId, executionId). Called by the
692
- * workflow layer at execution start in Step 4. No-op if the row exists.
693
- */
694
- recordListExecution(params: RecordListExecutionParams): Promise<void>
695
-
696
- // Company operations
697
- /**
698
- * Create a new company
699
- * @see LeadService.createCompany (apps/api/src/acquisition/lead-service.ts)
700
- */
701
- createCompany(params: CreateCompanyParams): Promise<AcqCompany>
702
-
703
- /**
704
- * Update an existing company
705
- * @see LeadService.updateCompany (apps/api/src/acquisition/lead-service.ts)
706
- */
707
- updateCompany(id: string, params: UpdateCompanyParams): Promise<AcqCompany>
708
-
709
- /**
710
- * Upsert a company by domain
711
- * @see LeadService.upsertCompany (apps/api/src/acquisition/lead-service.ts)
712
- */
713
- upsertCompany(params: UpsertCompanyParams): Promise<AcqCompany>
714
-
715
- /**
716
- * Get a company by ID
717
- * @see LeadService.getCompany (apps/api/src/acquisition/lead-service.ts)
718
- */
719
- getCompany(id: string, organizationId: string): Promise<AcqCompany | null>
720
-
721
- /**
722
- * List companies with optional filters
723
- * @see LeadService.listCompanies (apps/api/src/acquisition/lead-service.ts)
724
- */
725
- listCompanies(organizationId: string, filters: CompanyFilters): Promise<AcqCompany[]>
726
-
727
- /**
728
- * Delete a company
729
- * @see LeadService.deleteCompany (apps/api/src/acquisition/lead-service.ts)
730
- */
731
- deleteCompany(id: string, organizationId: string): Promise<void>
732
-
733
- // Contact operations
734
- /**
735
- * Create a new contact
736
- * @see LeadService.createContact (apps/api/src/acquisition/lead-service.ts)
737
- */
738
- createContact(params: CreateContactParams): Promise<AcqContact>
739
-
740
- /**
741
- * Update an existing contact
742
- * @see LeadService.updateContact (apps/api/src/acquisition/lead-service.ts)
743
- */
744
- updateContact(id: string, params: UpdateContactParams): Promise<AcqContact>
745
-
746
- /**
747
- * Upsert a contact by email
748
- * @see LeadService.upsertContact (apps/api/src/acquisition/lead-service.ts)
749
- */
750
- upsertContact(params: UpsertContactParams): Promise<AcqContact>
751
-
752
- /**
753
- * Get a contact by ID
754
- * @see LeadService.getContact (apps/api/src/acquisition/lead-service.ts)
755
- */
756
- getContact(id: string, organizationId: string): Promise<AcqContact | null>
757
-
758
- /**
759
- * List contacts with pagination and filters
760
- * @see LeadService.listContacts (apps/api/src/acquisition/lead-service.ts)
761
- */
762
- listContacts(
763
- organizationId: string,
764
- filters: ContactFilters,
765
- pagination: PaginationParams
766
- ): Promise<PaginatedResult<AcqContact>>
767
-
768
- /**
769
- * Delete a contact
770
- * @see LeadService.deleteContact (apps/api/src/acquisition/lead-service.ts)
771
- */
772
- deleteContact(id: string, organizationId: string): Promise<void>
773
-
774
- /**
775
- * Bulk import contacts
776
- * @see LeadService.bulkImportContacts (apps/api/src/acquisition/lead-service.ts)
777
- */
778
- bulkImportContacts(params: BulkImportParams): Promise<BulkImportResult>
779
-
780
- /**
781
- * Bulk import companies with domain dedup (skips existing domains).
782
- * Inserts in batches using Supabase bulk insert + ON CONFLICT.
783
- * @see LeadService.bulkImportCompanies (apps/api/src/business/acquisition/lead-service.ts)
784
- */
785
- bulkImportCompanies(params: BulkImportCompaniesParams): Promise<BulkImportCompaniesResult>
786
-
787
- /**
788
- * Deactivate all active contacts belonging to a company.
789
- * Used by qualification workflow to cascade company disqualification to contacts.
790
- */
791
- deactivateContactsByCompany(params: DeactivateContactsByCompanyParams): Promise<DeactivateContactsByCompanyResult>
792
-
793
- /**
794
- * Get a contact by email address
795
- * Used for looking up existing leads when they reply to outreach
796
- * @see LeadService.getContactByEmail (apps/api/src/acquisition/lead-service.ts)
797
- */
798
- getContactByEmail(email: string, organizationId: string): Promise<AcqContact | null>
799
-
800
- // Deal operations (acq_deals table)
801
- /**
802
- * Upsert a deal by Attio Deal ID
803
- * Creates or updates acq_deals record linking Attio Deal to Supabase
804
- * @see LeadService.upsertDeal (apps/api/src/acquisition/lead-service.ts)
805
- */
806
- upsertDeal(params: UpsertDealParams): Promise<AcqDeal>
807
-
808
- /**
809
- * Get a deal by contact email
810
- * Used for looking up existing deals when leads book via email (fallback lookup)
811
- * @see LeadService.getDealByEmail (apps/api/src/acquisition/lead-service.ts)
812
- */
813
- getDealByEmail(email: string, organizationId: string): Promise<AcqDeal | null>
814
-
815
- /**
816
- * Get a deal by SignatureAPI envelope ID
817
- * Used by webhook handler to find deal when contract is signed
818
- * @see LeadService.getDealByEnvelopeId (apps/api/src/acquisition/lead-service.ts)
819
- */
820
- getDealByEnvelopeId(envelopeId: string, organizationId: string): Promise<AcqDeal | null>
821
-
822
- /**
823
- * Update deal with signature envelope ID
824
- * Called when proposal is sent via SignatureAPI
825
- * @see LeadService.updateDealEnvelopeId (apps/api/src/acquisition/lead-service.ts)
826
- */
827
- updateDealEnvelopeId(dealId: string, envelopeId: string, organizationId: string): Promise<AcqDeal | null>
828
-
829
- // Deal-sync operations (mirror deal-sync.ts utilities as server-side methods)
830
-
831
- getDealById(params: GetDealByIdParams): Promise<AcqDeal | null>
832
-
833
- getContactById(params: GetContactByIdParams): Promise<AcqContact | null>
834
-
835
- getCompanyById(params: GetCompanyByIdParams): Promise<AcqCompany | null>
836
-
837
- updateDiscoveryData(params: UpdateDiscoveryDataParams): Promise<void>
838
-
839
- updateProposalData(params: UpdateProposalDataParams): Promise<void>
840
-
841
- markProposalSent(params: MarkProposalSentParams): Promise<void>
842
-
843
- markProposalReviewed(params: MarkProposalReviewedParams): Promise<void>
844
-
845
- updateCloseLostReason(params: UpdateCloseLostReasonParams): Promise<void>
846
-
847
- updateFees(params: UpdateFeesParams): Promise<void>
848
-
849
- transitionItem(params: TransitionItemParams): Promise<void>
850
-
851
- setContactNurture(params: SetContactNurtureParams): Promise<void>
852
-
853
- cancelSchedulesAndHitlByEmail(
854
- params: CancelSchedulesAndHitlByEmailParams
855
- ): Promise<{ schedulesCancelled: number; hitlDeleted: number }>
856
-
857
- cancelHitlByDealId(params: CancelHitlByDealIdParams): Promise<{ hitlDeleted: number }>
858
-
859
- clearDealFields(params: ClearDealFieldsParams): Promise<void>
860
-
861
- deleteDeal(params: DeleteDealParams): Promise<void>
862
-
863
- listDeals(organizationId: string, filters?: DealFilters): Promise<AcqDeal[]>
864
-
865
- getDealPipelineAnalytics(organizationId: string, recentLimit?: number): Promise<DealPipelineAnalytics>
866
-
867
- /**
868
- * Deep-merge enrichment data into a company or contact record.
869
- * Merges per source key rather than wholesale replacing the JSONB object.
870
- * @see LeadService.mergeEnrichmentData (apps/api/src/business/acquisition/lead-service.ts)
871
- */
872
- mergeEnrichmentData(
873
- id: string,
874
- orgId: string,
875
- table: 'acq_companies' | 'acq_contacts',
876
- data: Record<string, unknown>
877
- ): Promise<void>
878
-
879
- // Deal note operations (acq_deal_notes table)
880
- /**
881
- * Create a human-authored note on a deal
882
- * @see LeadService.createDealNote (apps/api/src/business/acquisition/lead-service.ts)
883
- */
884
- createDealNote(params: CreateDealNoteParams): Promise<AcqDealNote>
885
-
886
- /**
887
- * List notes for a deal, ordered by created_at DESC
888
- * @see LeadService.listDealNotes (apps/api/src/business/acquisition/lead-service.ts)
889
- */
890
- listDealNotes(params: ListDealNotesParams): Promise<AcqDealNote[]>
891
-
892
- // Deal task operations (acq_deal_tasks table)
893
- /**
894
- * Creates a new task attached to a deal.
895
- * @see LeadService.createDealTask (apps/api/src/business/acquisition/lead-service.ts)
896
- */
897
- createDealTask(params: CreateDealTaskParams): Promise<AcqDealTask>
898
-
899
- /**
900
- * Lists all tasks for a given deal, ordered by due date.
901
- * @see LeadService.listDealTasks (apps/api/src/business/acquisition/lead-service.ts)
902
- */
903
- listDealTasks(params: ListDealTasksParams): Promise<AcqDealTask[]>
904
-
905
- /**
906
- * Lists open (uncompleted) tasks within a date window across all deals.
907
- * @see LeadService.listDealTasksDue (apps/api/src/business/acquisition/lead-service.ts)
908
- */
909
- listDealTasksDue(params: ListDealTasksDueParams): Promise<AcqDealTask[]>
910
-
911
- /**
912
- * Marks a task as completed.
913
- * @see LeadService.completeDealTask (apps/api/src/business/acquisition/lead-service.ts)
914
- */
915
- completeDealTask(params: CompleteDealTaskParams): Promise<AcqDealTask>
916
-
917
- /**
918
- * Record a deal activity entry by deal ID.
919
- * Generic method for any activity type — used by SDK workflows.
920
- * @see LeadService.recordDealActivity (apps/api/src/business/acquisition/lead-service.ts)
921
- */
922
- recordDealActivity(params: RecordDealActivityParams): Promise<void>
923
-
924
- /**
925
- * Update the state_key on an acq_deals row.
926
- * @see LeadService.setDealStateKey (apps/api/src/business/acquisition/lead-service.ts)
927
- */
928
- setDealStateKey(params: SetDealStateKeyParams): Promise<{ ok: true }>
929
-
930
- /**
931
- * Transition a deal to a new stage, resolving pipeline_key automatically.
932
- * @see LeadService.transitionDeal (apps/api/src/business/acquisition/lead-service.ts)
933
- */
934
- transitionDeal(params: TransitionDealParams): Promise<{ deal: AcqDeal }>
935
-
936
- /**
937
- * Load a deal with its joined contact and company data.
938
- * @see LeadService.loadDeal (apps/api/src/business/acquisition/lead-service.ts)
939
- */
940
- loadDeal(params: LoadDealParams): Promise<DealDetail | null>
941
-
942
- // Social monitoring operations (acq_social_posts table)
943
- /**
944
- * Bulk upsert social posts (deduplicate by platform + platform_post_id)
945
- * @see LeadService.upsertSocialPosts (apps/api/src/business/acquisition/lead-service.ts)
946
- */
947
- upsertSocialPosts(params: UpsertSocialPostsParams): Promise<UpsertSocialPostsResult>
948
- }
535
+
536
+ export interface AddCompaniesToListParams {
537
+ organizationId: string
538
+ listId: string
539
+ companyIds: string[]
540
+ }
541
+
542
+ export interface AddCompaniesToListResult {
543
+ added: number
544
+ alreadyExisted: number
545
+ }
546
+
547
+ export interface RemoveCompaniesFromListParams {
548
+ organizationId: string
549
+ listId: string
550
+ companyIds: string[]
551
+ }
552
+
553
+ export interface RemoveCompaniesFromListResult {
554
+ removed: number
555
+ }
556
+
557
+ export interface RecordListExecutionParams {
558
+ organizationId: string
559
+ listId: string
560
+ executionId: string
561
+ configSnapshot?: Record<string, unknown>
562
+ }
563
+
564
+ export interface ListExecutionSummary {
565
+ executionId: string
566
+ resourceId: string
567
+ status: string
568
+ createdAt: string
569
+ completedAt: string | null
570
+ durationMs: number | null
571
+ }
572
+
573
+ // Bulk import (contacts)
574
+ export interface BulkImportParams {
575
+ organizationId: string
576
+ contacts: CreateContactParams[]
577
+ listId?: string
578
+ }
579
+
580
+ export interface BulkImportResult {
581
+ created: number
582
+ updated: number
583
+ errors: Array<{ email: string; error: string }>
584
+ }
585
+
586
+ // Bulk import (companies)
587
+ export interface BulkImportCompanyEntry {
588
+ name: string
589
+ domain: string
590
+ website?: string
591
+ locationCity?: string
592
+ locationState?: string
593
+ category?: string
594
+ source?: string
595
+ enrichmentData?: Record<string, unknown>
596
+ pipelineStatus?: Record<string, unknown>
597
+ }
598
+
599
+ export interface BulkImportCompaniesParams {
600
+ organizationId: string
601
+ batchId: string
602
+ companies: BulkImportCompanyEntry[]
603
+ }
604
+
605
+ export interface BulkImportCompaniesResult {
606
+ created: number
607
+ skipped: number
608
+ errors: Array<{ companyName: string; error: string }>
609
+ }
610
+
611
+ /**
612
+ * Lead Service interface for acquisition platform tools.
613
+ * Provides CRUD operations for lists, companies, and contacts.
614
+ *
615
+ * Implementation: apps/api/src/acquisition/lead-service.ts (LeadService class)
616
+ *
617
+ * Multi-tenancy: All operations require organizationId for tenant isolation.
618
+ * All queries are filtered by organizationId via RLS policies.
619
+ */
620
+ export interface ILeadService {
621
+ // List operations
622
+ /**
623
+ * Create a new list
624
+ * @see LeadService.createList (apps/api/src/acquisition/lead-service.ts)
625
+ */
626
+ createList(params: CreateListParams): Promise<AcqList>
627
+
628
+ /**
629
+ * Update an existing list
630
+ * @see LeadService.updateList (apps/api/src/acquisition/lead-service.ts)
631
+ */
632
+ updateList(id: string, params: UpdateListParams): Promise<AcqList>
633
+
634
+ /**
635
+ * Delete a list
636
+ * @see LeadService.deleteList (apps/api/src/acquisition/lead-service.ts)
637
+ */
638
+ deleteList(id: string, organizationId: string): Promise<void>
639
+
640
+ /**
641
+ * Add contacts to a list (upsert — idempotent on re-runs)
642
+ * @see LeadService.addContactsToList (apps/api/src/business/acquisition/lead-service.ts)
643
+ */
644
+ addContactsToList(params: AddContactsToListParams): Promise<AddContactsToListResult>
645
+
646
+ /**
647
+ * List all lists for an organization
648
+ * @see LeadService.listLists (apps/api/src/acquisition/lead-service.ts)
649
+ */
650
+ listLists(organizationId: string): Promise<AcqList[]>
651
+
652
+ /**
653
+ * Get a single list by ID.
654
+ */
655
+ getList(id: string, organizationId: string): Promise<AcqList | null>
656
+
657
+ /**
658
+ * Deep-merge patch the jsonb `config` column. Patch keys at any depth
659
+ * replace the corresponding subtree.
660
+ */
661
+ updateListConfig(params: UpdateListConfigParams): Promise<AcqList>
662
+
663
+ /**
664
+ * Add companies to a list via the acq_list_companies junction.
665
+ * Idempotent on (list_id, company_id).
666
+ */
667
+ addCompaniesToList(params: AddCompaniesToListParams): Promise<AddCompaniesToListResult>
668
+
669
+ /**
670
+ * Remove companies from a list (delete junction rows only — company rows untouched).
671
+ */
672
+ removeCompaniesFromList(params: RemoveCompaniesFromListParams): Promise<RemoveCompaniesFromListResult>
673
+
674
+ /**
675
+ * Live org-wide list telemetry — computed on demand from acq_companies
676
+ * and acq_contacts joined through the acq_list_companies / acq_list_members
677
+ * junctions. Replaces the batch-scoped getBatchTelemetry.
678
+ */
679
+ getListsTelemetry(organizationId: string): Promise<ListTelemetry[]>
680
+
681
+ /**
682
+ * On-demand progress aggregation: COUNT(*) FILTER over processing_state flags,
683
+ * keyed by the list's pipeline_config.stages[].key (Decision #4 + #7).
684
+ */
685
+ getListProgress(listId: string, organizationId: string): Promise<ListProgress | null>
686
+
687
+ /**
688
+ * Advance a company row within a list's explicit stage journey.
689
+ */
690
+ updateCompanyStage(params: UpdateCompanyStageParams): Promise<void>
691
+
692
+ /**
693
+ * Advance a contact row within a list's explicit stage journey.
694
+ */
695
+ updateContactStage(params: UpdateContactStageParams): Promise<void>
696
+
697
+ /**
698
+ * Per-list execution history — reads via the feature-owned
699
+ * acq_list_executions junction, joined to execution_logs for details.
700
+ */
701
+ getListExecutions(listId: string, organizationId: string): Promise<ListExecutionSummary[]>
702
+
703
+ /**
704
+ * Write a junction row linking (listId, executionId). Called by the
705
+ * workflow layer at execution start in Step 4. No-op if the row exists.
706
+ */
707
+ recordListExecution(params: RecordListExecutionParams): Promise<void>
708
+
709
+ // Company operations
710
+ /**
711
+ * Create a new company
712
+ * @see LeadService.createCompany (apps/api/src/acquisition/lead-service.ts)
713
+ */
714
+ createCompany(params: CreateCompanyParams): Promise<AcqCompany>
715
+
716
+ /**
717
+ * Update an existing company
718
+ * @see LeadService.updateCompany (apps/api/src/acquisition/lead-service.ts)
719
+ */
720
+ updateCompany(id: string, params: UpdateCompanyParams): Promise<AcqCompany>
721
+
722
+ /**
723
+ * Upsert a company by domain
724
+ * @see LeadService.upsertCompany (apps/api/src/acquisition/lead-service.ts)
725
+ */
726
+ upsertCompany(params: UpsertCompanyParams): Promise<AcqCompany>
727
+
728
+ /**
729
+ * Get a company by ID
730
+ * @see LeadService.getCompany (apps/api/src/acquisition/lead-service.ts)
731
+ */
732
+ getCompany(id: string, organizationId: string): Promise<AcqCompany | null>
733
+
734
+ /**
735
+ * List companies with optional filters
736
+ * @see LeadService.listCompanies (apps/api/src/acquisition/lead-service.ts)
737
+ */
738
+ listCompanies(organizationId: string, filters: CompanyFilters): Promise<AcqCompany[]>
739
+
740
+ /**
741
+ * Delete a company
742
+ * @see LeadService.deleteCompany (apps/api/src/acquisition/lead-service.ts)
743
+ */
744
+ deleteCompany(id: string, organizationId: string): Promise<void>
745
+
746
+ // Contact operations
747
+ /**
748
+ * Create a new contact
749
+ * @see LeadService.createContact (apps/api/src/acquisition/lead-service.ts)
750
+ */
751
+ createContact(params: CreateContactParams): Promise<AcqContact>
752
+
753
+ /**
754
+ * Update an existing contact
755
+ * @see LeadService.updateContact (apps/api/src/acquisition/lead-service.ts)
756
+ */
757
+ updateContact(id: string, params: UpdateContactParams): Promise<AcqContact>
758
+
759
+ /**
760
+ * Upsert a contact by email
761
+ * @see LeadService.upsertContact (apps/api/src/acquisition/lead-service.ts)
762
+ */
763
+ upsertContact(params: UpsertContactParams): Promise<AcqContact>
764
+
765
+ /**
766
+ * Get a contact by ID
767
+ * @see LeadService.getContact (apps/api/src/acquisition/lead-service.ts)
768
+ */
769
+ getContact(id: string, organizationId: string): Promise<AcqContact | null>
770
+
771
+ /**
772
+ * List contacts with pagination and filters
773
+ * @see LeadService.listContacts (apps/api/src/acquisition/lead-service.ts)
774
+ */
775
+ listContacts(
776
+ organizationId: string,
777
+ filters: ContactFilters,
778
+ pagination: PaginationParams
779
+ ): Promise<PaginatedResult<AcqContact>>
780
+
781
+ /**
782
+ * Delete a contact
783
+ * @see LeadService.deleteContact (apps/api/src/acquisition/lead-service.ts)
784
+ */
785
+ deleteContact(id: string, organizationId: string): Promise<void>
786
+
787
+ /**
788
+ * Bulk import contacts
789
+ * @see LeadService.bulkImportContacts (apps/api/src/acquisition/lead-service.ts)
790
+ */
791
+ bulkImportContacts(params: BulkImportParams): Promise<BulkImportResult>
792
+
793
+ /**
794
+ * Bulk import companies with domain dedup (skips existing domains).
795
+ * Inserts in batches using Supabase bulk insert + ON CONFLICT.
796
+ * @see LeadService.bulkImportCompanies (apps/api/src/business/acquisition/lead-service.ts)
797
+ */
798
+ bulkImportCompanies(params: BulkImportCompaniesParams): Promise<BulkImportCompaniesResult>
799
+
800
+ /**
801
+ * Deactivate all active contacts belonging to a company.
802
+ * Used by qualification workflow to cascade company disqualification to contacts.
803
+ */
804
+ deactivateContactsByCompany(params: DeactivateContactsByCompanyParams): Promise<DeactivateContactsByCompanyResult>
805
+
806
+ /**
807
+ * Get a contact by email address
808
+ * Used for looking up existing leads when they reply to outreach
809
+ * @see LeadService.getContactByEmail (apps/api/src/acquisition/lead-service.ts)
810
+ */
811
+ getContactByEmail(email: string, organizationId: string): Promise<AcqContact | null>
812
+
813
+ // Deal operations (acq_deals table)
814
+ /**
815
+ * Upsert a deal by Attio Deal ID
816
+ * Creates or updates acq_deals record linking Attio Deal to Supabase
817
+ * @see LeadService.upsertDeal (apps/api/src/acquisition/lead-service.ts)
818
+ */
819
+ upsertDeal(params: UpsertDealParams): Promise<AcqDeal>
820
+
821
+ /**
822
+ * Get a deal by contact email
823
+ * Used for looking up existing deals when leads book via email (fallback lookup)
824
+ * @see LeadService.getDealByEmail (apps/api/src/acquisition/lead-service.ts)
825
+ */
826
+ getDealByEmail(email: string, organizationId: string): Promise<AcqDeal | null>
827
+
828
+ /**
829
+ * Get a deal by SignatureAPI envelope ID
830
+ * Used by webhook handler to find deal when contract is signed
831
+ * @see LeadService.getDealByEnvelopeId (apps/api/src/acquisition/lead-service.ts)
832
+ */
833
+ getDealByEnvelopeId(envelopeId: string, organizationId: string): Promise<AcqDeal | null>
834
+
835
+ /**
836
+ * Update deal with signature envelope ID
837
+ * Called when proposal is sent via SignatureAPI
838
+ * @see LeadService.updateDealEnvelopeId (apps/api/src/acquisition/lead-service.ts)
839
+ */
840
+ updateDealEnvelopeId(dealId: string, envelopeId: string, organizationId: string): Promise<AcqDeal | null>
841
+
842
+ // Deal-sync operations (mirror deal-sync.ts utilities as server-side methods)
843
+
844
+ getDealById(params: GetDealByIdParams): Promise<AcqDeal | null>
845
+
846
+ getContactById(params: GetContactByIdParams): Promise<AcqContact | null>
847
+
848
+ getCompanyById(params: GetCompanyByIdParams): Promise<AcqCompany | null>
849
+
850
+ updateDiscoveryData(params: UpdateDiscoveryDataParams): Promise<void>
851
+
852
+ updateProposalData(params: UpdateProposalDataParams): Promise<void>
853
+
854
+ markProposalSent(params: MarkProposalSentParams): Promise<void>
855
+
856
+ markProposalReviewed(params: MarkProposalReviewedParams): Promise<void>
857
+
858
+ updateCloseLostReason(params: UpdateCloseLostReasonParams): Promise<void>
859
+
860
+ updateFees(params: UpdateFeesParams): Promise<void>
861
+
862
+ cacheInstantlyThreadIds(params: CacheInstantlyThreadIdsParams): Promise<void>
863
+
864
+ transitionItem(params: TransitionItemParams): Promise<void>
865
+
866
+ setContactNurture(params: SetContactNurtureParams): Promise<void>
867
+
868
+ cancelSchedulesAndHitlByEmail(
869
+ params: CancelSchedulesAndHitlByEmailParams
870
+ ): Promise<{ schedulesCancelled: number; hitlDeleted: number }>
871
+
872
+ cancelHitlByDealId(params: CancelHitlByDealIdParams): Promise<{ hitlDeleted: number }>
873
+
874
+ clearDealFields(params: ClearDealFieldsParams): Promise<void>
875
+
876
+ deleteDeal(params: DeleteDealParams): Promise<void>
877
+
878
+ listDeals(organizationId: string, filters?: DealFilters): Promise<AcqDeal[]>
879
+
880
+ getDealPipelineAnalytics(organizationId: string, recentLimit?: number): Promise<DealPipelineAnalytics>
881
+
882
+ /**
883
+ * Deep-merge enrichment data into a company or contact record.
884
+ * Merges per source key rather than wholesale replacing the JSONB object.
885
+ * @see LeadService.mergeEnrichmentData (apps/api/src/business/acquisition/lead-service.ts)
886
+ */
887
+ mergeEnrichmentData(
888
+ id: string,
889
+ orgId: string,
890
+ table: 'acq_companies' | 'acq_contacts',
891
+ data: Record<string, unknown>
892
+ ): Promise<void>
893
+
894
+ // Deal note operations (acq_deal_notes table)
895
+ /**
896
+ * Create a human-authored note on a deal
897
+ * @see LeadService.createDealNote (apps/api/src/business/acquisition/lead-service.ts)
898
+ */
899
+ createDealNote(params: CreateDealNoteParams): Promise<AcqDealNote>
900
+
901
+ /**
902
+ * List notes for a deal, ordered by created_at DESC
903
+ * @see LeadService.listDealNotes (apps/api/src/business/acquisition/lead-service.ts)
904
+ */
905
+ listDealNotes(params: ListDealNotesParams): Promise<AcqDealNote[]>
906
+
907
+ // Deal task operations (acq_deal_tasks table)
908
+ /**
909
+ * Creates a new task attached to a deal.
910
+ * @see LeadService.createDealTask (apps/api/src/business/acquisition/lead-service.ts)
911
+ */
912
+ createDealTask(params: CreateDealTaskParams): Promise<AcqDealTask>
913
+
914
+ /**
915
+ * Lists all tasks for a given deal, ordered by due date.
916
+ * @see LeadService.listDealTasks (apps/api/src/business/acquisition/lead-service.ts)
917
+ */
918
+ listDealTasks(params: ListDealTasksParams): Promise<AcqDealTask[]>
919
+
920
+ /**
921
+ * Lists open (uncompleted) tasks within a date window across all deals.
922
+ * @see LeadService.listDealTasksDue (apps/api/src/business/acquisition/lead-service.ts)
923
+ */
924
+ listDealTasksDue(params: ListDealTasksDueParams): Promise<AcqDealTask[]>
925
+
926
+ /**
927
+ * Marks a task as completed.
928
+ * @see LeadService.completeDealTask (apps/api/src/business/acquisition/lead-service.ts)
929
+ */
930
+ completeDealTask(params: CompleteDealTaskParams): Promise<AcqDealTask>
931
+
932
+ /**
933
+ * Record a deal activity entry by deal ID.
934
+ * Generic method for any activity type — used by SDK workflows.
935
+ * @see LeadService.recordDealActivity (apps/api/src/business/acquisition/lead-service.ts)
936
+ */
937
+ recordDealActivity(params: RecordDealActivityParams): Promise<void>
938
+
939
+ /**
940
+ * Update the state_key on an acq_deals row.
941
+ * @see LeadService.setDealStateKey (apps/api/src/business/acquisition/lead-service.ts)
942
+ */
943
+ setDealStateKey(params: SetDealStateKeyParams): Promise<{ ok: true }>
944
+
945
+ /**
946
+ * Transition a deal to a new stage, resolving pipeline_key automatically.
947
+ * @see LeadService.transitionDeal (apps/api/src/business/acquisition/lead-service.ts)
948
+ */
949
+ transitionDeal(params: TransitionDealParams): Promise<{ deal: AcqDeal }>
950
+
951
+ /**
952
+ * Load a deal with its joined contact and company data.
953
+ * @see LeadService.loadDeal (apps/api/src/business/acquisition/lead-service.ts)
954
+ */
955
+ loadDeal(params: LoadDealParams): Promise<DealDetail | null>
956
+
957
+ // Social monitoring operations (acq_social_posts table)
958
+ /**
959
+ * Bulk upsert social posts (deduplicate by platform + platform_post_id)
960
+ * @see LeadService.upsertSocialPosts (apps/api/src/business/acquisition/lead-service.ts)
961
+ */
962
+ upsertSocialPosts(params: UpsertSocialPostsParams): Promise<UpsertSocialPostsResult>
963
+ }