Repository navigation
Expand file tree
/
Copy pathdatabase.py
More file actions
846 lines (754 loc) · 32 KB
/
Copy pathdatabase.py
File metadata and controls
846 lines (754 loc) · 32 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
import sqlite3
import json
from datetime import datetime, date
from typing import Dict, Any, List, Optional
from config import settings
def get_connection():
conn = sqlite3.connect(settings.DATABASE_PATH, timeout=30.0)
conn.row_factory = sqlite3.Row
# High-Performance Pragma Configurations for Enterprise Scale
conn.execute("PRAGMA journal_mode = WAL") # Write-Ahead Logging allows concurrent readers & writers
conn.execute("PRAGMA synchronous = NORMAL") # High write throughput with full crash safety
conn.execute("PRAGMA cache_size = -64000") # 64MB RAM in-memory cache for ultra-fast queries
conn.execute("PRAGMA foreign_keys = ON") # Maintain relational integrity
conn.execute("PRAGMA busy_timeout = 30000") # 30-second retry queue to eliminate 'database locked' errors
return conn
def init_db():
conn = get_connection()
cursor = conn.cursor()
# Email Accounts Pool (Supports 20+ Gmail/Outlook accounts)
cursor.execute("""
CREATE TABLE IF NOT EXISTS email_accounts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
display_name TEXT DEFAULT 'Growth Partner',
smtp_host TEXT DEFAULT 'smtp.gmail.com',
smtp_port INTEGER DEFAULT 587,
smtp_user TEXT NOT NULL,
smtp_password TEXT NOT NULL,
daily_limit INTEGER DEFAULT 30,
is_warmup_enabled INTEGER DEFAULT 1,
status TEXT DEFAULT 'active',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Campaigns table
cursor.execute("""
CREATE TABLE IF NOT EXISTS campaigns (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
offer_description TEXT NOT NULL,
icp_description TEXT NOT NULL,
target_location TEXT,
status TEXT DEFAULT 'active',
strategy_json TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Leads table
cursor.execute("""
CREATE TABLE IF NOT EXISTS leads (
id INTEGER PRIMARY KEY AUTOINCREMENT,
campaign_id INTEGER,
company_name TEXT NOT NULL,
website TEXT,
email TEXT,
phone TEXT,
location TEXT,
rating REAL DEFAULT 0,
review_count INTEGER DEFAULT 0,
social_profiles TEXT,
status TEXT DEFAULT 'discovered',
lead_score INTEGER DEFAULT 0,
score_breakdown TEXT,
assigned_account_id INTEGER,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(campaign_id) REFERENCES campaigns(id),
FOREIGN KEY(assigned_account_id) REFERENCES email_accounts(id)
);
""")
# Audits table
cursor.execute("""
CREATE TABLE IF NOT EXISTS audits (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lead_id INTEGER UNIQUE,
raw_markdown TEXT,
page_load_seconds REAL,
identified_pain_points TEXT,
buying_signals TEXT,
tech_stack TEXT,
recommended_angle TEXT,
audit_slug TEXT UNIQUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(lead_id) REFERENCES leads(id)
);
""")
# Funnels table
cursor.execute("""
CREATE TABLE IF NOT EXISTS funnels (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lead_id INTEGER UNIQUE,
slug TEXT UNIQUE,
headline TEXT,
subheadline TEXT,
html_content TEXT,
visits INTEGER DEFAULT 0,
booking_clicked INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(lead_id) REFERENCES leads(id)
);
""")
# Outreach table
cursor.execute("""
CREATE TABLE IF NOT EXISTS outreach (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lead_id INTEGER,
account_id INTEGER,
channel TEXT NOT NULL,
subject TEXT,
body TEXT NOT NULL,
sequence_step INTEGER DEFAULT 1,
status TEXT DEFAULT 'drafted',
sent_at TIMESTAMP,
reply_snippet TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(lead_id) REFERENCES leads(id),
FOREIGN KEY(account_id) REFERENCES email_accounts(id)
);
""")
# Dossiers table
cursor.execute("""
CREATE TABLE IF NOT EXISTS dossiers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lead_id INTEGER UNIQUE,
company_summary TEXT,
key_pain_points TEXT,
conversation_openers TEXT,
budget_tier TEXT,
pricing_recommendation TEXT,
objection_handlers TEXT,
meeting_notes TEXT,
deal_outcome TEXT DEFAULT 'pending',
deal_value REAL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY(lead_id) REFERENCES leads(id)
);
""")
# Feedback loop table
cursor.execute("""
CREATE TABLE IF NOT EXISTS feedback_insights (
id INTEGER PRIMARY KEY AUTOINCREMENT,
campaign_id INTEGER,
total_leads INTEGER DEFAULT 0,
contacted_count INTEGER DEFAULT 0,
replies_count INTEGER DEFAULT 0,
won_count INTEGER DEFAULT 0,
winning_patterns TEXT,
learnings_summary TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Inbound email deduplication table (guarantees incoming emails are processed exactly once)
cursor.execute("""
CREATE TABLE IF NOT EXISTS processed_inbox_messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account_id INTEGER,
message_id TEXT UNIQUE,
sender_email TEXT,
subject TEXT,
detected_intent TEXT,
processed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Schema migration checks
try:
cursor.execute("ALTER TABLE outreach ADD COLUMN account_id INTEGER")
except Exception:
pass
try:
cursor.execute("ALTER TABLE leads ADD COLUMN assigned_account_id INTEGER")
except Exception:
pass
try:
cursor.execute("ALTER TABLE leads ADD COLUMN decision_maker TEXT")
except Exception:
pass
try:
cursor.execute("ALTER TABLE leads ADD COLUMN mx_valid INTEGER DEFAULT 1")
except Exception:
pass
# =========================================================================
# HIGH-SCALE PERFORMANCE INDEXES (Optimized for 100,000+ leads & 20+ inboxes)
# =========================================================================
cursor.execute("CREATE INDEX IF NOT EXISTS idx_leads_campaign_id ON leads(campaign_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_leads_email ON leads(email)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_leads_status ON leads(status)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_leads_assigned_account ON leads(assigned_account_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_leads_score ON leads(lead_score DESC)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_outreach_lead_step ON outreach(lead_id, sequence_step)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_outreach_status_sent ON outreach(status, sent_at)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_outreach_account_date ON outreach(account_id, status, sent_at)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_processed_msg_id ON processed_inbox_messages(message_id)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_processed_sender ON processed_inbox_messages(sender_email)")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_email_accounts_status ON email_accounts(status)")
# System State table (Stores persistent scheduler run timestamps across laptop shutdowns)
cursor.execute("""
CREATE TABLE IF NOT EXISTS system_state (
key TEXT PRIMARY KEY,
value TEXT,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
# Dynamic Column Migrations for Deliverability Health & First-Send Tracking
cursor.execute("PRAGMA table_info(email_accounts)")
existing_acc_cols = [r["name"] for r in cursor.fetchall()]
if "first_send_date" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN first_send_date TEXT")
if "health_status" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN health_status TEXT DEFAULT 'healthy'")
if "last_error_at" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN last_error_at TIMESTAMP")
if "last_error_message" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN last_error_message TEXT")
if "last_sent_at" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN last_sent_at TIMESTAMP")
if "health_reset_at" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN health_reset_at TIMESTAMP")
if "cooldown_until" not in existing_acc_cols:
cursor.execute("ALTER TABLE email_accounts ADD COLUMN cooldown_until TIMESTAMP")
cursor.execute("PRAGMA table_info(outreach)")
existing_outreach_cols = [r["name"] for r in cursor.fetchall()]
if "is_warmup" not in existing_outreach_cols:
cursor.execute("ALTER TABLE outreach ADD COLUMN is_warmup INTEGER DEFAULT 0")
if "error_message" not in existing_outreach_cols:
cursor.execute("ALTER TABLE outreach ADD COLUMN error_message TEXT")
if "message_id" not in existing_outreach_cols:
cursor.execute("ALTER TABLE outreach ADD COLUMN message_id TEXT")
if "action_taken" not in existing_outreach_cols:
cursor.execute("ALTER TABLE outreach ADD COLUMN action_taken TEXT")
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
def get_system_state(key: str, default: str = "") -> str:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT value FROM system_state WHERE key = ?", (key,))
row = cursor.fetchone()
conn.close()
return row["value"] if row else default
def set_system_state(key: str, value: str):
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO system_state (key, value, updated_at)
VALUES (?, ?, CURRENT_TIMESTAMP)
ON CONFLICT(key) DO UPDATE SET value = excluded.value, updated_at = CURRENT_TIMESTAMP
""", (key, value))
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
def update_account_warmup_settings(account_id: int, is_warmup: int, is_brand_new: bool = True):
conn = get_connection()
cursor = conn.cursor()
if is_brand_new:
# Reset created_at to current timestamp so 28-day ramp begins fresh at Day 1
cursor.execute("""
UPDATE email_accounts
SET is_warmup_enabled = ?, created_at = CURRENT_TIMESTAMP
WHERE id = ?
""", (is_warmup, account_id))
else:
cursor.execute("UPDATE email_accounts SET is_warmup_enabled = ? WHERE id = ?", (is_warmup, account_id))
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
# DB Helpers
def add_email_account(email: str, smtp_user: str, smtp_pass: str, smtp_host: str = "smtp.gmail.com", smtp_port: int = 587, name: str = "Growth Partner", is_warmup: int = 1, daily_limit: int = 30) -> int:
conn = get_connection()
cursor = conn.cursor()
clean_email = email.strip().lower()
if smtp_host == "smtp.gmail.com" and any(prov in clean_email for prov in ("outlook", "hotmail", "live.com", "msn.com")):
smtp_host = "smtp-mail.outlook.com"
cursor.execute("""
INSERT INTO email_accounts (email, display_name, smtp_host, smtp_port, smtp_user, smtp_password, daily_limit, is_warmup_enabled, status, health_status, last_error_message)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'active', 'healthy', NULL)
ON CONFLICT(email) DO UPDATE SET
display_name = excluded.display_name,
smtp_host = excluded.smtp_host,
smtp_port = excluded.smtp_port,
smtp_user = excluded.smtp_user,
smtp_password = excluded.smtp_password,
daily_limit = excluded.daily_limit,
is_warmup_enabled = excluded.is_warmup_enabled,
status = 'active',
health_status = 'healthy',
last_error_message = NULL
""", (clean_email, name, smtp_host, smtp_port, smtp_user.strip(), smtp_pass, daily_limit, is_warmup))
cursor.execute("SELECT id FROM email_accounts WHERE LOWER(email) = ?", (clean_email,))
row = cursor.fetchone()
acc_id = row["id"] if row else cursor.lastrowid
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
return acc_id
def get_all_email_accounts() -> List[Dict[str, Any]]:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT id, email, display_name, smtp_host, smtp_port, daily_limit, is_warmup_enabled, status, created_at FROM email_accounts")
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def save_campaign(offer: str, icp: str, location: str, name: str = "", strategy: dict = None) -> int:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT INTO campaigns (name, offer_description, icp_description, target_location, strategy_json)
VALUES (?, ?, ?, ?, ?)
""", (name or f"Campaign: {offer[:30]}", offer, icp, location, json.dumps(strategy or {})))
campaign_id = cursor.lastrowid
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
return campaign_id
def _normalize_website_host(url: str) -> str:
if not url:
return ""
host = url.strip().lower()
for prefix in ("https://", "http://"):
if host.startswith(prefix):
host = host[len(prefix):]
if host.startswith("www."):
host = host[4:]
return host.split("/")[0].split("?")[0].strip()
def save_lead(campaign_id: int, lead_data: dict) -> int:
conn = get_connection()
cursor = conn.cursor()
lead_email = (lead_data.get("email") or "").strip().lower()
website = (lead_data.get("website") or "").strip()
website_host = _normalize_website_host(website)
company_name = (lead_data.get("company_name") or "").strip()
existing_id = None
if lead_email:
cursor.execute(
"SELECT id FROM leads WHERE campaign_id = ? AND LOWER(TRIM(COALESCE(email, ''))) = ? LIMIT 1",
(campaign_id, lead_email),
)
row = cursor.fetchone()
if row:
existing_id = row["id"]
if existing_id is None and website_host:
cursor.execute(
"SELECT id, website FROM leads WHERE campaign_id = ? AND website IS NOT NULL AND website != ''",
(campaign_id,),
)
for cand in cursor.fetchall():
if _normalize_website_host(cand["website"]) == website_host:
existing_id = cand["id"]
break
if existing_id is None and company_name:
cursor.execute(
"SELECT id, email, website FROM leads WHERE campaign_id = ? AND LOWER(TRIM(company_name)) = LOWER(?) LIMIT 1",
(campaign_id, company_name),
)
row = cursor.fetchone()
if row and (not lead_email and not website_host or (not row["email"] and not row["website"])):
existing_id = row["id"]
if existing_id is not None:
lead_id = existing_id
else:
cursor.execute("""
INSERT INTO leads (campaign_id, company_name, website, email, phone, location, rating, review_count, social_profiles, lead_score, decision_maker, mx_valid)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
""", (
campaign_id,
lead_data.get("company_name", "Unknown"),
website,
lead_email or lead_data.get("email", ""),
lead_data.get("phone", ""),
lead_data.get("location", ""),
lead_data.get("rating", 0.0),
lead_data.get("review_count", 0),
json.dumps(lead_data.get("social_profiles", {})),
lead_data.get("lead_score", 0),
lead_data.get("decision_maker", ""),
1 if lead_data.get("mx_valid", True) else 0
))
lead_id = cursor.lastrowid
conn.commit()
conn.close()
return lead_id
def update_lead_status(lead_id: int, status: str, lead_score: Optional[int] = None, score_breakdown: Optional[dict] = None):
conn = get_connection()
cursor = conn.cursor()
if lead_score is not None:
cursor.execute("""
UPDATE leads SET status = ?, lead_score = ?, score_breakdown = ? WHERE id = ?
""", (status, lead_score, json.dumps(score_breakdown or {}), lead_id))
else:
cursor.execute("UPDATE leads SET status = ? WHERE id = ?", (status, lead_id))
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
def save_audit(lead_id: int, audit_data: dict) -> int:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO audits (lead_id, raw_markdown, page_load_seconds, identified_pain_points, buying_signals, tech_stack, recommended_angle, audit_slug)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (
lead_id,
audit_data.get("raw_markdown", ""),
audit_data.get("page_load_seconds", 0.0),
json.dumps(audit_data.get("identified_pain_points", [])),
json.dumps(audit_data.get("buying_signals", [])),
json.dumps(audit_data.get("tech_stack", [])),
audit_data.get("recommended_angle", ""),
audit_data.get("audit_slug", f"audit-lead-{lead_id}")
))
audit_id = cursor.lastrowid
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
return audit_id
def save_funnel(lead_id: int, slug: str, headline: str, subheadline: str, html_content: str):
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO funnels (lead_id, slug, headline, subheadline, html_content)
VALUES (?, ?, ?, ?, ?)
""", (lead_id, slug, headline, subheadline, html_content))
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
def save_outreach(lead_id: int, channel: str, subject: str, body: str, step: int = 1, account_id: Optional[int] = None):
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT email, status FROM leads WHERE id = ?", (lead_id,))
lead_row = cursor.fetchone()
if lead_row:
if lead_row["status"] in ("bounced", "unsubscribed", "replied"):
conn.close()
return None
lead_email = (lead_row["email"] or "").strip().lower()
if lead_email:
cursor.execute("SELECT 1 FROM suppression_list WHERE LOWER(email) = ?", (lead_email,))
if cursor.fetchone():
conn.close()
return None
cursor.execute("""
SELECT id FROM outreach
WHERE lead_id = ? AND sequence_step = ? AND status IN ('sent', 'drafted')
LIMIT 1
""", (lead_id, step))
if cursor.fetchone():
conn.close()
return None
cursor.execute("""
INSERT INTO outreach (lead_id, channel, subject, body, sequence_step, account_id)
VALUES (?, ?, ?, ?, ?, ?)
""", (lead_id, channel, subject, body, step, account_id))
outreach_id = cursor.lastrowid
conn.commit()
conn.close()
return outreach_id
def save_dossier(lead_id: int, dossier: dict):
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
INSERT OR REPLACE INTO dossiers (lead_id, company_summary, key_pain_points, conversation_openers, budget_tier, pricing_recommendation, objection_handlers)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (
lead_id,
dossier.get("company_summary", ""),
json.dumps(dossier.get("key_pain_points", [])),
json.dumps(dossier.get("conversation_openers", [])),
dossier.get("budget_tier", "Mid-tier"),
json.dumps(dossier.get("pricing_recommendation", {})),
json.dumps(dossier.get("objection_handlers", []))
))
# Permanent Suppression List table (Zero tolerance for sending to unsubscribed / bounced leads)
cursor.execute("""
CREATE TABLE IF NOT EXISTS suppression_list (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
reason TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_suppression_email ON suppression_list(email)")
# Second Brain Knowledge Store (Continuous Reinforcement Learning & Self-Improvement)
cursor.execute("""
CREATE TABLE IF NOT EXISTS second_brain_memory (
id INTEGER PRIMARY KEY AUTOINCREMENT,
category TEXT NOT NULL,
content TEXT NOT NULL,
sample_quote TEXT,
performance_score REAL DEFAULT 1.0,
times_applied INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
""")
cursor.execute("CREATE INDEX IF NOT EXISTS idx_second_brain_cat ON second_brain_memory(category)")
conn.commit()
conn.close()
def get_campaign_leads(campaign_id: int) -> List[Dict[str, Any]]:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT l.*, a.audit_slug, a.recommended_angle, f.slug as funnel_slug, d.id as has_dossier
FROM leads l
LEFT JOIN audits a ON l.id = a.lead_id
LEFT JOIN funnels f ON l.id = f.lead_id
LEFT JOIN dossiers d ON l.id = d.lead_id
WHERE l.campaign_id = ?
ORDER BY l.lead_score DESC, l.created_at DESC
""", (campaign_id,))
rows = [dict(r) for r in cursor.fetchall()]
conn.close()
return rows
def get_lead_details(lead_id: int) -> Optional[Dict[str, Any]]:
conn = get_connection()
cursor = conn.cursor()
cursor.execute("""
SELECT l.*, c.offer_description, c.icp_description, c.target_location
FROM leads l
JOIN campaigns c ON l.campaign_id = c.id
WHERE l.id = ?
""", (lead_id,))
lead_row = cursor.fetchone()
if not lead_row:
conn.close()
return None
lead = dict(lead_row)
cursor.execute("SELECT * FROM audits WHERE lead_id = ?", (lead_id,))
audit_row = cursor.fetchone()
lead["audit"] = dict(audit_row) if audit_row else None
if lead["audit"]:
lead["audit"]["identified_pain_points"] = json.loads(lead["audit"].get("identified_pain_points") or "[]")
lead["audit"]["buying_signals"] = json.loads(lead["audit"].get("buying_signals") or "[]")
lead["audit"]["tech_stack"] = json.loads(lead["audit"].get("tech_stack") or "[]")
cursor.execute("SELECT * FROM funnels WHERE lead_id = ?", (lead_id,))
funnel_row = cursor.fetchone()
lead["funnel"] = dict(funnel_row) if funnel_row else None
cursor.execute("SELECT * FROM outreach WHERE lead_id = ? ORDER BY sequence_step ASC", (lead_id,))
lead["outreach"] = [dict(r) for r in cursor.fetchall()]
cursor.execute("SELECT * FROM dossiers WHERE lead_id = ?", (lead_id,))
dossier_row = cursor.fetchone()
lead["dossier"] = dict(dossier_row) if dossier_row else None
if lead["dossier"]:
lead["dossier"]["key_pain_points"] = json.loads(lead["dossier"].get("key_pain_points") or "[]")
lead["dossier"]["conversation_openers"] = json.loads(lead["dossier"].get("conversation_openers") or "[]")
lead["dossier"]["pricing_recommendation"] = json.loads(lead["dossier"].get("pricing_recommendation") or "{}")
lead["dossier"]["objection_handlers"] = json.loads(lead["dossier"].get("objection_handlers") or "[]")
conn.close()
return lead
init_db()
def is_email_suppressed(email: str) -> bool:
"""Checks if an email is in the permanent suppression list."""
if not email:
return True
conn = get_connection()
cursor = conn.cursor()
cursor.execute("SELECT id FROM suppression_list WHERE LOWER(email) = LOWER(?)", (email.strip(),))
row = cursor.fetchone()
conn.close()
return bool(row)
def add_to_suppression_list(email: str, reason: str = "unsubscribe", conn=None):
"""Adds an email to the permanent suppression list and blocks future outreach."""
if not email:
return
close_conn = False
if conn is None:
conn = get_connection()
close_conn = True
cursor = conn.cursor()
cursor.execute("""
INSERT OR IGNORE INTO suppression_list (email, reason)
VALUES (LOWER(?), ?)
""", (email.strip(), reason))
if close_conn:
conn.commit()
conn.close()
def get_kill_switch_status() -> bool:
"""Returns True if the Emergency Kill Switch is ACTIVE (all sending halted)."""
val = get_system_state("emergency_kill_switch", "0")
return val in ("1", "true", "True")
def set_kill_switch(is_active: bool):
"""Sets the Emergency Kill Switch state."""
set_system_state("emergency_kill_switch", "1" if is_active else "0")