""" Collator Module (collator.py) COMPANY-CENTRIC signal fusion engine. Takes raw signals (jobs, news, tenders) and fuses them into Company Dossiers. """ import sqlite3 import re import json import streamlit as st from datetime import datetime from dataclasses import dataclass, field from typing import Optional from pathlib import Path from dotenv import load_dotenv # Load env env_path = Path(__file__).parent / '.env' load_dotenv(dotenv_path=env_path, override=True) # Fuzzy matching try: from rapidfuzz import fuzz FUZZY_AVAILABLE = True except ImportError: FUZZY_AVAILABLE = False DATABASE = "leads.db" # ============================================================================= # SIGNAL-TO-SERVICE-LINE MAPPING # Maps signal types to TD and CC relevance weights (0.0 to 1.0). # ============================================================================= SIGNAL_SERVICE_MAP = { 'restructuring': {'td': 1.0, 'cc': 0.6}, 'leadership_change': {'td': 0.4, 'cc': 1.0}, 'merger_acquisition': {'td': 1.0, 'cc': 0.7}, 'culture_crisis': {'td': 0.2, 'cc': 1.0}, 'sentiment_poor': {'td': 0.3, 'cc': 1.0}, 'pe_acquisition': {'td': 1.0, 'cc': 0.5}, 'digital_transformation': {'td': 0.8, 'cc': 0.3}, 'new_team': {'td': 0.3, 'cc': 0.9}, 'hiring_surge': {'td': 0.7, 'cc': 0.5}, 'programme_failure': {'td': 1.0, 'cc': 0.3}, 'operating_model_change': {'td': 1.0, 'cc': 0.4}, 'wellbeing_crisis': {'td': 0.1, 'cc': 1.0}, 'ai_readiness_assessment': {'td': 0.9, 'cc': 0.4}, 'ai_implementation_support': {'td': 0.8, 'cc': 0.5}, 'hiring_transformation_roles': {'td': 0.8, 'cc': 0.6}, 'general': {'td': 0.5, 'cc': 0.5}, } # LinkedIn group → service line mapping (for group-specific scoring) LINKEDIN_GROUP_SERVICE_MAP = { 'employee experience and engagement': {'td': 0.3, 'cc': 1.0, 'services': ['culture_diagnostics', 'mindset_behaviour']}, 'hr circle': {'td': 0.3, 'cc': 1.0, 'services': ['culture_diagnostics', 'leadership_strategy']}, 'cipd community': {'td': 0.2, 'cc': 1.0, 'services': ['mindset_behaviour', 'culture_diagnostics']}, 'change management institute': {'td': 1.0, 'cc': 0.5, 'services': ['change_management', 'project_programme_management']}, 'pmo professionals': {'td': 1.0, 'cc': 0.2, 'services': ['project_programme_management', 'tmo_pmo']}, 'uk government digital': {'td': 0.8, 'cc': 0.4, 'services': ['agile_lean', 'change_management']}, 'nhs leaders network': {'td': 0.6, 'cc': 0.8, 'services': ['leadership_strategy', 'change_management']}, 'management consultants network': {'td': 0.7, 'cc': 0.5, 'services': ['change_management', 'operating_models']}, 'leadership development network': {'td': 0.3, 'cc': 1.0, 'services': ['executive_coaching', 'leadership_strategy']}, 'm&a integration professionals': {'td': 1.0, 'cc': 0.5, 'services': ['ma_integration', 'change_management']}, } # ============================================================================= # SCORING WEIGHTS # ============================================================================= SCORE_WEIGHTS = { # ================================================================= # SCORING PHILOSOPHY: Two-tier system # - CORE signals (jobs, transformation news, restructuring) can reach 60pts # - SUPPORTING signals (sentiment, M&A, network, reports) add up to 40pts # - This prevents weak signal stacking from inflating scores # ================================================================= # Core transformation signals (max ~60 combined) 'job_signal': 15, # Has a relevant job posting 'news_signal': 15, # Has transformation news 'tender_signal': 10, # Has relevant tender # Core news type bonuses (only ONE applies — strongest wins) 'restructuring_news': 20, # Restructuring = urgent need 'leadership_change': 15, # New CEO/leadership = new initiatives 'ai_automation_news': 15, # AI/automation workforce impact 'closure_news': 15, # Branch/office closures = operational transformation 'appointment_news': 10, # New C-suite = change coming 'digital_news': 15, # Digital transformation initiatives # Core combo (only ONE combo bonus applies) 'job_plus_news': 20, # Job + News = transformation in progress # Job quality bonuses 'high_score_job': 15, # Job score >= 80 'multiple_jobs': 8, # Multiple job postings 'multiple_news': 5, # Multiple news articles 'urgent_tender': 10, # Urgent deadline tender # Supporting signals (max ~40 combined, capped in code) # Network bonuses 'network_tier1': 25, # Direct role connection (was 50 — too dominant) 'network_tier2': 15, # Senior connection 'network_tier3': 8, # Company connection # Annual report signals 'annual_report_signal': 8, # Has annual report with transformation signals 'annual_report_strong': 15, # Strong annual report signal (score >= 60) 'annual_report_plus_job': 10, # Annual report + job combo # Employee sentiment signals 'sentiment_poor': 15, # Rating < 3.0 — active morale crisis (was 35) 'sentiment_warning': 8, # Rating 3.0–3.5 — warning signs (was 20) 'management_crisis': 10, # Management sub-rating < 2.5 (was 25) 'sentiment_plus_job': 10, # Poor sentiment + job hiring (was 20) # PE/M&A deal signals — supporting context only (was 40/30) 'pe_acquisition': 15, # PE buyout confirmed 'trade_acquisition': 10, # Trade acquisition 'recent_acquisition': 5, # Deal within 90 days 'pe_plus_job': 10, # PE deal + transformation job posting (was 25) 'merger_acquisition': 10, # M&A news (was 30) # LinkedIn intelligence bonuses 'linkedin_strong_relationship': 20, # Relationship score >= 80 (was 40) 'linkedin_warm_relationship': 10, # Relationship score 60-79 (was 20) 'linkedin_transformation_post': 10, # Contact posting about transformation 'linkedin_intel_plus_job': 10, # LinkedIn intel + job posting combo (was 25) 'linkedin_multiple_contacts': 5, # 3+ contacts at same company # LinkedIn groups bonuses 'linkedin_group_signal': 8, # Active in a relevant LinkedIn group (was 15) 'linkedin_group_multi': 5, # Appears in 2+ groups 'linkedin_group_plus_job': 10, # Group activity + job posting combo (was 20) } # ============================================================================= # DATABASE SCHEMA # ============================================================================= def init_company_db(): """Initialize company-centric database schema.""" conn = sqlite3.connect(DATABASE) cursor = conn.cursor() # Master company table cursor.execute(""" CREATE TABLE IF NOT EXISTS companies ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, name_normalized TEXT NOT NULL, sector TEXT, overall_score INTEGER DEFAULT 0, signal_summary TEXT, network_status TEXT, best_contact TEXT, best_colleague TEXT, first_seen TEXT NOT NULL, last_updated TEXT NOT NULL, UNIQUE(name_normalized) ) """) # Job signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_jobs ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, job_title TEXT, job_score INTEGER, job_analysis TEXT, job_url TEXT, source TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # News signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_news ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, headline TEXT, news_score INTEGER, trigger_type TEXT, reason TEXT, urgency TEXT, news_url TEXT, source TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # Tender signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_tenders ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, title TEXT, value REAL, deadline TEXT, days_to_deadline INTEGER, is_urgent INTEGER, matched_keywords TEXT, tender_url TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # Network signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_network ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, contact_name TEXT, contact_position TEXT, colleague_name TEXT, connection_tier TEXT, match_score REAL, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # Annual report signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_annual_reports ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, company_number TEXT, filing_date TEXT, report_score INTEGER, signals_found TEXT, summary TEXT, key_quotes TEXT, urgency TEXT, document_url TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # Employee sentiment signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_sentiment ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, overall_rating REAL, management_rating REAL, culture_rating REAL, work_life_rating REAL, review_count INTEGER, sentiment_score INTEGER, signal_reason TEXT, source_url TEXT, source TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # PE/M&A deal signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_pe_deals ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, acquirer_name TEXT, is_pe_deal INTEGER DEFAULT 0, deal_type TEXT, deal_date TEXT, deal_value TEXT, source_url TEXT, source TEXT, pe_score INTEGER, signal_reason TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # LinkedIn intelligence signals linked to companies cursor.execute(""" CREATE TABLE IF NOT EXISTS signals_linkedin_intel ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, contact_name TEXT, contact_title TEXT, contact_url TEXT, colleague_name TEXT, connection_degree INTEGER, relationship_score INTEGER, relationship_tier TEXT, recommended_action TEXT, mutual_connections INTEGER, contact_active INTEGER DEFAULT 0, posts_about_transformation INTEGER DEFAULT 0, last_interaction_days INTEGER, intel_source TEXT, date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) # Indexes cursor.execute("CREATE INDEX IF NOT EXISTS idx_companies_score ON companies(overall_score DESC)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_companies_name ON companies(name_normalized)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_jobs_company ON signals_jobs(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_news_company ON signals_news(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_tenders_company ON signals_tenders(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_network_company ON signals_network(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_annual_reports_company ON signals_annual_reports(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_sentiment_company ON signals_sentiment(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_pe_deals_company ON signals_pe_deals(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_linkedin_intel_company ON signals_linkedin_intel(company_id)") # Follow-up tracking table cursor.execute(""" CREATE TABLE IF NOT EXISTS follow_ups ( id INTEGER PRIMARY KEY AUTOINCREMENT, company TEXT NOT NULL, company_id INTEGER, contact TEXT, channel TEXT DEFAULT 'email', stage TEXT DEFAULT 'drafted', last_action_date TEXT, next_action_date TEXT, notes TEXT, created_at TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_followups_next ON follow_ups(next_action_date)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_followups_stage ON follow_ups(stage)") # Source health tracking table cursor.execute(""" CREATE TABLE IF NOT EXISTS source_health ( id INTEGER PRIMARY KEY AUTOINCREMENT, source_name TEXT NOT NULL UNIQUE, last_scan_at TEXT, status TEXT DEFAULT 'never_run', last_error TEXT, records_found INTEGER DEFAULT 0, total_records INTEGER DEFAULT 0, api_key_set INTEGER DEFAULT 0, api_key_name TEXT ) """) # Add Companies House verification columns (safe to run on existing DB) try: cursor.execute("ALTER TABLE companies ADD COLUMN ch_verified INTEGER DEFAULT 0") except sqlite3.OperationalError: pass # Column already exists try: cursor.execute("ALTER TABLE companies ADD COLUMN ch_company_size TEXT DEFAULT ''") except sqlite3.OperationalError: pass try: cursor.execute("ALTER TABLE companies ADD COLUMN ch_status TEXT DEFAULT ''") except sqlite3.OperationalError: pass # Seed all 8 sources if not present for src in ['jobs', 'news', 'tenders', 'annual_reports', 'sentiment', 'pe_deals', 'linkedin_groups', 'linkedin_intel']: cursor.execute( "INSERT OR IGNORE INTO source_health (source_name) VALUES (?)", (src,) ) conn.commit() conn.close() # Schema migration: add td_score, cc_score, recommended_services columns _migrate_service_columns() # Schema migration: extracted-facts enrichment (Phase 1 quality upgrade) _migrate_extracted_facts() # Schema migration: macro_pulse (Phase 2 — UK macro indicator cache) _migrate_macro_pulse() # Schema migration: weekly_themes (Phase 3 — cross-sector theme cache) _migrate_weekly_themes() # Schema migration: feedback closed loop (recipient replies → digest) _migrate_feedback() # Schema migration: lead actions (dashboard one-click feedback) _migrate_lead_actions() PIPELINE_STAGES = [ "new", "researching", "ready_to_approach", "approached", "in_conversation", "won", "lost", "parked" ] PIPELINE_STAGE_LABELS = { "new": "New", "researching": "Researching", "ready_to_approach": "Ready to Approach", "approached": "Approached", "in_conversation": "In Conversation", "won": "Won", "lost": "Lost", "parked": "Parked", } def _migrate_service_columns(): """Add service-line scoring and pipeline columns to companies table if missing.""" conn = sqlite3.connect(DATABASE) cursor = conn.cursor() migrations = [ ("td_score", "ALTER TABLE companies ADD COLUMN td_score INTEGER DEFAULT 0"), ("cc_score", "ALTER TABLE companies ADD COLUMN cc_score INTEGER DEFAULT 0"), ("recommended_services", "ALTER TABLE companies ADD COLUMN recommended_services TEXT"), ("pipeline_stage", "ALTER TABLE companies ADD COLUMN pipeline_stage TEXT DEFAULT 'new'"), ] for col_name, sql in migrations: try: cursor.execute(sql) except sqlite3.OperationalError: pass # Column already exists conn.commit() conn.close() def _migrate_extracted_facts(): """Phase 1 quality upgrade: structured facts/quotes/confidence on signals. Adds optional enrichment columns to signals_news and signals_jobs and a canonical signal_facts table so downstream digest/briefing modules can pull £/$ figures, exec quotes, and confidence flags directly rather than re-parsing free text. """ conn = sqlite3.connect(DATABASE) cursor = conn.cursor() column_migrations = [ ("signals_news", "quantified_facts", "ALTER TABLE signals_news ADD COLUMN quantified_facts TEXT"), ("signals_news", "executive_quotes", "ALTER TABLE signals_news ADD COLUMN executive_quotes TEXT"), ("signals_news", "news_confidence", "ALTER TABLE signals_news ADD COLUMN news_confidence TEXT"), ("signals_news", "impact_scope", "ALTER TABLE signals_news ADD COLUMN impact_scope TEXT"), ("signals_jobs", "quantified_facts", "ALTER TABLE signals_jobs ADD COLUMN quantified_facts TEXT"), ("signals_jobs", "executive_quotes", "ALTER TABLE signals_jobs ADD COLUMN executive_quotes TEXT"), ("signals_jobs", "impact_scope", "ALTER TABLE signals_jobs ADD COLUMN impact_scope TEXT"), ] for _table, _col, sql in column_migrations: try: cursor.execute(sql) except sqlite3.OperationalError: pass # column already exists cursor.execute(""" CREATE TABLE IF NOT EXISTS signal_facts ( id INTEGER PRIMARY KEY AUTOINCREMENT, company_id INTEGER NOT NULL, signal_table TEXT NOT NULL, -- 'signals_news' | 'signals_jobs' | ... signal_id INTEGER NOT NULL, -- FK into the relevant signals_* table fact_type TEXT, -- 'investment' | 'headcount' | 'revenue' | 'margin' | 'timeline' | 'quote' | 'contract_value' | 'other' label TEXT, -- short human label, e.g. 'Q1 revenue', 'jobs at risk' value_numeric REAL, -- parsed numeric where possible value_text TEXT, -- original textual value (e.g. '$4,716m', '275') currency TEXT, -- 'GBP' | 'USD' | 'EUR' | NULL unit TEXT, -- 'm' | 'bn' | 'people' | '%' | NULL actor_name TEXT, -- exec name (for fact_type='quote') actor_title TEXT, -- exec title quote_text TEXT, -- full quote (for fact_type='quote') confidence TEXT, -- 'official' | 'confirmed' | 'rumour' | 'unknown' source_text TEXT, -- original sentence the fact was lifted from date_found TEXT NOT NULL, FOREIGN KEY (company_id) REFERENCES companies(id) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_signal_facts_company ON signal_facts(company_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_signal_facts_signal ON signal_facts(signal_table, signal_id)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_signal_facts_type ON signal_facts(fact_type)") conn.commit() conn.close() def _migrate_macro_pulse(): """Phase 2: cache for the UK macro indicator pack used by the weekly digest (gilt yields, BoE rate, distress index, hiring outlook, etc.). One row per (week_start, indicator). Re-running for the same week upserts. Bullets are stored as structured JSON so the digest can pick the top 4-6 by relevance without re-running the LLM.""" conn = sqlite3.connect(DATABASE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS macro_pulse ( id INTEGER PRIMARY KEY AUTOINCREMENT, week_start TEXT NOT NULL, -- ISO Monday of the week category TEXT, -- 'rates' | 'labour' | 'distress' | 'sector' | 'sentiment' | 'other' indicator TEXT NOT NULL, -- e.g. 'BoE base rate', '30-yr gilt yield' value_text TEXT, -- e.g. '5.77%', '3.75%', '£250m savings' value_numeric REAL, unit TEXT, change_text TEXT, -- e.g. 'highest since 1998', '+36.9% YoY' implication TEXT, -- 1-sentence Curium-relevant interpretation source TEXT, source_url TEXT, generated_at TEXT NOT NULL, UNIQUE(week_start, indicator) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_macro_pulse_week ON macro_pulse(week_start)") conn.commit() conn.close() def _migrate_weekly_themes(): """Phase 3: cache for the cross-sector themes the digest leads with. A theme is a named pattern (e.g. 'Forward-Deployed Engineers', 'Mid-market AI consolidation', 'Big-bank cost programmes') that spans 2+ companies in a single week. Each theme stores its supporting evidence as JSON so the digest can render it without re-running the LLM.""" conn = sqlite3.connect(DATABASE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS weekly_themes ( id INTEGER PRIMARY KEY AUTOINCREMENT, week_start TEXT NOT NULL, slug TEXT NOT NULL, -- short stable id, e.g. 'fde-rollouts' title TEXT NOT NULL, -- 'Forward-Deployed Engineers' theme_type TEXT, -- 'ai' | 'sector' | 'macro' | 'people' | 'other' sectors TEXT, -- JSON array of sector slugs touched companies TEXT, -- JSON array of company names cited summary TEXT, -- 2-3 sentence narrative evidence TEXT, -- JSON array of {company, fact, source_url} curium_relevance TEXT, -- 1-2 sentences linking to TD / CC / CODE 3i confidence TEXT, -- 'strong' | 'emerging' | 'speculative' generated_at TEXT NOT NULL, UNIQUE(week_start, slug) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_weekly_themes_week ON weekly_themes(week_start)") conn.commit() conn.close() def _migrate_lead_actions(): """One-click lead actions from the dashboard — thumbs up/down, actioned, converted. Feeds the weekly digest recap and long-term signal scoring.""" conn = sqlite3.connect(DATABASE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS lead_actions ( id INTEGER PRIMARY KEY AUTOINCREMENT, company TEXT NOT NULL, colleague TEXT NOT NULL, action TEXT NOT NULL, -- 'actioned' | 'converted' | 'not_relevant' | 'warm' | 'parked' notes TEXT, created_at TEXT NOT NULL ) """) cursor.execute(""" CREATE INDEX IF NOT EXISTS idx_lead_actions_company ON lead_actions(company, colleague) """) conn.commit() conn.close() def add_lead_action(company: str, colleague: str, action: str, notes: str = "") -> int: """Record a one-click action on a lead. Returns the new row id.""" _migrate_lead_actions() from datetime import datetime as _dt with sqlite3.connect(DATABASE) as conn: cur = conn.execute( "INSERT INTO lead_actions (company, colleague, action, notes, created_at) " "VALUES (?, ?, ?, ?, ?)", (company.strip(), colleague.strip(), action.strip(), (notes or "").strip(), _dt.utcnow().isoformat(timespec="seconds") + "Z"), ) conn.commit() return cur.lastrowid or 0 def get_lead_actions(days: int = 30) -> list[dict]: """Return all lead actions in the last `days` days, newest first.""" _migrate_lead_actions() cutoff = ( __import__("datetime").datetime.utcnow() - __import__("datetime").timedelta(days=days) ).isoformat(timespec="seconds") + "Z" with sqlite3.connect(DATABASE) as conn: conn.row_factory = sqlite3.Row rows = conn.execute( "SELECT * FROM lead_actions WHERE created_at >= ? ORDER BY created_at DESC", (cutoff,), ).fetchall() return [dict(r) for r in rows] def get_company_actions(company: str) -> list[dict]: """Return all actions ever recorded for a specific company.""" _migrate_lead_actions() with sqlite3.connect(DATABASE) as conn: conn.row_factory = sqlite3.Row rows = conn.execute( "SELECT * FROM lead_actions WHERE company = ? ORDER BY created_at DESC", (company,), ).fetchall() return [dict(r) for r in rows] def _migrate_feedback(): """Closed-loop feedback: recipient replies → ingested → digested. Two tables: - feedback_messages: raw inbox messages we've pulled via Graph. Keyed on message_id so re-polls are idempotent. - feedback_signals: LLM-parsed structured records (one or more per message). These are what feedback_digest.py summarises into the next week's digest header. """ conn = sqlite3.connect(DATABASE) cursor = conn.cursor() cursor.execute(""" CREATE TABLE IF NOT EXISTS feedback_messages ( id INTEGER PRIMARY KEY AUTOINCREMENT, message_id TEXT UNIQUE NOT NULL, -- Graph message id (or generated for non-Graph sources) sender TEXT, -- email address that replied sender_name TEXT, subject TEXT, body_text TEXT, received_at TEXT, -- ISO timestamp from the mailbox ingested_at TEXT NOT NULL, parsed INTEGER DEFAULT 0 -- 1 once feedback_signals rows exist ) """) cursor.execute(""" CREATE TABLE IF NOT EXISTS feedback_signals ( id INTEGER PRIMARY KEY AUTOINCREMENT, message_id INTEGER, -- FK to feedback_messages.id recipient TEXT, -- which team_email name this came from (matched on sender) sentiment TEXT, -- 'positive' | 'negative' | 'neutral' target_type TEXT, -- 'lead' | 'theme' | 'macro' | 'general' target_token TEXT, -- lead-bentley-2026w20 | theme-fde-rollouts | NULL target_label TEXT, -- human-readable thing it referred to suggestion TEXT, -- the actual ask / preference / complaint applied_at TEXT, -- NULL until the system reflects this back received_at TEXT NOT NULL, FOREIGN KEY (message_id) REFERENCES feedback_messages(id) ) """) cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_msgs_received " "ON feedback_messages(received_at DESC)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_signals_target " "ON feedback_signals(target_type, target_token)") cursor.execute("CREATE INDEX IF NOT EXISTS idx_feedback_signals_received " "ON feedback_signals(received_at DESC)") conn.commit() conn.close() def _store_signal_facts(company_id: int, signal_table: str, signal_id: int, quantified_facts: list | None, executive_quotes: list | None) -> None: """Persist structured extracted facts/quotes for a signal. Tolerant to missing/malformed input — never raises into the caller's transaction. Each entry in quantified_facts is expected to be a dict with optional keys: fact_type, label, value (str or number), currency, unit, confidence, source_text. Each entry in executive_quotes is a dict with: name, title, quote, confidence, source_text. """ if not company_id or not signal_id: return rows = [] now = datetime.now().isoformat() for f in (quantified_facts or []): if not isinstance(f, dict): continue raw_value = f.get("value") value_numeric = None value_text = None if isinstance(raw_value, (int, float)): value_numeric = float(raw_value) value_text = str(raw_value) elif raw_value is not None: value_text = str(raw_value)[:200] try: cleaned = re.sub(r"[^0-9.\-]", "", value_text) value_numeric = float(cleaned) if cleaned not in ("", "-", ".") else None except (ValueError, TypeError): value_numeric = None rows.append(( company_id, signal_table, signal_id, (f.get("fact_type") or "other")[:40], (f.get("label") or "")[:200], value_numeric, value_text, (f.get("currency") or None), (f.get("unit") or None), None, None, None, (f.get("confidence") or "unknown")[:20], (f.get("source_text") or "")[:500], now, )) for q in (executive_quotes or []): if not isinstance(q, dict): continue rows.append(( company_id, signal_table, signal_id, "quote", (q.get("title") or q.get("name") or "")[:200], None, None, None, None, (q.get("name") or "")[:120], (q.get("title") or "")[:200], (q.get("quote") or "")[:1000], (q.get("confidence") or "unknown")[:20], (q.get("source_text") or q.get("quote") or "")[:500], now, )) if not rows: return try: conn = get_connection() conn.executemany(""" INSERT INTO signal_facts ( company_id, signal_table, signal_id, fact_type, label, value_numeric, value_text, currency, unit, actor_name, actor_title, quote_text, confidence, source_text, date_found ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, rows) conn.commit() conn.close() except sqlite3.Error as e: print(f"signal_facts insert failed (non-fatal): {e}") def get_connection(): return sqlite3.connect(DATABASE) # ============================================================================= # COMPANY NAME NORMALIZATION & MATCHING # ============================================================================= def normalize_company_name(name: str) -> str: """Normalize company name for matching.""" if not name: return "" normalized = name.strip().upper() # Remove common suffixes suffixes = [ ' PLC', ' LTD', ' LIMITED', ' GROUP', ' HOLDINGS', ' INC', ' CORP', ' CORPORATION', ' UK', ' (UK)', ' INTERNATIONAL', ' INT\'L', ' & CO', ' AND CO', ' CO.', ' LLC', ' LLP' ] for suffix in suffixes: if normalized.endswith(suffix): normalized = normalized[:-len(suffix)].strip() # Remove punctuation normalized = re.sub(r'[^\w\s]', '', normalized) # Collapse whitespace normalized = ' '.join(normalized.split()) return normalized def match_company_name(name1: str, name2: str, threshold: int = 80) -> bool: """Check if two company names match.""" norm1 = normalize_company_name(name1) norm2 = normalize_company_name(name2) # Exact match if norm1 == norm2: return True # Fuzzy match if FUZZY_AVAILABLE: score = fuzz.ratio(norm1, norm2) if score >= threshold: return True # Also try token sort for different word orders score = fuzz.token_sort_ratio(norm1, norm2) if score >= threshold: return True return False def find_or_create_company(name: str, sector: str = None) -> int: """Find existing company or create new one. Returns company_id.""" if not name: return None normalized = normalize_company_name(name) if not normalized: return None conn = get_connection() cursor = conn.cursor() # Try exact normalized match first cursor.execute("SELECT id FROM companies WHERE name_normalized = ?", (normalized,)) result = cursor.fetchone() if result: conn.close() return result[0] # Try fuzzy match against existing companies if FUZZY_AVAILABLE: cursor.execute("SELECT id, name_normalized FROM companies") existing = cursor.fetchall() for company_id, existing_norm in existing: if match_company_name(name, existing_norm): conn.close() return company_id # Create new company now = datetime.now().isoformat() cursor.execute(""" INSERT INTO companies (name, name_normalized, sector, first_seen, last_updated) VALUES (?, ?, ?, ?, ?) """, (name, normalized, sector, now, now)) company_id = cursor.lastrowid conn.commit() conn.close() return company_id # ============================================================================= # SIGNAL DEDUPLICATION # ============================================================================= def _is_duplicate_signal(cursor, table: str, company_id: int, match_column: str, match_value: str, days: int = 30) -> bool: """Check if a duplicate signal already exists within the given time window. Args: cursor: Active database cursor table: Signal table name (signals_jobs, signals_news, etc.) company_id: Company to check against match_column: Column to match on (e.g. 'headline', 'job_title') match_value: Value to check for duplicates days: Time window in days to check for duplicates """ from datetime import timedelta cutoff = (datetime.now() - timedelta(days=days)).isoformat() cursor.execute( f"SELECT id FROM {table} WHERE company_id = ? AND {match_column} = ? AND date_found >= ? LIMIT 1", (company_id, match_value, cutoff) ) return cursor.fetchone() is not None # ============================================================================= # SIGNAL INGESTION # ============================================================================= def add_job_signal(company_name: str, job_title: str, job_score: int, job_analysis: str, job_url: str, source: str = "indeed_uk", quantified_facts: list | None = None, executive_quotes: list | None = None, impact_scope: str | None = None): """Add a job signal for a company. Optional `quantified_facts` / `executive_quotes` / `impact_scope` carry structured extraction output from brain.analyze_opportunity (Phase 1 quality upgrade). Stored both on the row and decomposed into signal_facts so downstream digests can pull them directly. """ company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: skip if same job_title for this company within 14 days if _is_duplicate_signal(cursor, 'signals_jobs', company_id, 'job_title', job_title, days=14): conn.close() return company_id cursor.execute(""" INSERT INTO signals_jobs ( company_id, job_title, job_score, job_analysis, job_url, source, date_found, quantified_facts, executive_quotes, impact_scope ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( company_id, job_title, job_score, job_analysis, job_url, source, datetime.now().isoformat(), json.dumps(quantified_facts) if quantified_facts else None, json.dumps(executive_quotes) if executive_quotes else None, impact_scope, )) signal_id = cursor.lastrowid conn.commit() conn.close() if quantified_facts or executive_quotes: _store_signal_facts(company_id, "signals_jobs", signal_id, quantified_facts, executive_quotes) # Recalculate company score recalculate_company_score(company_id) return company_id def add_news_signal(company_name: str, headline: str, news_score: int, trigger_type: str, reason: str, urgency: str, news_url: str, source: str = "gdelt", quantified_facts: list | None = None, executive_quotes: list | None = None, confidence: str | None = None, impact_scope: str | None = None): """Add a news signal for a company. Optional `quantified_facts` / `executive_quotes` / `confidence` / `impact_scope` carry structured extraction output from news_radar.analyze_news_signal (Phase 1 quality upgrade). Backwards-compatible: omitted args mean we behave exactly as before. """ company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: skip if same headline for this company within 30 days if _is_duplicate_signal(cursor, 'signals_news', company_id, 'headline', headline, days=30): conn.close() return company_id cursor.execute(""" INSERT INTO signals_news ( company_id, headline, news_score, trigger_type, reason, urgency, news_url, source, date_found, quantified_facts, executive_quotes, news_confidence, impact_scope ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, ( company_id, headline, news_score, trigger_type, reason, urgency, news_url, source, datetime.now().isoformat(), json.dumps(quantified_facts) if quantified_facts else None, json.dumps(executive_quotes) if executive_quotes else None, confidence, impact_scope, )) signal_id = cursor.lastrowid conn.commit() conn.close() if quantified_facts or executive_quotes: _store_signal_facts(company_id, "signals_news", signal_id, quantified_facts, executive_quotes) recalculate_company_score(company_id) return company_id def add_tender_signal(company_name: str, title: str, value: float, deadline: str, days_to_deadline: int, is_urgent: bool, matched_keywords: str, tender_url: str): """Add a tender signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() if _is_duplicate_signal(cursor, 'signals_tenders', company_id, 'title', title, days=14): conn.close() return company_id cursor.execute(""" INSERT INTO signals_tenders (company_id, title, value, deadline, days_to_deadline, is_urgent, matched_keywords, tender_url, date_found) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) """, (company_id, title, value, deadline, days_to_deadline, 1 if is_urgent else 0, matched_keywords, tender_url, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id def add_network_signal(company_name: str, contact_name: str, contact_position: str, colleague_name: str, connection_tier: str, match_score: float): """Add a network signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Check if this network connection already exists cursor.execute(""" SELECT id FROM signals_network WHERE company_id = ? AND contact_name = ? AND colleague_name = ? """, (company_id, contact_name, colleague_name)) if cursor.fetchone(): conn.close() return company_id # Already exists cursor.execute(""" INSERT INTO signals_network (company_id, contact_name, contact_position, colleague_name, connection_tier, match_score, date_found) VALUES (?, ?, ?, ?, ?, ?, ?) """, (company_id, contact_name, contact_position, colleague_name, connection_tier, match_score, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id def add_annual_report_signal(company_name: str, company_number: str, filing_date: str, report_score: int, signals_found: list, summary: str, key_quotes: list, urgency: str, document_url: str): """Add an annual report signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: check company_id + filing_date cursor.execute(""" SELECT id FROM signals_annual_reports WHERE company_id = ? AND filing_date = ? """, (company_id, filing_date)) if cursor.fetchone(): conn.close() return company_id # Already exists cursor.execute(""" INSERT INTO signals_annual_reports (company_id, company_number, filing_date, report_score, signals_found, summary, key_quotes, urgency, document_url, date_found) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (company_id, company_number, filing_date, report_score, json.dumps(signals_found), summary, json.dumps(key_quotes), urgency, document_url, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id def add_sentiment_signal(company_name: str, overall_rating: float, management_rating: float, culture_rating: float, work_life_rating: float, review_count: int, sentiment_score: int, signal_reason: str, source_url: str, source: str = "indeed_uk"): """Add an employee sentiment signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: check company_id + source cursor.execute(""" SELECT id FROM signals_sentiment WHERE company_id = ? AND source = ? """, (company_id, source)) if cursor.fetchone(): conn.close() return company_id # Already exists cursor.execute(""" INSERT INTO signals_sentiment (company_id, overall_rating, management_rating, culture_rating, work_life_rating, review_count, sentiment_score, signal_reason, source_url, source, date_found) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (company_id, overall_rating, management_rating, culture_rating, work_life_rating, review_count, sentiment_score, signal_reason, source_url, source, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id def add_pe_deal_signal(company_name: str, acquirer_name: str, is_pe_deal: bool, deal_type: str, deal_date: str, deal_value: str, source_url: str, source: str, pe_score: int, signal_reason: str): """Add a PE/M&A deal signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: check company_id + acquirer_name cursor.execute(""" SELECT id FROM signals_pe_deals WHERE company_id = ? AND acquirer_name = ? """, (company_id, acquirer_name)) if cursor.fetchone(): conn.close() return company_id # Already exists cursor.execute(""" INSERT INTO signals_pe_deals (company_id, acquirer_name, is_pe_deal, deal_type, deal_date, deal_value, source_url, source, pe_score, signal_reason, date_found) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (company_id, acquirer_name, 1 if is_pe_deal else 0, deal_type, deal_date, deal_value, source_url, source, pe_score, signal_reason, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id def add_linkedin_intel_signal(company_name: str, contact_name: str, contact_title: str, contact_url: str, colleague_name: str, connection_degree: int, relationship_score: int, relationship_tier: str, recommended_action: str, mutual_connections: int, contact_active: int, posts_about_transformation: int, last_interaction_days: int, intel_source: str = "profile_scan"): """Add a LinkedIn intelligence signal for a company.""" company_id = find_or_create_company(company_name) if not company_id: return None conn = get_connection() cursor = conn.cursor() # Deduplication: check company_id + contact_name + colleague_name cursor.execute(""" SELECT id FROM signals_linkedin_intel WHERE company_id = ? AND contact_name = ? AND colleague_name = ? """, (company_id, contact_name, colleague_name)) if cursor.fetchone(): # Update existing record with new data cursor.execute(""" UPDATE signals_linkedin_intel SET contact_title = ?, contact_url = ?, connection_degree = ?, relationship_score = ?, relationship_tier = ?, recommended_action = ?, mutual_connections = ?, contact_active = ?, posts_about_transformation = ?, last_interaction_days = ?, intel_source = ?, date_found = ? WHERE company_id = ? AND contact_name = ? AND colleague_name = ? """, (contact_title, contact_url, connection_degree, relationship_score, relationship_tier, recommended_action, mutual_connections, contact_active, posts_about_transformation, last_interaction_days, intel_source, datetime.now().isoformat(), company_id, contact_name, colleague_name)) else: cursor.execute(""" INSERT INTO signals_linkedin_intel (company_id, contact_name, contact_title, contact_url, colleague_name, connection_degree, relationship_score, relationship_tier, recommended_action, mutual_connections, contact_active, posts_about_transformation, last_interaction_days, intel_source, date_found) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, (company_id, contact_name, contact_title, contact_url, colleague_name, connection_degree, relationship_score, relationship_tier, recommended_action, mutual_connections, contact_active, posts_about_transformation, last_interaction_days, intel_source, datetime.now().isoformat())) conn.commit() conn.close() recalculate_company_score(company_id) return company_id # ============================================================================= # SCORE CALCULATION - THE FUSION LOGIC # ============================================================================= def _freshness_multiplier(signal_date_str: str) -> float: """Return a decay multiplier based on signal age. Steeper decay than before — old signals should not inflate scores. """ try: signal_date = datetime.fromisoformat(signal_date_str.replace('Z', '+00:00')) signal_date = signal_date.replace(tzinfo=None) except (ValueError, TypeError, AttributeError): return 0.3 # Unknown date: low weight age_days = (datetime.now() - signal_date).days if age_days <= 7: return 1.0 # This week: full weight if age_days <= 14: return 0.9 # Last two weeks if age_days <= 30: return 0.7 # This month if age_days <= 60: return 0.4 # Last 2 months if age_days <= 90: return 0.2 # Last quarter — stale return 0.0 # Expired — hard cutoff at 90 days def _signal_age_days(signal_date_str: str) -> int: """Return the age in days of a signal, or 999 if unparseable.""" try: signal_date = datetime.fromisoformat(signal_date_str.replace('Z', '+00:00')) signal_date = signal_date.replace(tzinfo=None) return (datetime.now() - signal_date).days except (ValueError, TypeError, AttributeError): return 999 # Hard expiry thresholds (days) — signals older than this are ignored SIGNAL_EXPIRY = { 'jobs': 90, 'news': 60, 'tenders': 90, 'sentiment': 180, 'pe_deals': 180, 'annual_reports': 365, } def _best_freshness(dates: list) -> float: """Return the AVERAGE freshness across signals (not max). Using max was causing stale signals to ride on fresh ones. Now each signal contributes proportionally to its own age. """ if not dates: return 0.5 valid = [d for d in dates if d] if not valid: return 0.3 multipliers = [_freshness_multiplier(d) for d in valid] # Use weighted approach: best signal counts more, but stale ones drag down if len(multipliers) == 1: return multipliers[0] best = max(multipliers) avg = sum(multipliers) / len(multipliers) return (best * 0.6) + (avg * 0.4) # Weighted towards best but avg matters def _verify_company_ch(company_id: int, company_name: str) -> dict: """Check Companies House for company status and size. Returns dict with 'valid' (bool), 'status', 'size', 'reason'. Results are cached in the companies table so we only check once. """ conn = get_connection() cursor = conn.cursor() # Check if already verified cursor.execute("SELECT ch_verified, ch_status, ch_company_size FROM companies WHERE id = ?", (company_id,)) row = cursor.fetchone() if row and row[0] == 1: conn.close() rejected = ['dissolved', 'liquidation', 'dormant', 'administration'] is_valid = not any(r in (row[1] or '').lower() for r in rejected) return {'valid': is_valid, 'status': row[1] or '', 'size': row[2] or '', 'reason': ''} # Try to verify via Companies House try: from financials import search_company, REJECTED_STATUSES result = search_company(company_name) if not result: # Not found — could be a trading name, foreign company, etc. Don't reject. cursor.execute("UPDATE companies SET ch_verified = 1, ch_status = 'not_found', ch_company_size = '' WHERE id = ?", (company_id,)) conn.commit() conn.close() return {'valid': True, 'status': 'not_found', 'size': '', 'reason': ''} status = (result.get('company_status', '') or '').lower() accounts_type = (result.get('accounts', {}).get('type', '') or '').lower() if isinstance(result.get('accounts'), dict) else '' # Determine size from accounts type size = 'unknown' if any(s in accounts_type for s in ['micro', 'small']): size = 'small' elif any(s in accounts_type for s in ['medium', 'full', 'group', 'large']): size = 'enterprise' elif accounts_type: size = accounts_type cursor.execute("UPDATE companies SET ch_verified = 1, ch_status = ?, ch_company_size = ? WHERE id = ?", (status, size, company_id)) conn.commit() conn.close() # Check if rejected is_rejected = any(r in status for r in [s.lower() for s in REJECTED_STATUSES]) return {'valid': not is_rejected, 'status': status, 'size': size, 'reason': f'Company status: {status}' if is_rejected else ''} except Exception as e: conn.close() # If CH check fails (e.g. no API key), don't block — just skip verification return {'valid': True, 'status': 'check_failed', 'size': '', 'reason': str(e)} def recalculate_company_score(company_id: int): """Recalculate overall score for a company based on all signals.""" conn = get_connection() cursor = conn.cursor() score = 0 core_score = 0 # Transformation evidence (jobs, news, tenders) — capped at 60 support_score = 0 # Supporting context (sentiment, M&A, network, reports) — capped at 40 signals = [] # Get company name for CH verification cursor.execute("SELECT name FROM companies WHERE id = ?", (company_id,)) company_row = cursor.fetchone() company_name = company_row[0] if company_row else "" # Companies House verification gate ch_result = _verify_company_ch(company_id, company_name) if not ch_result['valid']: # Company is dissolved/dormant/etc — zero it out cursor.execute(""" UPDATE companies SET overall_score = 0, signal_summary = ?, last_updated = ? WHERE id = ? """, (f"CH rejected: {ch_result['reason']}", datetime.now().isoformat(), company_id)) conn.commit() conn.close() return 0 # If company is micro/small, cap their score at 30 (below hot threshold) ch_size_cap = None if ch_result['size'] == 'small': ch_size_cap = 30 signals.append("CH: small company (score capped)") # Get job signals — filter out expired (>90 days old) cursor.execute("SELECT job_title, job_score, date_found FROM signals_jobs WHERE company_id = ?", (company_id,)) jobs = [j for j in cursor.fetchall() if _signal_age_days(j[2]) <= SIGNAL_EXPIRY['jobs']] job_count = len(jobs) if job_count > 0: job_freshness = _best_freshness([j[2] for j in jobs]) core_score += int(SCORE_WEIGHTS['job_signal'] * job_freshness) signals.append(f"{job_count} job(s)") # High score job bonus high_score_jobs = [j for j in jobs if j[1] and j[1] >= 80] if high_score_jobs: core_score += int(SCORE_WEIGHTS['high_score_job'] * job_freshness) signals.append("high-fit role") # Multiple jobs bonus if job_count > 1: core_score += int(SCORE_WEIGHTS['multiple_jobs'] * job_freshness) # Get news signals — filter out expired (>60 days old) cursor.execute("SELECT headline, news_score, trigger_type, urgency, date_found FROM signals_news WHERE company_id = ?", (company_id,)) news = [n for n in cursor.fetchall() if _signal_age_days(n[4]) <= SIGNAL_EXPIRY['news']] news_count = len(news) if news_count > 0: news_freshness = _best_freshness([n[4] for n in news]) core_score += int(SCORE_WEIGHTS['news_signal'] * news_freshness) signals.append(f"{news_count} news") # Check for specific trigger types — only apply BEST matching bonus (not all) trigger_types = [n[2] for n in news if n[2]] best_news_bonus = 0 best_news_label = "" for trigger, weight_key, label in [ ('restructuring', 'restructuring_news', 'restructuring'), ('ai_automation', 'ai_automation_news', 'AI/automation'), ('digital', 'digital_news', 'digital transformation'), ('leadership', 'leadership_change', 'leadership change'), ('closure', 'closure_news', 'closures'), ('appointment', 'appointment_news', 'new appointment'), ('merger', 'merger_acquisition', 'M&A'), ]: if trigger in trigger_types: bonus = int(SCORE_WEIGHTS[weight_key] * news_freshness) if bonus > best_news_bonus: best_news_bonus = bonus best_news_label = label signals.append(label) # Apply only the strongest news type bonus (prevents stacking) core_score += best_news_bonus # Multiple news bonus if news_count > 1: core_score += int(SCORE_WEIGHTS['multiple_news'] * news_freshness) # SIGNAL MULTIPLIER: Job + News = transformation in progress if job_count > 0 and news_count > 0: combo_freshness = max( _best_freshness([j[2] for j in jobs]), _best_freshness([n[4] for n in news]) ) core_score += int(SCORE_WEIGHTS['job_plus_news'] * combo_freshness) signals.append("job+news combo") # Get tender signals — filter expired (>90 days old) cursor.execute("SELECT title, value, is_urgent, date_found FROM signals_tenders WHERE company_id = ?", (company_id,)) tenders = [t for t in cursor.fetchall() if _signal_age_days(t[3]) <= SIGNAL_EXPIRY['tenders']] if tenders: tender_freshness = _best_freshness([t[3] for t in tenders]) core_score += int(SCORE_WEIGHTS['tender_signal'] * tender_freshness) signals.append(f"{len(tenders)} tender(s)") # Urgent tender bonus urgent_tenders = [t for t in tenders if t[2] == 1] if urgent_tenders: core_score += int(SCORE_WEIGHTS['urgent_tender'] * tender_freshness) signals.append("urgent tender") # Get annual report signals — filter expired (>365 days) cursor.execute("SELECT report_score, date_found FROM signals_annual_reports WHERE company_id = ?", (company_id,)) annual_reports = [r for r in cursor.fetchall() if _signal_age_days(r[1]) <= SIGNAL_EXPIRY['annual_reports']] if annual_reports: ar_freshness = _best_freshness([r[1] for r in annual_reports]) report_scores = [r[0] for r in annual_reports if r[0] is not None and r[0] > 0] best_report_score = max(report_scores) if report_scores else 0 if best_report_score >= 60: support_score += int(SCORE_WEIGHTS['annual_report_strong'] * ar_freshness) signals.append("strong annual report signal") else: support_score += int(SCORE_WEIGHTS['annual_report_signal'] * ar_freshness) signals.append("annual report signal") # Combo: annual report + jobs if job_count > 0: support_score += int(SCORE_WEIGHTS['annual_report_plus_job'] * ar_freshness) signals.append("report+job combo") # Get sentiment signals — filter expired (>180 days) cursor.execute("SELECT overall_rating, management_rating, date_found FROM signals_sentiment WHERE company_id = ?", (company_id,)) sentiment_signals = [s for s in cursor.fetchall() if _signal_age_days(s[2]) <= SIGNAL_EXPIRY['sentiment']] if sentiment_signals: sent_freshness = _best_freshness([s[2] for s in sentiment_signals]) ratings = [s[0] for s in sentiment_signals if s[0] is not None and s[0] > 0] best_rating = min(ratings) if ratings else None mgmt_ratings = [s[1] for s in sentiment_signals if s[1] is not None and s[1] > 0] best_mgmt = min(mgmt_ratings) if mgmt_ratings else None if best_rating is not None and best_rating < 3.0: support_score += int(SCORE_WEIGHTS['sentiment_poor'] * sent_freshness) signals.append("poor sentiment") elif best_rating is not None and best_rating < 3.5: support_score += int(SCORE_WEIGHTS['sentiment_warning'] * sent_freshness) signals.append("sentiment warning") if best_mgmt is not None and best_mgmt < 2.5: support_score += int(SCORE_WEIGHTS['management_crisis'] * sent_freshness) signals.append("management crisis") # Combo: sentiment + jobs if job_count > 0 and best_rating is not None and best_rating < 3.5: support_score += int(SCORE_WEIGHTS['sentiment_plus_job'] * sent_freshness) signals.append("sentiment+job combo") # Get PE/M&A deal signals — filter expired (>180 days) cursor.execute("SELECT acquirer_name, is_pe_deal, deal_date, date_found FROM signals_pe_deals WHERE company_id = ?", (company_id,)) pe_signals = [p for p in cursor.fetchall() if _signal_age_days(p[3]) <= SIGNAL_EXPIRY['pe_deals']] if pe_signals: pe_freshness = _best_freshness([p[3] for p in pe_signals]) has_pe = any(p[1] == 1 for p in pe_signals) if has_pe: support_score += int(SCORE_WEIGHTS['pe_acquisition'] * pe_freshness) signals.append("PE acquisition") else: support_score += int(SCORE_WEIGHTS['trade_acquisition'] * pe_freshness) signals.append("trade acquisition") # Recent deal bonus (within 90 days) for _, _, deal_date, _ in pe_signals: if deal_date: try: deal_dt = datetime.fromisoformat(deal_date.replace('Z', '+00:00')) if 'T' in deal_date else datetime.strptime(deal_date[:10], '%Y-%m-%d') days_since = (datetime.now() - deal_dt.replace(tzinfo=None)).days if days_since <= 90: support_score += SCORE_WEIGHTS['recent_acquisition'] signals.append("recent deal") break except (ValueError, TypeError): pass # Combo: PE deal + jobs if job_count > 0: support_score += int(SCORE_WEIGHTS['pe_plus_job'] * pe_freshness) signals.append("PE+job combo") # Get LinkedIn intelligence signals cursor.execute(""" SELECT contact_name, relationship_score, relationship_tier, contact_active, posts_about_transformation FROM signals_linkedin_intel WHERE company_id = ? """, (company_id,)) li_intel = cursor.fetchall() if li_intel: best_rel_score = max(r[1] for r in li_intel if r[1]) if any(r[1] for r in li_intel) else 0 if best_rel_score >= 80: support_score += SCORE_WEIGHTS['linkedin_strong_relationship'] signals.append("LI strong relationship") elif best_rel_score >= 60: support_score += SCORE_WEIGHTS['linkedin_warm_relationship'] signals.append("LI warm relationship") # Contact posting about transformation if any(r[4] == 1 for r in li_intel): support_score += SCORE_WEIGHTS['linkedin_transformation_post'] signals.append("LI transformation posts") # Multiple contacts at company if len(li_intel) >= 3: support_score += SCORE_WEIGHTS['linkedin_multiple_contacts'] signals.append(f"{len(li_intel)} LI contacts") # Combo: LinkedIn intel + job posting if job_count > 0 and best_rel_score >= 60: support_score += SCORE_WEIGHTS['linkedin_intel_plus_job'] signals.append("LI+job combo") # Get LinkedIn group signals (stored as news with source='linkedin_groups') cursor.execute(""" SELECT headline, reason, date_found FROM signals_news WHERE company_id = ? AND source = 'linkedin_groups' """, (company_id,)) li_group_signals = cursor.fetchall() if li_group_signals: lg_freshness = _best_freshness([g[2] for g in li_group_signals]) support_score += int(SCORE_WEIGHTS['linkedin_group_signal'] * lg_freshness) signals.append(f"{len(li_group_signals)} LI group(s)") # Multiple group appearances bonus if len(li_group_signals) >= 2: support_score += int(SCORE_WEIGHTS['linkedin_group_multi'] * lg_freshness) # Group + job combo if job_count > 0: support_score += int(SCORE_WEIGHTS['linkedin_group_plus_job'] * lg_freshness) signals.append("LI group+job combo") # Get network signals cursor.execute("SELECT contact_name, colleague_name, connection_tier FROM signals_network WHERE company_id = ?", (company_id,)) network = cursor.fetchall() best_contact = None best_colleague = None network_status = "Cold" if network: # Find best connection tier tiers = [n[2] for n in network] if 'DIRECT HIT' in tiers: support_score += SCORE_WEIGHTS['network_tier1'] network_status = "🎯 Direct" signals.append("🎯 direct connection") elif 'SENIOR CONNECTION' in tiers: support_score += SCORE_WEIGHTS['network_tier2'] network_status = "⭐ Senior" signals.append("⭐ senior connection") elif 'COMPANY CONNECTION' in tiers: support_score += SCORE_WEIGHTS['network_tier3'] network_status = "🔗 Company" signals.append("🔗 company connection") # Get best contact info (with service-affinity awareness) # Group connections by colleague to enable affinity-based routing colleague_connections = {} for contact, colleague, tier in network: if colleague not in colleague_connections or tier == 'DIRECT HIT': colleague_connections[colleague] = (contact, tier) if len(colleague_connections) > 1: # Multiple colleagues have connections — route by service affinity try: from network_loader import _get_team_service_focus team_focus = _get_team_service_focus() except ImportError: team_focus = {} # We'll use td_score_val and cc_score_val later, but they're not # computed yet. Use signal heuristics instead: td_signals = sum(1 for s in signals if any(kw in s for kw in ['restructuring', 'M&A', 'PE', 'programme', 'pmo', 'operating'])) cc_signals = sum(1 for s in signals if any(kw in s for kw in ['leadership', 'sentiment', 'culture', 'coaching', 'wellbeing'])) dominant = None if td_signals > cc_signals + 1: dominant = 'transformation_delivery' elif cc_signals > td_signals + 1: dominant = 'culture_capability' if dominant: # Prefer colleague whose focus matches the dominant need scored = [] for coll, (cont, tier) in colleague_connections.items(): focus = team_focus.get(coll.lower(), []) affinity = 1 if dominant in focus else 0 tier_val = 0 if tier == 'DIRECT HIT' else (1 if tier == 'SENIOR CONNECTION' else 2) scored.append((tier_val, -affinity, coll, cont)) scored.sort() best_colleague = scored[0][2] best_contact = scored[0][3] else: # No clear dominant — pick best tier for contact, colleague, tier in network: if tier == 'DIRECT HIT' or (not best_contact): best_contact = contact best_colleague = colleague else: for contact, colleague, tier in network: if tier == 'DIRECT HIT' or (not best_contact): best_contact = contact best_colleague = colleague # ================================================================= # TEMPORAL URGENCY SCORING # ================================================================= from datetime import timedelta now = datetime.now() # Collect all signal dates for clustering analysis all_signal_dates = [] for j in jobs: if j[2]: # date_found try: all_signal_dates.append(datetime.fromisoformat(j[2].replace('Z', '+00:00')).replace(tzinfo=None)) except (ValueError, TypeError): pass for n in news: if n[4]: # date_found try: all_signal_dates.append(datetime.fromisoformat(n[4].replace('Z', '+00:00')).replace(tzinfo=None)) except (ValueError, TypeError): pass # Signal clustering: 3+ signals within 14 days = things are moving fast if all_signal_dates: recent_14d = [d for d in all_signal_dates if (now - d).days <= 14] if len(recent_14d) >= 3: score += 15 signals.append("signal cluster (3+ in 14d)") # Leadership change + restructuring within 30 days = new leader reshaping org if news_count > 0: news_trigger_dates = {} for n in news: tt, date_str = n[2], n[4] if tt and date_str: try: dt = datetime.fromisoformat(date_str.replace('Z', '+00:00')).replace(tzinfo=None) if (now - dt).days <= 30: news_trigger_dates.setdefault(tt, []).append(dt) except (ValueError, TypeError): pass has_recent_leadership = 'leadership' in news_trigger_dates or 'appointment' in news_trigger_dates has_recent_restructuring = 'restructuring' in news_trigger_dates if has_recent_leadership and has_recent_restructuring: score += 20 signals.append("leadership+restructuring combo") # M&A + integration signals within 60 days has_recent_merger = 'merger' in news_trigger_dates if not has_recent_merger and pe_signals: for _, _, deal_date, _ in pe_signals: if deal_date: try: deal_dt = datetime.fromisoformat(deal_date.replace('Z', '+00:00')) if 'T' in deal_date else datetime.strptime(deal_date[:10], '%Y-%m-%d') if (now - deal_dt.replace(tzinfo=None)).days <= 60: has_recent_merger = True break except (ValueError, TypeError): pass has_recent_integration = any( 'integration' in (j[0] or '').lower() or 'merger' in (j[0] or '').lower() for j in jobs if j[2] and _freshness_multiplier(j[2]) >= 0.8 # within ~30 days ) if has_recent_merger and has_recent_integration: score += 15 signals.append("M&A+integration combo") # ================================================================= # DUAL SERVICE-LINE SCORING (TD and CC) # ================================================================= td_score_val = 0 cc_score_val = 0 all_recommended_services = set() # Collect signal types from news # Map short trigger types (as stored in DB) to SIGNAL_SERVICE_MAP keys TRIGGER_TO_SIGNAL = { 'leadership': 'leadership_change', 'merger': 'merger_acquisition', 'digital': 'digital_transformation', 'ai_automation': 'digital_transformation', 'appointment': 'leadership_change', 'closure': 'restructuring', } detected_signal_types = set() if news_count > 0: trigger_types = [n[2] for n in news if n[2]] for tt in trigger_types: if tt in SIGNAL_SERVICE_MAP: detected_signal_types.add(tt) elif tt in TRIGGER_TO_SIGNAL: detected_signal_types.add(TRIGGER_TO_SIGNAL[tt]) # Collect signal types from jobs (via job_analysis JSON) for job in jobs: job_analysis_text = job[1] # job_score field - we'll also check analysis # Check if job analysis contains service info (from brain.py) # Simple heuristic based on job title keywords job_title = (job[0] or '').lower() if any(kw in job_title for kw in ['programme', 'pmo', 'project', 'delivery', 'integration', 'operating model', 'agile']): td_score_val += 15 if any(kw in job_title for kw in ['leadership', 'culture', 'coaching', 'wellbeing', 'engagement', 'people', 'od ', 'organisational development', 'team effectiveness']): cc_score_val += 15 if any(kw in job_title for kw in ['change', 'transformation']): td_score_val += 8 cc_score_val += 8 # Apply signal-service map weights for sig_type in detected_signal_types: weights = SIGNAL_SERVICE_MAP.get(sig_type, {'td': 0.5, 'cc': 0.5}) td_score_val += int(15 * weights['td']) cc_score_val += int(15 * weights['cc']) # Sentiment signals boost CC strongly if sentiment_signals: _sl_ratings = [s[0] for s in sentiment_signals if s[0] is not None and s[0] > 0] _sl_best = min(_sl_ratings) if _sl_ratings else None if _sl_best is not None and _sl_best < 3.0: w = SIGNAL_SERVICE_MAP.get('sentiment_poor', {'td': 0.3, 'cc': 1.0}) td_score_val += int(20 * w['td']) cc_score_val += int(20 * w['cc']) elif _sl_best is not None and _sl_best < 3.5: w = SIGNAL_SERVICE_MAP.get('sentiment_poor', {'td': 0.3, 'cc': 1.0}) td_score_val += int(10 * w['td']) cc_score_val += int(10 * w['cc']) # PE/M&A signals boost TD strongly if pe_signals: w = SIGNAL_SERVICE_MAP.get('pe_acquisition', {'td': 1.0, 'cc': 0.5}) td_score_val += int(25 * w['td']) cc_score_val += int(25 * w['cc']) # Network and LinkedIn boost both proportionally if network: td_score_val += 10 cc_score_val += 10 if li_intel: td_score_val += 5 cc_score_val += 5 # LinkedIn group-specific TD/CC scoring and service recommendations if li_group_signals: for lg in li_group_signals: headline = (lg[0] or '').lower() for group_key, group_info in LINKEDIN_GROUP_SERVICE_MAP.items(): if group_key in headline: td_score_val += int(10 * group_info['td']) cc_score_val += int(10 * group_info['cc']) for svc in group_info.get('services', []): all_recommended_services.add(svc) break # ================================================================= # CROSS-SIGNAL CONVERGENCE PATTERNS # Multi-signal combinations that indicate active transformation # ================================================================= # Collect raw trigger types for convergence checks (these use short names: 'leadership', 'merger', etc.) raw_trigger_types = set(n[2] for n in news if n[2]) if news_count > 0 else set() # Pattern 1: "New leader reshaping culture" # Leadership change + poor sentiment = incoming culture transformation has_leadership = 'leadership' in raw_trigger_types or 'appointment' in raw_trigger_types or 'leadership_change' in detected_signal_types _conv_ratings = [s[0] for s in sentiment_signals if s[0] is not None and s[0] > 0] if sentiment_signals else [] has_poor_sentiment = bool(_conv_ratings) and min(_conv_ratings) < 3.5 if has_leadership and has_poor_sentiment: cc_score_val += 20 td_score_val += 10 signals.append("convergence: leader+sentiment") # Pattern 2: "Restructuring under pressure" # Restructuring + hiring surge (multiple jobs) = active transformation has_restructuring = 'restructuring' in raw_trigger_types or 'restructuring' in detected_signal_types or 'operating_model_change' in detected_signal_types has_hiring_surge = job_count >= 3 if has_restructuring and has_hiring_surge: td_score_val += 20 cc_score_val += 10 signals.append("convergence: restructure+hiring") # Pattern 3: "Post-acquisition integration chaos" # M&A/PE + jobs + sentiment = full transformation opportunity has_ma = 'merger' in raw_trigger_types or 'merger_acquisition' in detected_signal_types or bool(pe_signals) if has_ma and job_count > 0 and has_poor_sentiment: td_score_val += 20 cc_score_val += 20 signals.append("convergence: M&A+jobs+sentiment") # Pattern 4: "Culture crisis with no leadership" # Culture crisis + wellbeing issues + no leadership change = needs external help has_culture_crisis = 'culture_crisis' in detected_signal_types or 'wellbeing_crisis' in detected_signal_types or 'culture' in raw_trigger_types if has_culture_crisis and has_poor_sentiment and not has_leadership: cc_score_val += 25 signals.append("convergence: culture crisis (no leader)") # Pattern 5: "Digital transformation people gap" # Digital/AI signals + culture or team jobs = need people-side support has_digital = 'digital_transformation' in detected_signal_types or 'digital' in raw_trigger_types or 'ai_automation' in raw_trigger_types has_people_jobs = any(kw in (j[0] or '').lower() for j in jobs for kw in ['change', 'people', 'culture', 'engagement']) if has_digital and has_people_jobs: cc_score_val += 15 td_score_val += 10 signals.append("convergence: digital+people gap") # Build recommended services list # Also scan job titles for keyword-based service matching all_job_titles_lower = ' '.join((j[0] or '').lower() for j in jobs) if td_score_val >= 20: if any('programme' in (j[0] or '').lower() or 'pmo' in (j[0] or '').lower() for j in jobs): all_recommended_services.add('project_programme_management') if 'restructuring' in detected_signal_types or 'operating_model_change' in detected_signal_types: all_recommended_services.add('operating_models') all_recommended_services.add('change_management') if 'merger_acquisition' in detected_signal_types or pe_signals: all_recommended_services.add('ma_integration') # TMO/PMO: job titles or operating model change signals if any(kw in all_job_titles_lower for kw in ['tmo', 'pmo director', 'portfolio management', 'transformation office']): all_recommended_services.add('tmo_pmo') # Business Analysis: job titles mentioning BA/requirements/process if any(kw in all_job_titles_lower for kw in ['business analyst', 'business analysis', 'requirements', 'process improvement']): all_recommended_services.add('business_analysis') # Agile/Lean: digital transformation or agile job titles if 'digital_transformation' in detected_signal_types or any(kw in all_job_titles_lower for kw in ['agile', 'scrum', 'lean', 'ways of working']): all_recommended_services.add('agile_lean') # Service Desk: ITSM or service desk job titles if any(kw in all_job_titles_lower for kw in ['service desk', 'itsm', 'service management', 'it operations']): all_recommended_services.add('service_desk') if not all_recommended_services & {'project_programme_management', 'operating_models', 'ma_integration', 'tmo_pmo', 'business_analysis', 'agile_lean', 'service_desk'}: all_recommended_services.add('change_management') if cc_score_val >= 20: if 'leadership_change' in detected_signal_types: all_recommended_services.add('executive_coaching') all_recommended_services.add('leadership_strategy') if 'culture_crisis' in detected_signal_types: all_recommended_services.add('culture_diagnostics') all_recommended_services.add('code_3i') all_recommended_services.add('mindset_behaviour') if sentiment_signals: all_recommended_services.add('culture_diagnostics') # Poor management rating → dysfunctional teams / coaching if any(s[1] is not None and s[1] > 0 and s[1] < 2.5 for s in sentiment_signals): all_recommended_services.add('dysfunctional_teams') all_recommended_services.add('one_to_one_coaching') if 'new_team' in detected_signal_types: all_recommended_services.add('team_profiling') all_recommended_services.add('code_3i') all_recommended_services.add('facilitation') if 'wellbeing_crisis' in detected_signal_types: all_recommended_services.add('resilience') all_recommended_services.add('one_to_one_coaching') # Facilitation: strategy/offsite keywords in news if any(kw in all_job_titles_lower for kw in ['facilitation', 'workshop', 'offsite', 'strategy day']): all_recommended_services.add('facilitation') # Resilience: wellbeing/burnout keywords if any(kw in all_job_titles_lower for kw in ['wellbeing', 'resilience', 'mental health', 'burnout']): all_recommended_services.add('resilience') # Coaching: coaching/development keywords if any(kw in all_job_titles_lower for kw in ['coaching', 'personal development', 'performance coach', 'talent development']): all_recommended_services.add('one_to_one_coaching') # Dysfunctional teams: team conflict/dysfunction keywords if any(kw in all_job_titles_lower for kw in ['team conflict', 'team reset', 'team dysfunction']): all_recommended_services.add('dysfunctional_teams') # Mindset/behaviour: values/culture shift keywords if any(kw in all_job_titles_lower for kw in ['behavioural change', 'mindset', 'values programme', 'culture shift', 'psychological safety']): all_recommended_services.add('mindset_behaviour') if not all_recommended_services & {'executive_coaching', 'culture_diagnostics', 'team_profiling', 'facilitation', 'resilience', 'one_to_one_coaching', 'dysfunctional_teams', 'mindset_behaviour'}: all_recommended_services.add('leadership_strategy') # Cap scores using two-tier system: # Core (transformation evidence) capped at 60 # Supporting (context signals) capped at 40 core_score = min(core_score, 60) support_score = min(support_score, 40) score = core_score + support_score # Apply Companies House size cap if company is too small if ch_size_cap is not None: score = min(score, ch_size_cap) td_score_val = min(td_score_val, 100) cc_score_val = min(cc_score_val, 100) recommended_services_json = json.dumps(sorted(all_recommended_services)) # Update company record signal_summary = " | ".join(signals) if signals else "No signals" cursor.execute(""" UPDATE companies SET overall_score = ?, signal_summary = ?, network_status = ?, best_contact = ?, best_colleague = ?, last_updated = ?, td_score = ?, cc_score = ?, recommended_services = ? WHERE id = ? """, (min(score, 100), signal_summary, network_status, best_contact, best_colleague, datetime.now().isoformat(), td_score_val, cc_score_val, recommended_services_json, company_id)) conn.commit() conn.close() return score def recalculate_all_scores(): """Recalculate scores for all companies.""" conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT id FROM companies") companies = cursor.fetchall() conn.close() for (company_id,) in companies: recalculate_company_score(company_id) # ============================================================================= # DOSSIER RETRIEVAL # ============================================================================= @dataclass class CompanyDossier: """Complete dossier for a company.""" id: int name: str overall_score: int signal_summary: str network_status: str best_contact: str best_colleague: str sector: str first_seen: str last_updated: str # Service-line scores td_score: int = 0 cc_score: int = 0 recommended_services: list = field(default_factory=list) # Pipeline stage pipeline_stage: str = "new" # Signal details jobs: list = field(default_factory=list) news: list = field(default_factory=list) tenders: list = field(default_factory=list) network: list = field(default_factory=list) annual_reports: list = field(default_factory=list) sentiment_signals: list = field(default_factory=list) pe_deals: list = field(default_factory=list) linkedin_intel: list = field(default_factory=list) def get_company_dossier(company_id: int) -> Optional[CompanyDossier]: """Get complete dossier for a company.""" conn = get_connection() cursor = conn.cursor() # Get company (with service-line + pipeline columns, fallback for older schema) try: cursor.execute(""" SELECT id, name, overall_score, signal_summary, network_status, best_contact, best_colleague, sector, first_seen, last_updated, td_score, cc_score, recommended_services, pipeline_stage FROM companies WHERE id = ? """, (company_id,)) row = cursor.fetchone() has_service_cols = True except sqlite3.OperationalError: cursor.execute(""" SELECT id, name, overall_score, signal_summary, network_status, best_contact, best_colleague, sector, first_seen, last_updated FROM companies WHERE id = ? """, (company_id,)) row = cursor.fetchone() has_service_cols = False if not row: conn.close() return None # Parse recommended_services JSON rec_services = [] if has_service_cols and len(row) > 12 and row[12]: try: rec_services = json.loads(row[12]) except (json.JSONDecodeError, TypeError): rec_services = [] pipeline_stage = row[13] if has_service_cols and len(row) > 13 and row[13] else "new" dossier = CompanyDossier( id=row[0], name=row[1], overall_score=row[2] or 0, signal_summary=row[3] or "", network_status=row[4] or "Cold", best_contact=row[5], best_colleague=row[6], sector=row[7], first_seen=row[8], last_updated=row[9], td_score=row[10] if has_service_cols and len(row) > 10 else 0, cc_score=row[11] if has_service_cols and len(row) > 11 else 0, recommended_services=rec_services, pipeline_stage=pipeline_stage, ) # Get jobs cursor.execute(""" SELECT job_title, job_score, job_analysis, job_url, source, date_found FROM signals_jobs WHERE company_id = ? ORDER BY job_score DESC """, (company_id,)) dossier.jobs = [dict(zip(['title', 'score', 'analysis', 'url', 'source', 'date'], row)) for row in cursor.fetchall()] # Get news cursor.execute(""" SELECT headline, news_score, trigger_type, reason, urgency, news_url, source, date_found FROM signals_news WHERE company_id = ? ORDER BY news_score DESC """, (company_id,)) dossier.news = [dict(zip(['headline', 'score', 'trigger', 'reason', 'urgency', 'url', 'source', 'date'], row)) for row in cursor.fetchall()] # Get tenders cursor.execute(""" SELECT title, value, deadline, days_to_deadline, is_urgent, matched_keywords, tender_url, date_found FROM signals_tenders WHERE company_id = ? ORDER BY is_urgent DESC, days_to_deadline ASC """, (company_id,)) dossier.tenders = [dict(zip(['title', 'value', 'deadline', 'days', 'urgent', 'keywords', 'url', 'date'], row)) for row in cursor.fetchall()] # Get network cursor.execute(""" SELECT contact_name, contact_position, colleague_name, connection_tier, match_score, date_found FROM signals_network WHERE company_id = ? ORDER BY connection_tier """, (company_id,)) dossier.network = [dict(zip(['contact', 'position', 'colleague', 'tier', 'score', 'date'], row)) for row in cursor.fetchall()] # Get annual reports cursor.execute(""" SELECT company_number, filing_date, report_score, signals_found, summary, key_quotes, urgency, document_url, date_found FROM signals_annual_reports WHERE company_id = ? ORDER BY report_score DESC """, (company_id,)) dossier.annual_reports = [dict(zip(['company_number', 'filing_date', 'score', 'signals_found', 'summary', 'key_quotes', 'urgency', 'document_url', 'date'], row)) for row in cursor.fetchall()] # Get sentiment signals cursor.execute(""" SELECT overall_rating, management_rating, culture_rating, work_life_rating, review_count, sentiment_score, signal_reason, source_url, source, date_found FROM signals_sentiment WHERE company_id = ? ORDER BY sentiment_score DESC """, (company_id,)) dossier.sentiment_signals = [dict(zip(['overall_rating', 'management_rating', 'culture_rating', 'work_life_rating', 'review_count', 'sentiment_score', 'signal_reason', 'source_url', 'source', 'date'], row)) for row in cursor.fetchall()] # Get PE/M&A deal signals cursor.execute(""" SELECT acquirer_name, is_pe_deal, deal_type, deal_date, deal_value, source_url, source, pe_score, signal_reason, date_found FROM signals_pe_deals WHERE company_id = ? ORDER BY pe_score DESC """, (company_id,)) dossier.pe_deals = [dict(zip(['acquirer_name', 'is_pe_deal', 'deal_type', 'deal_date', 'deal_value', 'source_url', 'source', 'pe_score', 'signal_reason', 'date'], row)) for row in cursor.fetchall()] # Get LinkedIn intelligence signals cursor.execute(""" SELECT contact_name, contact_title, contact_url, colleague_name, connection_degree, relationship_score, relationship_tier, recommended_action, mutual_connections, contact_active, posts_about_transformation, last_interaction_days, intel_source, date_found FROM signals_linkedin_intel WHERE company_id = ? ORDER BY relationship_score DESC """, (company_id,)) dossier.linkedin_intel = [dict(zip(['contact_name', 'contact_title', 'contact_url', 'colleague_name', 'connection_degree', 'relationship_score', 'relationship_tier', 'recommended_action', 'mutual_connections', 'contact_active', 'posts_about_transformation', 'last_interaction_days', 'intel_source', 'date'], row)) for row in cursor.fetchall()] conn.close() return dossier @st.cache_data(ttl=60, show_spinner=False) def get_top_companies(limit: int = 20, min_score: int = 0) -> list[CompanyDossier]: """Get top companies by score.""" conn = get_connection() cursor = conn.cursor() cursor.execute(""" SELECT id FROM companies WHERE overall_score >= ? ORDER BY overall_score DESC LIMIT ? """, (min_score, limit)) company_ids = [row[0] for row in cursor.fetchall()] conn.close() return [get_company_dossier(cid) for cid in company_ids] @st.cache_data(ttl=60, show_spinner=False) def get_top_companies_by_service(service_line: str, limit: int = 20, min_score: int = 0) -> list: """Get top companies filtered by service line. Args: service_line: 'transformation_delivery', 'culture_capability', or 'code_3i' limit: Max results min_score: Minimum service-line score threshold Returns: List of CompanyDossier objects """ conn = get_connection() cursor = conn.cursor() try: if service_line == 'transformation_delivery': cursor.execute(""" SELECT id FROM companies WHERE td_score >= ? ORDER BY td_score DESC LIMIT ? """, (min_score, limit)) elif service_line == 'culture_capability': cursor.execute(""" SELECT id FROM companies WHERE cc_score >= ? ORDER BY cc_score DESC LIMIT ? """, (min_score, limit)) elif service_line == 'code_3i': cursor.execute(""" SELECT id FROM companies WHERE recommended_services LIKE '%code_3i%' ORDER BY cc_score DESC LIMIT ? """, (limit,)) else: cursor.execute(""" SELECT id FROM companies WHERE overall_score >= ? ORDER BY overall_score DESC LIMIT ? """, (min_score, limit)) except sqlite3.OperationalError: # Fallback if new columns don't exist yet cursor.execute(""" SELECT id FROM companies WHERE overall_score >= ? ORDER BY overall_score DESC LIMIT ? """, (min_score, limit)) company_ids = [row[0] for row in cursor.fetchall()] conn.close() return [get_company_dossier(cid) for cid in company_ids] @st.cache_data(ttl=60, show_spinner=False) def get_company_stats() -> dict: """Get summary statistics.""" conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT COUNT(*) FROM companies") total_companies = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM companies WHERE overall_score >= 50") hot_companies = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM companies WHERE network_status != 'Cold'") with_network = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_jobs") total_jobs = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_news") total_news = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_tenders") total_tenders = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_annual_reports") total_reports = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_sentiment") total_sentiment = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM signals_pe_deals") total_pe_deals = cursor.fetchone()[0] try: cursor.execute("SELECT COUNT(*) FROM signals_linkedin_intel") total_linkedin_intel = cursor.fetchone()[0] except Exception: total_linkedin_intel = 0 # LinkedIn tier breakdown — based on composite action score (company hotness + LI signals) li_act_now = li_warm = li_nurture = li_posting = 0 try: # action_score = company_score/2 + transformation bonus + active bonus + mutual bonus cursor.execute(""" SELECT (c.overall_score / 2 + li.posts_about_transformation * 20 + li.contact_active * 10 + CASE WHEN li.mutual_connections > 0 THEN 10 ELSE 0 END) AS action_score FROM signals_linkedin_intel li JOIN companies c ON li.company_id = c.id """) for (score,) in cursor.fetchall(): if score >= 70: li_act_now += 1 elif score >= 50: li_warm += 1 else: li_nurture += 1 cursor.execute("SELECT COUNT(*) FROM signals_linkedin_intel WHERE posts_about_transformation = 1") li_posting = cursor.fetchone()[0] except Exception: pass # Service-line pipeline counts td_hot = cc_hot = 0 try: cursor.execute("SELECT COUNT(*) FROM companies WHERE td_score >= 30") td_hot = cursor.fetchone()[0] cursor.execute("SELECT COUNT(*) FROM companies WHERE cc_score >= 30") cc_hot = cursor.fetchone()[0] except sqlite3.OperationalError: pass conn.close() return { 'total_companies': total_companies, 'hot_companies': hot_companies, 'with_network': with_network, 'total_jobs': total_jobs, 'total_news': total_news, 'total_tenders': total_tenders, 'total_reports': total_reports, 'total_sentiment': total_sentiment, 'total_pe_deals': total_pe_deals, 'total_linkedin_intel': total_linkedin_intel, 'li_act_now': li_act_now, 'li_warm': li_warm, 'li_nurture': li_nurture, 'li_posting': li_posting, 'td_hot': td_hot, 'cc_hot': cc_hot, } @st.cache_data(ttl=60, show_spinner=False) def get_top_linkedin_actions(limit: int = 5) -> list: """Get top LinkedIn contacts ranked by composite action score (company hotness + LI signals). Only returns contacts at hot companies (score >= 50) with at least one positive signal. """ conn = get_connection() cursor = conn.cursor() results = [] try: cursor.execute(""" SELECT li.contact_name, li.contact_title, li.contact_url, li.colleague_name, li.connection_degree, li.relationship_score, li.relationship_tier, li.recommended_action, li.mutual_connections, li.contact_active, li.posts_about_transformation, li.last_interaction_days, c.name AS company_name, c.id AS company_id, c.overall_score AS company_score, (c.overall_score / 2 + li.posts_about_transformation * 20 + li.contact_active * 10 + CASE WHEN li.mutual_connections > 0 THEN 10 ELSE 0 END) AS action_score FROM signals_linkedin_intel li JOIN companies c ON li.company_id = c.id WHERE c.overall_score >= 50 AND (li.contact_active = 1 OR li.posts_about_transformation = 1) ORDER BY (c.overall_score / 2 + li.posts_about_transformation * 20 + li.contact_active * 10 + CASE WHEN li.mutual_connections > 0 THEN 10 ELSE 0 END) DESC LIMIT ? """, (limit,)) columns = [desc[0] for desc in cursor.description] for row in cursor.fetchall(): results.append(dict(zip(columns, row))) except Exception: pass conn.close() return results # ============================================================================= # PIPELINE STAGE MANAGEMENT # ============================================================================= def update_pipeline_stage(company_id: int, stage: str) -> bool: """Update a company's pipeline stage.""" if stage not in PIPELINE_STAGES: return False conn = get_connection() cursor = conn.cursor() cursor.execute( "UPDATE companies SET pipeline_stage = ?, last_updated = ? WHERE id = ?", (stage, datetime.now().isoformat(), company_id) ) conn.commit() conn.close() return True def get_companies_by_stage(stage: str = None) -> dict: """Get companies grouped by pipeline stage. If stage is None, returns all stages. Otherwise returns only the given stage. Returns dict of {stage: [CompanyDossier, ...]}. """ conn = get_connection() cursor = conn.cursor() if stage and stage in PIPELINE_STAGES: try: cursor.execute( "SELECT id FROM companies WHERE pipeline_stage = ? ORDER BY overall_score DESC", (stage,) ) except sqlite3.OperationalError: cursor.execute("SELECT id FROM companies ORDER BY overall_score DESC") else: cursor.execute("SELECT id FROM companies ORDER BY overall_score DESC") company_ids = [row[0] for row in cursor.fetchall()] conn.close() dossiers = [get_company_dossier(cid) for cid in company_ids] grouped = {s: [] for s in PIPELINE_STAGES} for d in dossiers: s = d.pipeline_stage if d.pipeline_stage in PIPELINE_STAGES else "new" grouped[s].append(d) if stage and stage in PIPELINE_STAGES: return {stage: grouped.get(stage, [])} return grouped def get_pipeline_stats() -> dict: """Get count of companies per pipeline stage.""" conn = get_connection() cursor = conn.cursor() stats = {} try: cursor.execute("SELECT pipeline_stage, COUNT(*) FROM companies GROUP BY pipeline_stage") for row in cursor.fetchall(): stage = row[0] if row[0] else "new" stats[stage] = row[1] except sqlite3.OperationalError: cursor.execute("SELECT COUNT(*) FROM companies") stats["new"] = cursor.fetchone()[0] conn.close() return stats # ============================================================================= # FOLLOW-UP TRACKING # ============================================================================= FOLLOW_UP_STAGES = ["drafted", "sent", "followed_up_1", "followed_up_2", "replied", "no_response"] FOLLOW_UP_CHANNELS = ["email", "linkedin", "colleague_intro"] def create_follow_up(company: str, contact: str = None, channel: str = "email", notes: str = None, company_id: int = None) -> int: """Create a follow-up record when an email/message is drafted.""" from datetime import timedelta conn = get_connection() cursor = conn.cursor() now = datetime.now() next_action = (now + timedelta(days=3)).strftime('%Y-%m-%d') cursor.execute(""" INSERT INTO follow_ups (company, company_id, contact, channel, stage, last_action_date, next_action_date, notes, created_at) VALUES (?, ?, ?, ?, 'drafted', ?, ?, ?, ?) """, (company, company_id, contact, channel, now.isoformat(), next_action, notes, now.isoformat())) follow_up_id = cursor.lastrowid conn.commit() conn.close() return follow_up_id def update_follow_up(follow_up_id: int, stage: str = None, notes: str = None, next_action_date: str = None) -> bool: """Update a follow-up record's stage, notes, or next action date.""" conn = get_connection() cursor = conn.cursor() updates = [] params = [] if stage and stage in FOLLOW_UP_STAGES: updates.append("stage = ?") params.append(stage) updates.append("last_action_date = ?") params.append(datetime.now().isoformat()) if notes is not None: updates.append("notes = ?") params.append(notes) if next_action_date: updates.append("next_action_date = ?") params.append(next_action_date) if not updates: conn.close() return False params.append(follow_up_id) cursor.execute(f"UPDATE follow_ups SET {', '.join(updates)} WHERE id = ?", params) conn.commit() conn.close() return True def advance_follow_up(follow_up_id: int) -> str: """Advance a follow-up to the next stage and set next action date.""" from datetime import timedelta conn = get_connection() cursor = conn.cursor() cursor.execute("SELECT stage FROM follow_ups WHERE id = ?", (follow_up_id,)) row = cursor.fetchone() if not row: conn.close() return None current = row[0] stage_order = FOLLOW_UP_STAGES idx = stage_order.index(current) if current in stage_order else 0 next_stage = stage_order[min(idx + 1, len(stage_order) - 1)] # Set next follow-up delay based on stage delay_days = { "drafted": 1, "sent": 3, "followed_up_1": 5, "followed_up_2": 7, "replied": 0, "no_response": 0 } next_date = (datetime.now() + timedelta(days=delay_days.get(next_stage, 3))).strftime('%Y-%m-%d') cursor.execute(""" UPDATE follow_ups SET stage = ?, last_action_date = ?, next_action_date = ? WHERE id = ? """, (next_stage, datetime.now().isoformat(), next_date, follow_up_id)) conn.commit() conn.close() return next_stage def get_follow_ups(overdue_only: bool = False, limit: int = 20) -> list[dict]: """Get follow-up records, optionally filtered to overdue only.""" conn = get_connection() cursor = conn.cursor() today = datetime.now().strftime('%Y-%m-%d') try: if overdue_only: cursor.execute(""" SELECT id, company, company_id, contact, channel, stage, last_action_date, next_action_date, notes, created_at FROM follow_ups WHERE next_action_date <= ? AND stage NOT IN ('replied', 'no_response') ORDER BY next_action_date ASC LIMIT ? """, (today, limit)) else: cursor.execute(""" SELECT id, company, company_id, contact, channel, stage, last_action_date, next_action_date, notes, created_at FROM follow_ups WHERE stage NOT IN ('replied', 'no_response') ORDER BY next_action_date ASC LIMIT ? """, (limit,)) columns = ['id', 'company', 'company_id', 'contact', 'channel', 'stage', 'last_action_date', 'next_action_date', 'notes', 'created_at'] results = [dict(zip(columns, row)) for row in cursor.fetchall()] except sqlite3.OperationalError: results = [] conn.close() return results def get_follow_up_stats() -> dict: """Get summary of follow-up pipeline.""" conn = get_connection() cursor = conn.cursor() today = datetime.now().strftime('%Y-%m-%d') stats = {'total': 0, 'overdue': 0, 'by_stage': {}} try: cursor.execute("SELECT COUNT(*) FROM follow_ups WHERE stage NOT IN ('replied', 'no_response')") stats['total'] = cursor.fetchone()[0] cursor.execute( "SELECT COUNT(*) FROM follow_ups WHERE next_action_date <= ? AND stage NOT IN ('replied', 'no_response')", (today,) ) stats['overdue'] = cursor.fetchone()[0] cursor.execute("SELECT stage, COUNT(*) FROM follow_ups GROUP BY stage") for row in cursor.fetchall(): stats['by_stage'][row[0]] = row[1] except sqlite3.OperationalError: pass conn.close() return stats # ============================================================================= # SOURCE HEALTH TRACKING # ============================================================================= # API key environment variable names per source SOURCE_API_KEYS = { 'jobs': 'ADZUNA_APP_ID', # Adzuna API; falls back to scraping if unset 'news': 'NEWSAPI_KEY', 'tenders': None, # Contracts Finder, no key needed 'annual_reports': 'COMPANIES_HOUSE_API_KEY', 'sentiment': None, # Web scraping 'pe_deals': None, # Web scraping 'linkedin_groups': None, # Uses session cookies 'linkedin_intel': None, # Uses session cookies 'councils': None, # Targeted UK council scan (~70 councils) 'web_discovery': 'ANTHROPIC_API_KEY', # Claude+web_search direct } # Human-readable setup instructions per source SOURCE_SETUP_INSTRUCTIONS = { 'jobs': 'Set ADZUNA_APP_ID + ADZUNA_APP_KEY (free at developer.adzuna.com) for reliable UK job board coverage. Without them, falls back to Playwright scraping which is frequently blocked by Cloudflare on cloud IPs.', 'news': 'Add NEWSAPI_KEY to .env file. Get a free key from newsapi.org.', 'tenders': 'No API key needed. Uses Contracts Finder public API.', 'annual_reports': 'Add COMPANIES_HOUSE_API_KEY to .env file. Register at developer.company-information.service.gov.uk.', 'sentiment': 'No API key needed. Scrapes public review sites.', 'pe_deals': 'No API key needed. Scrapes financial news sources.', 'linkedin_groups': 'Requires LinkedIn session. Click LinkedIn Deep > Setup LinkedIn Login in sidebar.', 'linkedin_intel': 'Requires LinkedIn session. Click LinkedIn Deep > Setup LinkedIn Login in sidebar.', 'councils': 'Targeted scan of ~70 UK councils — Network mapping (warm intros) + Tenders + Jobs + News + People per council. No API key needed; included in HUNT NOW.', 'web_discovery': 'Claude + web_search hunts for senior moves / restructures / contract awards that scrapers and APIs miss. Requires ANTHROPIC_API_KEY (already set if other Claude features work). Costs ~£0.30 per hunt.', } def update_source_health(source_name: str, status: str, records_found: int = 0, error: str = None): """Update the health record for a data source after a scan. Args: source_name: One of the 9 source keys (jobs, news, etc.) status: 'success', 'error', 'disabled' records_found: Number of records found in this scan error: Error message if status is 'error' """ import os conn = get_connection() cursor = conn.cursor() now = datetime.now().isoformat() # Check API key status api_key_name = SOURCE_API_KEYS.get(source_name) api_key_set = 1 if api_key_name: api_key_set = 1 if os.environ.get(api_key_name) else 0 # Get current total_records cursor.execute("SELECT total_records FROM source_health WHERE source_name = ?", (source_name,)) row = cursor.fetchone() current_total = row[0] if row else 0 new_total = current_total + records_found cursor.execute(""" INSERT INTO source_health (source_name, last_scan_at, status, last_error, records_found, total_records, api_key_set, api_key_name) VALUES (?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(source_name) DO UPDATE SET last_scan_at = excluded.last_scan_at, status = excluded.status, last_error = excluded.last_error, records_found = excluded.records_found, total_records = ?, api_key_set = excluded.api_key_set, api_key_name = excluded.api_key_name """, (source_name, now, status, error[:200] if error else None, records_found, new_total, api_key_set, api_key_name, new_total)) conn.commit() conn.close() def get_all_source_health() -> list: """Get health status for all 9 sources. Returns: List of dicts with keys: source_name, last_scan_at, status, last_error, records_found, total_records, api_key_set, api_key_name """ import os conn = get_connection() cursor = conn.cursor() try: cursor.execute(""" SELECT source_name, last_scan_at, status, last_error, records_found, total_records, api_key_set, api_key_name FROM source_health ORDER BY source_name """) columns = ['source_name', 'last_scan_at', 'status', 'last_error', 'records_found', 'total_records', 'api_key_set', 'api_key_name'] results = [dict(zip(columns, row)) for row in cursor.fetchall()] except Exception: results = [] conn.close() # Update api_key_set live (in case env vars changed since last scan) for r in results: key_name = SOURCE_API_KEYS.get(r['source_name']) if key_name: r['api_key_set'] = 1 if os.environ.get(key_name) else 0 else: r['api_key_set'] = 1 # No key needed r['setup_instructions'] = SOURCE_SETUP_INSTRUCTIONS.get(r['source_name'], '') # Ensure all 9 sources are represented existing = {r['source_name'] for r in results} for src in SOURCE_API_KEYS: if src not in existing: key_name = SOURCE_API_KEYS.get(src) results.append({ 'source_name': src, 'last_scan_at': None, 'status': 'never_run', 'last_error': None, 'records_found': 0, 'total_records': 0, 'api_key_set': 1 if (not key_name or os.environ.get(key_name)) else 0, 'api_key_name': key_name, 'setup_instructions': SOURCE_SETUP_INSTRUCTIONS.get(src, ''), }) return results def backfill_source_health(): """Backfill source_health from existing DB data so sources with records don't show 'never_run'.""" import os conn = get_connection() cursor = conn.cursor() # Check if source_health already has entries with actual scan data try: cursor.execute("SELECT COUNT(*) FROM source_health WHERE status != 'never_run'") if cursor.fetchone()[0] > 0: conn.close() return # Already has real data, don't overwrite except Exception: conn.close() return # Count records per source from existing signal tables source_counts = {} count_queries = { 'jobs': "SELECT COUNT(*) FROM signals_jobs", 'news': "SELECT COUNT(*) FROM signals_news", 'tenders': "SELECT COUNT(*) FROM signals_tenders", 'annual_reports': "SELECT COUNT(*) FROM signals_annual_reports", 'sentiment': "SELECT COUNT(*) FROM signals_sentiment", 'pe_deals': "SELECT COUNT(*) FROM signals_pe_deals", 'linkedin_intel': "SELECT COUNT(*) FROM signals_linkedin_intel", } for source, query in count_queries.items(): try: cursor.execute(query) count = cursor.fetchone()[0] source_counts[source] = count except Exception: source_counts[source] = 0 # LinkedIn groups - check if any companies have linkedin activity in signals_network try: cursor.execute("SELECT COUNT(*) FROM signals_network") source_counts['linkedin_groups'] = cursor.fetchone()[0] except Exception: source_counts['linkedin_groups'] = 0 now = datetime.now().isoformat() for source_name, count in source_counts.items(): api_key_name = SOURCE_API_KEYS.get(source_name) api_key_set = 1 if api_key_name: api_key_set = 1 if os.environ.get(api_key_name) else 0 if count > 0: status = 'success' elif api_key_name and not os.environ.get(api_key_name): status = 'error' else: status = 'never_run' try: cursor.execute(""" INSERT INTO source_health (source_name, last_scan_at, status, last_error, records_found, total_records, api_key_set, api_key_name) VALUES (?, ?, ?, NULL, 0, ?, ?, ?) ON CONFLICT(source_name) DO UPDATE SET status = CASE WHEN source_health.status = 'never_run' THEN excluded.status ELSE source_health.status END, total_records = excluded.total_records, api_key_set = excluded.api_key_set, api_key_name = excluded.api_key_name """, (source_name, now if count > 0 else None, status, count, api_key_set, api_key_name)) except Exception: pass conn.commit() conn.close() def get_signal_completeness(company_id: int) -> dict: """Check which of 9 data sources have data for a given company. Returns: dict with keys: checked (int), total (int), sources (dict of source->bool) """ conn = get_connection() cursor = conn.cursor() sources = {} tables = { 'jobs': 'signals_jobs', 'news': 'signals_news', 'tenders': 'signals_tenders', 'annual_reports': 'signals_annual_reports', 'sentiment': 'signals_sentiment', 'pe_deals': 'signals_pe_deals', 'network': 'signals_network', 'linkedin_intel': 'signals_linkedin_intel', } for source, table in tables.items(): try: cursor.execute(f"SELECT COUNT(*) FROM {table} WHERE company_id = ?", (company_id,)) count = cursor.fetchone()[0] sources[source] = count > 0 except Exception: sources[source] = False conn.close() checked = sum(1 for v in sources.values() if v) return { 'checked': checked, 'total': len(sources), 'sources': sources, } def calculate_confidence(company_id: int) -> dict: """Calculate confidence score for approaching a company. Factors: - Signal freshness (newer = higher) - Source completeness (more sources checked = higher) - Network confidence (warm route = higher) - Signal count (more corroborating signals = higher) Returns: dict with keys: level (HIGH/MEDIUM-HIGH/MEDIUM/LOW), score (0-100), explanation (str), details (dict) """ conn = get_connection() cursor = conn.cursor() score = 0 details = {} # 1. Source completeness (0-30 points) completeness = get_signal_completeness(company_id) checked = completeness['checked'] completeness_score = min(30, int(checked / completeness['total'] * 30)) score += completeness_score details['completeness'] = f"{checked}/{completeness['total']} sources" # 2. Signal freshness (0-25 points) signal_tables = ['signals_jobs', 'signals_news', 'signals_sentiment', 'signals_pe_deals', 'signals_linkedin_intel'] newest_days = 999 oldest_days = 0 for table in signal_tables: try: cursor.execute(f"SELECT date_found FROM {table} WHERE company_id = ? ORDER BY date_found DESC LIMIT 1", (company_id,)) row = cursor.fetchone() if row and row[0]: dt = datetime.fromisoformat(row[0]) days = (datetime.now() - dt).days newest_days = min(newest_days, days) oldest_days = max(oldest_days, days) except Exception: pass if newest_days <= 7: freshness_score = 25 elif newest_days <= 14: freshness_score = 20 elif newest_days <= 30: freshness_score = 15 elif newest_days <= 90: freshness_score = 8 else: freshness_score = 0 score += freshness_score details['newest_signal'] = f"{newest_days}d" if newest_days < 999 else "None" details['oldest_signal'] = f"{oldest_days}d" if oldest_days > 0 else "None" # 3. Network confidence (0-25 points) cursor.execute("SELECT network_status, best_contact, best_colleague FROM companies WHERE id = ?", (company_id,)) company_row = cursor.fetchone() has_warm_route = False if company_row: net_status = company_row[0] or "Cold" if net_status != "Cold" and company_row[1] and company_row[2]: has_warm_route = True score += 25 details['network'] = f"Warm via {company_row[2]}" else: # Check LinkedIn intel cursor.execute(""" SELECT COUNT(*) FROM signals_linkedin_intel WHERE company_id = ? AND (contact_active = 1 OR posts_about_transformation = 1) """, (company_id,)) li_count = cursor.fetchone()[0] if li_count > 0: score += 15 details['network'] = f"{li_count} LinkedIn contacts" else: details['network'] = "Cold" # 4. Signal count (0-20 points) total_signals = 0 for table in signal_tables: try: cursor.execute(f"SELECT COUNT(*) FROM {table} WHERE company_id = ?", (company_id,)) total_signals += cursor.fetchone()[0] except Exception: pass if total_signals >= 5: signal_score = 20 elif total_signals >= 3: signal_score = 15 elif total_signals >= 1: signal_score = 8 else: signal_score = 0 score += signal_score details['signal_count'] = total_signals conn.close() # Determine level if score >= 75: level = "HIGH" elif score >= 55: level = "MEDIUM-HIGH" elif score >= 35: level = "MEDIUM" else: level = "LOW" explanation_parts = [] explanation_parts.append(f"{details['signal_count']} verified signals") explanation_parts.append(f"{details['completeness']} checked") if newest_days < 999: explanation_parts.append(f"Newest: {newest_days}d") if has_warm_route: explanation_parts.append("Direct connection via colleague") return { 'level': level, 'score': min(score, 100), 'explanation': ' | '.join(explanation_parts), 'details': details, } def clear_all_data(): """Clear all company and signal data.""" conn = get_connection() cursor = conn.cursor() cursor.execute("DELETE FROM signals_network") cursor.execute("DELETE FROM signals_annual_reports") cursor.execute("DELETE FROM signals_sentiment") cursor.execute("DELETE FROM signals_pe_deals") cursor.execute("DELETE FROM signals_tenders") cursor.execute("DELETE FROM signals_news") cursor.execute("DELETE FROM signals_jobs") try: cursor.execute("DELETE FROM signals_linkedin_intel") except Exception: pass # Table may not exist yet cursor.execute("DELETE FROM companies") conn.commit() conn.close() # Bust Streamlit caches so pages reflect the cleared data get_top_companies.clear() get_top_companies_by_service.clear() get_company_stats.clear() get_top_linkedin_actions.clear() # ============================================================================= # INITIALIZATION # ============================================================================= # Initialize on import init_company_db() backfill_source_health() if __name__ == "__main__": # Test print("Testing Collator...") # Add some test signals add_job_signal("Barclays PLC", "Head of Transformation", 85, "Direct hit for CODE", "https://example.com/job1") add_news_signal("Barclays", "Barclays announces major restructuring", 75, "restructuring", "Cost cutting initiative", "high", "https://example.com/news1") add_network_signal("Barclays UK", "Sarah Jones", "Head of HR", "Adam", "SENIOR CONNECTION", 85.0) # Get dossier dossiers = get_top_companies(limit=5) for d in dossiers: print(f"\n{'='*60}") print(f"🏢 {d.name} - Score: {d.overall_score}") print(f" Signals: {d.signal_summary}") print(f" Network: {d.network_status}") if d.best_colleague and d.best_contact: print(f" Contact: {d.best_colleague} → {d.best_contact}") print(f" Jobs: {len(d.jobs)}, News: {len(d.news)}, Tenders: {len(d.tenders)}")