Spaces:
Sleeping

File size: 13,256 Bytes
a87217c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
"""
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())