"""Caller ID (plan step 3.5): who is calling, matched on the server. normalise("+30 210-600 1234") -> "2106001234" match(db, number) -> the active customer whose phone is that number, or None card(db, customer) -> what the popup shows: name, nickname, phone, email, notes, visits, total spent, the last 3 orders Greek numbers come in many shapes (+30…, 0030…, 30… with 12 digits, spaces, dashes, brackets); moved here from the manager's PhoneListener.jsx so every screen agrees and the browser doesn't download the whole customer list to match a call. """ from __future__ import annotations import re RECENT = 3 def normalise(raw: str | None) -> str: if not raw: return "" s = re.sub(r"[\s\-().+/]", "", str(raw)) if s.startswith("0030"): s = s[4:] elif s.startswith("30") and len(s) > 10: s = s[2:] return s def match(db, number: str | None): """The active customer with this number (the most recently created if several), or None.""" from models.customers import Customer wanted = normalise(number) if not wanted: return None hits = [c for c in db.query(Customer).filter(Customer.is_active.is_(True), Customer.phone.isnot(None)) .order_by(Customer.id.desc()).all() if normalise(c.phone) == wanted] return hits[0] if hits else None def card(db, customer) -> dict: from models.order import Order from models.table import Table orders = db.query(Order).filter(Order.customer_id == customer.id).order_by(Order.opened_at.desc()).all() done = [o for o in orders if o.status in ("closed", "paid")] live = lambda o: [i for i in o.items if i.status in ("active", "paid")] # noqa: E731 tables = {t.id: (t.label or f"T{t.number}") for t in db.query(Table).all()} return { "id": customer.id, "name": customer.name, "nickname": customer.nickname, "phone": customer.phone, "email": customer.email, "notes": customer.notes, "visit_count": len(done), "total_spent": round(sum(i.unit_price * i.quantity for o in done for i in live(o)), 2), "recent_orders": [{ "id": o.id, "opened_at": o.opened_at.isoformat() if o.opened_at else None, "table_name": tables.get(o.table_id) if o.table_id else None, "status": o.status, "total": round(sum(i.unit_price * i.quantity for i in live(o)), 2), "item_count": sum(i.quantity for i in live(o)), } for o in orders[:RECENT]], }