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
+1
View File
@@ -85,6 +85,7 @@ CODES: dict[str, tuple[int, str]] = {
"refund.items_changed": (409, "Some of these items were refunded in the meantime. Check the order and try again."),
"online.not_found": (404, "Online order {order_id} not found."),
"online.status_changed": (409, "This online order was changed on another screen in the meantime. Check where it is now."),
"caller_id.key_invalid": (403, "The phone system's key is missing or wrong."),
"display.media_unknown": (404, "Image {name} not found."),
"display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."),
"display.media_too_big": (413, "The image is too big (at most {max_mb} MB)."),
@@ -0,0 +1,35 @@
"""phone_calls: the caller ID call log (plan step 3.5)
Revision ID: 0023_phone_calls
Revises: 0022_customer_display_key
Create Date: 2026-11-17 12:00:00
"""
from alembic import op
import sqlalchemy as sa
from core.timeutil import UTCDateTime
revision = '0023_phone_calls'
down_revision = '0022_customer_display_key'
branch_labels = None
depends_on = None
def upgrade() -> None:
op.create_table('phone_calls',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('at', UTCDateTime(), nullable=False),
sa.Column('number', sa.String(), nullable=False),
sa.Column('ext', sa.String(), nullable=True),
sa.Column('customer_id', sa.Integer(), nullable=True),
sa.ForeignKeyConstraint(['customer_id'], ['customers.id'], ondelete='SET NULL'),
sa.PrimaryKeyConstraint('id'),
)
with op.batch_alter_table('phone_calls', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_phone_calls_id'), ['id'], unique=False)
batch_op.create_index(batch_op.f('ix_phone_calls_at'), ['at'], unique=False)
def downgrade() -> None:
op.drop_table('phone_calls')
+1
View File
@@ -10,6 +10,7 @@ import models.table # noqa: F401
import models.printer # noqa: F401
import models.product # noqa: F401
import models.customers # noqa: F401
import models.phone_call # noqa: F401
import models.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob
import models.business_day # noqa: F401
import models.shift # noqa: F401 WaiterShift, ShiftBreak
+15
View File
@@ -0,0 +1,15 @@
from sqlalchemy import Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
class PhoneCall(Base):
"""An incoming call the venue's phone system reported (caller ID, plan step 3.5)."""
__tablename__ = "phone_calls"
id = Column(Integer, primary_key=True, index=True)
at = Column(UTCDateTime, default=utcnow, nullable=False, index=True)
number = Column(String, nullable=False) # as the phone system sent it
ext = Column(String, nullable=True) # the extension that was dialled
customer_id = Column(Integer, ForeignKey("customers.id", ondelete="SET NULL"), nullable=True)
+5 -2
View File
@@ -1,14 +1,17 @@
"""Module manifest — see core/modules/model.py and APPS_PLATFORM §4."""
from core.modules.model import Module, Mount, Perm
from core.modules.model import Module, Mount, Perm, SettingDef
MODULE = Module(
key='caller_id',
kind='integration',
name='Caller ID',
description="Incoming phone calls from the venue's phone system (Grandstream UCM).",
description="Incoming phone calls from the venue's phone system (Grandstream UCM): who is calling, with their last orders.",
permissions=(
Perm('caller_id.use', 'See incoming calls', roles=('owner', 'store_manager', 'staff_manager')),
),
settings=(
SettingDef('caller_id.secret', '', 'Optional shared secret for the phone system webhook: when set, the UCM Action URL must add &key=<secret>. Plan step 3.5.', type='str'),
),
routers=(
Mount('routers.phone', '/api/phone'),
),
+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]}
+59
View File
@@ -0,0 +1,59 @@
"""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]],
}
+97
View File
@@ -0,0 +1,97 @@
"""Caller ID as an integration (plan step 3.5): the phone system's webhook logs the call, the
server matches the customer (Greek number rules) and publishes `call_incoming` on the main live
connection to the users with caller_id.use and to the counter POS screens; the old public
socket is gone; an optional shared secret; the call log; the lookup."""
import pytest
from services.caller_id import normalise
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
@pytest.mark.parametrize("raw", ["2106001234", "+30 210 600 1234", "0030-210-600-1234", "302106001234", "(210) 600-1234"])
def test_greek_numbers_normalise(raw):
assert normalise(raw) == "2106001234"
def test_short_numbers_keep_their_30():
assert normalise("3012345") == "3012345" and normalise(None) == ""
@pytest.fixture
def eleni(db, make_user):
from models.customers import Customer
from models.order import Order, OrderItem
owner = make_user(role="owner")
c = Customer(name="Eleni Papa", nickname="Lena", phone="+30 697 111 2222", notes="Likes the corner table", created_by_id=owner.id)
db.add(c)
db.flush()
o = Order(opened_by=owner.id, status="closed", customer_id=c.id)
db.add(o)
db.flush()
from models.product import Product
p = Product(name="Souvlaki", base_price=4.0)
db.add(p)
db.flush()
db.add(OrderItem(order_id=o.id, product_id=p.id, added_by=owner.id, quantity=3, unit_price=4.0, status="paid", printed=True))
db.commit()
return c
@pytest.fixture
def sent(monkeypatch):
import services.ws_bus as bus
got = []
real = bus.broadcast_sync
monkeypatch.setattr(bus, "broadcast_sync", lambda kind, data, **kw: (got.append((kind, data, kw)), real(kind, data, **kw)))
return got
def test_a_call_is_logged_matched_and_published_to_who_may_see_it(client, db, owner_h, pair, make_user, eleni, sent):
from core.access.queries import users_with_key
pos_token, pos = pair("pos_counter", "Till")
make_user(role="waiter") # no caller_id.use: doesn't hear it
r = client.get("/api/phone/call-event", params={"caller": "6971112222", "ext": "100"})
assert r.status_code == 200, r.text
assert r.json()["matched"] is True
(kind, data, kw), = [x for x in sent if x[0] == "call_incoming"]
assert data["number"] == "6971112222" and data["ext"] == "100"
card = data["customer"]
assert (card["name"], card["nickname"], card["visit_count"], card["total_spent"]) == ("Eleni Papa", "Lena", 1, 12.0)
assert card["recent_orders"][0]["item_count"] == 3
assert sorted(kw["user_ids"]) == sorted(u.id for u in users_with_key(db, "caller_id.use"))
assert kw["device_ids"] == [pos.json()["id"]]
# an unknown number: still logged and published, no customer
client.get("/api/phone/call-event", params={"caller": "2100000000"})
assert sent[-1][1]["customer"] is None
log = client.get("/api/phone/calls", headers=owner_h).json()["calls"]
assert [(c["number"], c["customer"]["name"] if c["customer"] else None) for c in log] == [("2100000000", None), ("6971112222", "Eleni Papa")]
def test_nothing_can_listen_without_signing_in(client, owner_h, make_user):
from starlette.websockets import WebSocketDisconnect
with pytest.raises(Exception):
with client.websocket_connect("/api/phone/ws") as ws:
ws.receive_text()
assert client.get("/api/phone/calls").status_code in (401, 403)
from tests.conftest import TEST_PASSWORD
make_user(role="waiter", username="w_calls")
tok = client.post("/api/auth/login", json={"client": "manager", "username": "w_calls", "password": TEST_PASSWORD}).json().get("access_token")
assert client.get("/api/phone/calls", headers={"Authorization": f"Bearer {tok}"} if tok else {}).status_code in (401, 403)
assert WebSocketDisconnect
def test_the_optional_shared_secret(client, db, sent, owner_h):
from models.settings import PosSettings
db.add(PosSettings(key="caller_id.secret", value="s3cret-ucm"))
db.commit()
assert err(client.get("/api/phone/call-event", params={"caller": "2101234567"})) == "caller_id.key_invalid"
assert err(client.get("/api/phone/call-event", params={"caller": "2101234567", "key": "wrong"})) == "caller_id.key_invalid"
assert client.get("/api/phone/call-event", params={"caller": "2101234567", "key": "s3cret-ucm"}).status_code == 200
assert len([x for x in sent if x[0] == "call_incoming"]) == 1
def test_lookup_by_phone(client, owner_h, eleni):
r = client.get("/api/customers/lookup", params={"phone": "0030 697 111 2222"}, headers=owner_h)
assert r.status_code == 200, r.text
assert r.json()["customer"]["id"] == eleni.id
assert client.get("/api/customers/lookup", params={"phone": "123"}, headers=owner_h).json()["customer"] is None