Update services/lead_logic.py
Browse files- services/lead_logic.py +75 -94
services/lead_logic.py
CHANGED
|
@@ -6,116 +6,98 @@ from typing import List, Dict
|
|
| 6 |
import pandas as pd
|
| 7 |
|
| 8 |
CANONICAL_COLUMNS = [
|
| 9 |
-
"Lead ID", "Lead Date", "Customer Name", "Phone", "Location", "Requirement",
|
| 10 |
"Status", "Assigned To", "Priority", "Lead Score", "Next Action",
|
| 11 |
"Human Intervention", "AI Summary", "WhatsApp Action", "Last Contact", "Call Result"
|
| 12 |
]
|
| 13 |
|
| 14 |
-
REQUIRED_META_COLUMNS = ["LEADS DATE", "NAME", "CONTACT", "LOCATION", "REQUIREMENTS", "TIME"]
|
| 15 |
-
|
| 16 |
|
| 17 |
def build_demo_leads() -> pd.DataFrame:
|
| 18 |
rows = [
|
| 19 |
-
["L001", "2026-08-22", "Demo Customer 1", "", "Banashankari", "3BHK full interior", "
|
| 20 |
-
["L002", "2026-08-22", "Demo Customer 2", "", "JP Nagar", "Modular kitchen", "
|
| 21 |
-
["L003", "2026-08-22", "Demo Customer 3", "", "Kanakapura Road", "2BHK interior", "
|
|
|
|
|
|
|
| 22 |
]
|
| 23 |
return pd.DataFrame(rows, columns=CANONICAL_COLUMNS)
|
| 24 |
|
| 25 |
|
| 26 |
-
def
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
return normalized[key]
|
| 36 |
-
return None
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
def _clean_phone(value) -> str:
|
| 40 |
-
if pd.isna(value):
|
| 41 |
-
return ""
|
| 42 |
-
# Excel often converts phone numbers to floats such as 8050559394.0
|
| 43 |
-
text = str(value).strip()
|
| 44 |
-
if text.endswith(".0") and text[:-2].replace("+", "").isdigit():
|
| 45 |
-
text = text[:-2]
|
| 46 |
-
digits = re.sub(r"[^0-9+]", "", text)
|
| 47 |
-
return digits
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
def _clean_date(value) -> str:
|
| 51 |
-
if pd.isna(value) or str(value).strip() == "":
|
| 52 |
-
return ""
|
| 53 |
-
try:
|
| 54 |
-
ts = pd.to_datetime(value, dayfirst=True, errors="raise")
|
| 55 |
-
return ts.strftime("%Y-%m-%d")
|
| 56 |
-
except Exception:
|
| 57 |
-
return str(value).strip()
|
| 58 |
|
| 59 |
|
| 60 |
def normalize_excel(path: str) -> pd.DataFrame:
|
| 61 |
-
"""Import ONLY the six fields supplied by Meta/Facebook/Instagram.
|
| 62 |
-
|
| 63 |
-
Expected logical columns:
|
| 64 |
-
LEADS DATE, NAME, CONTACT, LOCATION, REQUIREMENTS, TIME
|
| 65 |
-
|
| 66 |
-
Everything else in the lead-management model is initialized by the application
|
| 67 |
-
and should be generated later by AI or the human supervisor.
|
| 68 |
-
"""
|
| 69 |
raw = pd.read_excel(path)
|
| 70 |
-
raw.columns =
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
if
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
# Keep only the six genuine Meta fields.
|
| 90 |
-
meta = raw[[date_c, name_c, phone_c, loc_c, req_c, time_c]].copy()
|
| 91 |
-
meta.columns = ["Lead Date", "Customer Name", "Phone", "Location", "Requirement", "Meta Time/Response"]
|
| 92 |
-
|
| 93 |
-
# Remove rows that are clearly not customer leads. A name OR phone must exist.
|
| 94 |
-
meta["Customer Name"] = meta["Customer Name"].fillna("").astype(str).str.strip()
|
| 95 |
-
meta["Phone"] = meta["Phone"].apply(_clean_phone)
|
| 96 |
-
meta["Location"] = meta["Location"].fillna("").astype(str).str.strip()
|
| 97 |
-
meta["Requirement"] = meta["Requirement"].fillna("").astype(str).str.strip()
|
| 98 |
-
meta["Meta Time/Response"] = meta["Meta Time/Response"].fillna("").astype(str).str.strip()
|
| 99 |
-
meta["Lead Date"] = meta["Lead Date"].apply(_clean_date)
|
| 100 |
-
meta = meta[(meta["Customer Name"] != "") | (meta["Phone"] != "")].reset_index(drop=True)
|
| 101 |
|
| 102 |
out = pd.DataFrame()
|
| 103 |
-
out["Lead ID"] = [f"
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
out["
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 109 |
out["Assigned To"] = "AI Queue"
|
| 110 |
out["Priority"] = "Unscored"
|
| 111 |
out["Lead Score"] = 0
|
| 112 |
-
out["Next Action"] = "
|
| 113 |
-
|
| 114 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 115 |
out["WhatsApp Action"] = ""
|
| 116 |
out["Last Contact"] = ""
|
| 117 |
out["Call Result"] = ""
|
| 118 |
-
|
| 119 |
return out[CANONICAL_COLUMNS]
|
| 120 |
|
| 121 |
|
|
@@ -164,18 +146,17 @@ def qualify_from_conversation(lead: Dict, transcript: str, scenario: str = "Full
|
|
| 164 |
|
| 165 |
score = 35
|
| 166 |
signals = []
|
| 167 |
-
if _contains(text, "3bhk", "
|
| 168 |
score += 10; signals.append("clear requirement")
|
| 169 |
-
if _contains(text, "next month", "immediate", "this month", "possession"
|
| 170 |
score += 15; signals.append("near-term timeline")
|
| 171 |
-
if re.search(r"\b
|
| 172 |
score += 15; signals.append("budget stated")
|
| 173 |
if _contains(text, "floor plan", "floorplan", "plan available"):
|
| 174 |
score += 8; signals.append("floor plan available")
|
| 175 |
-
|
| 176 |
-
wants_site = _contains(text, "site visit", "visit the site", "someone to visit", "come and visit", "visit my flat", "visit my house") or scenario == "Site visit interest"
|
| 177 |
wants_quote = _contains(text, "quotation", "quote", "estimate")
|
| 178 |
-
wants_catalog = _contains(text, "catalog", "catalogue", "previous work", "images", "photos"
|
| 179 |
if wants_site: score += 12; signals.append("site visit interest")
|
| 180 |
if wants_quote: score += 10; signals.append("quotation interest")
|
| 181 |
if wants_catalog: score += 5; signals.append("portfolio interest")
|
|
@@ -200,7 +181,7 @@ def qualify_from_conversation(lead: Dict, transcript: str, scenario: str = "Full
|
|
| 200 |
|
| 201 |
wa_actions = []
|
| 202 |
if wants_catalog: wa_actions.append("Send approved catalogue / previous-work portfolio")
|
| 203 |
-
if _contains(text, "floor plan"
|
| 204 |
if wants_site: wa_actions.append("Send site-visit acknowledgement after human confirms availability")
|
| 205 |
if wants_quote: wa_actions.append("Send quotation acknowledgement; quotation remains human-reviewed")
|
| 206 |
if not wa_actions: wa_actions.append("Send permitted thank-you / follow-up message")
|
|
|
|
| 6 |
import pandas as pd
|
| 7 |
|
| 8 |
CANONICAL_COLUMNS = [
|
| 9 |
+
"Lead ID", "Lead Date", "Customer Name", "Phone", "Location", "Requirement",
|
| 10 |
"Status", "Assigned To", "Priority", "Lead Score", "Next Action",
|
| 11 |
"Human Intervention", "AI Summary", "WhatsApp Action", "Last Contact", "Call Result"
|
| 12 |
]
|
| 13 |
|
|
|
|
|
|
|
| 14 |
|
| 15 |
def build_demo_leads() -> pd.DataFrame:
|
| 16 |
rows = [
|
| 17 |
+
["L001", "2026-08-22", "Demo Customer 1", "", "Banashankari", "3BHK full interior", "New", "AI Queue", "Unscored", 0, "AI qualification call", "No", "", "", "", ""],
|
| 18 |
+
["L002", "2026-08-22", "Demo Customer 2", "", "JP Nagar", "Modular kitchen", "New", "AI Queue", "Unscored", 0, "AI qualification call", "No", "", "", "", ""],
|
| 19 |
+
["L003", "2026-08-22", "Demo Customer 3", "", "Kanakapura Road", "2BHK interior", "Quote Requested", "Employee 1", "HOT", 82, "Prepare quote", "Yes", "Customer requested quotation.", "Send quotation / confirmation on WhatsApp", "", ""],
|
| 20 |
+
["L004", "2026-08-21", "Demo Customer 4", "", "Uttarahalli", "Wardrobe & loft", "Not Received", "AI Queue", "WARM", 45, "Retry call", "No", "No answer in previous attempt.", "Send approved callback template if permitted", "", "No answer"],
|
| 21 |
+
["L005", "2026-08-21", "Demo Customer 5", "", "RR Nagar", "Renovation", "Site Visit Requested", "Employee 1", "HOT", 91, "Confirm site visit", "Yes", "Customer has immediate renovation need and requested a visit.", "Confirm requested visit window", "", "Qualified"],
|
| 22 |
]
|
| 23 |
return pd.DataFrame(rows, columns=CANONICAL_COLUMNS)
|
| 24 |
|
| 25 |
|
| 26 |
+
def _unique_headers(cols):
|
| 27 |
+
seen = {}
|
| 28 |
+
result = []
|
| 29 |
+
for c in cols:
|
| 30 |
+
base = str(c).strip() if c is not None and str(c).strip() else "UNNAMED"
|
| 31 |
+
n = seen.get(base, 0)
|
| 32 |
+
result.append(base if n == 0 else f"{base}_{n+1}")
|
| 33 |
+
seen[base] = n + 1
|
| 34 |
+
return result
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
|
| 37 |
def normalize_excel(path: str) -> pd.DataFrame:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
raw = pd.read_excel(path)
|
| 39 |
+
raw.columns = _unique_headers(raw.columns)
|
| 40 |
+
raw = raw.dropna(how="all").copy()
|
| 41 |
+
|
| 42 |
+
def find_col(*tokens):
|
| 43 |
+
for col in raw.columns:
|
| 44 |
+
norm = re.sub(r"[^a-z0-9]", "", str(col).lower())
|
| 45 |
+
for t in tokens:
|
| 46 |
+
if re.sub(r"[^a-z0-9]", "", t.lower()) in norm:
|
| 47 |
+
return col
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
name_c = find_col("name")
|
| 51 |
+
phone_c = find_col("contact", "phone", "mobile")
|
| 52 |
+
loc_c = find_col("location", "area")
|
| 53 |
+
req_c = find_col("requirement")
|
| 54 |
+
date_c = find_col("leadsdate", "lead date", "date")
|
| 55 |
+
follow_cols = [c for c in raw.columns if "follow" in str(c).lower()]
|
| 56 |
+
remarks_cols = [c for c in raw.columns if "remark" in str(c).lower()]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
out = pd.DataFrame()
|
| 59 |
+
out["Lead ID"] = [f"AUG-{i+1:03d}" for i in range(len(raw))]
|
| 60 |
+
out["Lead Date"] = raw[date_c].astype(str) if date_c else ""
|
| 61 |
+
out["Customer Name"] = raw[name_c].fillna("").astype(str) if name_c else ""
|
| 62 |
+
out["Phone"] = raw[phone_c].fillna("").astype(str) if phone_c else ""
|
| 63 |
+
out["Location"] = raw[loc_c].fillna("").astype(str) if loc_c else ""
|
| 64 |
+
out["Requirement"] = raw[req_c].fillna("").astype(str) if req_c else ""
|
| 65 |
+
|
| 66 |
+
combined = pd.Series([""] * len(raw), index=raw.index, dtype="object")
|
| 67 |
+
for c in follow_cols + remarks_cols:
|
| 68 |
+
combined = (combined.astype(str) + " | " + raw[c].fillna("").astype(str)).str.strip(" |")
|
| 69 |
+
|
| 70 |
+
def infer_status(text):
|
| 71 |
+
t = str(text).lower()
|
| 72 |
+
if "site visit" in t: return "Site Visit Requested"
|
| 73 |
+
if "quote sent" in t or "quotation sent" in t: return "Quote Sent"
|
| 74 |
+
if "request for quote" in t or "quote request" in t: return "Quote Requested"
|
| 75 |
+
if "not interested" in t: return "Not Interested"
|
| 76 |
+
if "not received" in t or "no answer" in t: return "Not Received"
|
| 77 |
+
if "call back" in t or "callback" in t: return "Callback Requested"
|
| 78 |
+
if "reject" in t: return "Rejected"
|
| 79 |
+
if "image" in t or "message" in t or "catalog" in t: return "Information Requested"
|
| 80 |
+
return "New"
|
| 81 |
+
|
| 82 |
+
out["Status"] = combined.map(infer_status)
|
| 83 |
out["Assigned To"] = "AI Queue"
|
| 84 |
out["Priority"] = "Unscored"
|
| 85 |
out["Lead Score"] = 0
|
| 86 |
+
out["Next Action"] = out["Status"].map({
|
| 87 |
+
"Site Visit Requested": "Human follow-up / site visit",
|
| 88 |
+
"Quote Requested": "Human review / quote",
|
| 89 |
+
"Quote Sent": "Follow up quotation",
|
| 90 |
+
"Not Received": "Retry call",
|
| 91 |
+
"Callback Requested": "Schedule callback",
|
| 92 |
+
"Information Requested": "Send approved content",
|
| 93 |
+
"Not Interested": "Close lead",
|
| 94 |
+
"Rejected": "Close lead",
|
| 95 |
+
}).fillna("AI qualification call")
|
| 96 |
+
out["Human Intervention"] = out["Status"].isin(["Site Visit Requested", "Quote Requested"]).map({True:"Yes", False:"No"})
|
| 97 |
+
out["AI Summary"] = combined.where(combined.str.len() > 0, "")
|
| 98 |
out["WhatsApp Action"] = ""
|
| 99 |
out["Last Contact"] = ""
|
| 100 |
out["Call Result"] = ""
|
|
|
|
| 101 |
return out[CANONICAL_COLUMNS]
|
| 102 |
|
| 103 |
|
|
|
|
| 146 |
|
| 147 |
score = 35
|
| 148 |
signals = []
|
| 149 |
+
if _contains(text, "3bhk", "2bhk", "villa", "apartment", "kitchen", "wardrobe", "renovation"):
|
| 150 |
score += 10; signals.append("clear requirement")
|
| 151 |
+
if _contains(text, "next month", "immediate", "this month", "possession"):
|
| 152 |
score += 15; signals.append("near-term timeline")
|
| 153 |
+
if re.search(r"\b(8|9|10|11|12|13|14|15|16|17|18|20)\s*(lakh|lac|l)\b", text):
|
| 154 |
score += 15; signals.append("budget stated")
|
| 155 |
if _contains(text, "floor plan", "floorplan", "plan available"):
|
| 156 |
score += 8; signals.append("floor plan available")
|
| 157 |
+
wants_site = _contains(text, "site visit", "visit the site", "someone to visit", "come and visit") or scenario == "Site visit interest"
|
|
|
|
| 158 |
wants_quote = _contains(text, "quotation", "quote", "estimate")
|
| 159 |
+
wants_catalog = _contains(text, "catalog", "catalogue", "previous work", "images", "photos") or scenario == "Catalogue request"
|
| 160 |
if wants_site: score += 12; signals.append("site visit interest")
|
| 161 |
if wants_quote: score += 10; signals.append("quotation interest")
|
| 162 |
if wants_catalog: score += 5; signals.append("portfolio interest")
|
|
|
|
| 181 |
|
| 182 |
wa_actions = []
|
| 183 |
if wants_catalog: wa_actions.append("Send approved catalogue / previous-work portfolio")
|
| 184 |
+
if _contains(text, "floor plan"): wa_actions.append("Request/confirm floor plan upload")
|
| 185 |
if wants_site: wa_actions.append("Send site-visit acknowledgement after human confirms availability")
|
| 186 |
if wants_quote: wa_actions.append("Send quotation acknowledgement; quotation remains human-reviewed")
|
| 187 |
if not wa_actions: wa_actions.append("Send permitted thank-you / follow-up message")
|