# -*- coding: utf-8 -*- import sys, httpx from dotenv import load_dotenv import os load_dotenv() DIRECTUS_URL = os.getenv("DIRECTUS_URL", "http://localhost:8055").rstrip("/") DIRECTUS_TOKEN = os.getenv("DIRECTUS_TOKEN", "") HEADERS = { "Authorization": f"Bearer {DIRECTUS_TOKEN}", "Content-Type": "application/json", } client = httpx.Client(base_url=DIRECTUS_URL, headers=HEADERS, timeout=30) COLLECTIONS = ["calls", "calls_74951284933"] def get_all(collection: str, fields: str) -> list: items = [] offset = 0 limit = 200 while True: resp = client.get( f"/items/{collection}", params={"fields": fields, "limit": limit, "offset": offset, "sort": "id"}, ) if resp.status_code != 200: print(f" ERROR fetching {collection}: {resp.status_code}", file=sys.stderr) break data = resp.json().get("data", []) if not data: break items.extend(data) offset += limit return items def main(): contacts_map = {} contacts = get_all("contacts", "id,phone_number,name,company") for c in contacts: phone = (c.get("phone_number") or "").strip() if phone: contacts_map[phone] = c print(f"Loaded {len(contacts_map)} contacts.") total_updated = 0 for col in COLLECTIONS: calls = get_all(col, "id,call_id,caller_number,callee_number,caller_name,callee_name") print(f" {col}: {len(calls)} calls") for call in calls: updates = {} for side in ("caller", "callee"): num = call.get(f"{side}_number") or "" contact = contacts_map.get(num) if contact: name = contact.get("name") or "" company = contact.get("company") or "" label = f"{name} ({company})" if name and company else (name or company) if label and call.get(f"{side}_name") != label: updates[f"{side}_name"] = label if updates: try: resp = client.patch(f"/items/{col}/{call['id']}", json=updates) if resp.status_code in (200, 201): total_updated += 1 print(f" Updated {col} id={call['id']}: {updates}") else: print(f" FAILED {col} id={call['id']}: {resp.status_code} {resp.text[:200]}", file=sys.stderr) except Exception as e: print(f" ERROR {col} id={call['id']}: {e}", file=sys.stderr) print(f"\nUpdated {total_updated} calls.") client.close() if __name__ == "__main__": main()