""" 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'
  • {c["name"]}' + (f' — {c["position"]}' if c["position"] else "") + '
  • ' 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'
  • {col} knows {names}
  • ' ) others_html = ( '
    ' '🤝 Others in Curium connected here — coordinate before approaching:
    ' '' ) rows_html += f"""
    {it['organisation']}
    {it['signal']}
    🎯 {it['hook']}
    Your route in:
    {others_html}
    """ html = f"""

    🎯 Validated opportunities in your network

    Hi {colleague},

    A LinkedIn job-alert search surfaced UK companies actively hiring Heads of Change, Transformation Managers and Programme leaders — 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 you have a senior route in:

    {rows_html}

    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.

    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.

    {fb_prompt}
    """ 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())