Seth commited on
Commit ·
b921b15
1
Parent(s): c2b90a5
update
Browse files- backend/app/database.py +35 -2
- backend/app/main.py +44 -69
- backend/app/outreach_leads.py +193 -1
- backend/app/outreach_routes.py +4 -3
- frontend/src/pages/Leads.jsx +3 -3
backend/app/database.py
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
|
|
|
|
|
| 1 |
from sqlalchemy import (
|
| 2 |
create_engine,
|
| 3 |
Column,
|
|
@@ -9,9 +11,10 @@ from sqlalchemy import (
|
|
| 9 |
JSON,
|
| 10 |
ForeignKey,
|
| 11 |
UniqueConstraint,
|
|
|
|
| 12 |
)
|
| 13 |
from sqlalchemy.ext.declarative import declarative_base
|
| 14 |
-
from sqlalchemy.orm import sessionmaker
|
| 15 |
from datetime import datetime
|
| 16 |
import os
|
| 17 |
from pathlib import Path
|
|
@@ -21,11 +24,41 @@ DATA_DIR = Path("/data")
|
|
| 21 |
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 22 |
DB_PATH = os.getenv("HF_DATABASE_PATH", str(DATA_DIR / "emailout.db"))
|
| 23 |
|
| 24 |
-
engine = create_engine(
|
|
|
|
|
|
|
|
|
|
| 25 |
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 26 |
Base = declarative_base()
|
| 27 |
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
class User(Base):
|
| 30 |
__tablename__ = "users"
|
| 31 |
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
|
| 3 |
from sqlalchemy import (
|
| 4 |
create_engine,
|
| 5 |
Column,
|
|
|
|
| 11 |
JSON,
|
| 12 |
ForeignKey,
|
| 13 |
UniqueConstraint,
|
| 14 |
+
event,
|
| 15 |
)
|
| 16 |
from sqlalchemy.ext.declarative import declarative_base
|
| 17 |
+
from sqlalchemy.orm import Session, sessionmaker
|
| 18 |
from datetime import datetime
|
| 19 |
import os
|
| 20 |
from pathlib import Path
|
|
|
|
| 24 |
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
| 25 |
DB_PATH = os.getenv("HF_DATABASE_PATH", str(DATA_DIR / "emailout.db"))
|
| 26 |
|
| 27 |
+
engine = create_engine(
|
| 28 |
+
f"sqlite:///{DB_PATH}",
|
| 29 |
+
connect_args={"check_same_thread": False, "timeout": 30},
|
| 30 |
+
)
|
| 31 |
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
| 32 |
Base = declarative_base()
|
| 33 |
|
| 34 |
|
| 35 |
+
@event.listens_for(engine, "connect")
|
| 36 |
+
def _sqlite_pragmas(dbapi_connection, _connection_record):
|
| 37 |
+
cursor = dbapi_connection.cursor()
|
| 38 |
+
cursor.execute("PRAGMA journal_mode=WAL")
|
| 39 |
+
cursor.execute("PRAGMA synchronous=NORMAL")
|
| 40 |
+
cursor.execute("PRAGMA busy_timeout=30000")
|
| 41 |
+
cursor.close()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def db_commit_with_retry(session: Session, *, attempts: int = 5) -> None:
|
| 45 |
+
"""Retry commits when SQLite is busy (common under concurrent webhooks + campaign ticks)."""
|
| 46 |
+
last_err = None
|
| 47 |
+
for i in range(max(1, attempts)):
|
| 48 |
+
try:
|
| 49 |
+
session.commit()
|
| 50 |
+
return
|
| 51 |
+
except Exception as e:
|
| 52 |
+
last_err = e
|
| 53 |
+
msg = str(e).lower()
|
| 54 |
+
if "locked" not in msg and "busy" not in msg:
|
| 55 |
+
raise
|
| 56 |
+
session.rollback()
|
| 57 |
+
time.sleep(min(0.05 * (2**i), 1.0))
|
| 58 |
+
if last_err:
|
| 59 |
+
raise last_err
|
| 60 |
+
|
| 61 |
+
|
| 62 |
class User(Base):
|
| 63 |
__tablename__ = "users"
|
| 64 |
|
backend/app/main.py
CHANGED
|
@@ -27,6 +27,7 @@ from calendar import monthrange
|
|
| 27 |
from .database import (
|
| 28 |
get_db,
|
| 29 |
SessionLocal,
|
|
|
|
| 30 |
Tenant,
|
| 31 |
TenantMembership,
|
| 32 |
User,
|
|
@@ -83,10 +84,17 @@ from .outreach_routes import (
|
|
| 83 |
)
|
| 84 |
from .outreach_leads import (
|
| 85 |
build_outreach_thread,
|
|
|
|
| 86 |
lead_is_outreach_campaign,
|
| 87 |
outreach_actions_count,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
stop_contact_outreach,
|
| 89 |
upsert_crm_lead_from_outreach_reply,
|
|
|
|
|
|
|
| 90 |
)
|
| 91 |
from .deal_revenue import build_quarterly_board
|
| 92 |
|
|
@@ -2037,7 +2045,7 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2037 |
ct.linkedin_invite_pending = 0
|
| 2038 |
ct.linkedin_connection_accepted_at = now
|
| 2039 |
updated += 1
|
| 2040 |
-
|
| 2041 |
return {"ok": True, "updated_contacts": updated, "event": event}
|
| 2042 |
|
| 2043 |
if event in ("mail_opened", "mail_link_clicked"):
|
|
@@ -2066,16 +2074,18 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2066 |
rec.open_count = int(rec.open_count or 0) + 1
|
| 2067 |
except (TypeError, ValueError):
|
| 2068 |
rec.open_count = 1
|
| 2069 |
-
|
| 2070 |
refresh_outreach_execution_stats_for_file(db, tenant_id, file_id)
|
| 2071 |
-
|
| 2072 |
return {"ok": True, "event": event, "updated_receipt_id": rec.id}
|
| 2073 |
|
| 2074 |
-
if event
|
| 2075 |
account_id = _safe_str((body or {}).get("account_id"))
|
| 2076 |
-
role = _safe_str((body or {}).get("role"))
|
| 2077 |
-
if role != "inbox":
|
| 2078 |
return {"ok": True, "ignored": True, "reason": "not_inbox"}
|
|
|
|
|
|
|
| 2079 |
|
| 2080 |
ua = (
|
| 2081 |
db.query(UnipileAccount)
|
|
@@ -2092,27 +2102,9 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2092 |
trk = _safe_str((body or {}).get("tracking_id"))
|
| 2093 |
label = _safe_str((body or {}).get("label"))
|
| 2094 |
|
| 2095 |
-
rec =
|
| 2096 |
-
|
| 2097 |
-
|
| 2098 |
-
db.query(OutreachSendReceipt)
|
| 2099 |
-
.filter(
|
| 2100 |
-
OutreachSendReceipt.tenant_id == tenant_id,
|
| 2101 |
-
OutreachSendReceipt.channel == "gmail",
|
| 2102 |
-
OutreachSendReceipt.unipile_message_id == parent_id,
|
| 2103 |
-
)
|
| 2104 |
-
.first()
|
| 2105 |
-
)
|
| 2106 |
-
if not rec and parent_rfc:
|
| 2107 |
-
rec = (
|
| 2108 |
-
db.query(OutreachSendReceipt)
|
| 2109 |
-
.filter(
|
| 2110 |
-
OutreachSendReceipt.tenant_id == tenant_id,
|
| 2111 |
-
OutreachSendReceipt.channel == "gmail",
|
| 2112 |
-
OutreachSendReceipt.smtp_message_id == parent_rfc,
|
| 2113 |
-
)
|
| 2114 |
-
.first()
|
| 2115 |
-
)
|
| 2116 |
if not rec and trk:
|
| 2117 |
rec = (
|
| 2118 |
db.query(OutreachSendReceipt)
|
|
@@ -2144,9 +2136,16 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2144 |
)
|
| 2145 |
|
| 2146 |
folders = (body or {}).get("folders") or []
|
| 2147 |
-
|
|
|
|
| 2148 |
bounce_like = any("bounce" in str(f).lower() for f in folders if f) or "undeliverable" in subj
|
| 2149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2150 |
|
| 2151 |
if rec:
|
| 2152 |
when = _parse_unipile_webhook_datetime((body or {}).get("date")) or now
|
|
@@ -2154,47 +2153,15 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2154 |
stopped = False
|
| 2155 |
if bounce_like and not rec.bounced_at:
|
| 2156 |
rec.bounced_at = when
|
| 2157 |
-
elif
|
| 2158 |
-
|
| 2159 |
-
rec
|
| 2160 |
-
contact = (
|
| 2161 |
-
db.query(Contact)
|
| 2162 |
-
.filter(
|
| 2163 |
-
Contact.tenant_id == rec.tenant_id,
|
| 2164 |
-
Contact.id == rec.contact_id,
|
| 2165 |
-
)
|
| 2166 |
-
.first()
|
| 2167 |
)
|
| 2168 |
-
|
| 2169 |
-
|
| 2170 |
-
|
| 2171 |
-
or _safe_str((body or {}).get("body"))
|
| 2172 |
-
)
|
| 2173 |
-
reply_subj = _safe_str((body or {}).get("subject"))
|
| 2174 |
-
n_actions = outreach_actions_count(db, rec.tenant_id, rec.file_id)
|
| 2175 |
-
stopped = stop_contact_outreach(
|
| 2176 |
-
db,
|
| 2177 |
-
contact,
|
| 2178 |
-
reason="email_reply",
|
| 2179 |
-
when=when,
|
| 2180 |
-
file_id=rec.file_id,
|
| 2181 |
-
n_actions=n_actions,
|
| 2182 |
-
)
|
| 2183 |
-
lead_row = upsert_crm_lead_from_outreach_reply(
|
| 2184 |
-
db,
|
| 2185 |
-
rec.tenant_id,
|
| 2186 |
-
contact,
|
| 2187 |
-
file_id=rec.file_id,
|
| 2188 |
-
channel="gmail",
|
| 2189 |
-
reply_subject=reply_subj,
|
| 2190 |
-
reply_body=reply_body,
|
| 2191 |
-
reply_at=when,
|
| 2192 |
-
raw_webhook=body if isinstance(body, dict) else None,
|
| 2193 |
-
)
|
| 2194 |
-
lead_id = lead_row.id
|
| 2195 |
-
db.commit()
|
| 2196 |
refresh_outreach_execution_stats_for_file(db, rec.tenant_id, rec.file_id)
|
| 2197 |
-
|
| 2198 |
return {
|
| 2199 |
"ok": True,
|
| 2200 |
"event": event,
|
|
@@ -2203,6 +2170,14 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2203 |
"lead_id": lead_id,
|
| 2204 |
}
|
| 2205 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2206 |
return {"ok": True, "ignored": True, "reason": "no_matching_receipt"}
|
| 2207 |
|
| 2208 |
if event == "message_received":
|
|
@@ -2273,7 +2248,7 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
|
|
| 2273 |
"lead_id": lead_row.id,
|
| 2274 |
}
|
| 2275 |
)
|
| 2276 |
-
|
| 2277 |
return {"ok": True, "event": event, "updated": updated}
|
| 2278 |
|
| 2279 |
return {"ok": True, "ignored": True, "reason": "unsupported_event", "event": event or ""}
|
|
|
|
| 27 |
from .database import (
|
| 28 |
get_db,
|
| 29 |
SessionLocal,
|
| 30 |
+
db_commit_with_retry,
|
| 31 |
Tenant,
|
| 32 |
TenantMembership,
|
| 33 |
User,
|
|
|
|
| 84 |
)
|
| 85 |
from .outreach_leads import (
|
| 86 |
build_outreach_thread,
|
| 87 |
+
find_gmail_receipt_by_parent_hints,
|
| 88 |
lead_is_outreach_campaign,
|
| 89 |
outreach_actions_count,
|
| 90 |
+
process_inbound_email_reply,
|
| 91 |
+
prospect_email_for_reply_match,
|
| 92 |
+
prospect_emails_for_reply_match,
|
| 93 |
+
resolve_gmail_receipt_by_prospect_emails,
|
| 94 |
stop_contact_outreach,
|
| 95 |
upsert_crm_lead_from_outreach_reply,
|
| 96 |
+
_is_likely_email_reply,
|
| 97 |
+
_reply_sender_email,
|
| 98 |
)
|
| 99 |
from .deal_revenue import build_quarterly_board
|
| 100 |
|
|
|
|
| 2045 |
ct.linkedin_invite_pending = 0
|
| 2046 |
ct.linkedin_connection_accepted_at = now
|
| 2047 |
updated += 1
|
| 2048 |
+
db_commit_with_retry(db)
|
| 2049 |
return {"ok": True, "updated_contacts": updated, "event": event}
|
| 2050 |
|
| 2051 |
if event in ("mail_opened", "mail_link_clicked"):
|
|
|
|
| 2074 |
rec.open_count = int(rec.open_count or 0) + 1
|
| 2075 |
except (TypeError, ValueError):
|
| 2076 |
rec.open_count = 1
|
| 2077 |
+
db_commit_with_retry(db)
|
| 2078 |
refresh_outreach_execution_stats_for_file(db, tenant_id, file_id)
|
| 2079 |
+
db_commit_with_retry(db)
|
| 2080 |
return {"ok": True, "event": event, "updated_receipt_id": rec.id}
|
| 2081 |
|
| 2082 |
+
if event in ("mail_received", "mail_sent"):
|
| 2083 |
account_id = _safe_str((body or {}).get("account_id"))
|
| 2084 |
+
role = _safe_str((body or {}).get("role")).lower()
|
| 2085 |
+
if event == "mail_received" and role != "inbox":
|
| 2086 |
return {"ok": True, "ignored": True, "reason": "not_inbox"}
|
| 2087 |
+
if event == "mail_sent" and role not in ("sent", "outbox"):
|
| 2088 |
+
return {"ok": True, "ignored": True, "reason": "not_sent"}
|
| 2089 |
|
| 2090 |
ua = (
|
| 2091 |
db.query(UnipileAccount)
|
|
|
|
| 2102 |
trk = _safe_str((body or {}).get("tracking_id"))
|
| 2103 |
label = _safe_str((body or {}).get("label"))
|
| 2104 |
|
| 2105 |
+
rec = find_gmail_receipt_by_parent_hints(
|
| 2106 |
+
db, tenant_id, parent_id=parent_id, parent_rfc=parent_rfc
|
| 2107 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2108 |
if not rec and trk:
|
| 2109 |
rec = (
|
| 2110 |
db.query(OutreachSendReceipt)
|
|
|
|
| 2136 |
)
|
| 2137 |
|
| 2138 |
folders = (body or {}).get("folders") or []
|
| 2139 |
+
subj_raw = _safe_str((body or {}).get("subject"))
|
| 2140 |
+
subj = subj_raw.lower()
|
| 2141 |
bounce_like = any("bounce" in str(f).lower() for f in folders if f) or "undeliverable" in subj
|
| 2142 |
+
likely_reply = _is_likely_email_reply(subj_raw, in_reply if isinstance(in_reply, dict) else None)
|
| 2143 |
+
|
| 2144 |
+
if not rec and likely_reply and not bounce_like:
|
| 2145 |
+
prospect_ems = prospect_emails_for_reply_match(
|
| 2146 |
+
body if isinstance(body, dict) else {}, event=event
|
| 2147 |
+
)
|
| 2148 |
+
rec = resolve_gmail_receipt_by_prospect_emails(db, tenant_id, prospect_ems)
|
| 2149 |
|
| 2150 |
if rec:
|
| 2151 |
when = _parse_unipile_webhook_datetime((body or {}).get("date")) or now
|
|
|
|
| 2153 |
stopped = False
|
| 2154 |
if bounce_like and not rec.bounced_at:
|
| 2155 |
rec.bounced_at = when
|
| 2156 |
+
elif likely_reply and not bounce_like:
|
| 2157 |
+
result = process_inbound_email_reply(
|
| 2158 |
+
db, tenant_id, rec, body=body if isinstance(body, dict) else {}, when=when
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2159 |
)
|
| 2160 |
+
stopped = result.get("outreach_stopped", False)
|
| 2161 |
+
lead_id = result.get("lead_id")
|
| 2162 |
+
db_commit_with_retry(db)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2163 |
refresh_outreach_execution_stats_for_file(db, rec.tenant_id, rec.file_id)
|
| 2164 |
+
db_commit_with_retry(db)
|
| 2165 |
return {
|
| 2166 |
"ok": True,
|
| 2167 |
"event": event,
|
|
|
|
| 2170 |
"lead_id": lead_id,
|
| 2171 |
}
|
| 2172 |
|
| 2173 |
+
_unipile_webhook_log.info(
|
| 2174 |
+
"%s ignored: no_matching_receipt prospect=%s subject=%s parent_id=%s trk=%s",
|
| 2175 |
+
event,
|
| 2176 |
+
prospect_email_for_reply_match(body if isinstance(body, dict) else {}, event=event),
|
| 2177 |
+
subj_raw[:120],
|
| 2178 |
+
parent_id or "",
|
| 2179 |
+
trk or "",
|
| 2180 |
+
)
|
| 2181 |
return {"ok": True, "ignored": True, "reason": "no_matching_receipt"}
|
| 2182 |
|
| 2183 |
if event == "message_received":
|
|
|
|
| 2248 |
"lead_id": lead_row.id,
|
| 2249 |
}
|
| 2250 |
)
|
| 2251 |
+
db_commit_with_retry(db)
|
| 2252 |
return {"ok": True, "event": event, "updated": updated}
|
| 2253 |
|
| 2254 |
return {"ok": True, "ignored": True, "reason": "unsupported_event", "event": event or ""}
|
backend/app/outreach_leads.py
CHANGED
|
@@ -9,9 +9,17 @@ import re
|
|
| 9 |
from datetime import datetime
|
| 10 |
from typing import Any, Dict, List, Optional
|
| 11 |
|
|
|
|
| 12 |
from sqlalchemy.orm import Session
|
| 13 |
|
| 14 |
-
from .database import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
OUTREACH_LEAD_SOURCE = "emailout_campaign"
|
| 17 |
OUTREACH_LEAD_ID_PREFIX = "emailout-"
|
|
@@ -347,6 +355,190 @@ def lead_is_outreach_campaign(row: CrmLead) -> bool:
|
|
| 347 |
return sid.startswith(OUTREACH_LEAD_ID_PREFIX)
|
| 348 |
|
| 349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 350 |
def outreach_actions_count(db: Session, tenant_id: int, file_id: str) -> int:
|
| 351 |
from .outreach_routes import build_ordered_actions, load_campaign_plan_from_json
|
| 352 |
|
|
|
|
| 9 |
from datetime import datetime
|
| 10 |
from typing import Any, Dict, List, Optional
|
| 11 |
|
| 12 |
+
from sqlalchemy import func, or_
|
| 13 |
from sqlalchemy.orm import Session
|
| 14 |
|
| 15 |
+
from .database import (
|
| 16 |
+
Contact,
|
| 17 |
+
CrmLead,
|
| 18 |
+
GeneratedSequence,
|
| 19 |
+
OutreachSendReceipt,
|
| 20 |
+
UploadedFile,
|
| 21 |
+
db_commit_with_retry,
|
| 22 |
+
)
|
| 23 |
|
| 24 |
OUTREACH_LEAD_SOURCE = "emailout_campaign"
|
| 25 |
OUTREACH_LEAD_ID_PREFIX = "emailout-"
|
|
|
|
| 355 |
return sid.startswith(OUTREACH_LEAD_ID_PREFIX)
|
| 356 |
|
| 357 |
|
| 358 |
+
def _is_likely_email_reply(subject: str, in_reply: Optional[dict]) -> bool:
|
| 359 |
+
if isinstance(in_reply, dict) and (in_reply.get("id") or in_reply.get("message_id")):
|
| 360 |
+
return True
|
| 361 |
+
subj = _safe_str(subject).lower()
|
| 362 |
+
return subj.startswith("re:") or subj.startswith("re ")
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def _reply_sender_email(body: dict) -> str:
|
| 366 |
+
fa = body.get("from_attendee") if isinstance(body.get("from_attendee"), dict) else {}
|
| 367 |
+
return _safe_str(fa.get("identifier") or fa.get("email")).lower()
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def _attendee_emails(attendees: Any) -> List[str]:
|
| 371 |
+
out: List[str] = []
|
| 372 |
+
if not isinstance(attendees, list):
|
| 373 |
+
return out
|
| 374 |
+
for item in attendees:
|
| 375 |
+
if isinstance(item, dict):
|
| 376 |
+
em = _safe_str(item.get("identifier") or item.get("email")).lower()
|
| 377 |
+
if em and "@" in em:
|
| 378 |
+
out.append(em)
|
| 379 |
+
elif isinstance(item, str) and "@" in item:
|
| 380 |
+
out.append(item.strip().lower())
|
| 381 |
+
return out
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def prospect_emails_for_reply_match(body: dict, *, event: str) -> List[str]:
|
| 385 |
+
"""Emails used to match a campaign contact for reply attribution."""
|
| 386 |
+
seen: set[str] = set()
|
| 387 |
+
out: List[str] = []
|
| 388 |
+
|
| 389 |
+
def add(raw: str) -> None:
|
| 390 |
+
em = _safe_str(raw).lower()
|
| 391 |
+
if em and "@" in em and em not in seen:
|
| 392 |
+
seen.add(em)
|
| 393 |
+
out.append(em)
|
| 394 |
+
|
| 395 |
+
if event == "mail_sent":
|
| 396 |
+
add(_reply_sender_email(body))
|
| 397 |
+
for key in ("to_attendees", "to", "cc_attendees", "cc"):
|
| 398 |
+
for addr in _attendee_emails(body.get(key)):
|
| 399 |
+
add(addr)
|
| 400 |
+
return out
|
| 401 |
+
add(_reply_sender_email(body))
|
| 402 |
+
return out
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def prospect_email_for_reply_match(body: dict, *, event: str) -> str:
|
| 406 |
+
emails = prospect_emails_for_reply_match(body, event=event)
|
| 407 |
+
return emails[0] if emails else ""
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def resolve_gmail_receipt_by_prospect_emails(
|
| 411 |
+
db: Session,
|
| 412 |
+
tenant_id: int,
|
| 413 |
+
emails: List[str],
|
| 414 |
+
) -> Optional[OutreachSendReceipt]:
|
| 415 |
+
for em in emails:
|
| 416 |
+
rec = find_gmail_receipt_for_inbound_reply(db, tenant_id, em)
|
| 417 |
+
if rec:
|
| 418 |
+
return rec
|
| 419 |
+
return None
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def find_gmail_receipt_for_inbound_reply(
|
| 423 |
+
db: Session,
|
| 424 |
+
tenant_id: int,
|
| 425 |
+
from_email: str,
|
| 426 |
+
) -> Optional[OutreachSendReceipt]:
|
| 427 |
+
"""Fallback when UniPile in_reply_to ids do not match stored send receipt ids."""
|
| 428 |
+
email = _safe_str(from_email).lower()
|
| 429 |
+
if not email or "@" not in email:
|
| 430 |
+
return None
|
| 431 |
+
contacts = (
|
| 432 |
+
db.query(Contact)
|
| 433 |
+
.filter(
|
| 434 |
+
Contact.tenant_id == tenant_id,
|
| 435 |
+
func.lower(Contact.email) == email,
|
| 436 |
+
)
|
| 437 |
+
.all()
|
| 438 |
+
)
|
| 439 |
+
best: Optional[OutreachSendReceipt] = None
|
| 440 |
+
for ct in contacts:
|
| 441 |
+
if not ct.file_id:
|
| 442 |
+
continue
|
| 443 |
+
rec = (
|
| 444 |
+
db.query(OutreachSendReceipt)
|
| 445 |
+
.filter(
|
| 446 |
+
OutreachSendReceipt.tenant_id == tenant_id,
|
| 447 |
+
OutreachSendReceipt.file_id == ct.file_id,
|
| 448 |
+
OutreachSendReceipt.contact_id == ct.id,
|
| 449 |
+
OutreachSendReceipt.channel == "gmail",
|
| 450 |
+
OutreachSendReceipt.status == "sent",
|
| 451 |
+
)
|
| 452 |
+
.order_by(OutreachSendReceipt.step_slot.desc(), OutreachSendReceipt.id.desc())
|
| 453 |
+
.first()
|
| 454 |
+
)
|
| 455 |
+
if rec and (best is None or rec.step_slot > best.step_slot):
|
| 456 |
+
best = rec
|
| 457 |
+
return best
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def find_gmail_receipt_by_parent_hints(
|
| 461 |
+
db: Session,
|
| 462 |
+
tenant_id: int,
|
| 463 |
+
*,
|
| 464 |
+
parent_id: str,
|
| 465 |
+
parent_rfc: str,
|
| 466 |
+
) -> Optional[OutreachSendReceipt]:
|
| 467 |
+
if parent_id:
|
| 468 |
+
rec = (
|
| 469 |
+
db.query(OutreachSendReceipt)
|
| 470 |
+
.filter(
|
| 471 |
+
OutreachSendReceipt.tenant_id == tenant_id,
|
| 472 |
+
OutreachSendReceipt.channel == "gmail",
|
| 473 |
+
or_(
|
| 474 |
+
OutreachSendReceipt.unipile_message_id == parent_id,
|
| 475 |
+
OutreachSendReceipt.unipile_tracking_id == parent_id,
|
| 476 |
+
),
|
| 477 |
+
)
|
| 478 |
+
.first()
|
| 479 |
+
)
|
| 480 |
+
if rec:
|
| 481 |
+
return rec
|
| 482 |
+
if parent_rfc:
|
| 483 |
+
rec = (
|
| 484 |
+
db.query(OutreachSendReceipt)
|
| 485 |
+
.filter(
|
| 486 |
+
OutreachSendReceipt.tenant_id == tenant_id,
|
| 487 |
+
OutreachSendReceipt.channel == "gmail",
|
| 488 |
+
OutreachSendReceipt.smtp_message_id == parent_rfc,
|
| 489 |
+
)
|
| 490 |
+
.first()
|
| 491 |
+
)
|
| 492 |
+
if rec:
|
| 493 |
+
return rec
|
| 494 |
+
return None
|
| 495 |
+
|
| 496 |
+
|
| 497 |
+
def process_inbound_email_reply(
|
| 498 |
+
db: Session,
|
| 499 |
+
tenant_id: int,
|
| 500 |
+
rec: OutreachSendReceipt,
|
| 501 |
+
*,
|
| 502 |
+
body: dict,
|
| 503 |
+
when: datetime,
|
| 504 |
+
) -> dict:
|
| 505 |
+
"""Stop outreach for contact, upsert lead, mark receipt replied. Returns summary dict."""
|
| 506 |
+
contact = (
|
| 507 |
+
db.query(Contact)
|
| 508 |
+
.filter(Contact.tenant_id == rec.tenant_id, Contact.id == rec.contact_id)
|
| 509 |
+
.first()
|
| 510 |
+
)
|
| 511 |
+
if not contact:
|
| 512 |
+
return {"outreach_stopped": False, "lead_id": None}
|
| 513 |
+
if not rec.replied_at:
|
| 514 |
+
rec.replied_at = when
|
| 515 |
+
reply_body = _strip_html_simple(
|
| 516 |
+
_safe_str(body.get("body_plain")) or _safe_str(body.get("body"))
|
| 517 |
+
)
|
| 518 |
+
reply_subj = _safe_str(body.get("subject"))
|
| 519 |
+
n_actions = outreach_actions_count(db, rec.tenant_id, rec.file_id)
|
| 520 |
+
stopped = stop_contact_outreach(
|
| 521 |
+
db,
|
| 522 |
+
contact,
|
| 523 |
+
reason="email_reply",
|
| 524 |
+
when=when,
|
| 525 |
+
file_id=rec.file_id,
|
| 526 |
+
n_actions=n_actions,
|
| 527 |
+
)
|
| 528 |
+
lead_row = upsert_crm_lead_from_outreach_reply(
|
| 529 |
+
db,
|
| 530 |
+
rec.tenant_id,
|
| 531 |
+
contact,
|
| 532 |
+
file_id=rec.file_id,
|
| 533 |
+
channel="gmail",
|
| 534 |
+
reply_subject=reply_subj,
|
| 535 |
+
reply_body=reply_body,
|
| 536 |
+
reply_at=when,
|
| 537 |
+
raw_webhook=body,
|
| 538 |
+
)
|
| 539 |
+
return {"outreach_stopped": stopped, "lead_id": lead_row.id, "contact_id": contact.id}
|
| 540 |
+
|
| 541 |
+
|
| 542 |
def outreach_actions_count(db: Session, tenant_id: int, file_id: str) -> int:
|
| 543 |
from .outreach_routes import build_ordered_actions, load_campaign_plan_from_json
|
| 544 |
|
backend/app/outreach_routes.py
CHANGED
|
@@ -27,6 +27,7 @@ from .database import (
|
|
| 27 |
UnipileAccount,
|
| 28 |
UploadedFile,
|
| 29 |
User,
|
|
|
|
| 30 |
)
|
| 31 |
from .gpt_service import normalize_email_body_format
|
| 32 |
from .outreach_leads import contact_outreach_stopped
|
|
@@ -1196,10 +1197,10 @@ def tick_campaign_execution(
|
|
| 1196 |
break
|
| 1197 |
c, slot, act = nxt
|
| 1198 |
_execute_one_send(db, tc, uf, user_row, c, slot, act)
|
| 1199 |
-
|
| 1200 |
_refresh_execution_counters(db, ex, int(tc.tenant_id), file_id, ex.progress_total or len(contacts) * len(actions))
|
| 1201 |
-
|
| 1202 |
|
| 1203 |
_refresh_execution_counters(db, ex, int(tc.tenant_id), file_id, ex.progress_total or len(contacts) * len(actions))
|
| 1204 |
-
|
| 1205 |
return get_campaign_execution(file_id, tc)
|
|
|
|
| 27 |
UnipileAccount,
|
| 28 |
UploadedFile,
|
| 29 |
User,
|
| 30 |
+
db_commit_with_retry,
|
| 31 |
)
|
| 32 |
from .gpt_service import normalize_email_body_format
|
| 33 |
from .outreach_leads import contact_outreach_stopped
|
|
|
|
| 1197 |
break
|
| 1198 |
c, slot, act = nxt
|
| 1199 |
_execute_one_send(db, tc, uf, user_row, c, slot, act)
|
| 1200 |
+
db_commit_with_retry(db)
|
| 1201 |
_refresh_execution_counters(db, ex, int(tc.tenant_id), file_id, ex.progress_total or len(contacts) * len(actions))
|
| 1202 |
+
db_commit_with_retry(db)
|
| 1203 |
|
| 1204 |
_refresh_execution_counters(db, ex, int(tc.tenant_id), file_id, ex.progress_total or len(contacts) * len(actions))
|
| 1205 |
+
db_commit_with_retry(db)
|
| 1206 |
return get_campaign_execution(file_id, tc)
|
frontend/src/pages/Leads.jsx
CHANGED
|
@@ -387,7 +387,7 @@ export default function Leads() {
|
|
| 387 |
return (
|
| 388 |
<AppShell
|
| 389 |
title="Leads"
|
| 390 |
-
subtitle="Replies from Smartlead campaigns appear here.
|
| 391 |
>
|
| 392 |
<MainTableWorkspace
|
| 393 |
primaryAction={{ label: 'New lead', to: '/' }}
|
|
@@ -432,8 +432,8 @@ export default function Leads() {
|
|
| 432 |
) : leads.length === 0 ? (
|
| 433 |
<div className="text-center py-16 text-slate-500 space-y-3">
|
| 434 |
<p>
|
| 435 |
-
No leads yet. When a prospect replies
|
| 436 |
-
|
| 437 |
</p>
|
| 438 |
<Button size="sm" variant="secondary" onClick={() => seedDemoLeads()} disabled={seedBusy}>
|
| 439 |
Load demo rows (preview UI)
|
|
|
|
| 387 |
return (
|
| 388 |
<AppShell
|
| 389 |
title="Leads"
|
| 390 |
+
subtitle="Replies from EMAILOUT and Smartlead campaigns appear here. UniPile webhooks are configured on Settings."
|
| 391 |
>
|
| 392 |
<MainTableWorkspace
|
| 393 |
primaryAction={{ label: 'New lead', to: '/' }}
|
|
|
|
| 432 |
) : leads.length === 0 ? (
|
| 433 |
<div className="text-center py-16 text-slate-500 space-y-3">
|
| 434 |
<p>
|
| 435 |
+
No leads yet. When a prospect replies to an EMAILOUT campaign (via UniPile) or a
|
| 436 |
+
Smartlead campaign, they will show up here automatically.
|
| 437 |
</p>
|
| 438 |
<Button size="sm" variant="secondary" onClick={() => seedDemoLeads()} disabled={seedBusy}>
|
| 439 |
Load demo rows (preview UI)
|