Seth commited on
Commit
c2b90a5
·
1 Parent(s): 2c28af1
backend/app/database.py CHANGED
@@ -142,6 +142,8 @@ class Contact(Base):
142
  linkedin_connection_accepted_at = Column(DateTime, nullable=True)
143
  linkedin_last_followup_sent_at = Column(DateTime, nullable=True)
144
  linkedin_followup_next_email_number = Column(Integer, nullable=True)
 
 
145
  created_at = Column(DateTime, default=datetime.utcnow())
146
 
147
 
@@ -506,6 +508,10 @@ def run_migrations(connection_engine):
506
  conn.execute(text("ALTER TABLE contacts ADD COLUMN linkedin_last_followup_sent_at DATETIME"))
507
  if "linkedin_followup_next_email_number" not in ctcols:
508
  conn.execute(text("ALTER TABLE contacts ADD COLUMN linkedin_followup_next_email_number INTEGER"))
 
 
 
 
509
 
510
  insp = inspect(connection_engine)
511
  if insp.has_table("file_outreach_executions"):
 
142
  linkedin_connection_accepted_at = Column(DateTime, nullable=True)
143
  linkedin_last_followup_sent_at = Column(DateTime, nullable=True)
144
  linkedin_followup_next_email_number = Column(Integer, nullable=True)
145
+ outreach_stopped_at = Column(DateTime, nullable=True)
146
+ outreach_stop_reason = Column(String, nullable=True)
147
  created_at = Column(DateTime, default=datetime.utcnow())
148
 
149
 
 
508
  conn.execute(text("ALTER TABLE contacts ADD COLUMN linkedin_last_followup_sent_at DATETIME"))
509
  if "linkedin_followup_next_email_number" not in ctcols:
510
  conn.execute(text("ALTER TABLE contacts ADD COLUMN linkedin_followup_next_email_number INTEGER"))
511
+ if "outreach_stopped_at" not in ctcols:
512
+ conn.execute(text("ALTER TABLE contacts ADD COLUMN outreach_stopped_at DATETIME"))
513
+ if "outreach_stop_reason" not in ctcols:
514
+ conn.execute(text("ALTER TABLE contacts ADD COLUMN outreach_stop_reason TEXT"))
515
 
516
  insp = inspect(connection_engine)
517
  if insp.has_table("file_outreach_executions"):
backend/app/main.py CHANGED
@@ -81,6 +81,13 @@ from .outreach_routes import (
81
  refresh_outreach_execution_stats_for_file,
82
  normalize_smtp_message_id,
83
  )
 
 
 
 
 
 
 
84
  from .deal_revenue import build_quarterly_board
85
 
86
  app = FastAPI()
@@ -882,6 +889,12 @@ def _crm_lead_to_dict(row: CrmLead) -> dict:
882
  "created_at": row.created_at.isoformat() if row.created_at else None,
883
  "updated_at": row.updated_at.isoformat() if row.updated_at else None,
884
  "company_details": _lead_company_details_dict(row),
 
 
 
 
 
 
885
  }
886
 
887
 
@@ -2137,17 +2150,132 @@ async def unipile_webhook(request: Request, db: Session = Depends(get_db)):
2137
 
2138
  if rec:
2139
  when = _parse_unipile_webhook_datetime((body or {}).get("date")) or now
 
 
2140
  if bounce_like and not rec.bounced_at:
2141
  rec.bounced_at = when
2142
- elif has_reply_parent and not bounce_like and not rec.replied_at:
2143
- rec.replied_at = when
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2144
  db.commit()
2145
  refresh_outreach_execution_stats_for_file(db, rec.tenant_id, rec.file_id)
2146
  db.commit()
2147
- return {"ok": True, "event": event, "updated_receipt_id": rec.id}
 
 
 
 
 
 
2148
 
2149
  return {"ok": True, "ignored": True, "reason": "no_matching_receipt"}
2150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2151
  return {"ok": True, "ignored": True, "reason": "unsupported_event", "event": event or ""}
2152
 
2153
 
@@ -2188,7 +2316,7 @@ async def unipile_webhook_url_hint(request: Request):
2188
  "message_delivered",
2189
  ],
2190
  "doc": "https://developer.unipile.com/docs/new-messages-webhook",
2191
- "note": "LinkedIn/chat channels — not used for Gmail mail_received.",
2192
  },
2193
  ],
2194
  "debug_logging": "Set UNIPILE_WEBHOOK_LOG_EVENTS=1 to log each webhook's event name, role, and JSON keys (no body content).",
@@ -5911,6 +6039,38 @@ async def seed_demo_deals(t: TenantContext = Depends(get_tenant_context)):
5911
  return {"ok": True, "removed_previous_demo_rows": removed, "inserted": len(samples)}
5912
 
5913
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5914
  @app.get("/api/leads/{lead_id}/smartlead-thread")
5915
  async def lead_smartlead_thread(lead_id: int, t: TenantContext = Depends(get_tenant_context)):
5916
  """Fetch full thread from Smartlead API (Admin API key required)."""
@@ -5922,6 +6082,11 @@ async def lead_smartlead_thread(lead_id: int, t: TenantContext = Depends(get_ten
5922
  )
5923
  if not row:
5924
  raise HTTPException(status_code=404, detail="Lead not found")
 
 
 
 
 
5925
  if not row.smartlead_lead_id or not row.campaign_id:
5926
  raise HTTPException(status_code=400, detail="Lead missing Smartlead campaign/lead id")
5927
  try:
 
81
  refresh_outreach_execution_stats_for_file,
82
  normalize_smtp_message_id,
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
 
93
  app = FastAPI()
 
889
  "created_at": row.created_at.isoformat() if row.created_at else None,
890
  "updated_at": row.updated_at.isoformat() if row.updated_at else None,
891
  "company_details": _lead_company_details_dict(row),
892
+ "source": (
893
+ (row.raw_webhook or {}).get("source")
894
+ if isinstance(row.raw_webhook, dict)
895
+ else None
896
+ )
897
+ or ("emailout_campaign" if lead_is_outreach_campaign(row) else "smartlead"),
898
  }
899
 
900
 
 
2150
 
2151
  if rec:
2152
  when = _parse_unipile_webhook_datetime((body or {}).get("date")) or now
2153
+ lead_id = None
2154
+ stopped = False
2155
  if bounce_like and not rec.bounced_at:
2156
  rec.bounced_at = when
2157
+ elif has_reply_parent and not bounce_like:
2158
+ if not rec.replied_at:
2159
+ rec.replied_at = when
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
+ if contact:
2169
+ reply_body = _strip_html_simple(
2170
+ _safe_str((body or {}).get("body_plain"))
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
  db.commit()
2198
+ return {
2199
+ "ok": True,
2200
+ "event": event,
2201
+ "updated_receipt_id": rec.id,
2202
+ "outreach_stopped": stopped,
2203
+ "lead_id": lead_id,
2204
+ }
2205
 
2206
  return {"ok": True, "ignored": True, "reason": "no_matching_receipt"}
2207
 
2208
+ if event == "message_received":
2209
+ account_id = _safe_str((body or {}).get("account_id"))
2210
+ sender = (body or {}).get("sender") if isinstance((body or {}).get("sender"), dict) else {}
2211
+ account_info = (body or {}).get("account_info") if isinstance((body or {}).get("account_info"), dict) else {}
2212
+ sender_pid = _safe_str(sender.get("attendee_provider_id"))
2213
+ our_pid = _safe_str(account_info.get("user_id"))
2214
+ if sender_pid and our_pid and sender_pid == our_pid:
2215
+ return {"ok": True, "ignored": True, "reason": "own_message"}
2216
+
2217
+ if not account_id or not sender_pid:
2218
+ return {"ok": True, "ignored": True, "reason": "missing_sender"}
2219
+
2220
+ ua = (
2221
+ db.query(UnipileAccount)
2222
+ .filter(UnipileAccount.unipile_account_id == account_id)
2223
+ .first()
2224
+ )
2225
+ if not ua:
2226
+ return {"ok": True, "ignored": True, "reason": "unknown_account"}
2227
+
2228
+ tenant_id = int(ua.tenant_id)
2229
+ contacts = (
2230
+ db.query(Contact)
2231
+ .filter(
2232
+ Contact.tenant_id == tenant_id,
2233
+ Contact.unipile_provider_id == sender_pid,
2234
+ Contact.source.in_(("apollo_csv", "linkedin_campaign")),
2235
+ )
2236
+ .all()
2237
+ )
2238
+ if not contacts:
2239
+ return {"ok": True, "ignored": True, "reason": "no_matching_contact"}
2240
+
2241
+ when = _parse_unipile_webhook_datetime((body or {}).get("timestamp")) or now
2242
+ msg_text = _safe_str((body or {}).get("message"))
2243
+ updated: List[dict] = []
2244
+ for ct in contacts:
2245
+ if not ct.file_id:
2246
+ continue
2247
+ n_actions = outreach_actions_count(db, tenant_id, ct.file_id)
2248
+ stopped = stop_contact_outreach(
2249
+ db,
2250
+ ct,
2251
+ reason="linkedin_reply",
2252
+ when=when,
2253
+ file_id=ct.file_id,
2254
+ n_actions=n_actions,
2255
+ )
2256
+ lead_row = upsert_crm_lead_from_outreach_reply(
2257
+ db,
2258
+ tenant_id,
2259
+ ct,
2260
+ file_id=ct.file_id,
2261
+ channel="linkedin",
2262
+ reply_subject="",
2263
+ reply_body=msg_text,
2264
+ reply_at=when,
2265
+ raw_webhook=body if isinstance(body, dict) else None,
2266
+ )
2267
+ refresh_outreach_execution_stats_for_file(db, tenant_id, ct.file_id)
2268
+ updated.append(
2269
+ {
2270
+ "contact_id": ct.id,
2271
+ "file_id": ct.file_id,
2272
+ "outreach_stopped": stopped,
2273
+ "lead_id": lead_row.id,
2274
+ }
2275
+ )
2276
+ db.commit()
2277
+ return {"ok": True, "event": event, "updated": updated}
2278
+
2279
  return {"ok": True, "ignored": True, "reason": "unsupported_event", "event": event or ""}
2280
 
2281
 
 
2316
  "message_delivered",
2317
  ],
2318
  "doc": "https://developer.unipile.com/docs/new-messages-webhook",
2319
+ "note": "LinkedIn replies stop outreach for that contact and create a Lead. Ignores messages sent by your own account.",
2320
  },
2321
  ],
2322
  "debug_logging": "Set UNIPILE_WEBHOOK_LOG_EVENTS=1 to log each webhook's event name, role, and JSON keys (no body content).",
 
6039
  return {"ok": True, "removed_previous_demo_rows": removed, "inserted": len(samples)}
6040
 
6041
 
6042
+ @app.get("/api/leads/{lead_id}/outreach-thread")
6043
+ async def lead_outreach_thread(lead_id: int, t: TenantContext = Depends(get_tenant_context)):
6044
+ """Full sent + received thread for EMAILOUT wizard campaign leads."""
6045
+ db = t.db
6046
+ row = (
6047
+ db.query(CrmLead)
6048
+ .filter(CrmLead.tenant_id == t.tenant_id, CrmLead.id == lead_id)
6049
+ .first()
6050
+ )
6051
+ if not row:
6052
+ raise HTTPException(status_code=404, detail="Lead not found")
6053
+ if not lead_is_outreach_campaign(row):
6054
+ raise HTTPException(status_code=400, detail="Lead is not from an EMAILOUT campaign")
6055
+ if not row.contact_id or not row.campaign_id:
6056
+ raise HTTPException(status_code=400, detail="Lead missing contact or campaign file id")
6057
+ contact = (
6058
+ db.query(Contact)
6059
+ .filter(Contact.tenant_id == t.tenant_id, Contact.id == row.contact_id)
6060
+ .first()
6061
+ )
6062
+ if not contact:
6063
+ raise HTTPException(status_code=404, detail="Linked contact not found")
6064
+ messages = build_outreach_thread(db, t.tenant_id, contact, row.campaign_id)
6065
+ return {
6066
+ "source": "emailout_campaign",
6067
+ "campaign_id": row.campaign_id,
6068
+ "campaign_name": row.campaign_name or "",
6069
+ "contact_id": row.contact_id,
6070
+ "messages": messages,
6071
+ }
6072
+
6073
+
6074
  @app.get("/api/leads/{lead_id}/smartlead-thread")
6075
  async def lead_smartlead_thread(lead_id: int, t: TenantContext = Depends(get_tenant_context)):
6076
  """Fetch full thread from Smartlead API (Admin API key required)."""
 
6082
  )
6083
  if not row:
6084
  raise HTTPException(status_code=404, detail="Lead not found")
6085
+ if lead_is_outreach_campaign(row):
6086
+ raise HTTPException(
6087
+ status_code=400,
6088
+ detail="Use /api/leads/{id}/outreach-thread for EMAILOUT campaign leads",
6089
+ )
6090
  if not row.smartlead_lead_id or not row.campaign_id:
6091
  raise HTTPException(status_code=400, detail="Lead missing Smartlead campaign/lead id")
6092
  try:
backend/app/outreach_leads.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Per-contact outreach stop, CRM lead upsert, and conversation thread for EMAILOUT campaigns.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ 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 Contact, CrmLead, GeneratedSequence, OutreachSendReceipt, UploadedFile
15
+
16
+ OUTREACH_LEAD_SOURCE = "emailout_campaign"
17
+ OUTREACH_LEAD_ID_PREFIX = "emailout-"
18
+
19
+
20
+ def _safe_str(val: Any) -> str:
21
+ if val is None:
22
+ return ""
23
+ return str(val).strip()
24
+
25
+
26
+ def _strip_html_simple(text: str) -> str:
27
+ t = _safe_str(text)
28
+ if not t:
29
+ return ""
30
+ t = re.sub(r"<br\s*/?>", "\n", t, flags=re.I)
31
+ t = re.sub(r"</p>", "\n", t, flags=re.I)
32
+ t = re.sub(r"<[^>]+>", "", t)
33
+ return t.replace("\r\n", "\n").strip()
34
+
35
+
36
+ def contact_outreach_stopped(contact: Contact) -> bool:
37
+ return bool(getattr(contact, "outreach_stopped_at", None))
38
+
39
+
40
+ def _campaign_name_for_file(db: Session, tenant_id: int, file_id: str) -> str:
41
+ uf = (
42
+ db.query(UploadedFile)
43
+ .filter(UploadedFile.tenant_id == tenant_id, UploadedFile.file_id == file_id)
44
+ .first()
45
+ )
46
+ if uf and uf.filename:
47
+ return _safe_str(uf.filename)
48
+ return file_id or "Campaign"
49
+
50
+
51
+ def skip_remaining_outreach_slots(
52
+ db: Session,
53
+ tenant_id: int,
54
+ file_id: str,
55
+ contact_id: int,
56
+ n_actions: int,
57
+ reason: str,
58
+ ) -> int:
59
+ """Create skipped receipts for unsent slots so campaign progress can complete."""
60
+ created = 0
61
+ detail = f"Sequence stopped: {reason}"[:500]
62
+ for slot in range(max(0, int(n_actions))):
63
+ exists = (
64
+ db.query(OutreachSendReceipt.id)
65
+ .filter(
66
+ OutreachSendReceipt.tenant_id == tenant_id,
67
+ OutreachSendReceipt.file_id == file_id,
68
+ OutreachSendReceipt.contact_id == contact_id,
69
+ OutreachSendReceipt.step_slot == slot,
70
+ )
71
+ .first()
72
+ )
73
+ if exists:
74
+ continue
75
+ db.add(
76
+ OutreachSendReceipt(
77
+ tenant_id=tenant_id,
78
+ file_id=file_id,
79
+ contact_id=contact_id,
80
+ step_slot=slot,
81
+ channel="",
82
+ action="",
83
+ status="skipped",
84
+ detail=detail,
85
+ )
86
+ )
87
+ created += 1
88
+ return created
89
+
90
+
91
+ def stop_contact_outreach(
92
+ db: Session,
93
+ contact: Contact,
94
+ *,
95
+ reason: str,
96
+ when: Optional[datetime] = None,
97
+ file_id: Optional[str] = None,
98
+ n_actions: int = 0,
99
+ ) -> bool:
100
+ """Stop all future outreach for this contact. Returns True if newly stopped."""
101
+ if contact_outreach_stopped(contact):
102
+ return False
103
+ contact.outreach_stopped_at = when or datetime.utcnow()
104
+ contact.outreach_stop_reason = _safe_str(reason)[:120] or "reply"
105
+ if file_id and n_actions > 0:
106
+ skip_remaining_outreach_slots(
107
+ db,
108
+ int(contact.tenant_id or 0),
109
+ file_id,
110
+ int(contact.id),
111
+ n_actions,
112
+ reason,
113
+ )
114
+ return True
115
+
116
+
117
+ def _append_thread_message(raw: Optional[dict], entry: dict) -> dict:
118
+ base = dict(raw) if isinstance(raw, dict) else {}
119
+ messages = list(base.get("messages") or [])
120
+ for m in messages:
121
+ if (
122
+ isinstance(m, dict)
123
+ and m.get("direction") == entry.get("direction")
124
+ and m.get("at") == entry.get("at")
125
+ and m.get("body") == entry.get("body")
126
+ ):
127
+ return base
128
+ messages.append(entry)
129
+ messages.sort(key=lambda m: m.get("at") or "")
130
+ base["messages"] = messages
131
+ base["source"] = OUTREACH_LEAD_SOURCE
132
+ return base
133
+
134
+
135
+ def upsert_crm_lead_from_outreach_reply(
136
+ db: Session,
137
+ tenant_id: int,
138
+ contact: Contact,
139
+ *,
140
+ file_id: str,
141
+ channel: str,
142
+ reply_subject: str,
143
+ reply_body: str,
144
+ reply_at: datetime,
145
+ raw_webhook: Optional[dict] = None,
146
+ ) -> CrmLead:
147
+ campaign_id = file_id
148
+ campaign_name = _campaign_name_for_file(db, tenant_id, file_id)
149
+ lead_key = f"{OUTREACH_LEAD_ID_PREFIX}{contact.id}"
150
+
151
+ row = (
152
+ db.query(CrmLead)
153
+ .filter(
154
+ CrmLead.tenant_id == tenant_id,
155
+ CrmLead.contact_id == contact.id,
156
+ CrmLead.campaign_id == campaign_id,
157
+ )
158
+ .first()
159
+ )
160
+ if not row:
161
+ row = (
162
+ db.query(CrmLead)
163
+ .filter(
164
+ CrmLead.tenant_id == tenant_id,
165
+ CrmLead.smartlead_lead_id == lead_key,
166
+ )
167
+ .first()
168
+ )
169
+
170
+ clean_body = _strip_html_simple(reply_body)
171
+ thread_entry = {
172
+ "direction": "inbound",
173
+ "channel": channel,
174
+ "subject": _safe_str(reply_subject),
175
+ "body": clean_body,
176
+ "at": reply_at.replace(microsecond=0).isoformat() + "Z",
177
+ }
178
+
179
+ if row:
180
+ old_ts = row.last_reply_at
181
+ if not old_ts or (reply_at and reply_at >= old_ts):
182
+ row.last_reply_subject = _safe_str(reply_subject)
183
+ row.last_reply_body = clean_body
184
+ row.last_reply_at = reply_at
185
+ row.email = contact.email or row.email
186
+ row.first_name = contact.first_name or row.first_name
187
+ row.last_name = contact.last_name or row.last_name
188
+ row.company_name = contact.company or row.company_name
189
+ row.title = contact.title or row.title
190
+ row.campaign_name = campaign_name or row.campaign_name
191
+ row.contact_id = contact.id
192
+ row.raw_webhook = _append_thread_message(row.raw_webhook, thread_entry)
193
+ if raw_webhook:
194
+ row.raw_webhook["last_webhook"] = raw_webhook
195
+ else:
196
+ raw: Dict[str, Any] = {
197
+ "source": OUTREACH_LEAD_SOURCE,
198
+ "file_id": file_id,
199
+ "contact_id": contact.id,
200
+ "messages": [thread_entry],
201
+ }
202
+ if raw_webhook:
203
+ raw["last_webhook"] = raw_webhook
204
+ row = CrmLead(
205
+ tenant_id=tenant_id,
206
+ smartlead_lead_id=lead_key,
207
+ campaign_id=campaign_id,
208
+ campaign_name=campaign_name,
209
+ email=contact.email or "",
210
+ first_name=contact.first_name or "",
211
+ last_name=contact.last_name or "",
212
+ company_name=contact.company or "",
213
+ title=contact.title or "",
214
+ last_reply_subject=_safe_str(reply_subject),
215
+ last_reply_body=clean_body,
216
+ last_reply_at=reply_at,
217
+ crm_status="new_lead",
218
+ contact_id=contact.id,
219
+ raw_webhook=raw,
220
+ )
221
+ db.add(row)
222
+
223
+ db.flush()
224
+ return row
225
+
226
+
227
+ def _gmail_channel_filter():
228
+ from sqlalchemy import or_
229
+
230
+ return or_(GeneratedSequence.channel == "gmail", GeneratedSequence.channel == "email")
231
+
232
+
233
+ def build_outreach_thread(
234
+ db: Session,
235
+ tenant_id: int,
236
+ contact: Contact,
237
+ file_id: str,
238
+ ) -> List[dict]:
239
+ """Chronological sent + received messages for a campaign contact."""
240
+ from .outreach_routes import build_ordered_actions, load_campaign_plan_from_json
241
+
242
+ uf = (
243
+ db.query(UploadedFile)
244
+ .filter(UploadedFile.tenant_id == tenant_id, UploadedFile.file_id == file_id)
245
+ .first()
246
+ )
247
+ actions: List[dict] = []
248
+ if uf and getattr(uf, "sequence_plan_json", None):
249
+ try:
250
+ steps, parallel = load_campaign_plan_from_json(json.loads(uf.sequence_plan_json))
251
+ actions = build_ordered_actions(steps, parallel_tracks=parallel)
252
+ except Exception:
253
+ actions = []
254
+
255
+ receipts = (
256
+ db.query(OutreachSendReceipt)
257
+ .filter(
258
+ OutreachSendReceipt.tenant_id == tenant_id,
259
+ OutreachSendReceipt.file_id == file_id,
260
+ OutreachSendReceipt.contact_id == contact.id,
261
+ OutreachSendReceipt.status == "sent",
262
+ )
263
+ .order_by(OutreachSendReceipt.step_slot.asc())
264
+ .all()
265
+ )
266
+
267
+ thread: List[dict] = []
268
+ seq_id = int(contact.row_index or 0)
269
+
270
+ for rec in receipts:
271
+ act = actions[rec.step_slot] if rec.step_slot < len(actions) else {}
272
+ order = int(act.get("order") or (rec.step_slot + 1))
273
+ channel = rec.channel or act.get("channel") or "gmail"
274
+ gen = (
275
+ db.query(GeneratedSequence)
276
+ .filter(
277
+ GeneratedSequence.tenant_id == tenant_id,
278
+ GeneratedSequence.file_id == file_id,
279
+ GeneratedSequence.sequence_id == seq_id,
280
+ GeneratedSequence.step_order == order,
281
+ )
282
+ .first()
283
+ )
284
+ if not gen and channel == "gmail":
285
+ gen = (
286
+ db.query(GeneratedSequence)
287
+ .filter(
288
+ GeneratedSequence.tenant_id == tenant_id,
289
+ GeneratedSequence.file_id == file_id,
290
+ GeneratedSequence.sequence_id == seq_id,
291
+ _gmail_channel_filter(),
292
+ GeneratedSequence.email_number == order,
293
+ )
294
+ .first()
295
+ )
296
+ if not gen:
297
+ gen = (
298
+ db.query(GeneratedSequence)
299
+ .filter(
300
+ GeneratedSequence.tenant_id == tenant_id,
301
+ GeneratedSequence.file_id == file_id,
302
+ GeneratedSequence.sequence_id == seq_id,
303
+ GeneratedSequence.channel == "linkedin",
304
+ GeneratedSequence.step_order == order,
305
+ )
306
+ .first()
307
+ )
308
+
309
+ body = _safe_str(gen.email_content if gen else "")
310
+ subject = _safe_str(gen.subject if gen and channel == "gmail" else "")
311
+ sent_at = rec.created_at or datetime.utcnow()
312
+ thread.append(
313
+ {
314
+ "direction": "outbound",
315
+ "channel": channel,
316
+ "action": rec.action or act.get("action") or "",
317
+ "subject": subject,
318
+ "body": body,
319
+ "at": sent_at.replace(microsecond=0).isoformat() + "Z",
320
+ "step_slot": rec.step_slot,
321
+ }
322
+ )
323
+
324
+ lead = (
325
+ db.query(CrmLead)
326
+ .filter(
327
+ CrmLead.tenant_id == tenant_id,
328
+ CrmLead.contact_id == contact.id,
329
+ CrmLead.campaign_id == file_id,
330
+ )
331
+ .first()
332
+ )
333
+ if lead and isinstance(lead.raw_webhook, dict):
334
+ for msg in lead.raw_webhook.get("messages") or []:
335
+ if isinstance(msg, dict) and msg.get("direction") == "inbound":
336
+ thread.append(msg)
337
+
338
+ thread.sort(key=lambda m: m.get("at") or "")
339
+ return thread
340
+
341
+
342
+ def lead_is_outreach_campaign(row: CrmLead) -> bool:
343
+ raw = row.raw_webhook if isinstance(row.raw_webhook, dict) else {}
344
+ if raw.get("source") == OUTREACH_LEAD_SOURCE:
345
+ return True
346
+ sid = _safe_str(row.smartlead_lead_id)
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
+
353
+ uf = (
354
+ db.query(UploadedFile)
355
+ .filter(UploadedFile.tenant_id == tenant_id, UploadedFile.file_id == file_id)
356
+ .first()
357
+ )
358
+ if not uf or not getattr(uf, "sequence_plan_json", None):
359
+ return 0
360
+ try:
361
+ steps, parallel = load_campaign_plan_from_json(json.loads(uf.sequence_plan_json))
362
+ return len(build_ordered_actions(steps, parallel_tracks=parallel))
363
+ except Exception:
364
+ return 0
backend/app/outreach_routes.py CHANGED
@@ -29,6 +29,7 @@ from .database import (
29
  User,
30
  )
31
  from .gpt_service import normalize_email_body_format
 
32
  from .tenant_deps import TenantContext, get_tenant_context
33
 
34
  router = APIRouter(prefix="/api/campaign-files", tags=["campaign-files"])
@@ -657,6 +658,8 @@ def _find_next_send(
657
  except (TypeError, ValueError):
658
  li_h = 72
659
  for c in contacts:
 
 
660
  for slot in range(n_actions):
661
  if _receipt_for(db, tenant_id, file_id, c.id, slot):
662
  continue
@@ -850,6 +853,11 @@ def _execute_one_send(
850
  db.add(rec)
851
  db.flush()
852
 
 
 
 
 
 
853
  gen = _fetch_generated(db, tenant_id, file_id, int(contact.row_index or 0), channel, order)
854
  if not gen:
855
  rec.status = "failed"
 
29
  User,
30
  )
31
  from .gpt_service import normalize_email_body_format
32
+ from .outreach_leads import contact_outreach_stopped
33
  from .tenant_deps import TenantContext, get_tenant_context
34
 
35
  router = APIRouter(prefix="/api/campaign-files", tags=["campaign-files"])
 
658
  except (TypeError, ValueError):
659
  li_h = 72
660
  for c in contacts:
661
+ if contact_outreach_stopped(c):
662
+ continue
663
  for slot in range(n_actions):
664
  if _receipt_for(db, tenant_id, file_id, c.id, slot):
665
  continue
 
853
  db.add(rec)
854
  db.flush()
855
 
856
+ if contact_outreach_stopped(contact):
857
+ rec.status = "skipped"
858
+ rec.detail = _safe_str(contact.outreach_stop_reason) or "Outreach stopped (reply received)."
859
+ return rec
860
+
861
  gen = _fetch_generated(db, tenant_id, file_id, int(contact.row_index or 0), channel, order)
862
  if not gen:
863
  rec.status = "failed"
frontend/src/pages/Leads.jsx CHANGED
@@ -171,17 +171,31 @@ export default function Leads() {
171
 
172
  const updateStatus = (leadId, crmStatus) => patchLead(leadId, { crm_status: crmStatus });
173
 
174
- const loadThread = async (leadId) => {
 
 
 
 
175
  setThreadLoading(true);
176
  setThreadData(null);
177
  try {
178
- const res = await apiFetch(`/api/leads/${leadId}/smartlead-thread`);
 
 
 
 
 
179
  const data = await res.json();
180
  if (!res.ok) throw new Error(data.detail || 'Failed to load thread');
181
- setThreadData(data.history);
182
  } catch (e) {
183
  console.error(e);
184
- alert(e.message || 'Could not load Smartlead thread (check API key)');
 
 
 
 
 
185
  } finally {
186
  setThreadLoading(false);
187
  }
@@ -731,7 +745,7 @@ export default function Leads() {
731
  variant="outline"
732
  size="sm"
733
  className="gap-1"
734
- onClick={() => loadThread(selected.id)}
735
  disabled={threadLoading}
736
  >
737
  {threadLoading ? (
@@ -739,7 +753,9 @@ export default function Leads() {
739
  ) : (
740
  <ExternalLink className="h-4 w-4" />
741
  )}
742
- Full thread (Smartlead)
 
 
743
  </Button>
744
  </div>
745
  {selected.last_reply_subject && (
@@ -752,7 +768,54 @@ export default function Leads() {
752
  </div>
753
  </div>
754
 
755
- {threadData != null && (
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
756
  <div className="mt-4 rounded-lg border border-slate-200 p-3 bg-white overflow-x-auto">
757
  <pre className="text-xs text-slate-700 whitespace-pre-wrap break-all">
758
  {typeof threadData === 'string'
@@ -760,7 +823,7 @@ export default function Leads() {
760
  : JSON.stringify(threadData, null, 2)}
761
  </pre>
762
  </div>
763
- )}
764
  </>
765
  )}
766
  </SlideOverPanel>
 
171
 
172
  const updateStatus = (leadId, crmStatus) => patchLead(leadId, { crm_status: crmStatus });
173
 
174
+ const isOutreachLead = (lead) =>
175
+ lead?.source === 'emailout_campaign' ||
176
+ (lead?.smartlead_lead_id || '').startsWith('emailout-');
177
+
178
+ const loadThread = async (lead) => {
179
  setThreadLoading(true);
180
  setThreadData(null);
181
  try {
182
+ const outreach = isOutreachLead(lead);
183
+ const res = await apiFetch(
184
+ outreach
185
+ ? `/api/leads/${lead.id}/outreach-thread`
186
+ : `/api/leads/${lead.id}/smartlead-thread`
187
+ );
188
  const data = await res.json();
189
  if (!res.ok) throw new Error(data.detail || 'Failed to load thread');
190
+ setThreadData(outreach ? data.messages : data.history);
191
  } catch (e) {
192
  console.error(e);
193
+ alert(
194
+ e.message ||
195
+ (isOutreachLead(lead)
196
+ ? 'Could not load campaign thread'
197
+ : 'Could not load Smartlead thread (check API key)')
198
+ );
199
  } finally {
200
  setThreadLoading(false);
201
  }
 
745
  variant="outline"
746
  size="sm"
747
  className="gap-1"
748
+ onClick={() => loadThread(selected)}
749
  disabled={threadLoading}
750
  >
751
  {threadLoading ? (
 
753
  ) : (
754
  <ExternalLink className="h-4 w-4" />
755
  )}
756
+ {isOutreachLead(selected)
757
+ ? 'Full conversation'
758
+ : 'Full thread (Smartlead)'}
759
  </Button>
760
  </div>
761
  {selected.last_reply_subject && (
 
768
  </div>
769
  </div>
770
 
771
+ {threadData != null && Array.isArray(threadData) && threadData.length > 0 ? (
772
+ <div className="mt-4 space-y-3">
773
+ {threadData.map((msg, idx) => {
774
+ const outbound = msg.direction === 'outbound';
775
+ const channel =
776
+ msg.channel === 'linkedin'
777
+ ? 'LinkedIn'
778
+ : msg.channel === 'gmail'
779
+ ? 'Email'
780
+ : msg.channel || 'Message';
781
+ return (
782
+ <div
783
+ key={`${msg.at || idx}-${msg.direction}`}
784
+ className={cn(
785
+ 'rounded-lg border p-3 text-sm',
786
+ outbound
787
+ ? 'border-violet-200 bg-violet-50/60'
788
+ : 'border-emerald-200 bg-emerald-50/60'
789
+ )}
790
+ >
791
+ <div className="mb-1 flex flex-wrap items-center gap-2 text-xs text-slate-500">
792
+ <span className="font-semibold text-slate-700">
793
+ {outbound ? 'You sent' : 'They replied'}
794
+ </span>
795
+ <span>·</span>
796
+ <span>{channel}</span>
797
+ {msg.at ? (
798
+ <>
799
+ <span>·</span>
800
+ <span>
801
+ {new Date(msg.at).toLocaleString()}
802
+ </span>
803
+ </>
804
+ ) : null}
805
+ </div>
806
+ {msg.subject ? (
807
+ <p className="mb-1 text-xs font-medium text-slate-600">
808
+ Subject: {msg.subject}
809
+ </p>
810
+ ) : null}
811
+ <p className="whitespace-pre-wrap text-slate-800">
812
+ {msg.body || '—'}
813
+ </p>
814
+ </div>
815
+ );
816
+ })}
817
+ </div>
818
+ ) : threadData != null ? (
819
  <div className="mt-4 rounded-lg border border-slate-200 p-3 bg-white overflow-x-auto">
820
  <pre className="text-xs text-slate-700 whitespace-pre-wrap break-all">
821
  {typeof threadData === 'string'
 
823
  : JSON.stringify(threadData, null, 2)}
824
  </pre>
825
  </div>
826
+ ) : null}
827
  </>
828
  )}
829
  </SlideOverPanel>