Add lead-engine source code to main repo
This commit is contained in:
87
lead-engine/db.py
Normal file
87
lead-engine/db.py
Normal file
@@ -0,0 +1,87 @@
|
||||
import sqlite3
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
# Robust path handling:
|
||||
# 1. Get the directory where this script (db.py) lives
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
# 2. Define data directory and db path relative to it
|
||||
DATA_DIR = os.path.join(BASE_DIR, 'data')
|
||||
DB_PATH = os.path.join(DATA_DIR, 'leads.db')
|
||||
|
||||
def init_db():
|
||||
# Ensure data directory exists
|
||||
if not os.path.exists(DATA_DIR):
|
||||
os.makedirs(DATA_DIR)
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
c = conn.cursor()
|
||||
c.execute('''
|
||||
CREATE TABLE IF NOT EXISTS leads (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
source_id TEXT UNIQUE,
|
||||
received_at TIMESTAMP,
|
||||
company_name TEXT,
|
||||
contact_name TEXT,
|
||||
email TEXT,
|
||||
phone TEXT,
|
||||
raw_body TEXT,
|
||||
enrichment_data TEXT,
|
||||
status TEXT DEFAULT 'new',
|
||||
response_draft TEXT,
|
||||
sent_at TIMESTAMP
|
||||
)
|
||||
''')
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def insert_lead(lead_data):
|
||||
# Ensure DB exists before inserting (if ingest runs before init)
|
||||
if not os.path.exists(DB_PATH):
|
||||
init_db()
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
c = conn.cursor()
|
||||
try:
|
||||
c.execute('''
|
||||
INSERT INTO leads (source_id, received_at, company_name, contact_name, email, phone, raw_body, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
lead_data.get('id'),
|
||||
datetime.now(),
|
||||
lead_data.get('company'),
|
||||
lead_data.get('contact'),
|
||||
lead_data.get('email'),
|
||||
lead_data.get('phone'),
|
||||
lead_data.get('raw_body'),
|
||||
'new'
|
||||
))
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.IntegrityError:
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def get_leads():
|
||||
if not os.path.exists(DB_PATH):
|
||||
init_db()
|
||||
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
c = conn.cursor()
|
||||
c.execute('SELECT * FROM leads ORDER BY received_at DESC')
|
||||
rows = c.fetchall()
|
||||
conn.close()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def update_lead_status(lead_id, status, response_draft=None):
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
c = conn.cursor()
|
||||
if response_draft:
|
||||
c.execute('UPDATE leads SET status = ?, response_draft = ? WHERE id = ?', (status, response_draft, lead_id))
|
||||
else:
|
||||
c.execute('UPDATE leads SET status = ? WHERE id = ?', (status, lead_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user