from collections import defaultdict import csv from datetime import date, timedelta from pathlib import Path import re ROOT = Path(__file__).resolve().parent AS_OF = date(2026, 11, 20) # UTC calendar date of the snapshot CUTOFF = AS_OF - timedelta(days=30) with (ROOT / 'crm-fixture.csv').open(encoding='utf-8-sig', newline='') as stream: rows = list(csv.DictReader(stream)) if len({row['id'] for row in rows}) != len(rows) or any(not row['id'] for row in rows): raise ValueError('Expected one record per non-empty ID') active = [row for row in rows if row['status'] == 'open'] inbound = [row for row in rows if row['inbound'] == 'yes' and date(2026, 11, 1) <= date.fromisoformat(row['created_at']) < AS_OF] dated = [row for row in active if row['last_activity_at']] def contact_key(row): value = row['contact'].strip() if row['channel'] == 'email' and re.fullmatch(r'[^\s@]+@[^\s@]+\.[^\s@]+', value): return 'email:' + value.lower() if row['channel'] == 'phone' and re.fullmatch(r'\+[1-9]\d{7,14}', value): return 'phone:' + value return None groups = defaultdict(list) for row in rows: key = contact_key(row) if key: groups[key].append(row['id']) repeated = [group for group in groups.values() if len(group) > 1] report = [ ('missing_owner', len(active), [row['id'] for row in active if not row['owner_id']]), ('missing_source', len(inbound), [row['id'] for row in inbound if not row['source']]), ('stale_activity', len(dated), [row['id'] for row in dated if date.fromisoformat(row['last_activity_at']) < CUTOFF]), ('invalid_contact', len(inbound), [row['id'] for row in inbound if not contact_key(row)]), ('duplicate_candidates', sum(map(len, groups.values())), [record_id for group in repeated for record_id in group]), ('unknown_activity_date', len(active), [row['id'] for row in active if not row['last_activity_at']]), ] with (ROOT / 'crm-report.csv').open('w', encoding='utf-8-sig', newline='') as stream: writer = csv.writer(stream) writer.writerow(['check', 'flagged', 'eligible', 'percent', 'record_ids']) for code, eligible, ids in report: percent = f'{len(ids) / eligible:.1%}' if eligible else '' writer.writerow([code, len(ids), eligible, percent, '|'.join(ids)])