"""Read-only sender candidates for mail triage; never chooses between companies.""" from email.utils import parseaddr def find_sender_candidates(sender, query, ignored_domains=()): address = parseaddr(str(sender or ''))[1].strip().lower() domain = address.rsplit('@', 1)[1] if '@' in address else '' if not domain: return {'address': address, 'domain': domain, 'candidates': [], 'ambiguous': False} rows = query(""" SELECT c.id, c.name, 'customer' AS kind, 'contact_email' AS source, ct.id AS contact_id, CONCAT_WS(' ', ct.first_name, ct.last_name) AS contact_name FROM contacts ct JOIN contact_companies cc ON cc.contact_id = ct.id JOIN customers c ON c.id = cc.customer_id WHERE ct.is_active = true AND c.is_active = true AND LOWER(TRIM(ct.email)) = %s UNION ALL SELECT v.id, v.name, 'vendor', 'contact_email', ct.id, CONCAT_WS(' ', ct.first_name, ct.last_name) FROM contacts ct JOIN vendor_contacts vc ON vc.contact_id = ct.id JOIN vendors v ON v.id = vc.vendor_id WHERE ct.is_active = true AND v.is_active = true AND LOWER(TRIM(ct.email)) = %s UNION ALL SELECT id, name, 'customer', 'exact_email', NULL, NULL FROM customers WHERE is_active = true AND LOWER(TRIM(email)) = %s UNION ALL SELECT id, name, 'vendor', 'exact_email', NULL, NULL FROM vendors WHERE is_active = true AND LOWER(TRIM(email)) = %s """, (address, address, address, address)) or [] if domain not in ignored_domains and 'bmc' not in domain: rows += query(""" SELECT c.id, c.name, 'customer' AS kind, 'saved_domain' AS source, NULL AS contact_id, NULL AS contact_name FROM email_domain_customer_mappings m JOIN customers c ON c.id = m.customer_id WHERE c.is_active = true AND LOWER(TRIM(m.domain)) = %s UNION ALL SELECT id, name, 'customer', 'exact_domain', NULL, NULL FROM customers WHERE is_active = true AND LOWER(TRIM(email_domain)) IN (%s, %s) UNION ALL SELECT v.id, v.name, 'vendor', 'exact_domain', NULL, NULL FROM vendors v JOIN vendor_email_domains d ON d.vendor_id = v.id WHERE v.is_active = true AND LOWER(TRIM(d.domain)) = %s """, (domain, domain, 'www.' + domain, domain)) or [] candidates = {} priority = {'contact_email': 0, 'exact_email': 1, 'saved_domain': 2, 'exact_domain': 3} for row in sorted(rows, key=lambda row: (priority[row['source']], row['name'].lower(), row['id'])): key = (row['kind'], row['id']) if key not in candidates: candidates[key] = dict(row) values = list(candidates.values()) return {'address': address, 'domain': domain, 'candidates': values, 'ambiguous': len(values) > 1}