feat(connect): caller ID as an integration: calls on the signed-in live connection, matched on the server

Plan step 3.5.
- The public /api/phone/ws socket is removed (anyone on the LAN could listen to every
  caller). GET /api/phone/call-event stays public for the Grandstream UCM but is LAN-only in
  the proxy (the 443 blocks' LAN-only location now covers it, in nginx-proxy/nginx.conf and
  install.sh), with an optional shared secret (setting caller_id.secret → &key=).
- Calls are logged (phone_calls, migration 0023), matched to a customer on the server
  (services/caller_id.py: Greek number rules moved from the manager) and published as
  `call_incoming` {call_id, at, number, ext, customer card: visits, spent, last 3 orders} to
  users with caller_id.use and to the counter POS screens. GET /api/phone/calls (the log),
  GET /api/customers/lookup?phone=. Calls older than a minute don't pop up (replays).
- Manager: PhoneListener on the live connection and the shared Dialog (no more downloading
  every customer to match); Integrations → Caller ID shows the server's log live and the UCM
  Action URL. Counter: CallPopup with "New takeaway sale".
- Tests: tests/test_caller_id.py (10), terminal unit test, e2e terminal and manager.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 09:06:39 +02:00
co-authored by Claude Opus 5.5
parent 88a9703902
commit dabe807ce0
28 changed files with 609 additions and 501 deletions
+11
View File
@@ -7,6 +7,7 @@ from models.customers import Customer
from models.order import Order, OrderItem
from models.user import User
from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest
from core.access.deps import require_any
from routers.deps import require_manager, get_current_user
router = APIRouter()
@@ -66,6 +67,16 @@ def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: U
return _customer_out(customer, db)
@router.get("/lookup")
def lookup_customer(phone: str = Query(..., max_length=40), db: Session = Depends(get_db),
user: User = Depends(require_any("caller_id.use", "core.dashboard.access"))):
"""Who has this phone number (caller ID, plan step 3.5): matched on the server with the Greek
number rules (services/caller_id.py) → {customer: card | null}."""
from services import caller_id
c = caller_id.match(db, phone)
return {"customer": caller_id.card(db, c) if c else None}
@router.get("/{customer_id}", response_model=CustomerOut)
def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
c = db.query(Customer).filter(Customer.id == customer_id).first()
+70 -54
View File
@@ -1,65 +1,81 @@
"""Caller ID: incoming calls from the venue's phone system (Grandstream UCM), plan step 3.5.
GET /api/phone/call-event?caller=…&ext=…[&key=…] the UCM's "Action URL" on every incoming call.
No sign-in (the phone system has none), so: LAN-only in the proxy (nginx-proxy/nginx.conf and
the copy in install.sh), and an optional shared secret (setting caller_id.secret; when set,
`key` must match). The call is logged (phone_calls), matched to a customer on the server
(services/caller_id.py), and published on the main live connection as `call_incoming`
{call_id, at, number, ext, customer} to the users holding caller_id.use and to the counter
POS screens. Nothing on the LAN can listen without signing in (the old public
/api/phone/ws socket is gone).
GET /api/phone/calls?limit= the call log (caller_id.use), newest first.
"""
Phone call event receiver + WebSocket broadcaster.
from __future__ import annotations
The Grandstream UCM sends a simple HTTP GET to /api/phone/call-event
with caller ID and extension details. We broadcast that to all connected
WebSocket clients (manager dashboard Phone page).
import secrets
from typing import Optional
The call-event endpoint is intentionally unauthenticated so the UCM device
(which has no JWT) can POST to it directly on the local LAN.
"""
from fastapi import APIRouter, Depends, Query
from sqlalchemy.orm import Session
from core.access.deps import public
import asyncio
import json
import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
from core.access.deps import public, require
from core.errors import XeniaError
from database import get_db
router = APIRouter()
logger = logging.getLogger(__name__)
# In-memory list of active WebSocket connections to the Phone page.
_connections: list[WebSocket] = []
KEY = "caller_id.use"
SECRET = "caller_id.secret"
@router.websocket("/ws", dependencies=[Depends(public())])
async def phone_ws(websocket: WebSocket):
await websocket.accept()
_connections.append(websocket)
logger.debug("phone_ws: client connected (%d total)", len(_connections))
try:
# Keep the connection alive; client drives nothing, server pushes events.
while True:
await asyncio.sleep(25)
await websocket.send_text(json.dumps({"type": "ping"}))
except (WebSocketDisconnect, Exception):
pass
finally:
_connections.remove(websocket)
logger.debug("phone_ws: client disconnected (%d total)", len(_connections))
def _setting(db, key: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return (row.value or "") if row else ""
def call_out(db, call, customer=None) -> dict:
from services import caller_id
from models.customers import Customer
if customer is None and call.customer_id:
customer = db.get(Customer, call.customer_id)
return {"call_id": call.id, "at": call.at.isoformat() if call.at else None, "number": call.number, "ext": call.ext,
"customer": caller_id.card(db, customer) if customer is not None else None}
def _audience(db) -> tuple[list[int], list[int]]:
from core.access.queries import users_with_key
from models.device import Device
users = [u.id for u in users_with_key(db, KEY)]
pos = [i for (i,) in db.query(Device.id).filter(Device.app_key == "pos_counter", Device.revoked_at.is_(None))]
return users, pos
@router.get("/call-event", dependencies=[Depends(public())])
async def call_event(
caller: str = Query(..., description="Caller ID number from UCM"),
ext: str = Query("", description="Dialled extension"),
):
"""
Called by the Grandstream UCM Action URL on every incoming call.
Example: GET /api/phone/call-event?caller=2106001234&ext=100
"""
payload = json.dumps({"type": "incoming_call", "caller": caller, "ext": ext})
dead = []
for ws in list(_connections):
try:
await ws.send_text(payload)
except Exception:
dead.append(ws)
for ws in dead:
try:
_connections.remove(ws)
except ValueError:
pass
logger.info("phone call-event: caller=%s ext=%s (notified %d clients)", caller, ext, len(_connections) - len(dead))
return {"status": "ok", "notified": len(_connections) - len(dead)}
def call_event(caller: str = Query(..., max_length=40, description="Caller ID number from the UCM"),
ext: str = Query("", max_length=20, description="Dialled extension"),
key: Optional[str] = Query(None, max_length=200),
db: Session = Depends(get_db)):
"""Example: GET /api/phone/call-event?caller=2106001234&ext=100"""
from models.phone_call import PhoneCall
from services import caller_id
from services.ws_bus import broadcast_sync
secret = _setting(db, SECRET)
if secret and not (key and secrets.compare_digest(key, secret)):
raise XeniaError("caller_id.key_invalid")
customer = caller_id.match(db, caller)
call = PhoneCall(number=caller.strip(), ext=ext.strip() or None, customer_id=customer.id if customer else None)
db.add(call)
db.commit()
db.refresh(call)
payload = call_out(db, call, customer)
users, pos = _audience(db)
if users or pos:
broadcast_sync("call_incoming", payload, user_ids=users, device_ids=pos)
return {"status": "ok", "call_id": call.id, "matched": customer is not None}
@router.get("/calls")
def call_log(limit: int = Query(50, ge=1, le=500), db: Session = Depends(get_db), user=Depends(require(KEY))):
from models.phone_call import PhoneCall
calls = db.query(PhoneCall).order_by(PhoneCall.at.desc(), PhoneCall.id.desc()).limit(limit).all()
return {"calls": [call_out(db, c) for c in calls]}