61 lines
1.5 KiB
Python
61 lines
1.5 KiB
Python
from __future__ import annotations
|
|||
|
|
|
||
|
|
import sqlite3
|
||
|
|
from datetime import datetime, timezone
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from .settings import ROOT
|
||
|
|
|
||
|
|
DB_PATH = ROOT / "data" / "leads.sqlite"
|
||
|
|
|
||
|
|
|
||
|
|
def _conn() -> sqlite3.Connection:
|
||
|
|
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||
|
|
conn = sqlite3.connect(DB_PATH)
|
||
|
|
conn.row_factory = sqlite3.Row
|
||
|
|
conn.execute(
|
||
|
|
"""
|
||
|
|
CREATE TABLE IF NOT EXISTS leads (
|
||
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||
|
|
session_id TEXT,
|
||
|
|
name TEXT,
|
||
|
|
phone TEXT,
|
||
|
|
note TEXT,
|
||
|
|
slots_json TEXT,
|
||
|
|
scheme_json TEXT,
|
||
|
|
created_at TEXT
|
||
|
|
)
|
||
|
|
"""
|
||
|
|
)
|
||
|
|
return conn
|
||
|
|
|
||
|
|
|
||
|
|
def add_lead(
|
||
|
|
*,
|
||
|
|
session_id: str,
|
||
|
|
name: str,
|
||
|
|
phone: str,
|
||
|
|
note: str,
|
||
|
|
slots_json: str,
|
||
|
|
scheme_json: str,
|
||
|
|
) -> int:
|
||
|
|
now = datetime.now(timezone.utc).isoformat()
|
||
|
|
with _conn() as conn:
|
||
|
|
cur = conn.execute(
|
||
|
|
"""
|
||
|
|
INSERT INTO leads (session_id, name, phone, note, slots_json, scheme_json, created_at)
|
||
|
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||
|
|
""",
|
||
|
|
(session_id, name, phone, note, slots_json, scheme_json, now),
|
||
|
|
)
|
||
|
|
return int(cur.lastrowid)
|
||
|
|
|
||
|
|
|
||
|
|
def list_leads(limit: int = 50) -> list[dict]:
|
||
|
|
with _conn() as conn:
|
||
|
|
rows = conn.execute(
|
||
|
|
"SELECT id, session_id, name, phone, note, created_at FROM leads ORDER BY id DESC LIMIT ?",
|
||
|
|
(limit,),
|
||
|
|
).fetchall()
|
||
|
|
return [dict(row) for row in rows]
|