Spaces:
Sleeping

curium-intel / scripts /send_validated_opps.py
mipwr-admin's picture
Sync from GitHub main β€” ERP priority, WMCA/Shropshire watchlist, network preserve-owners fix (a7395ea)
a87217c verified
Raw History Blame Contribute Delete
13.3 kB
"""
Email each connected colleague the validated transformation opportunities
in THEIR network.
Source: a LinkedIn job-alert search (Transformation/Change/Programme Manager
Β· Head of/Director Β· Birmingham 80km) cross-referenced against the team
network + the tool's tracked signals. The validated set lives in
netnew_opportunities (stream='transformation', source mentions 'LinkedIn
jobs search').
For each enabled team_emails colleague, this finds their SENIOR connections
at the validated companies and sends a personalised note: company, the live
hiring signal (why it's an opportunity), and their warm contact. Internal
only β€” nothing goes to any external contact.
Run via GitHub Actions (where the mail secrets live):
python scripts/send_validated_opps.py # send
python scripts/send_validated_opps.py --dry-run # print, don't send
"""
from __future__ import annotations
import sqlite3
import sys
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(REPO_ROOT))
try:
from dotenv import load_dotenv
load_dotenv(REPO_ROOT / ".env", override=False)
except ImportError:
pass
import mailer
import weekly_digest # reuses get_team_emails()
from network_loader import is_excluded_contact
DATABASE = str(REPO_ROOT / "leads.db")
DRY_RUN = "--dry-run" in sys.argv
# Validated opportunities β€” embedded so the script is self-contained and
# doesn't depend on netnew_opportunities being pre-populated in whichever
# environment runs it. Connections are computed live from network_graph.
# Source: LinkedIn job-alert search (Transformation/Change/Programme Manager
# Β· Head of/Director Β· Birmingham 80km), cross-referenced 2026.
VALIDATED = [
{"organisation": "West Midlands Combined Authority",
"signal": "Advertising Project Sponsor; the platform already tracks WMCA as HOT (score 50) with 8 live job signals β€” an active, under-resourced public-sector programme.",
"hook": "Combined-authority transformation delivery β€” Curium's public-sector sweet spot, LGR-adjacent."},
{"organisation": "Turner & Townsend",
"signal": "Advertising Project/Programme Lead for Major Programmes; tracked (score 36) plus 4 live job signals.",
"hook": "Programme-delivery surge β€” interim / augmentation opportunity."},
{"organisation": "Aviva",
"signal": "Advertising Head of Engineering Platforms; tracked (score 31); senior contacts up to Group CEO/COO level.",
"hook": "Above core ICP (mega-cap) but exceptional C-suite access β€” relationship play."},
{"organisation": "Arup",
"signal": "Advertising Enterprise Lead; deep People/OD bench in the network including a Global Transformation Director.",
"hook": "Global transformation programme β€” strong People & culture warm routes."},
{"organisation": "Nationwide Building Society",
"signal": "Advertising Senior Transformation Manager; People Director in the network.",
"hook": "Active transformation hire + a People Director route in."},
{"organisation": "Severn Trent",
"signal": "Advertising Senior Programme Manager AND Portfolio Manager (two open roles); Group HR Director in the network.",
"hook": "Two open programme roles = a programme under-resourced right now."},
{"organisation": "University of Birmingham",
"signal": "Advertising Delivery Manager; very deep network bench (20+ senior contacts).",
"hook": "HE transformation; multiple warm routes."},
{"organisation": "CGI",
"signal": "Advertising Agile Delivery Lead; SVP-level contact in the network.",
"hook": "SI delivery partner β€” possible partnership angle."},
{"organisation": "Kainos",
"signal": "Advertising Senior Program Manager (Public Sector); Head of Change Consulting in the network.",
"hook": "Public-sector delivery; warm change-consulting contact."},
{"organisation": "MHR",
"signal": "Advertising Senior Manager, Project Management; Public Sector Account Director in the network.",
"hook": "HR/payroll software + public sector."},
{"organisation": "SCC",
"signal": "Advertising Transition Manager; MD (UK Digital Workplace) in the network.",
"hook": "IT-services transition β€” warm MD route."},
]
def _validated_opps() -> list[dict]:
return list(VALIDATED)
def _senior_contacts(colleague: str, org: str) -> list[dict]:
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
rows = conn.execute(
"""SELECT contact_name, position FROM network_graph
WHERE status='ACTIVE' AND colleague_owner=? AND LOWER(company) LIKE ?
ORDER BY is_senior DESC""",
(colleague, f"%{org.lower()}%"),
).fetchall()
conn.close()
out = []
for r in rows:
if is_excluded_contact(r["position"] or ""):
continue
out.append({"name": r["contact_name"], "position": r["position"] or ""})
return out
def _other_team_contacts(org: str, exclude_colleague: str) -> dict[str, list[dict]]:
"""All OTHER Curium colleagues' senior contacts at this org, grouped by
colleague β€” so the recipient can coordinate a multi-threaded approach.
Excludes the recipient (their own contacts are shown separately)."""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
rows = conn.execute(
"""SELECT contact_name, position, colleague_owner FROM network_graph
WHERE status='ACTIVE' AND colleague_owner != ? AND LOWER(company) LIKE ?
ORDER BY is_senior DESC""",
(exclude_colleague, f"%{org.lower()}%"),
).fetchall()
conn.close()
by_colleague: dict[str, list[dict]] = {}
seen: set[tuple[str, str]] = set()
for r in rows:
if is_excluded_contact(r["position"] or ""):
continue
key = (r["colleague_owner"], (r["contact_name"] or "").lower())
if key in seen:
continue
seen.add(key)
by_colleague.setdefault(r["colleague_owner"], []).append(
{"name": r["contact_name"], "position": r["position"] or ""}
)
return by_colleague
def _build_email(colleague: str, items: list[dict]) -> tuple[str, str]:
"""Return (subject, html) for a colleague's validated-opps email."""
# Reuse the platform's shared feedback prompt so EVERY platform email
# carries the same feedback mechanism as the Monday digest (web form +
# reply-to). Falls back to empty string if unavailable.
try:
fb_prompt = weekly_digest._feedback_prompt_html(recipient_name=colleague)
except Exception:
fb_prompt = ""
n = len(items)
subject = (f"{n} validated opportunit{'y' if n == 1 else 'ies'} in your network "
f"β€” companies hiring transformation leaders now")
rows_html = ""
for it in items:
contacts_html = "".join(
f'<li><strong>{c["name"]}</strong>'
+ (f' β€” {c["position"]}' if c["position"] else "") + '</li>'
for c in it["contacts"][:3]
)
# Wider Curium relationship map into this account β€” who else is
# connected, so the recipient can coordinate a joint approach.
others = _other_team_contacts(it["organisation"], colleague)
others_html = ""
if others:
lines = []
# Show the strongest few colleagues (most senior contacts first)
for col, contacts in list(others.items())[:5]:
names = ", ".join(
f'{c["name"]}' + (f' ({c["position"]})' if c["position"] else "")
for c in contacts[:2]
)
lines.append(
f'<li><strong>{col}</strong> knows {names}</li>'
)
others_html = (
'<div style="font-size:0.84em;margin-top:8px;color:#2e7d32;">'
'🀝 Others in Curium connected here β€” coordinate before approaching:</div>'
'<ul style="margin:4px 0 0 0;font-size:0.84em;color:#37474f;">'
+ "".join(lines) + '</ul>'
)
rows_html += f"""
<div style="border-left:4px solid #1a237e;padding:10px 16px;margin:14px 0;background:#fafafa;">
<div style="font-weight:700;color:#1a237e;font-size:1.05em;">{it['organisation']}</div>
<div style="font-size:0.9em;color:#333;margin:4px 0;">{it['signal']}</div>
<div style="font-size:0.86em;color:#546e7a;margin:4px 0;">🎯 <em>{it['hook']}</em></div>
<div style="font-size:0.88em;margin-top:6px;">Your route in:</div>
<ul style="margin:4px 0 0 0;font-size:0.88em;">{contacts_html}</ul>
{others_html}
</div>"""
html = f"""
<div style="font-family:Calibri,Arial,sans-serif;max-width:640px;margin:0 auto;">
<h2 style="color:#1a237e;border-bottom:2px solid #1a237e;padding-bottom:6px;">
🎯 Validated opportunities in your network</h2>
<p>Hi {colleague},</p>
<p>A LinkedIn job-alert search surfaced UK companies actively hiring
<strong>Heads of Change, Transformation Managers and Programme leaders</strong> β€”
which means they have more transformation work than they can staff. We
cross-referenced them against your network and the platform's tracked
signals. These are the ones where <strong>you have a senior route in</strong>:</p>
{rows_html}
<p style="font-size:0.9em;color:#333;margin-top:18px;">
The job ad is the buying signal. Where others in Curium are also connected,
have a quick word first and plan a coordinated approach β€” a multi-threaded
account beats a single cold message every time. A short, warm note to your
contact ("noticed you're scaling up your transformation team; happy to share
how we help land programmes like this") is a natural opener.</p>
<p style="font-size:0.8em;color:#9e9e9e;margin-top:20px;border-top:1px solid #eee;padding-top:8px;">
Curium Lead Intelligence Β· validated from a live LinkedIn job-alert search,
cross-referenced against your 1st-degree network. Nothing has been sent to
any external contact β€” these are suggestions for you to action.</p>
{fb_prompt}
</div>"""
return subject, html
_SENT_MARKER_KEY = "validated_opps_sent_date" # YYYY-MM-DD UTC
def _already_sent_today() -> bool:
"""Once-per-day guard so redundant cron triggers don't double-send."""
try:
from settings_store import get_setting
from datetime import datetime, timezone
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
return get_setting(_SENT_MARKER_KEY) == today
except Exception:
return False
def _mark_sent_today() -> None:
try:
from settings_store import set_setting
from datetime import datetime, timezone
set_setting(_SENT_MARKER_KEY,
datetime.now(timezone.utc).strftime("%Y-%m-%d"))
except Exception:
pass
def main() -> int:
force = "--force" in sys.argv
# Guard only applies to real sends (not dry-run). Lets us run two
# redundant cron triggers safely β€” first to fire wins, rest no-op.
if not DRY_RUN and not force and _already_sent_today():
print("βœ… Validated-opps email already sent today β€” no-op (cron redundancy).")
return 0
opps = _validated_opps()
if not opps:
print("No validated opportunities found in netnew_opportunities.")
return 1
recipients = weekly_digest.get_team_emails()
sent, skipped = [], []
for r in recipients:
name, email = r["name"], r["email"]
# Build this colleague's items (only orgs where they have a senior contact)
items = []
for o in opps:
contacts = _senior_contacts(name, o["organisation"])
if contacts:
items.append({**o, "contacts": contacts})
if not items:
skipped.append(f"{name} (no warm route)")
continue
subject, html = _build_email(name, items)
if DRY_RUN:
print(f"\n=== {name} <{email}> β€” {len(items)} opportunities ===")
print(subject)
for it in items:
print(f" β€’ {it['organisation']}: {', '.join(c['name'] for c in it['contacts'][:3])}")
sent.append(f"{name} (dry-run, {len(items)} opps)")
continue
result = mailer.send(to_email=email, subject=subject, html=html)
if result.get("success"):
print(f"βœ“ {name} β†’ {email} ({len(items)} opportunities)")
sent.append(f"{name} ({len(items)})")
else:
print(f"βœ— {name} β†’ {result.get('message')}")
skipped.append(f"{name} (send failed)")
# Mark sent (real sends only) so redundant triggers no-op, and push the
# marker back to shared state so the second cron runner sees it.
if not DRY_RUN and sent:
_mark_sent_today()
try:
import state_sync
state_sync.push_state(force=True, verbose=False)
except Exception:
pass
print(f"\nSent: {sent}")
print(f"Skipped: {skipped}")
return 0
if __name__ == "__main__":
raise SystemExit(main())