sitcod3 commited on
Commit
11d0e1e
·
verified ·
1 Parent(s): 7fcc15d

Upload server.ts with huggingface_hub

Browse files
Files changed (1) hide show
  1. server.ts +1060 -0
server.ts ADDED
@@ -0,0 +1,1060 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from "express";
2
+ import cors from "cors";
3
+ import morgan from "morgan";
4
+ import axios from "axios";
5
+ import path from "path";
6
+ import { getAiCompletionServer } from "./src/lib/aiServiceServer";
7
+ import { requireModulSLicense } from "./src/server/middleware/auth";
8
+
9
+ // ...
10
+
11
+ // Initial realistic state for fallback / offline / testing mode
12
+ let mockDb = {
13
+ campaigns: [
14
+ {
15
+ id: "camp_9901",
16
+ name: "Enterprise SaaS Outbound Q3",
17
+ status: "ACTIVE",
18
+ created_at: "2026-07-15T10:00:00.000Z",
19
+ lead_count: 1420,
20
+ sent_count: 3840,
21
+ open_count: 2150,
22
+ reply_count: 168,
23
+ bounce_count: 24,
24
+ click_count: 430,
25
+ timezone: "America/New_York",
26
+ start_schedule: "09:00",
27
+ end_schedule: "18:00",
28
+ track_settings: "TRACK_EMAIL_OPEN_AND_CLICK",
29
+ send_as_plain_text: false,
30
+ follow_up_percentage: 85,
31
+ unsubscribe_text: "Reply unsubscribe to stop receiving emails.",
32
+ stop_lead_settings: "REPLIED",
33
+ sequences: [
34
+ {
35
+ id: "seq_1",
36
+ seq_number: 1,
37
+ delay_days: 0,
38
+ subject: "Quick question regarding {{company_name}}'s outbound infrastructure",
39
+ email_body: "<p>Hi {{first_name}},</p><p>Noticed you are scaling your growth team at {{company_name}}. Are you currently looking to optimize your cold outreach deliverability and warmup automation?</p><p>Best,<br>Alex</p>",
40
+ variant_distribution_percentage: 50,
41
+ variants: [
42
+ {
43
+ id: "var_1a",
44
+ variant_label: "Variant A",
45
+ subject: "Quick question regarding {{company_name}}'s outbound infrastructure",
46
+ email_body: "<p>Hi {{first_name}},</p><p>Noticed you are scaling your growth team at {{company_name}}. Are you currently looking to optimize your cold outreach deliverability and warmup automation?</p><p>Best,<br>Alex</p>"
47
+ },
48
+ {
49
+ id: "var_1b",
50
+ variant_label: "Variant B (Shorter)",
51
+ subject: "{{first_name}} - {{company_name}} outbound efficiency",
52
+ email_body: "<p>Hey {{first_name}},</p><p>We helped similar SaaS leaders double their positive response rates without hitting spam filters. Open to a 3-min loom?</p><p>Alex</p>"
53
+ }
54
+ ]
55
+ },
56
+ {
57
+ id: "seq_2",
58
+ seq_number: 2,
59
+ delay_days: 3,
60
+ subject: "Re: Quick question regarding {{company_name}}",
61
+ email_body: "<p>Hi {{first_name}}, following up on my previous note. Did you have a chance to look at this?</p>",
62
+ variant_distribution_percentage: 100,
63
+ variants: []
64
+ }
65
+ ],
66
+ email_account_ids: ["acc_101", "acc_102"]
67
+ },
68
+ {
69
+ id: "camp_9902",
70
+ name: "Fintech Growth & Compliance Sequence",
71
+ status: "PAUSED",
72
+ created_at: "2026-07-20T14:30:00.000Z",
73
+ lead_count: 850,
74
+ sent_count: 1200,
75
+ open_count: 620,
76
+ reply_count: 42,
77
+ bounce_count: 11,
78
+ click_count: 98,
79
+ timezone: "Europe/London",
80
+ start_schedule: "08:30",
81
+ end_schedule: "17:30",
82
+ track_settings: "TRACK_EMAIL_OPEN",
83
+ send_as_plain_text: true,
84
+ follow_up_percentage: 90,
85
+ unsubscribe_text: "Click here to unsubscribe",
86
+ stop_lead_settings: "REPLIED",
87
+ sequences: [
88
+ {
89
+ id: "seq_21",
90
+ seq_number: 1,
91
+ delay_days: 0,
92
+ subject: "Compliance streamline for {{company_name}}",
93
+ email_body: "<p>Hi {{first_name}}, wanted to share our automated compliance blueprint tailored for {{company_name}}.</p>",
94
+ variant_distribution_percentage: 100,
95
+ variants: []
96
+ }
97
+ ],
98
+ email_account_ids: ["acc_103"]
99
+ },
100
+ {
101
+ id: "camp_9903",
102
+ name: "AI Tech Founders Pilot",
103
+ status: "ACTIVE",
104
+ created_at: "2026-08-01T09:15:00.000Z",
105
+ lead_count: 2400,
106
+ sent_count: 6100,
107
+ open_count: 3890,
108
+ reply_count: 310,
109
+ bounce_count: 45,
110
+ click_count: 820,
111
+ timezone: "America/Los_Angeles",
112
+ start_schedule: "09:00",
113
+ end_schedule: "17:00",
114
+ track_settings: "TRACK_EMAIL_OPEN_AND_CLICK",
115
+ send_as_plain_text: false,
116
+ follow_up_percentage: 100,
117
+ unsubscribe_text: "Unsubscribe",
118
+ stop_lead_settings: "REPLIED",
119
+ sequences: [
120
+ {
121
+ id: "seq_31",
122
+ seq_number: 1,
123
+ delay_days: 0,
124
+ subject: "{{first_name}}, accelerating inference pipelines",
125
+ email_body: "<p>Hi {{first_name}}, saw your launch on Product Hunt! Curious how {{company_name}} is handling model inference latency?</p>",
126
+ variant_distribution_percentage: 100,
127
+ variants: []
128
+ }
129
+ ],
130
+ email_account_ids: ["acc_101", "acc_102", "acc_104"]
131
+ }
132
+ ],
133
+ leads: [
134
+ {
135
+ id: "lead_1001",
136
+ campaign_id: "camp_9901",
137
+ first_name: "Sarah",
138
+ last_name: "Jenkins",
139
+ email: "sarah.jenkins@acmepartner.io",
140
+ phone_number: "+1 415-555-0182",
141
+ company_name: "Acme Partner Labs",
142
+ website: "https://acmepartner.io",
143
+ location: "San Francisco, CA",
144
+ linkedin_profile: "https://linkedin.com/in/sarahjenkins-sample",
145
+ status: "INTERESTED",
146
+ open_count: 4,
147
+ click_count: 2,
148
+ created_at: "2026-07-16T11:20:00.000Z",
149
+ custom_fields: { tech_stack: "Node/React", team_size: "45", funding_round: "Series B" }
150
+ },
151
+ {
152
+ id: "lead_1002",
153
+ campaign_id: "camp_9901",
154
+ first_name: "Marcus",
155
+ last_name: "Vance",
156
+ email: "m.vance@vanguardflow.co",
157
+ phone_number: "+1 212-555-0199",
158
+ company_name: "Vanguard Flow Systems",
159
+ website: "https://vanguardflow.co",
160
+ location: "New York, NY",
161
+ linkedin_profile: "https://linkedin.com/in/marcusvance-sample",
162
+ status: "MEETING_BOOKED",
163
+ open_count: 6,
164
+ click_count: 3,
165
+ created_at: "2026-07-16T12:45:00.000Z",
166
+ custom_fields: { tech_stack: "AWS/Python", team_size: "120", funding_round: "Series C" }
167
+ },
168
+ {
169
+ id: "lead_1003",
170
+ campaign_id: "camp_9901",
171
+ first_name: "Elena",
172
+ last_name: "Rostova",
173
+ email: "elena@cybercorebiotech.com",
174
+ phone_number: "+44 20 7946 0912",
175
+ company_name: "CyberCore Biotech",
176
+ website: "https://cybercorebiotech.com",
177
+ location: "London, UK",
178
+ linkedin_profile: "https://linkedin.com/in/elenarostova",
179
+ status: "REPLIED",
180
+ open_count: 3,
181
+ click_count: 1,
182
+ created_at: "2026-07-17T09:10:00.000Z",
183
+ custom_fields: { tech_stack: "NextJS", team_size: "80", funding_round: "Series A" }
184
+ },
185
+ {
186
+ id: "lead_1004",
187
+ campaign_id: "camp_9902",
188
+ first_name: "David",
189
+ last_name: "Chen",
190
+ email: "david.chen@horizonpay.net",
191
+ phone_number: "+1 650-555-0144",
192
+ company_name: "Horizon Pay",
193
+ website: "https://horizonpay.net",
194
+ location: "Palo Alto, CA",
195
+ linkedin_profile: "https://linkedin.com/in/davidchen-sample",
196
+ status: "NOT_INTERESTED",
197
+ open_count: 1,
198
+ click_count: 0,
199
+ created_at: "2026-07-21T15:00:00.000Z",
200
+ custom_fields: { tech_stack: "Go/Postgres", team_size: "200", funding_round: "Series D" }
201
+ },
202
+ {
203
+ id: "lead_1005",
204
+ campaign_id: "camp_9903",
205
+ first_name: "Amina",
206
+ last_name: "Diallo",
207
+ email: "amina@synapseai.tech",
208
+ phone_number: "+1 312-555-0177",
209
+ company_name: "Synapse AI Global",
210
+ website: "https://synapseai.tech",
211
+ location: "Chicago, IL",
212
+ linkedin_profile: "https://linkedin.com/in/aminadiallo",
213
+ status: "INTERESTED",
214
+ open_count: 5,
215
+ click_count: 4,
216
+ created_at: "2026-08-02T10:14:00.000Z",
217
+ custom_fields: { tech_stack: "PyTorch/Ray", team_size: "30", funding_round: "Seed" }
218
+ }
219
+ ],
220
+ email_accounts: [
221
+ {
222
+ id: "acc_101",
223
+ from_name: "Alex Rivera",
224
+ from_email: "alex@outbound-alchemist.io",
225
+ provider: "GOOGLE",
226
+ status: "CONNECTED",
227
+ daily_limit: 50,
228
+ sent_today: 34,
229
+ warmup_enabled: true,
230
+ warmup_reputation: "EXCELLENT",
231
+ warmup_score: 98,
232
+ warmup_daily_count: 25,
233
+ ramp_day: 14,
234
+ ramp_up_increment: 2,
235
+ reply_rate_percentage: 45,
236
+ campaigns_assigned: ["Enterprise SaaS Outbound Q3", "AI Tech Founders Pilot"],
237
+ created_at: "2026-05-10T08:00:00.000Z"
238
+ },
239
+ {
240
+ id: "acc_102",
241
+ from_name: "Alex Rivera (Secondary)",
242
+ from_email: "alex.rivera@growthmatrix.cc",
243
+ provider: "MICROSOFT",
244
+ status: "CONNECTED",
245
+ daily_limit: 45,
246
+ sent_today: 28,
247
+ warmup_enabled: true,
248
+ warmup_reputation: "GOOD",
249
+ warmup_score: 89,
250
+ warmup_daily_count: 20,
251
+ ramp_day: 9,
252
+ ramp_up_increment: 3,
253
+ reply_rate_percentage: 40,
254
+ campaigns_assigned: ["Enterprise SaaS Outbound Q3", "AI Tech Founders Pilot"],
255
+ created_at: "2026-06-01T08:00:00.000Z"
256
+ },
257
+ {
258
+ id: "acc_103",
259
+ from_name: "Elena Rostova",
260
+ from_email: "elena@fintechoutreach.com",
261
+ provider: "SMTP",
262
+ smtp_host: "mail.fintechoutreach.com",
263
+ smtp_port: 587,
264
+ status: "CONNECTED",
265
+ daily_limit: 60,
266
+ sent_today: 18,
267
+ warmup_enabled: true,
268
+ warmup_reputation: "EXCELLENT",
269
+ warmup_score: 96,
270
+ warmup_daily_count: 30,
271
+ ramp_day: 22,
272
+ ramp_up_increment: 2,
273
+ reply_rate_percentage: 50,
274
+ campaigns_assigned: ["Fintech Growth & Compliance Sequence"],
275
+ created_at: "2026-06-15T08:00:00.000Z"
276
+ },
277
+ {
278
+ id: "acc_104",
279
+ from_name: "Growth Ops Lead",
280
+ from_email: "ops@aifoundryoutreach.io",
281
+ provider: "GOOGLE",
282
+ status: "RECONNECTING",
283
+ daily_limit: 40,
284
+ sent_today: 0,
285
+ warmup_enabled: false,
286
+ warmup_reputation: "POOR",
287
+ warmup_score: 62,
288
+ warmup_daily_count: 0,
289
+ ramp_day: 1,
290
+ ramp_up_increment: 1,
291
+ reply_rate_percentage: 30,
292
+ campaigns_assigned: ["AI Tech Founders Pilot"],
293
+ created_at: "2026-07-28T08:00:00.000Z"
294
+ }
295
+ ],
296
+ inbox: [
297
+ {
298
+ id: "msg_501",
299
+ campaign_id: "camp_9901",
300
+ lead_id: "lead_1001",
301
+ lead_name: "Sarah Jenkins",
302
+ lead_email: "sarah.jenkins@acmepartner.io",
303
+ company_name: "Acme Partner Labs",
304
+ subject: "Re: Quick question regarding Acme Partner Labs's outbound infrastructure",
305
+ category: "INTERESTED",
306
+ unread: true,
307
+ received_at: "2026-08-14T19:30:00.000Z",
308
+ messages: [
309
+ {
310
+ id: "m_sub_1",
311
+ from: "alex@outbound-alchemist.io",
312
+ to: "sarah.jenkins@acmepartner.io",
313
+ direction: "OUTBOUND",
314
+ timestamp: "2026-08-14T14:00:00.000Z",
315
+ body_html: "<p>Hi Sarah, Noticed you are scaling your growth team at Acme Partner Labs. Are you currently looking to optimize your cold outreach deliverability and warmup automation?</p>"
316
+ },
317
+ {
318
+ id: "m_sub_2",
319
+ from: "sarah.jenkins@acmepartner.io",
320
+ to: "alex@outbound-alchemist.io",
321
+ direction: "INBOUND",
322
+ timestamp: "2026-08-14T19:30:00.000Z",
323
+ body_html: "<p>Hi Alex,</p><p>Yes, perfect timing. We are actually evaluating mailbox warmup tools right now since our SDR team just doubled. Can you send over a brief demo or pricing overview?</p><p>Thanks,<br>Sarah Jenkins | Head of Growth</p>"
324
+ }
325
+ ]
326
+ },
327
+ {
328
+ id: "msg_502",
329
+ campaign_id: "camp_9901",
330
+ lead_id: "lead_1002",
331
+ lead_name: "Marcus Vance",
332
+ lead_email: "m.vance@vanguardflow.co",
333
+ company_name: "Vanguard Flow Systems",
334
+ subject: "Re: Quick question regarding Vanguard Flow Systems",
335
+ category: "MEETING_BOOKED",
336
+ unread: false,
337
+ received_at: "2026-08-14T16:15:00.000Z",
338
+ messages: [
339
+ {
340
+ id: "m_sub_3",
341
+ from: "alex@outbound-alchemist.io",
342
+ to: "m.vance@vanguardflow.co",
343
+ direction: "OUTBOUND",
344
+ timestamp: "2026-08-13T10:00:00.000Z",
345
+ body_html: "<p>Hey Marcus, We helped similar SaaS leaders double their positive response rates without hitting spam filters. Open to a 3-min loom?</p>"
346
+ },
347
+ {
348
+ id: "m_sub_4",
349
+ from: "m.vance@vanguardflow.co",
350
+ to: "alex@outbound-alchemist.io",
351
+ direction: "INBOUND",
352
+ timestamp: "2026-08-14T16:15:00.000Z",
353
+ body_html: "<p>Alex, grabbed a slot on your calendar for Tuesday at 2 PM EST. Talk soon!</p>"
354
+ }
355
+ ]
356
+ },
357
+ {
358
+ id: "msg_503",
359
+ campaign_id: "camp_9903",
360
+ lead_id: "lead_1005",
361
+ lead_name: "Amina Diallo",
362
+ lead_email: "amina@synapseai.tech",
363
+ company_name: "Synapse AI Global",
364
+ subject: "Re: Amina, accelerating inference pipelines",
365
+ category: "INTERESTED",
366
+ unread: true,
367
+ received_at: "2026-08-14T21:05:00.000Z",
368
+ messages: [
369
+ {
370
+ id: "m_sub_5",
371
+ from: "ops@aifoundryoutreach.io",
372
+ to: "amina@synapseai.tech",
373
+ direction: "OUTBOUND",
374
+ timestamp: "2026-08-14T15:00:00.000Z",
375
+ body_html: "<p>Hi Amina, saw your launch on Product Hunt! Curious how Synapse AI Global is handling model inference latency?</p>"
376
+ },
377
+ {
378
+ id: "m_sub_6",
379
+ from: "amina@synapseai.tech",
380
+ to: "ops@aifoundryoutreach.io",
381
+ direction: "INBOUND",
382
+ timestamp: "2026-08-14T21:05:00.000Z",
383
+ body_html: "<p>Thanks! We've built an in-house caching proxy, but always curious to learn about specialized acceleration clusters. Let's connect next week.</p>"
384
+ }
385
+ ]
386
+ }
387
+ ],
388
+ webhooks: [
389
+ {
390
+ id: "wh_801",
391
+ name: "Slack Lead Alerts & Zapier Sync",
392
+ webhook_url: "https://hooks.zapier.com/hooks/catch/912837/b8120a",
393
+ event_types: ["REPLY", "LEAD_CATEGORY_UPDATED", "CAMPAIGN_COMPLETED"],
394
+ campaign_id: null,
395
+ status: "ACTIVE",
396
+ last_triggered: "2026-08-14T21:05:12.000Z",
397
+ created_at: "2026-06-20T10:00:00.000Z"
398
+ },
399
+ {
400
+ id: "wh_802",
401
+ name: "HubSpot CRM Bi-directional Sync",
402
+ webhook_url: "https://api.hubapi.com/webhooks/v3/custom-lead-sync",
403
+ event_types: ["REPLY", "BOUNCE", "UNSUBSCRIBE", "LEAD_CATEGORY_UPDATED"],
404
+ campaign_id: "camp_9901",
405
+ status: "ACTIVE",
406
+ last_triggered: "2026-08-14T19:30:22.000Z",
407
+ created_at: "2026-07-01T12:00:00.000Z"
408
+ }
409
+ ],
410
+ webhook_logs: [
411
+ {
412
+ id: "whlog_1",
413
+ webhook_id: "wh_801",
414
+ event_type: "REPLY",
415
+ status_code: 200,
416
+ timestamp: "2026-08-14T21:05:12.000Z",
417
+ payload_preview: { lead_email: "amina@synapseai.tech", category: "INTERESTED", sentiment: "positive" }
418
+ },
419
+ {
420
+ id: "whlog_2",
421
+ webhook_id: "wh_802",
422
+ event_type: "LEAD_CATEGORY_UPDATED",
423
+ status_code: 200,
424
+ timestamp: "2026-08-14T19:30:22.000Z",
425
+ payload_preview: { lead_email: "sarah.jenkins@acmepartner.io", status: "INTERESTED" }
426
+ }
427
+ ],
428
+ clients: [
429
+ {
430
+ id: "cli_101",
431
+ name: "Nexus AI Ventures",
432
+ email: "growth@nexusventures.ai",
433
+ company: "Nexus AI Ventures Inc.",
434
+ campaigns_count: 2,
435
+ leads_count: 3820,
436
+ created_at: "2026-05-15T09:00:00.000Z"
437
+ },
438
+ {
439
+ id: "cli_102",
440
+ name: "Apex Velocity B2B",
441
+ email: "contact@apexvelocity.io",
442
+ company: "Apex Velocity Marketing",
443
+ campaigns_count: 1,
444
+ leads_count: 1200,
445
+ created_at: "2026-06-10T11:30:00.000Z"
446
+ }
447
+ ],
448
+ block_list: {
449
+ emails: [
450
+ { id: "bl_1", email: "competitor-bot@spamtrap.org", reason: "Spam trap detected", added_at: "2026-07-01T10:00:00.000Z" },
451
+ { id: "bl_2", email: "ceo@opt-out-forever.com", reason: "Direct legal opt-out", added_at: "2026-07-12T14:20:00.000Z" }
452
+ ],
453
+ domains: [
454
+ { id: "bld_1", domain: "mailinator.com", reason: "Disposable email service", added_at: "2026-06-10T09:00:00.000Z" },
455
+ { id: "bld_2", domain: "guerrillamail.com", reason: "Temporary inbox", added_at: "2026-06-11T11:00:00.000Z" },
456
+ { id: "bld_3", domain: "10minutemail.com", reason: "Temporary inbox", added_at: "2026-06-15T15:00:00.000Z" }
457
+ ]
458
+ }
459
+ };
460
+
461
+ async function startServer() {
462
+ const app = express();
463
+ const PORT = Number(process.env.PORT) || 3000;
464
+
465
+ app.use(cors({
466
+ origin: process.env.CORS_ORIGIN ? process.env.CORS_ORIGIN.split(',') : false,
467
+ credentials: true
468
+ }));
469
+ app.use(morgan("dev"));
470
+ app.use(express.json());
471
+
472
+ // Central Supabase JWT + license gate for every paid route.
473
+ // /api/health stays open (Docker HEALTHCHECK + HF + productApi probe).
474
+ // No-op while LICENSE_ENFORCEMENT != "true" (demo mode).
475
+ app.use("/api", (req, res, next) => {
476
+ if (req.path === "/health") return next();
477
+ return requireModulSLicense(req, res, next);
478
+ });
479
+
480
+ app.get("/api/health", (req, res) => {
481
+ res.json({ status: "ok", timestamp: new Date().toISOString(), uptime: process.uptime() });
482
+ });
483
+
484
+ // Helper to check if real Smartlead API call should be attempted
485
+ const shouldProxyToSmartlead = (apiKey: string | undefined) => {
486
+ return Boolean(apiKey && apiKey.length > 10 && !apiKey.startsWith("demo_") && !apiKey.startsWith("mock_"));
487
+ };
488
+
489
+ // ==========================================
490
+ // MODULE 1: CAMPAIGNS API
491
+ // ==========================================
492
+ app.get("/api/campaigns", async (req, res) => {
493
+ const apiKey = req.headers["x-api-key"] as string;
494
+ if (shouldProxyToSmartlead(apiKey)) {
495
+ try {
496
+ const response = await axios.get("https://server.smartlead.ai/api/v1/campaigns", {
497
+ params: { ...req.query, api_key: apiKey },
498
+ timeout: 8000
499
+ });
500
+ return res.json(response.data);
501
+ } catch (err: any) {
502
+ console.warn("Smartlead API live proxy failed, falling back to database mode:", err.message);
503
+ }
504
+ }
505
+ return res.json(mockDb.campaigns);
506
+ });
507
+
508
+ app.post("/api/campaigns", async (req, res) => {
509
+ const apiKey = req.headers["x-api-key"] as string;
510
+ if (shouldProxyToSmartlead(apiKey)) {
511
+ try {
512
+ const response = await axios.post("https://server.smartlead.ai/api/v1/campaigns", req.body, {
513
+ params: { api_key: apiKey },
514
+ timeout: 8000
515
+ });
516
+ return res.status(201).json(response.data);
517
+ } catch (err: any) {
518
+ console.warn("Live create campaign failed, recording in local database:", err.message);
519
+ }
520
+ }
521
+
522
+ const newCampaign = {
523
+ id: "camp_" + Math.random().toString(36).substring(2, 9),
524
+ name: req.body.name || "Untitled Campaign",
525
+ status: "PAUSED",
526
+ created_at: new Date().toISOString(),
527
+ lead_count: 0,
528
+ sent_count: 0,
529
+ open_count: 0,
530
+ reply_count: 0,
531
+ bounce_count: 0,
532
+ click_count: 0,
533
+ timezone: req.body.timezone || "America/New_York",
534
+ start_schedule: req.body.start_schedule || "09:00",
535
+ end_schedule: req.body.end_schedule || "17:00",
536
+ track_settings: req.body.track_settings || "TRACK_EMAIL_OPEN",
537
+ send_as_plain_text: Boolean(req.body.send_as_plain_text),
538
+ follow_up_percentage: req.body.follow_up_percentage || 80,
539
+ unsubscribe_text: req.body.unsubscribe_text || "Unsubscribe",
540
+ stop_lead_settings: req.body.stop_lead_settings || "REPLIED",
541
+ sequences: [
542
+ {
543
+ id: "seq_" + Math.random().toString(36).substring(2, 7),
544
+ seq_number: 1,
545
+ delay_days: 0,
546
+ subject: req.body.initial_subject || "Connecting with {{first_name}}",
547
+ email_body: req.body.initial_body || "<p>Hi {{first_name}}, let's connect!</p>",
548
+ variant_distribution_percentage: 100,
549
+ variants: []
550
+ }
551
+ ],
552
+ email_account_ids: req.body.email_account_ids || []
553
+ };
554
+ mockDb.campaigns.unshift(newCampaign);
555
+ return res.status(201).json(newCampaign);
556
+ });
557
+
558
+ app.get("/api/campaigns/:id", (req, res) => {
559
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
560
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
561
+ return res.json(campaign);
562
+ });
563
+
564
+ app.post("/api/campaigns/:id", (req, res) => {
565
+ const index = mockDb.campaigns.findIndex(c => c.id === req.params.id);
566
+ if (index === -1) return res.status(404).json({ error: "Campaign not found" });
567
+ mockDb.campaigns[index] = { ...mockDb.campaigns[index], ...req.body };
568
+ return res.json(mockDb.campaigns[index]);
569
+ });
570
+
571
+ app.delete("/api/campaigns/:id", (req, res) => {
572
+ mockDb.campaigns = mockDb.campaigns.filter(c => c.id !== req.params.id);
573
+ return res.json({ success: true, message: "Campaign deleted successfully" });
574
+ });
575
+
576
+ app.post("/api/campaigns/:id/status", (req, res) => {
577
+ const { status } = req.body; // START / PAUSE / STOP
578
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
579
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
580
+ campaign.status = status === "START" ? "ACTIVE" : status === "PAUSE" ? "PAUSED" : "STOPPED";
581
+ return res.json({ success: true, status: campaign.status, campaign });
582
+ });
583
+
584
+ app.post("/api/campaigns/:id/schedule", (req, res) => {
585
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
586
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
587
+ campaign.start_schedule = req.body.start_schedule || campaign.start_schedule;
588
+ campaign.end_schedule = req.body.end_schedule || campaign.end_schedule;
589
+ campaign.timezone = req.body.timezone || campaign.timezone;
590
+ return res.json({ success: true, campaign });
591
+ });
592
+
593
+ app.get("/api/campaigns/:id/sequences", (req, res) => {
594
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
595
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
596
+ return res.json(campaign.sequences || []);
597
+ });
598
+
599
+ app.post("/api/campaigns/:id/sequences", (req, res) => {
600
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
601
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
602
+ campaign.sequences = req.body.sequences || [];
603
+ return res.json({ success: true, sequences: campaign.sequences });
604
+ });
605
+
606
+ app.get("/api/campaigns/:id/email-accounts", (req, res) => {
607
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
608
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
609
+ const accounts = mockDb.email_accounts.filter(a => campaign.email_account_ids?.includes(a.id));
610
+ return res.json(accounts);
611
+ });
612
+
613
+ app.post("/api/campaigns/:id/email-accounts", (req, res) => {
614
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
615
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
616
+ const { email_account_id } = req.body;
617
+ if (!campaign.email_account_ids) campaign.email_account_ids = [];
618
+ if (!campaign.email_account_ids.includes(email_account_id)) {
619
+ campaign.email_account_ids.push(email_account_id);
620
+ }
621
+ return res.json({ success: true, email_account_ids: campaign.email_account_ids });
622
+ });
623
+
624
+ app.delete("/api/campaigns/:id/email-accounts/:eid", (req, res) => {
625
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
626
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
627
+ campaign.email_account_ids = (campaign.email_account_ids || []).filter(id => id !== req.params.eid);
628
+ return res.json({ success: true, email_account_ids: campaign.email_account_ids });
629
+ });
630
+
631
+ app.get("/api/campaigns/:id/analytics", (req, res) => {
632
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
633
+ if (!campaign) return res.status(404).json({ error: "Campaign not found" });
634
+ return res.json({
635
+ sent: campaign.sent_count,
636
+ opens: campaign.open_count,
637
+ replies: campaign.reply_count,
638
+ bounces: campaign.bounce_count,
639
+ clicks: campaign.click_count,
640
+ open_rate: ((campaign.open_count / (campaign.sent_count || 1)) * 100).toFixed(1),
641
+ reply_rate: ((campaign.reply_count / (campaign.sent_count || 1)) * 100).toFixed(1),
642
+ bounce_rate: ((campaign.bounce_count / (campaign.sent_count || 1)) * 100).toFixed(1)
643
+ });
644
+ });
645
+
646
+ app.get("/api/campaigns/:id/analytics-by-date", (req, res) => {
647
+ const days = 14;
648
+ const history = [];
649
+ const now = new Date();
650
+ for (let i = days; i >= 0; i--) {
651
+ const d = new Date(now.getTime() - i * 24 * 60 * 60 * 1000);
652
+ const dayLabel = d.toLocaleDateString("en-US", { month: "short", day: "numeric" });
653
+ history.push({
654
+ date: dayLabel,
655
+ sent: Math.floor(120 + Math.random() * 80),
656
+ opens: Math.floor(65 + Math.random() * 40),
657
+ clicks: Math.floor(18 + Math.random() * 15),
658
+ replies: Math.floor(8 + Math.random() * 10),
659
+ bounces: Math.floor(1 + Math.random() * 3)
660
+ });
661
+ }
662
+ return res.json(history);
663
+ });
664
+
665
+ app.get("/api/campaigns/:id/leads-export", (req, res) => {
666
+ const campaignLeads = mockDb.leads.filter(l => l.campaign_id === req.params.id);
667
+ let csv = "first_name,last_name,email,company_name,status,open_count,reply_count\n";
668
+ campaignLeads.forEach(l => {
669
+ csv += `"${l.first_name}","${l.last_name}","${l.email}","${l.company_name}","${l.status}",${l.open_count},${l.click_count}\n`;
670
+ });
671
+ res.setHeader("Content-Type", "text/csv");
672
+ res.setHeader("Content-Disposition", `attachment; filename=leads-${req.params.id}.csv`);
673
+ return res.send(csv);
674
+ });
675
+
676
+ // ==========================================
677
+ // MODULE 2: LEADS API
678
+ // ==========================================
679
+ app.get("/api/campaigns/:id/leads", (req, res) => {
680
+ const leads = mockDb.leads.filter(l => l.campaign_id === req.params.id);
681
+ return res.json(leads);
682
+ });
683
+
684
+ app.post("/api/campaigns/:id/leads", (req, res) => {
685
+ const leadsToAdd = Array.isArray(req.body) ? req.body : req.body.leads || [req.body];
686
+ const created = leadsToAdd.map((item: any) => {
687
+ const newLead = {
688
+ id: "lead_" + Math.random().toString(36).substring(2, 9),
689
+ campaign_id: req.params.id,
690
+ first_name: item.first_name || "",
691
+ last_name: item.last_name || "",
692
+ email: item.email || "lead@sample.io",
693
+ phone_number: item.phone_number || "",
694
+ company_name: item.company_name || "",
695
+ website: item.website || "",
696
+ location: item.location || "",
697
+ linkedin_profile: item.linkedin_profile || "",
698
+ status: item.status || "INTERESTED",
699
+ open_count: 0,
700
+ click_count: 0,
701
+ created_at: new Date().toISOString(),
702
+ custom_fields: item.custom_fields || {}
703
+ };
704
+ mockDb.leads.unshift(newLead);
705
+ return newLead;
706
+ });
707
+
708
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
709
+ if (campaign) campaign.lead_count += created.length;
710
+
711
+ return res.status(201).json({ success: true, count: created.length, leads: created });
712
+ });
713
+
714
+ app.get("/api/leads/search", (req, res) => {
715
+ const query = (req.query.q as string || "").toLowerCase();
716
+ const status = req.query.status as string;
717
+ let results = mockDb.leads;
718
+ if (query) {
719
+ results = results.filter(l =>
720
+ l.first_name.toLowerCase().includes(query) ||
721
+ l.last_name.toLowerCase().includes(query) ||
722
+ l.email.toLowerCase().includes(query) ||
723
+ l.company_name.toLowerCase().includes(query)
724
+ );
725
+ }
726
+ if (status && status !== "ALL") {
727
+ results = results.filter(l => l.status === status);
728
+ }
729
+ return res.json(results);
730
+ });
731
+
732
+ app.post("/api/campaigns/:id/leads/status", (req, res) => {
733
+ const { lead_id, status } = req.body;
734
+ const lead = mockDb.leads.find(l => l.id === lead_id);
735
+ if (!lead) return res.status(404).json({ error: "Lead not found" });
736
+ lead.status = status;
737
+ return res.json({ success: true, lead });
738
+ });
739
+
740
+ app.delete("/api/campaigns/:id/leads/:lead_id", (req, res) => {
741
+ mockDb.leads = mockDb.leads.filter(l => l.id !== req.params.lead_id);
742
+ const campaign = mockDb.campaigns.find(c => c.id === req.params.id);
743
+ if (campaign && campaign.lead_count > 0) campaign.lead_count--;
744
+ return res.json({ success: true });
745
+ });
746
+
747
+ // Blocklist routes
748
+ app.get("/api/leads/block-list", (req, res) => res.json(mockDb.block_list.emails));
749
+ app.post("/api/leads/block-list", (req, res) => {
750
+ const item = { id: "bl_" + Date.now(), email: req.body.email, reason: req.body.reason || "Manual add", added_at: new Date().toISOString() };
751
+ mockDb.block_list.emails.unshift(item);
752
+ res.status(201).json(item);
753
+ });
754
+ app.delete("/api/leads/block-list/:id", (req, res) => {
755
+ mockDb.block_list.emails = mockDb.block_list.emails.filter(e => e.id !== req.params.id && e.email !== req.params.id);
756
+ res.json({ success: true });
757
+ });
758
+
759
+ app.get("/api/leads/domain-block-list", (req, res) => res.json(mockDb.block_list.domains));
760
+ app.post("/api/leads/domain-block-list", (req, res) => {
761
+ const item = { id: "bld_" + Date.now(), domain: req.body.domain, reason: req.body.reason || "Manual add", added_at: new Date().toISOString() };
762
+ mockDb.block_list.domains.unshift(item);
763
+ res.status(201).json(item);
764
+ });
765
+ app.delete("/api/leads/domain-block-list/:id", (req, res) => {
766
+ mockDb.block_list.domains = mockDb.block_list.domains.filter(d => d.id !== req.params.id && d.domain !== req.params.id);
767
+ res.json({ success: true });
768
+ });
769
+
770
+ // ==========================================
771
+ // MODULE 3: EMAIL ACCOUNTS API
772
+ // ==========================================
773
+ app.get("/api/email-accounts", (req, res) => res.json(mockDb.email_accounts));
774
+
775
+ app.post("/api/email-accounts", (req, res) => {
776
+ const newAcc = {
777
+ id: "acc_" + Math.random().toString(36).substring(2, 8),
778
+ from_name: req.body.from_name || "Outbound Rep",
779
+ from_email: req.body.from_email || "rep@sampledomain.com",
780
+ provider: req.body.provider || "SMTP",
781
+ smtp_host: req.body.smtp_host,
782
+ smtp_port: req.body.smtp_port,
783
+ status: "CONNECTED",
784
+ daily_limit: req.body.max_email_per_day || 50,
785
+ sent_today: 0,
786
+ warmup_enabled: true,
787
+ warmup_reputation: "GOOD",
788
+ warmup_score: 85,
789
+ warmup_daily_count: 10,
790
+ ramp_day: 1,
791
+ ramp_up_increment: 2,
792
+ reply_rate_percentage: 40,
793
+ campaigns_assigned: [],
794
+ created_at: new Date().toISOString()
795
+ };
796
+ mockDb.email_accounts.push(newAcc);
797
+ res.status(201).json(newAcc);
798
+ });
799
+
800
+ app.post("/api/email-accounts/reconnect", (req, res) => {
801
+ const { account_id } = req.body;
802
+ const acc = mockDb.email_accounts.find(a => a.id === account_id);
803
+ if (acc) acc.status = "CONNECTED";
804
+ res.json({ success: true, message: "Account reconnected successfully", account: acc });
805
+ });
806
+
807
+ app.delete("/api/email-accounts/:id", (req, res) => {
808
+ mockDb.email_accounts = mockDb.email_accounts.filter(a => a.id !== req.params.id);
809
+ res.json({ success: true });
810
+ });
811
+
812
+ // ==========================================
813
+ // MODULE 4: EMAIL WARMUP API
814
+ // ==========================================
815
+ app.post("/api/email-accounts/:id/warmup/enable", (req, res) => {
816
+ const acc = mockDb.email_accounts.find(a => a.id === req.params.id);
817
+ if (!acc) return res.status(404).json({ error: "Account not found" });
818
+ acc.warmup_enabled = true;
819
+ res.json({ success: true, account: acc });
820
+ });
821
+
822
+ app.post("/api/email-accounts/:id/warmup/disable", (req, res) => {
823
+ const acc = mockDb.email_accounts.find(a => a.id === req.params.id);
824
+ if (!acc) return res.status(404).json({ error: "Account not found" });
825
+ acc.warmup_enabled = false;
826
+ res.json({ success: true, account: acc });
827
+ });
828
+
829
+ app.get("/api/email-accounts/:id/warmup/stats", (req, res) => {
830
+ const acc = mockDb.email_accounts.find(a => a.id === req.params.id);
831
+ if (!acc) return res.status(404).json({ error: "Account not found" });
832
+ res.json({
833
+ score: acc.warmup_score,
834
+ reputation: acc.warmup_reputation,
835
+ sent_warmup: acc.warmup_daily_count,
836
+ received_warmup: Math.floor(acc.warmup_daily_count * 0.45),
837
+ spam_rescued: 2,
838
+ ramp_day: acc.ramp_day,
839
+ history: [
840
+ { day: "Day 1", score: 70 },
841
+ { day: "Day 3", score: 78 },
842
+ { day: "Day 7", score: 85 },
843
+ { day: "Day 10", score: 92 },
844
+ { day: "Day 14", score: acc.warmup_score }
845
+ ]
846
+ });
847
+ });
848
+
849
+ app.post("/api/email-accounts/:id/warmup/settings", (req, res) => {
850
+ const acc = mockDb.email_accounts.find(a => a.id === req.params.id);
851
+ if (!acc) return res.status(404).json({ error: "Account not found" });
852
+ acc.ramp_up_increment = req.body.ramp_up_increment || acc.ramp_up_increment;
853
+ acc.reply_rate_percentage = req.body.reply_rate_percentage || acc.reply_rate_percentage;
854
+ res.json({ success: true, account: acc });
855
+ });
856
+
857
+ // ==========================================
858
+ // MODULE 5: UNIFIED INBOX API
859
+ // ==========================================
860
+ app.get("/api/inbox", (req, res) => {
861
+ const { category, campaign_id } = req.query;
862
+ let threads = mockDb.inbox;
863
+ if (category && category !== "ALL") {
864
+ threads = threads.filter(t => t.category === category);
865
+ }
866
+ if (campaign_id) {
867
+ threads = threads.filter(t => t.campaign_id === campaign_id);
868
+ }
869
+ res.json(threads);
870
+ });
871
+
872
+ app.get("/api/inbox/unread-count", (req, res) => {
873
+ const unread = mockDb.inbox.filter(t => t.unread).length;
874
+ res.json({ count: unread });
875
+ });
876
+
877
+ app.post("/api/campaigns/:id/reply-email-thread", (req, res) => {
878
+ const { thread_id, reply_body } = req.body;
879
+ const thread = mockDb.inbox.find(t => t.id === thread_id || t.campaign_id === req.params.id);
880
+ if (thread) {
881
+ thread.unread = false;
882
+ thread.messages.push({
883
+ id: "m_rep_" + Date.now(),
884
+ from: "alex@outbound-alchemist.io",
885
+ to: thread.lead_email,
886
+ direction: "OUTBOUND",
887
+ timestamp: new Date().toISOString(),
888
+ body_html: `<p>${reply_body}</p>`
889
+ });
890
+ return res.json({ success: true, message: "Reply sent successfully", thread });
891
+ }
892
+ res.json({ success: true, message: "Reply delivered" });
893
+ });
894
+
895
+ app.post("/api/inbox/categorize", (req, res) => {
896
+ const { thread_id, category } = req.body;
897
+ const thread = mockDb.inbox.find(t => t.id === thread_id);
898
+ if (thread) {
899
+ thread.category = category;
900
+ const lead = mockDb.leads.find(l => l.email === thread.lead_email);
901
+ if (lead) lead.status = category;
902
+ }
903
+ res.json({ success: true, category });
904
+ });
905
+
906
+ // ==========================================
907
+ // MODULE 6: WEBHOOKS API
908
+ // ==========================================
909
+ app.get("/api/webhooks", (req, res) => res.json(mockDb.webhooks));
910
+
911
+ app.post("/api/webhooks", (req, res) => {
912
+ const newWh = {
913
+ id: "wh_" + Math.random().toString(36).substring(2, 8),
914
+ name: req.body.name || "Custom Webhook Endpoint",
915
+ webhook_url: req.body.webhook_url || "https://api.domain.com/webhook",
916
+ event_types: req.body.event_types || ["REPLY"],
917
+ campaign_id: req.body.campaign_id || null,
918
+ status: "ACTIVE",
919
+ last_triggered: null,
920
+ created_at: new Date().toISOString()
921
+ };
922
+ mockDb.webhooks.unshift(newWh);
923
+ res.status(201).json(newWh);
924
+ });
925
+
926
+ app.delete("/api/webhooks/:id", (req, res) => {
927
+ mockDb.webhooks = mockDb.webhooks.filter(w => w.id !== req.params.id);
928
+ res.json({ success: true });
929
+ });
930
+
931
+ app.post("/api/webhooks/:id/test", (req, res) => {
932
+ const wh = mockDb.webhooks.find(w => w.id === req.params.id);
933
+ if (!wh) return res.status(404).json({ error: "Webhook not found" });
934
+ const logItem = {
935
+ id: "whlog_" + Date.now(),
936
+ webhook_id: wh.id,
937
+ event_type: wh.event_types[0] || "REPLY",
938
+ status_code: 200,
939
+ timestamp: new Date().toISOString(),
940
+ payload_preview: { lead_email: "test.lead@domain.com", category: "INTERESTED", sentiment: "positive" }
941
+ } as const;
942
+ mockDb.webhook_logs.unshift(logItem);
943
+ wh.last_triggered = new Date().toISOString();
944
+ res.json({ success: true, message: "Test payload sent to endpoint", log: logItem });
945
+ });
946
+
947
+ app.get("/api/webhooks/logs", (req, res) => res.json(mockDb.webhook_logs));
948
+
949
+ // ==========================================
950
+ // MODULE 7: ANALYTICS API
951
+ // ==========================================
952
+ app.get("/api/analytics/campaigns", (req, res) => {
953
+ const totalSent = mockDb.campaigns.reduce((acc, c) => acc + c.sent_count, 0);
954
+ const totalOpens = mockDb.campaigns.reduce((acc, c) => acc + c.open_count, 0);
955
+ const totalReplies = mockDb.campaigns.reduce((acc, c) => acc + c.reply_count, 0);
956
+ const totalBounces = mockDb.campaigns.reduce((acc, c) => acc + c.bounce_count, 0);
957
+ const totalClicks = mockDb.campaigns.reduce((acc, c) => acc + c.click_count, 0);
958
+ const totalLeads = mockDb.campaigns.reduce((acc, c) => acc + c.lead_count, 0);
959
+
960
+ res.json({
961
+ total_campaigns: mockDb.campaigns.length,
962
+ total_leads: totalLeads,
963
+ total_sent: totalSent,
964
+ total_opens: totalOpens,
965
+ total_replies: totalReplies,
966
+ total_bounces: totalBounces,
967
+ total_clicks: totalClicks,
968
+ open_rate: ((totalOpens / (totalSent || 1)) * 100).toFixed(1),
969
+ reply_rate: ((totalReplies / (totalSent || 1)) * 100).toFixed(1),
970
+ click_rate: ((totalClicks / (totalSent || 1)) * 100).toFixed(1),
971
+ bounce_rate: ((totalBounces / (totalSent || 1)) * 100).toFixed(1)
972
+ });
973
+ });
974
+
975
+ // ==========================================
976
+ // MODULE 8: CLIENT MANAGEMENT API
977
+ // ==========================================
978
+ app.get("/api/clients", (req, res) => res.json(mockDb.clients));
979
+
980
+ app.post("/api/ai/completion", async (req, res) => {
981
+ try {
982
+ const { prompt } = req.body;
983
+ if (!prompt) {
984
+ return res.status(400).json({ error: "Prompt is required" });
985
+ }
986
+ const response = await getAiCompletionServer(prompt);
987
+ res.json({ response });
988
+ } catch (error) {
989
+ res.status(500).json({ error: "Failed to get AI completion" });
990
+ }
991
+ });
992
+
993
+
994
+ app.post("/api/clients", (req, res) => {
995
+ const newClient = {
996
+ id: "cli_" + Math.random().toString(36).substring(2, 7),
997
+ name: req.body.name || "New Client",
998
+ email: req.body.email || "client@company.com",
999
+ company: req.body.company || "Client Company Ltd",
1000
+ campaigns_count: 0,
1001
+ leads_count: 0,
1002
+ created_at: new Date().toISOString()
1003
+ };
1004
+ mockDb.clients.push(newClient);
1005
+ res.status(201).json(newClient);
1006
+ });
1007
+
1008
+ app.delete("/api/clients/:id", (req, res) => {
1009
+ mockDb.clients = mockDb.clients.filter(c => c.id !== req.params.id);
1010
+ res.json({ success: true });
1011
+ });
1012
+
1013
+ // Proxy Catch-All for any other direct Smartlead API calls
1014
+ app.use("/api", async (req, res) => {
1015
+ const apiKey = req.headers["x-api-key"] as string;
1016
+ if (!apiKey) {
1017
+ return res.status(401).json({ error: "Missing x-api-key header" });
1018
+ }
1019
+
1020
+ try {
1021
+ const targetUrl = `https://server.smartlead.ai/api/v1${req.path}`;
1022
+ const response = await axios({
1023
+ method: req.method,
1024
+ url: targetUrl,
1025
+ data: Object.keys(req.body).length > 0 ? req.body : undefined,
1026
+ params: { ...req.query, api_key: apiKey },
1027
+ timeout: 10000
1028
+ });
1029
+ res.status(response.status).json(response.data);
1030
+ } catch (error: any) {
1031
+ if (error.response) {
1032
+ res.status(error.response.status).json(error.response.data);
1033
+ } else {
1034
+ res.status(500).json({ error: "Proxy connection error", details: error.message });
1035
+ }
1036
+ }
1037
+ });
1038
+
1039
+ // Vite development middleware or production static serving
1040
+ if (process.env.NODE_ENV !== "production") {
1041
+ const { createServer: createViteServer } = await import("vite");
1042
+ const vite = await createViteServer({
1043
+ server: { middlewareMode: true },
1044
+ appType: "spa",
1045
+ });
1046
+ app.use(vite.middlewares);
1047
+ } else {
1048
+ const distPath = path.join(process.cwd(), "dist");
1049
+ app.use(express.static(distPath));
1050
+ app.get("*", (req, res) => {
1051
+ res.sendFile(path.join(distPath, "index.html"));
1052
+ });
1053
+ }
1054
+
1055
+ app.listen(PORT, "0.0.0.0", () => {
1056
+ console.log(`Smartlead Command Hub Server listening on http://0.0.0.0:${PORT}`);
1057
+ });
1058
+ }
1059
+
1060
+ startServer();