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
@@ -47,6 +47,7 @@ The manager calls the API **same-origin, with relative paths**. The waiter app r
| `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` | | `local_backend/services/table_qr.py`, `services/qr_orders.py` | The QR menu at the table (phase 3S): every active table has a random `qr_token`; the menu snapshot carries only its sha256 (`qr`), so the cloud can check a code but never make one. A new code (rotate) kills the printed one at the next push (`/api/tables` and `/api/connect/qr` are in `MENU_PATHS`). A QR order with a valid table goes straight onto the table's open order (or a new one), to the kitchen, with a `qr_order` message to the table's waiters; the audit row `QR_ORDER` (note = the cloud ref) keeps repeats out. Manager page `/online/qr` |
| `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) | | `local_backend/routers/fees.py` | The venue's online ordering settings (`connect_orders.ordering`: services, hours, slots, ASAP; `reservations`: bookings, food ahead, fire minutes), delivery areas and fee rules, the fee line's name/VAT, and the venue's links (`links.order`, `links.menu` from the cloud's `apps_url`). Everything here travels to the cloud in the menu snapshot (contract C-2) |
| `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory | | `local_backend/routers/customer_display.py`, `terminal/src/apps/customer-display/` | The customer display (3.4): the counter POS pushes `POST /api/display/state` (`useDisplay()` in `apps/pos/usePos.js`: the sale cart, the payment dialog's bill, then "paid"); only displays whose `linked_device_id` is that POS get `display.state`. The idle screen is the venue's design (`customer_display.idle`: name, logo, both, blank, image, slideshow, QR, a line of text, dark/light), images in `/app/data/display_media`, served by name at `/api/display/media/{name}` (public, LAN, random names). The POS's last state lives in memory |
| `local_backend/routers/phone.py`, `services/caller_id.py` | Caller ID (3.5): the UCM's `GET /api/phone/call-event` is public but **LAN-only in the proxy** (the same `location ~ ^/api/(devices/pair-request|phone/call-event)` block in `nginx-proxy/nginx.conf` and `install.sh`) with an optional `caller_id.secret`; calls are logged (`phone_calls`), matched on the server (Greek number rules) and published as `call_incoming` to users with `caller_id.use` and to the counter screens. There is no public call socket any more |
| `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) | | `local_backend/routers/ws.py` | Real-time event stream (seq + cursor replay) |
| `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` | | `waiter_pwa/src/config/server.js` | **Where the backend is**: active venue, `apiBase()`, `wsUrl()`, `assetUrl()`, `storageKey()`, `dbName()`, `deliveryMode()` |
| `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below | | `waiter_pwa/android/`, `capacitor.config.json` | Native Android app (Capacitor 8). See "Native Android app" below |
+6 -3
View File
@@ -246,7 +246,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
@@ -288,7 +289,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
@@ -330,7 +332,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
+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."), "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.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."), "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_unknown": (404, "Image {name} not found."),
"display.media_type": (422, "Upload a JPG, PNG, WebP or GIF image."), "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)."), "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.printer # noqa: F401
import models.product # noqa: F401 import models.product # noqa: F401
import models.customers # 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.order # noqa: F401 also registers OrderAuditLog, OrderDiscount, PrintJob
import models.business_day # noqa: F401 import models.business_day # noqa: F401
import models.shift # noqa: F401 WaiterShift, ShiftBreak 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.""" """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( MODULE = Module(
key='caller_id', key='caller_id',
kind='integration', kind='integration',
name='Caller ID', 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=( permissions=(
Perm('caller_id.use', 'See incoming calls', roles=('owner', 'store_manager', 'staff_manager')), 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=( routers=(
Mount('routers.phone', '/api/phone'), 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.order import Order, OrderItem
from models.user import User from models.user import User
from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest from schemas.customers import CustomerCreate, CustomerUpdate, CustomerOut, AssignCustomerRequest
from core.access.deps import require_any
from routers.deps import require_manager, get_current_user from routers.deps import require_manager, get_current_user
router = APIRouter() router = APIRouter()
@@ -66,6 +67,16 @@ def create_customer(body: CustomerCreate, db: Session = Depends(get_db), user: U
return _customer_out(customer, db) 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) @router.get("/{customer_id}", response_model=CustomerOut)
def get_customer(customer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)): 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() 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 import secrets
with caller ID and extension details. We broadcast that to all connected from typing import Optional
WebSocket clients (manager dashboard Phone page).
The call-event endpoint is intentionally unauthenticated so the UCM device from fastapi import APIRouter, Depends, Query
(which has no JWT) can POST to it directly on the local LAN. from sqlalchemy.orm import Session
"""
from core.access.deps import public from core.access.deps import public, require
import asyncio from core.errors import XeniaError
import json from database import get_db
import logging
from fastapi import Depends, APIRouter, WebSocket, WebSocketDisconnect, Query
router = APIRouter() router = APIRouter()
logger = logging.getLogger(__name__) KEY = "caller_id.use"
SECRET = "caller_id.secret"
# In-memory list of active WebSocket connections to the Phone page.
_connections: list[WebSocket] = []
@router.websocket("/ws", dependencies=[Depends(public())]) def _setting(db, key: str) -> str:
async def phone_ws(websocket: WebSocket): from models.settings import PosSettings
await websocket.accept() row = db.query(PosSettings).filter(PosSettings.key == key).first()
_connections.append(websocket) return (row.value or "") if row else ""
logger.debug("phone_ws: client connected (%d total)", len(_connections))
try:
# Keep the connection alive; client drives nothing, server pushes events. def call_out(db, call, customer=None) -> dict:
while True: from services import caller_id
await asyncio.sleep(25) from models.customers import Customer
await websocket.send_text(json.dumps({"type": "ping"})) if customer is None and call.customer_id:
except (WebSocketDisconnect, Exception): customer = db.get(Customer, call.customer_id)
pass return {"call_id": call.id, "at": call.at.isoformat() if call.at else None, "number": call.number, "ext": call.ext,
finally: "customer": caller_id.card(db, customer) if customer is not None else None}
_connections.remove(websocket)
logger.debug("phone_ws: client disconnected (%d total)", len(_connections))
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())]) @router.get("/call-event", dependencies=[Depends(public())])
async def call_event( def call_event(caller: str = Query(..., max_length=40, description="Caller ID number from the UCM"),
caller: str = Query(..., description="Caller ID number from UCM"), ext: str = Query("", max_length=20, description="Dialled extension"),
ext: str = Query("", 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"""
Called by the Grandstream UCM Action URL on every incoming call. from models.phone_call import PhoneCall
Example: GET /api/phone/call-event?caller=2106001234&ext=100 from services import caller_id
""" from services.ws_bus import broadcast_sync
payload = json.dumps({"type": "incoming_call", "caller": caller, "ext": ext}) secret = _setting(db, SECRET)
dead = [] if secret and not (key and secrets.compare_digest(key, secret)):
for ws in list(_connections): raise XeniaError("caller_id.key_invalid")
try: customer = caller_id.match(db, caller)
await ws.send_text(payload) call = PhoneCall(number=caller.strip(), ext=ext.strip() or None, customer_id=customer.id if customer else None)
except Exception: db.add(call)
dead.append(ws) db.commit()
for ws in dead: db.refresh(call)
try: payload = call_out(db, call, customer)
_connections.remove(ws) users, pos = _audience(db)
except ValueError: if users or pos:
pass broadcast_sync("call_incoming", payload, user_ids=users, device_ids=pos)
logger.info("phone call-event: caller=%s ext=%s (notified %d clients)", caller, ext, len(_connections) - len(dead)) return {"status": "ok", "call_id": call.id, "matched": customer is not None}
return {"status": "ok", "notified": len(_connections) - len(dead)}
@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
+1 -1
View File
@@ -8,7 +8,7 @@
"build": "vite build", "build": "vite build",
"preview": "vite preview", "preview": "vite preview",
"test": "node --test \"tests/*.test.mjs\"", "test": "node --test \"tests/*.test.mjs\"",
"lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx" "lint": "eslint eslint.config.js tests src/shell src/live src/pages/platform src/pages/online src/pages/staff src/pages/Settings/sections src/pages/LoginPage.jsx src/components/NotificationBell.jsx src/components/PhoneListener.jsx src/pages/PhonePage.jsx src/store/phoneStore.js src/components/UserMenuButton.jsx src/pages/reports/operations/LogsPanel.jsx src/api/client.js src/store/authStore.js src/main.jsx"
}, },
"dependencies": { "dependencies": {
"@tanstack/react-query": "^5.107.1", "@tanstack/react-query": "^5.107.1",
@@ -1,358 +1,81 @@
/** // Caller ID in the manager (plan step 3.5): an incoming call arrives on the signed-in live
* Mounts once inside AppLayout. Holds the WebSocket connection to /api/phone/ws, // connection (`call_incoming`, only for users with caller_id.use), already matched to a
* matches incoming callers against the customer list, and renders the call popup // customer by the server (services/caller_id.py). Shows a popup over any page: the customer's
* over whatever page is currently open. // card with their last orders, or the unknown number. Replaces the old public /api/phone/ws
*/ // socket and the browser-side matching of the whole customer list. Calls older than a minute
import { useEffect, useCallback, useRef, useState } from 'react' // (a reconnect replays events) don't pop up; the call log has them.
import { PhoneIncoming, X, Mail, Phone, MessageSquare, Tag, import { PhoneIncoming, ShoppingBag, Tag, TrendingUp, User } from 'lucide-react'
ShoppingBag, TrendingUp, Clock, User } from 'lucide-react' import { useCan, useModule } from '@xenia/access'
import client from '../api/client' import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import { useLiveEvent } from '../live/useLiveEvent'
import usePhoneStore from '../store/phoneStore' import usePhoneStore from '../store/phoneStore'
/* ─── Phone normalisation ─────────────────────────────────────────────────── */ const FRESH_MS = 60_000
function normalisePhone(raw) {
if (!raw) return ''
let s = raw.replace(/[\s\-().+]/g, '')
if (s.startsWith('0030')) s = s.slice(4)
else if (s.startsWith('30') && s.length > 10) s = s.slice(2)
return s
}
function phonesMatch(a, b) {
const na = normalisePhone(a), nb = normalisePhone(b)
return na.length > 0 && na === nb
}
function buildWsUrl() {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
return `${proto}://${window.location.host}/api/phone/ws`
}
/* ─── Helpers ─────────────────────────────────────────────────────────────── */
function formatTime(date) {
return date.toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function formatDate(dateStr) {
if (!dateStr) return '—'
return new Date(dateStr).toLocaleDateString('el-GR', { day: '2-digit', month: 'short', year: 'numeric' })
}
function formatCurrency(n) {
return `€${Number(n || 0).toFixed(2)}`
}
/* ─── Ripple rings ────────────────────────────────────────────────────────── */
function RippleRings({ color }) {
return (
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
{[0, 1, 2].map(i => (
<span key={i} style={{
position: 'absolute', width: 80, height: 80, borderRadius: '50%',
border: `2px solid ${color}`, opacity: 0,
animation: `phoneRipple 2s ease-out ${i * 0.6}s infinite`,
}} />
))}
</div>
)
}
/* ─── Known customer modal ────────────────────────────────────────────────── */
function KnownCustomerModal({ call, customer, orders, onClose }) {
const recent = (orders || []).slice(0, 3)
return (
<div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
<div onClick={onClose} style={{
position: 'fixed', inset: 0, zIndex: 9990,
background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
animation: 'fadeIn 0.2s ease',
}} />
<div style={{
position: 'fixed', zIndex: 9991,
top: '50%', left: '50%',
transform: 'translate(-50%,-50%)',
width: '100%', maxWidth: 480, padding: '0 16px',
animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
}}>
<div style={{
background: '#0f1117', borderRadius: 20, overflow: 'hidden',
boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
}}>
<div style={{ height: 3, background: 'linear-gradient(90deg,#d4a853,#f0c87a,#d4a853)' }} />
<div style={{ padding: '24px 24px 20px', position: 'relative' }}>
<button onClick={onClose} style={{
position: 'absolute', top: 20, right: 20,
width: 32, height: 32, borderRadius: 8,
background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
color: '#9ca3af', cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
><X size={14} /></button>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
<div style={{ position: 'relative', width: 44, height: 44 }}>
<RippleRings color="#d4a853" />
<div style={{
width: 44, height: 44, borderRadius: '50%',
background: 'linear-gradient(135deg,#d4a853,#f0c87a)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
position: 'relative', zIndex: 1,
}}><PhoneIncoming size={18} color="#0f1117" /></div>
</div>
<div>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#d4a853', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
<div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)} · {call.caller}</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
<div style={{
width: 56, height: 56, borderRadius: 14, flexShrink: 0,
background: 'linear-gradient(135deg,#1e293b,#334155)',
border: '1px solid rgba(212,168,83,0.3)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 22, fontWeight: 700, color: '#d4a853',
}}>{customer.name?.[0]?.toUpperCase() || '?'}</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', lineHeight: 1.2, letterSpacing: '-0.01em' }}>{customer.name}</div>
{customer.nickname && (
<div style={{ fontSize: 13, color: '#d4a853', marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
<Tag size={11} />{customer.nickname}
</div>
)}
</div>
</div>
</div>
<div style={{ height: 1, background: 'rgba(255,255,255,0.06)', margin: '0 24px' }} />
<div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
{customer.email && (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<Mail size={13} color="#6b7280" style={{ flexShrink: 0 }} />
<span style={{ fontSize: 13, color: '#d1d5db' }}>{customer.email}</span>
</div>
)}
{customer.phone && (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<Phone size={13} color="#6b7280" style={{ flexShrink: 0 }} />
<span style={{ fontSize: 13, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>{customer.phone}</span>
</div>
)}
{customer.notes && (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 2 }}>
<MessageSquare size={13} color="#6b7280" style={{ flexShrink: 0, marginTop: 1 }} />
<span style={{ fontSize: 13, color: '#9ca3af', lineHeight: 1.5, fontStyle: 'italic' }}>"{customer.notes}"</span>
</div>
)}
</div>
<div style={{
margin: '0 24px',
background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
borderRadius: 12, display: 'grid', gridTemplateColumns: '1fr 1fr',
}}>
<div style={{ padding: '12px 16px', borderRight: '1px solid rgba(255,255,255,0.07)' }}>
<div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Επισκέψεις</div>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
<ShoppingBag size={14} color="#d4a853" />{customer.visit_count ?? 0}
</div>
</div>
<div style={{ padding: '12px 16px' }}>
<div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Σύνολο</div>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
<TrendingUp size={14} color="#d4a853" />{formatCurrency(customer.total_spent)}
</div>
</div>
</div>
<div style={{ padding: '16px 24px 0' }}>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', color: '#6b7280', textTransform: 'uppercase', marginBottom: 8 }}>Πρόσφατες Παραγγελίες</div>
{recent.length === 0 ? (
<div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px dashed rgba(255,255,255,0.08)', fontSize: 12, color: '#4b5563', textAlign: 'center' }}>
Δεν υπάρχουν παραγγελίες ακόμα
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{recent.map(order => (
<div key={order.id} style={{
display: 'flex', alignItems: 'center', gap: 10,
padding: '9px 12px', borderRadius: 10,
background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)',
}}>
<Clock size={12} color="#6b7280" style={{ flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 12, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>
{formatDate(order.opened_at)}
{order.table_name && <span style={{ color: '#6b7280' }}> · {order.table_name}</span>}
</div>
<div style={{ fontSize: 11, color: '#6b7280', marginTop: 1 }}>{order.item_count} είδη</div>
</div>
<div style={{ fontSize: 13, fontWeight: 600, color: '#d4a853', fontVariantNumeric: 'tabular-nums' }}>{formatCurrency(order.total)}</div>
</div>
))}
</div>
)}
</div>
<div style={{ padding: '20px 24px' }}>
<button onClick={onClose} style={{
width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
background: 'rgba(212,168,83,0.12)', color: '#d4a853', fontSize: 13, fontWeight: 600,
letterSpacing: '0.02em', transition: 'all 0.15s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.2)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.12)' }}
>Κλείσιμο</button>
</div>
</div>
</div>
</div>
)
}
/* ─── Unknown caller modal ────────────────────────────────────────────────── */
function UnknownCallerModal({ call, onClose }) {
return (
<div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
<div onClick={onClose} style={{
position: 'fixed', inset: 0, zIndex: 9990,
background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
animation: 'fadeIn 0.2s ease',
}} />
<div style={{
position: 'fixed', zIndex: 9991,
top: '50%', left: '50%',
transform: 'translate(-50%,-50%)',
width: '100%', maxWidth: 360, padding: '0 16px',
animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
}}>
<div style={{
background: '#0f1117', borderRadius: 20, overflow: 'hidden',
boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
}}>
<div style={{ height: 3, background: 'linear-gradient(90deg,#3b82f6,#6366f1,#3b82f6)' }} />
<div style={{ padding: '28px 24px 24px', position: 'relative' }}>
<button onClick={onClose} style={{
position: 'absolute', top: 20, right: 20,
width: 32, height: 32, borderRadius: 8,
background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
color: '#9ca3af', cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
><X size={14} /></button>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
<div style={{ position: 'relative', width: 44, height: 44 }}>
<RippleRings color="#3b82f6" />
<div style={{
width: 44, height: 44, borderRadius: '50%',
background: 'linear-gradient(135deg,#1d4ed8,#3b82f6)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
position: 'relative', zIndex: 1,
}}><PhoneIncoming size={18} color="#fff" /></div>
</div>
<div>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#3b82f6', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
<div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)}</div>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '20px 0 8px' }}>
<div style={{
width: 56, height: 56, borderRadius: 14,
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}><User size={24} color="#4b5563" /></div>
<div style={{ fontSize: 12, color: '#6b7280' }}>Άγνωστος καλών</div>
<div style={{ fontSize: 28, fontWeight: 700, color: '#f9fafb', letterSpacing: '0.02em', fontVariantNumeric: 'tabular-nums' }}>
{call.caller || '—'}
</div>
{call.ext && <div style={{ fontSize: 12, color: '#6b7280' }}>Εσωτερικό: {call.ext}</div>}
</div>
<div style={{ marginTop: 20 }}>
<button onClick={onClose} style={{
width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
background: 'rgba(59,130,246,0.1)', color: '#3b82f6', fontSize: 13, fontWeight: 600,
transition: 'all 0.15s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.18)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.1)' }}
>Κλείσιμο</button>
</div>
</div>
</div>
</div>
</div>
)
}
/* ─── PhoneListener ───────────────────────────────────────────────────────── */
export default function PhoneListener() { export default function PhoneListener() {
const on = useModule('caller_id')
const allowed = useCan('caller_id.use')
const { activeCall, dismissCall, setActiveCall, addCallToLog } = usePhoneStore() const { activeCall, dismissCall, setActiveCall, addCallToLog } = usePhoneStore()
const [customers, setCustomers] = useState([]) useLiveEvent('call_incoming', call => {
if (!on || !allowed || !call) return
useEffect(() => { addCallToLog(call)
client.get('/api/customers/') if (!call.at || Date.now() - Date.parse(call.at) < FRESH_MS) setActiveCall(call)
.then(r => setCustomers(r.data || [])) })
.catch(() => {})
}, [])
const handleIncoming = useCallback(async ({ caller, ext }) => {
const at = new Date()
const matched = customers.find(c => phonesMatch(c.phone, caller))
let orders = null
if (matched) {
try {
const r = await client.get(`/api/customers/${matched.id}/orders`)
orders = r.data?.orders ?? []
} catch { orders = [] }
}
const entry = { caller, ext, at, customer: matched || null, orders }
addCallToLog(entry)
setActiveCall(entry)
}, [customers, addCallToLog, setActiveCall])
useEffect(() => {
let ws, dead = false
function connect() {
if (dead) return
ws = new WebSocket(buildWsUrl())
ws.onclose = () => { if (!dead) setTimeout(connect, 3000) }
ws.onerror = () => ws.close()
ws.onmessage = (ev) => {
try {
const data = JSON.parse(ev.data)
if (data.type === 'incoming_call') handleIncoming({ caller: data.caller, ext: data.ext })
} catch {}
}
}
connect()
return () => { dead = true; ws?.close() }
}, [handleIncoming])
if (!activeCall) return null if (!activeCall) return null
return <CallDialog call={activeCall} onClose={dismissCall} />
}
export function CallDialog({ call, onClose }) {
const { t } = useTranslation('manager')
const { formatMoney, formatTime, formatDate } = useFormat()
const c = call.customer
return ( return (
<Dialog open size="md" onClose={onClose} title={t('calls.incoming')}
footer={<Button variant="secondary" onClick={onClose} data-testid="call-close">{t('calls.close')}</Button>}>
<div className="grid gap-4" data-testid="call-popup" data-call={call.call_id}>
<div className="flex items-center gap-3">
<span className="size-12 rounded-full bg-accent-soft text-accent-ink flex items-center justify-center shrink-0">
{c ? <span className="text-title font-semibold">{c.name?.[0]?.toUpperCase()}</span> : <PhoneIncoming size={20} aria-hidden="true" />}
</span>
<div className="min-w-0">
<p className="text-heading font-semibold text-ink truncate" data-testid="call-name">{c ? c.name : t('calls.unknown')}</p>
<p className="text-label text-ink-2">
{call.number}{call.ext ? ` · ${t('calls.ext', { ext: call.ext })}` : ''}{call.at ? ` · ${formatTime(call.at)}` : ''}
</p>
{c?.nickname && <p className="text-label text-accent-ink flex items-center gap-1"><Tag size={12} aria-hidden="true" />{c.nickname}</p>}
</div>
</div>
{c ? (
<> <>
<style>{` {c.notes && <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-body">“{c.notes}”</p>}
@keyframes fadeIn { from{opacity:0} to{opacity:1} } <div className="grid grid-cols-2 gap-2">
@keyframes slideUp { <Stat icon={<ShoppingBag size={14} aria-hidden="true" />} label={t('calls.visits')} value={c.visit_count} />
from{opacity:0;transform:translate(-50%,calc(-50% + 24px))} <Stat icon={<TrendingUp size={14} aria-hidden="true" />} label={t('calls.spent')} value={formatMoney(c.total_spent)} />
to{opacity:1;transform:translate(-50%,-50%)} </div>
} <div className="grid gap-1.5">
@keyframes phoneRipple { <p className="text-label font-medium text-ink-2">{t('calls.recent')}</p>
0%{transform:scale(1);opacity:0.6} {c.recent_orders.length === 0 ? <p className="text-label text-ink-3">{t('calls.noOrders')}</p> : c.recent_orders.map(o => (
100%{transform:scale(2.8);opacity:0} <div key={o.id} className="flex items-center gap-3 p-2 rounded-control bg-surface-2 text-body">
} <span className="flex-1">{formatDate(o.opened_at)}{o.table_name ? ` · ${o.table_name}` : ''} · {t('calls.items', { count: o.item_count })}</span>
`}</style> <span className="font-medium">{formatMoney(o.total)}</span>
{activeCall.customer </div>
? <KnownCustomerModal call={activeCall} customer={activeCall.customer} orders={activeCall.orders} onClose={dismissCall} /> ))}
: <UnknownCallerModal call={activeCall} onClose={dismissCall} /> </div>
}
</> </>
) : (
<p className="text-body text-ink-2 flex items-center gap-2"><User size={16} aria-hidden="true" />{t('calls.unknownBody')}</p>
)}
</div>
</Dialog>
)
}
function Stat({ icon, label, value }) {
return (
<div className="p-3 rounded-control border border-line">
<p className="text-caption text-ink-2">{label}</p>
<p className="text-title font-semibold text-ink flex items-center gap-1.5">{icon}{value}</p>
</div>
) )
} }
+53 -82
View File
@@ -1,96 +1,67 @@
import { Phone, PhoneIncoming, ChevronRight, Wifi, WifiOff } from 'lucide-react' // Integrations → Caller ID (plan step 3.5): the call log (GET /api/phone/calls, kept on the
// server, so it survives a reload and shows calls taken while the manager was closed), new calls
// live, a tap opens the caller's card; and how to connect the phone system (the UCM Action URL).
import { useCallback, useEffect, useState } from 'react'
import { PhoneIncoming } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
import client from '../api/client'
import { useLiveEvent } from '../live/useLiveEvent'
import usePhoneStore from '../store/phoneStore' import usePhoneStore from '../store/phoneStore'
function formatTime(date) {
return date.toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
export default function PhonePage() { export default function PhonePage() {
const { log, setActiveCall } = usePhoneStore() const { t } = useTranslation('manager')
const { formatDateTime } = useFormat()
const setActiveCall = usePhoneStore(s => s.setActiveCall)
const [calls, setCalls] = useState(null)
const [error, setError] = useState(null)
const load = useCallback(async () => {
try { setCalls((await client.get('/api/phone/calls', { params: { limit: 100 } })).data.calls); setError(null) } catch (err) { setError(errorMessage(err, t)) }
}, [t])
useEffect(() => { load() }, [load])
useLiveEvent('call_incoming', load)
useLiveEvent('ready', load)
const hook = `${window.location.protocol}//${window.location.hostname}/api/phone/call-event?caller=\${CALLERID}&ext=\${EXTEN}`
return ( return (
<div style={{ padding: 32, fontFamily: "'DM Sans','Segoe UI',sans-serif", maxWidth: 680, margin: '0 auto' }}> <div className="p-4 md:p-6 grid gap-6 max-w-3xl" data-testid="phone-page">
<header className="grid gap-1">
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}> <h1 className="text-heading font-semibold text-ink">{t('calls.title')}</h1>
<div style={{ <p className="text-body text-ink-2">{t('calls.intro')}</p>
width: 40, height: 40, borderRadius: 10, </header>
background: 'linear-gradient(135deg,#064e3b,#065f46)', <section className="rounded-card border border-line bg-surface overflow-hidden" aria-labelledby="calls-h">
border: '1px solid rgba(52,211,153,0.2)', <h2 id="calls-h" className="px-4 py-3 border-b border-line text-label font-semibold text-ink-2">{t('calls.log')}</h2>
display: 'flex', alignItems: 'center', justifyContent: 'center', {error ? <div className="p-6"><EmptyState title={error} /></div>
}}> : calls == null ? <div className="p-6 flex justify-center"><Spinner /></div>
<Phone size={18} color="#34d399" /> : calls.length === 0 ? <div className="p-6"><EmptyState icon={<PhoneIncoming size={28} />} title={t('calls.none')} /></div>
</div> : (
<div> <ul className="divide-y divide-line" data-testid="call-log">
<h1 style={{ fontSize: 16, fontWeight: 700, color: '#0f172a', margin: 0, letterSpacing: '-0.01em' }}> {calls.map(c => (
Εισερχόμενες Κλήσεις <li key={c.call_id}>
</h1> <button type="button" onClick={() => setActiveCall(c)} data-testid="call-row"
<p style={{ fontSize: 12, color: '#94a3b8', margin: '2px 0 0' }}>Grandstream UCM · Caller ID</p> className="w-full px-4 py-3 flex items-center gap-3 text-left hover:bg-surface-2 transition-colors duration-fast">
</div> <span className="size-9 rounded-full bg-surface-2 text-ink-2 flex items-center justify-center shrink-0 font-semibold">
</div> {c.customer ? c.customer.name?.[0]?.toUpperCase() : <PhoneIncoming size={14} aria-hidden="true" />}
<div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 16, overflow: 'hidden' }}>
<div style={{
padding: '12px 16px', borderBottom: '1px solid #f1f5f9',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
}}>
<span style={{ fontSize: 11, fontWeight: 600, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
Πρόσφατες Κλήσεις
</span> </span>
{log.length > 0 && ( <span className="flex-1 min-w-0">
<span style={{ fontSize: 11, color: '#cbd5e1' }}>{log.length} κλήσεις</span> <span className="block text-body font-medium text-ink truncate">{c.customer ? c.customer.name : c.number}</span>
)} <span className="block text-label text-ink-2">{c.customer ? c.number : t('calls.unknown')}{c.ext ? ` · ${t('calls.ext', { ext: c.ext })}` : ''}</span>
</div>
{log.length === 0 ? (
<div style={{ padding: '48px 16px', textAlign: 'center', color: '#cbd5e1', fontSize: 13 }}>
Δεν έχουν ληφθεί κλήσεις ακόμα.
</div>
) : (
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{log.map((entry, i) => (
<li
key={i}
onClick={() => setActiveCall(entry)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 16px',
borderBottom: i < log.length - 1 ? '1px solid #f8fafc' : 'none',
cursor: 'pointer', transition: 'background 0.1s',
}}
onMouseEnter={e => { e.currentTarget.style.background = '#f8fafc' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
>
<div style={{
width: 34, height: 34, borderRadius: 10, flexShrink: 0,
background: entry.customer ? '#fef3c7' : '#f1f5f9',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{entry.customer
? <span style={{ fontSize: 14, fontWeight: 700, color: '#d97706' }}>
{entry.customer.name?.[0]?.toUpperCase()}
</span> </span>
: <PhoneIncoming size={14} color="#94a3b8" /> <span className="text-label text-ink-3">{formatDateTime(c.at, 'datetimeShort')}</span>
} </button>
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>
{entry.customer ? entry.customer.name : entry.caller || '—'}
</div>
<div style={{ fontSize: 11, color: '#94a3b8', marginTop: 1 }}>
{entry.customer ? entry.caller : 'Άγνωστος'}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 11, color: '#cbd5e1', fontVariantNumeric: 'tabular-nums' }}>
{formatTime(entry.at)}
</span>
<ChevronRight size={12} color="#cbd5e1" />
</div>
</li> </li>
))} ))}
</ul> </ul>
)} )}
</div> </section>
<section className="p-4 rounded-card border border-line bg-surface-2 grid gap-1.5">
<h2 className="text-label font-semibold text-ink">{t('calls.setup')}</h2>
<p className="text-label text-ink-2">{t('calls.setupBody')}</p>
<code className="text-label text-ink break-all bg-surface p-2 rounded-control border border-line">{hook}</code>
<p className="text-caption text-ink-3">{t('calls.setupSecret')}</p>
</section>
</div> </div>
) )
} }
+4 -2
View File
@@ -1,11 +1,13 @@
import { create } from 'zustand' import { create } from 'zustand'
// Caller ID (plan step 3.5): the call on screen and the calls seen in this session. A call is
// the server's `call_incoming` payload: { call_id, at, number, ext, customer | null }.
const usePhoneStore = create((set) => ({ const usePhoneStore = create((set) => ({
activeCall: null, // { caller, ext, at, customer, orders } | null activeCall: null,
log: [], // last 20 calls log: [], // last 20 calls
setActiveCall: (call) => set({ activeCall: call }), setActiveCall: (call) => set({ activeCall: call }),
dismissCall: () => set({ activeCall: null }), dismissCall: () => set({ activeCall: null }),
addCallToLog: (entry) => set(s => ({ log: [entry, ...s.log].slice(0, 20) })), addCallToLog: (entry) => set(s => ({ log: [entry, ...s.log.filter(c => c.call_id !== entry.call_id)].slice(0, 20) })),
})) }))
export default usePhoneStore export default usePhoneStore
+6 -3
View File
@@ -143,7 +143,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
@@ -185,7 +186,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
@@ -227,7 +229,8 @@ server {
ssl_ciphers HIGH:!aNULL:!MD5; ssl_ciphers HIGH:!aNULL:!MD5;
# Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair. # Device pairing is LAN-only (APPS_PLATFORM D-8): a device must be in the venue to pair.
location /api/devices/pair-request { # So is the phone system's call webhook (caller ID, plan step 3.5): only the venue's UCM calls it.
location ~ ^/api/(devices/pair-request|phone/call-event) {
allow 10.0.0.0/8; allow 10.0.0.0/8;
allow 172.16.0.0/12; allow 172.16.0.0/12;
allow 192.168.0.0/16; allow 192.168.0.0/16;
+3
View File
@@ -116,5 +116,8 @@
"media_type": "Ανεβάστε εικόνα JPG, PNG, WebP ή GIF.", "media_type": "Ανεβάστε εικόνα JPG, PNG, WebP ή GIF.",
"media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).", "media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).",
"qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός." "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός."
},
"caller_id": {
"key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος."
} }
} }
+20
View File
@@ -658,5 +658,25 @@
"pickSlides": "Διαλέξτε τις φωτογραφίες, με τη σειρά (ξανά πάτημα για αφαίρεση)", "pickSlides": "Διαλέξτε τις φωτογραφίες, με τη σειρά (ξανά πάτημα για αφαίρεση)",
"upload": "Ανέβασμα εικόνων", "upload": "Ανέβασμα εικόνων",
"noImages": "Δεν υπάρχουν εικόνες: ανεβάστε (JPG, PNG, WebP ή GIF, έως 5 MB)." "noImages": "Δεν υπάρχουν εικόνες: ανεβάστε (JPG, PNG, WebP ή GIF, έως 5 MB)."
},
"calls": {
"title": "Αναγνώριση κλήσης",
"intro": "Εισερχόμενες κλήσεις από το τηλεφωνικό σας κέντρο, με την καρτέλα του πελάτη όταν τον γνωρίζουμε. Η διαχείριση και το ταμείο δείχνουν ειδοποίηση.",
"incoming": "Εισερχόμενη κλήση",
"close": "Κλείσιμο",
"unknown": "Άγνωστος καλών",
"unknownBody": "Δεν είναι ακόμα πελάτης σας.",
"ext": "εσωτ. {{ext}}",
"visits": "Επισκέψεις",
"spent": "Σύνολο",
"recent": "Τελευταίες παραγγελίες",
"noOrders": "Καμία παραγγελία ακόμα",
"items_one": "{{count}} είδος",
"items_other": "{{count}} είδη",
"log": "Κλήσεις",
"none": "Καμία κλήση ακόμα",
"setup": "Σύνδεση του τηλεφωνικού κέντρου",
"setupBody": "Στο Grandstream UCM, ορίστε το Action URL για τις εισερχόμενες κλήσεις σε αυτή τη διεύθυνση (λειτουργεί μόνο μέσα από το κατάστημα):",
"setupSecret": "Για επιπλέον ασφάλεια, ορίστε ένα κλειδί στις Ρυθμίσεις (caller_id.secret) και προσθέστε &key=<το κλειδί> στη διεύθυνση."
} }
} }
+7
View File
@@ -464,6 +464,13 @@
"arrive": "Ήρθαν: καθίστε τους", "arrive": "Ήρθαν: καθίστε τους",
"cancel": "Ακύρωση", "cancel": "Ακύρωση",
"noShow": "Δεν ήρθαν" "noShow": "Δεν ήρθαν"
},
"call": {
"title": "Εισερχόμενη κλήση",
"unknown": "Άγνωστος καλών",
"takeaway": "Νέα πώληση για παραλαβή",
"visits_one": "{{count}} επίσκεψη · {{spent}}",
"visits_other": "{{count}} επισκέψεις · {{spent}}"
} }
}, },
"display": { "display": {
+3
View File
@@ -116,5 +116,8 @@
"media_type": "Upload a JPG, PNG, WebP or GIF image.", "media_type": "Upload a JPG, PNG, WebP or GIF image.",
"media_too_big": "The image is too big (at most {{max_mb}} MB).", "media_too_big": "The image is too big (at most {{max_mb}} MB).",
"qr_url_missing": "Enter the link the QR code opens." "qr_url_missing": "Enter the link the QR code opens."
},
"caller_id": {
"key_invalid": "The phone system's key is missing or wrong."
} }
} }
+20
View File
@@ -658,5 +658,25 @@
"pickSlides": "Pick the photos, in order (tap again to remove)", "pickSlides": "Pick the photos, in order (tap again to remove)",
"upload": "Upload images", "upload": "Upload images",
"noImages": "No images yet: upload some (JPG, PNG, WebP or GIF, up to 5 MB)." "noImages": "No images yet: upload some (JPG, PNG, WebP or GIF, up to 5 MB)."
},
"calls": {
"title": "Caller ID",
"intro": "Incoming calls from your phone system, with the caller's customer card when we know them. The manager and the counter show a popup.",
"incoming": "Incoming call",
"close": "Close",
"unknown": "Unknown caller",
"unknownBody": "Not one of your customers yet.",
"ext": "ext. {{ext}}",
"visits": "Visits",
"spent": "Spent",
"recent": "Last orders",
"noOrders": "No orders yet",
"items_one": "{{count}} item",
"items_other": "{{count}} items",
"log": "Calls",
"none": "No calls yet",
"setup": "Connect the phone system",
"setupBody": "In the Grandstream UCM, set the Action URL for incoming calls to this address (it only works from inside the venue):",
"setupSecret": "For extra safety, set a key in Settings (caller_id.secret) and add &key=<the key> to the address."
} }
} }
+7
View File
@@ -464,6 +464,13 @@
"arrive": "They're here: seat them", "arrive": "They're here: seat them",
"cancel": "Cancel", "cancel": "Cancel",
"noShow": "No-show" "noShow": "No-show"
},
"call": {
"title": "Incoming call",
"unknown": "Unknown caller",
"takeaway": "New takeaway sale",
"visits_one": "{{count}} visit · {{spent}}",
"visits_other": "{{count}} visits · {{spent}}"
} }
}, },
"display": { "display": {
+44
View File
@@ -0,0 +1,44 @@
// Caller ID at the counter (plan step 3.5): the venue's phone rings → the server matches the
// customer and sends `call_incoming` to the counter screens (addressed to the devices). A popup
// shows who is calling (their card and last orders, or the number) with "New takeaway sale"
// (the usual reason a regular calls). Calls older than a minute (a reconnect replays events)
// don't pop up.
import { PhoneIncoming, ShoppingBag } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
export default function CallPopup({ call, onClose, onTakeaway }) {
const { t } = useTranslation('terminal')
const { formatMoney, formatDate } = useFormat()
const c = call.customer
return (
<Dialog open size="sm" onClose={onClose} title={t('pos.call.title')}
footer={<>
<Button variant="secondary" onClick={onClose} data-testid="call-close">{t('pos.dialog.close')}</Button>
<Button icon={<ShoppingBag size={16} />} onClick={onTakeaway} data-testid="call-takeaway">{t('pos.call.takeaway')}</Button>
</>}>
<div className="grid gap-3" data-testid="call-popup" data-call={call.call_id}>
<div className="flex items-center gap-3">
<span className="size-12 rounded-full bg-accent-soft text-accent-ink flex items-center justify-center shrink-0 text-title font-semibold">
{c ? c.name?.[0]?.toUpperCase() : <PhoneIncoming size={20} aria-hidden="true" />}
</span>
<div className="min-w-0">
<p className="text-heading font-semibold truncate" data-testid="call-name">{c ? c.name : t('pos.call.unknown')}</p>
<p className="text-label text-ink-2">{call.number}{c?.nickname ? ` · ${c.nickname}` : ''}</p>
</div>
</div>
{c?.notes && <p className="p-2 rounded-control bg-warning-soft text-warning-ink text-body">“{c.notes}”</p>}
{c && (
<div className="grid gap-1">
<p className="text-label text-ink-2">{t('pos.call.visits', { count: c.visit_count, spent: formatMoney(c.total_spent) })}</p>
{c.recent_orders.map(o => (
<div key={o.id} className="flex justify-between gap-2 p-2 rounded-control bg-surface-2 text-body">
<span>{formatDate(o.opened_at)}{o.table_name ? ` · ${o.table_name}` : ''}</span><span>{formatMoney(o.total)}</span>
</div>
))}
</div>
)}
</div>
</Dialog>
)
}
+15
View File
@@ -22,6 +22,8 @@ import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultS
import { findOnline, ONLINE_LISTS } from './logic/online' import { findOnline, ONLINE_LISTS } from './logic/online'
import { BOOKING_LIST, findBooking } from './logic/bookings' import { BOOKING_LIST, findBooking } from './logic/bookings'
import BookingPanel from './BookingPanel' import BookingPanel from './BookingPanel'
import CallPopup from './CallPopup'
import { isFresh } from './logic/calls'
import BookingsView from './BookingsView' import BookingsView from './BookingsView'
import { zoneCounts } from './logic/tables' import { zoneCounts } from './logic/tables'
import OnlinePanel from './OnlinePanel' import OnlinePanel from './OnlinePanel'
@@ -79,6 +81,14 @@ function Counter({ menu, t }) {
ring() ring()
if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 })) if (mode !== 'online') toast.info(t('pos.online.arrived', { count: data?.count ?? 1 }))
}) })
// caller ID (3.5): the venue's phone rings; the server says who it is
const callerOn = useModule('caller_id')
const [call, setCall] = useState(null)
useLiveEvent('call_incoming', data => {
if (!callerOn || !isFresh(data)) return
ring()
setCall(data)
})
useLiveEvent('reservation_requested', data => { useLiveEvent('reservation_requested', data => {
if (!onlineOn) return if (!onlineOn) return
ring() ring()
@@ -226,6 +236,11 @@ function Counter({ menu, t }) {
</> </>
)} )}
{call && (
<CallPopup call={call} onClose={() => setCall(null)}
onTakeaway={() => { setCall(null); setMode('sale'); leaveTable(); setOrderType('takeaway') }} />
)}
{dialog && ( {dialog && (
<ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)} <ProductDialog product={dialog} orderType={atTable ? 'here' : orderType} onClose={() => setDialog(null)}
onAdd={line => setCart(c => addLine(c, line))} /> onAdd={line => setCart(c => addLine(c, line))} />
+8
View File
@@ -0,0 +1,8 @@
// Caller ID at the counter (plan step 3.5). Pure: unit-tested in Node (tests/pos.test.mjs).
export const FRESH_MS = 60_000
/** Should this call pop up now? (A reconnect replays events: old calls stay quiet.) */
export function isFresh(call, now = Date.now()) {
return !!call && (!call.at || now - Date.parse(call.at) < FRESH_MS)
}
+9
View File
@@ -221,3 +221,12 @@ test('table bookings at the counter (S.6)', async () => {
assert.equal(whenLabel(new Date().toISOString(), fmt, t), 'pos.bookings.today:21:30') assert.equal(whenLabel(new Date().toISOString(), fmt, t), 'pos.bookings.today:21:30')
assert.equal(whenLabel('2020-01-01T10:00:00Z', fmt, t), 'other day') assert.equal(whenLabel('2020-01-01T10:00:00Z', fmt, t), 'other day')
}) })
test('caller ID: only fresh calls pop up (3.5)', async () => {
const { isFresh, FRESH_MS } = await import('../src/apps/pos/logic/calls.js')
const now = Date.parse('2026-11-17T10:00:00Z')
assert.equal(isFresh({ at: '2026-11-17T09:59:30Z' }, now), true)
assert.equal(isFresh({ at: new Date(now - FRESH_MS - 1).toISOString() }, now), false)
assert.equal(isFresh({}, now), true)
assert.equal(isFresh(null, now), false)
})
+13
View File
@@ -590,6 +590,19 @@ try {
r.check('fees: …and it never shows in the products list', !(await api('GET', '/api/products/?all=true', { token: boss })).some(p => p.id === feeProduct?.id)) r.check('fees: …and it never shows in the products list', !(await api('GET', '/api/products/?all=true', { token: boss })).some(p => p.id === feeProduct?.id))
await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true }) await page.screenshot({ path: path.join(OUT, 'manager-fees.png'), fullPage: true })
// 3.5: caller ID in the manager, on the signed-in live connection
await api('PUT', '/api/platform/modules/caller_id', { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${APP}/apps/phone`)
await page.getByTestId('phone-page').waitFor({ timeout: 10_000 })
await page.waitForFunction(() => document.documentElement.dataset.live === 'ready', null, { timeout: 10_000 }).catch(() => {})
await fetch(`${backend.url}/api/phone/call-event?caller=2101112233&ext=101`)
r.check('caller ID: a call pops up in the manager (unknown number)', await page.getByTestId('call-popup').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& (await page.getByTestId('call-popup').textContent()).includes('2101112233'))
await page.getByTestId('call-close').click()
r.check('caller ID: …and is in the call log', await page.getByTestId('call-row').first().waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
&& (await page.getByTestId('call-log').textContent()).includes('2101112233'))
await page.screenshot({ path: path.join(OUT, 'manager-calls.png'), fullPage: true })
// 3.4: the customer display's idle screen, the venue's choice // 3.4: the customer display's idle screen, the venue's choice
await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {}) await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {})
await page.goto(`${APP}/settings`) await page.goto(`${APP}/settings`)
+18
View File
@@ -732,6 +732,24 @@ try {
r.check('3.4: …or a slideshow of its photos, with its line of text', r.check('3.4: …or a slideshow of its photos, with its line of text',
await myDisplay.waitForFunction(() => document.querySelectorAll('[data-testid="display-slide"]').length === 2, null, { timeout: 20_000 }).then(() => true).catch(() => false) await myDisplay.waitForFunction(() => document.querySelectorAll('[data-testid="display-slide"]').length === 2, null, { timeout: 20_000 }).then(() => true).catch(() => false)
&& (await myDisplay.getByTestId('display-message').textContent()) === 'Today: 2 for 1') && (await myDisplay.getByTestId('display-message').textContent()) === 'Today: 2 for 1')
// ── 3.5: caller ID at the counter ────────────────────────────────────────
await api('PUT', '/api/platform/modules/caller_id', { token: boss, body: { enabled: true } }).catch(() => {})
await api('POST', '/api/customers/', { token: boss, body: { name: 'Kostas Regular', phone: '+30 697 555 1234', notes: 'Always extra tzatziki' } })
const callRes = await fetch(`${backend.url}/api/phone/call-event?caller=6975551234&ext=100`)
r.check('3.5: the phone system\'s webhook takes the call', callRes.ok, String(callRes.status))
r.check('3.5: the counter pops up who is calling (matched on the server)', await shown(page, 'call-popup', 8000)
&& (await page.getByTestId('call-name').textContent()) === 'Kostas Regular' && (await page.getByTestId('call-popup').textContent()).includes('extra tzatziki'))
await page.screenshot({ path: path.join(OUT, 'terminal-pos-call.png') })
await page.getByTestId('call-takeaway').click()
r.check('3.5: …"New takeaway sale" opens a takeaway sale', await page.getByTestId('type-takeaway').getAttribute('aria-checked') === 'true'
&& await page.getByTestId('call-popup').count() === 0)
const oldWs = await new Promise(res => {
const ws = new WebSocket(`${backend.url.replace('http', 'ws')}/api/phone/ws`)
ws.onopen = () => { ws.close(); res('open') }
ws.onerror = () => res('refused')
setTimeout(() => res('timeout'), 5000)
})
r.check('3.5: the old public call socket is gone (nothing listens without signing in)', oldWs !== 'open', oldWs)
await myDisplay.context().close() await myDisplay.context().close()
await otherDisplay.context().close() await otherDisplay.context().close()
drawerServer.close() drawerServer.close()