From dabe807ce0259ad4b6e502fddf6862d77794bb4d Mon Sep 17 00:00:00 2001 From: bonamin Date: Mon, 16 Nov 2026 09:06:39 +0200 Subject: [PATCH] feat(connect): caller ID as an integration: calls on the signed-in live connection, matched on the server MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/README.md | 1 + install.sh | 9 +- local_backend/core/errors.py | 1 + .../migrations/versions/0023_phone_calls.py | 35 ++ local_backend/models/all.py | 1 + local_backend/models/phone_call.py | 15 + local_backend/modules/caller_id/manifest.py | 7 +- local_backend/routers/customers.py | 11 + local_backend/routers/phone.py | 124 +++--- local_backend/services/caller_id.py | 59 +++ local_backend/tests/test_caller_id.py | 97 ++++ manager_dashboard/package.json | 2 +- .../src/components/PhoneListener.jsx | 419 +++--------------- manager_dashboard/src/pages/PhonePage.jsx | 147 +++--- manager_dashboard/src/store/phoneStore.js | 6 +- nginx-proxy/nginx.conf | 9 +- packages/i18n/locales/el/errors.json | 3 + packages/i18n/locales/el/manager.json | 20 + packages/i18n/locales/el/terminal.json | 7 + packages/i18n/locales/en/errors.json | 3 + packages/i18n/locales/en/manager.json | 20 + packages/i18n/locales/en/terminal.json | 7 + terminal/src/apps/pos/CallPopup.jsx | 44 ++ terminal/src/apps/pos/PosScreen.jsx | 15 + terminal/src/apps/pos/logic/calls.js | 8 + terminal/tests/pos.test.mjs | 9 + tests/e2e/manager.mjs | 13 + tests/e2e/terminal.mjs | 18 + 28 files changed, 609 insertions(+), 501 deletions(-) create mode 100644 local_backend/migrations/versions/0023_phone_calls.py create mode 100644 local_backend/models/phone_call.py create mode 100644 local_backend/services/caller_id.py create mode 100644 local_backend/tests/test_caller_id.py create mode 100644 terminal/src/apps/pos/CallPopup.jsx create mode 100644 terminal/src/apps/pos/logic/calls.js diff --git a/docs/README.md b/docs/README.md index 0b8e0eb..07c5b52 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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/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/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) | | `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 | diff --git a/install.sh b/install.sh index 522a678..3f3f008 100644 --- a/install.sh +++ b/install.sh @@ -246,7 +246,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; @@ -288,7 +289,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; @@ -330,7 +332,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py index b5882af..1c17a02 100644 --- a/local_backend/core/errors.py +++ b/local_backend/core/errors.py @@ -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)."), diff --git a/local_backend/migrations/versions/0023_phone_calls.py b/local_backend/migrations/versions/0023_phone_calls.py new file mode 100644 index 0000000..3083df4 --- /dev/null +++ b/local_backend/migrations/versions/0023_phone_calls.py @@ -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') diff --git a/local_backend/models/all.py b/local_backend/models/all.py index f61d555..0041bda 100644 --- a/local_backend/models/all.py +++ b/local_backend/models/all.py @@ -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 diff --git a/local_backend/models/phone_call.py b/local_backend/models/phone_call.py new file mode 100644 index 0000000..4f29cb7 --- /dev/null +++ b/local_backend/models/phone_call.py @@ -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) diff --git a/local_backend/modules/caller_id/manifest.py b/local_backend/modules/caller_id/manifest.py index ddf375a..665b878 100644 --- a/local_backend/modules/caller_id/manifest.py +++ b/local_backend/modules/caller_id/manifest.py @@ -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=. Plan step 3.5.', type='str'), + ), routers=( Mount('routers.phone', '/api/phone'), ), diff --git a/local_backend/routers/customers.py b/local_backend/routers/customers.py index ab7a900..c7f1481 100644 --- a/local_backend/routers/customers.py +++ b/local_backend/routers/customers.py @@ -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() diff --git a/local_backend/routers/phone.py b/local_backend/routers/phone.py index fafc58d..f2d2ad5 100644 --- a/local_backend/routers/phone.py +++ b/local_backend/routers/phone.py @@ -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]} diff --git a/local_backend/services/caller_id.py b/local_backend/services/caller_id.py new file mode 100644 index 0000000..7eb6951 --- /dev/null +++ b/local_backend/services/caller_id.py @@ -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]], + } diff --git a/local_backend/tests/test_caller_id.py b/local_backend/tests/test_caller_id.py new file mode 100644 index 0000000..2063c4b --- /dev/null +++ b/local_backend/tests/test_caller_id.py @@ -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 diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json index 85d7d2e..62ed65d 100644 --- a/manager_dashboard/package.json +++ b/manager_dashboard/package.json @@ -8,7 +8,7 @@ "build": "vite build", "preview": "vite preview", "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": { "@tanstack/react-query": "^5.107.1", diff --git a/manager_dashboard/src/components/PhoneListener.jsx b/manager_dashboard/src/components/PhoneListener.jsx index 68f6393..c1a1939 100644 --- a/manager_dashboard/src/components/PhoneListener.jsx +++ b/manager_dashboard/src/components/PhoneListener.jsx @@ -1,358 +1,81 @@ -/** - * Mounts once inside AppLayout. Holds the WebSocket connection to /api/phone/ws, - * matches incoming callers against the customer list, and renders the call popup - * over whatever page is currently open. - */ -import { useEffect, useCallback, useRef, useState } from 'react' -import { PhoneIncoming, X, Mail, Phone, MessageSquare, Tag, - ShoppingBag, TrendingUp, Clock, User } from 'lucide-react' -import client from '../api/client' +// Caller ID in the manager (plan step 3.5): an incoming call arrives on the signed-in live +// connection (`call_incoming`, only for users with caller_id.use), already matched to a +// customer by the server (services/caller_id.py). Shows a popup over any page: the customer's +// 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 +// (a reconnect replays events) don't pop up; the call log has them. +import { PhoneIncoming, ShoppingBag, Tag, TrendingUp, User } from 'lucide-react' +import { useCan, useModule } from '@xenia/access' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog } from '@xenia/ui' +import { useLiveEvent } from '../live/useLiveEvent' import usePhoneStore from '../store/phoneStore' -/* ─── Phone normalisation ─────────────────────────────────────────────────── */ -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 -} +const FRESH_MS = 60_000 -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 ( -
- {[0, 1, 2].map(i => ( - - ))} -
- ) -} - -/* ─── Known customer modal ────────────────────────────────────────────────── */ -function KnownCustomerModal({ call, customer, orders, onClose }) { - const recent = (orders || []).slice(0, 3) - return ( -
-
-
-
-
- -
- - -
-
- -
-
-
-
Εισερχόμενη Κλήση
-
{formatTime(call.at)} · {call.caller}
-
-
- -
-
{customer.name?.[0]?.toUpperCase() || '?'}
-
-
{customer.name}
- {customer.nickname && ( -
- {customer.nickname} -
- )} -
-
-
- -
- -
- {customer.email && ( -
- - {customer.email} -
- )} - {customer.phone && ( -
- - {customer.phone} -
- )} - {customer.notes && ( -
- - "{customer.notes}" -
- )} -
- -
-
-
Επισκέψεις
-
- {customer.visit_count ?? 0} -
-
-
-
Σύνολο
-
- {formatCurrency(customer.total_spent)} -
-
-
- -
-
Πρόσφατες Παραγγελίες
- {recent.length === 0 ? ( -
- Δεν υπάρχουν παραγγελίες ακόμα -
- ) : ( -
- {recent.map(order => ( -
- -
-
- {formatDate(order.opened_at)} - {order.table_name && · {order.table_name}} -
-
{order.item_count} είδη
-
-
{formatCurrency(order.total)}
-
- ))} -
- )} -
- -
- -
-
-
-
- ) -} - -/* ─── Unknown caller modal ────────────────────────────────────────────────── */ -function UnknownCallerModal({ call, onClose }) { - return ( -
-
-
-
-
-
- - -
-
- -
-
-
-
Εισερχόμενη Κλήση
-
{formatTime(call.at)}
-
-
- -
-
-
Άγνωστος καλών
-
- {call.caller || '—'} -
- {call.ext &&
Εσωτερικό: {call.ext}
} -
- -
- -
-
-
-
-
- ) -} - -/* ─── PhoneListener ───────────────────────────────────────────────────────── */ export default function PhoneListener() { + const on = useModule('caller_id') + const allowed = useCan('caller_id.use') const { activeCall, dismissCall, setActiveCall, addCallToLog } = usePhoneStore() - const [customers, setCustomers] = useState([]) - - useEffect(() => { - client.get('/api/customers/') - .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]) - + useLiveEvent('call_incoming', call => { + if (!on || !allowed || !call) return + addCallToLog(call) + if (!call.at || Date.now() - Date.parse(call.at) < FRESH_MS) setActiveCall(call) + }) if (!activeCall) return null + return +} +export function CallDialog({ call, onClose }) { + const { t } = useTranslation('manager') + const { formatMoney, formatTime, formatDate } = useFormat() + const c = call.customer return ( - <> - - {activeCall.customer - ? - : - } - + {t('calls.close')}}> +
+
+ + {c ? {c.name?.[0]?.toUpperCase()} : +
+

{c ? c.name : t('calls.unknown')}

+

+ {call.number}{call.ext ? ` · ${t('calls.ext', { ext: call.ext })}` : ''}{call.at ? ` · ${formatTime(call.at)}` : ''} +

+ {c?.nickname &&

} +
+
+ {c ? ( + <> + {c.notes &&

“{c.notes}”

} +
+
+
+

{t('calls.recent')}

+ {c.recent_orders.length === 0 ?

{t('calls.noOrders')}

: c.recent_orders.map(o => ( +
+ {formatDate(o.opened_at)}{o.table_name ? ` · ${o.table_name}` : ''} · {t('calls.items', { count: o.item_count })} + {formatMoney(o.total)} +
+ ))} +
+ + ) : ( +

+ )} +
+
+ ) +} + +function Stat({ icon, label, value }) { + return ( +
+

{label}

+

{icon}{value}

+
) } diff --git a/manager_dashboard/src/pages/PhonePage.jsx b/manager_dashboard/src/pages/PhonePage.jsx index 73b3966..e7f3224 100644 --- a/manager_dashboard/src/pages/PhonePage.jsx +++ b/manager_dashboard/src/pages/PhonePage.jsx @@ -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' -function formatTime(date) { - return date.toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) -} - 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 ( -
- -
-
- -
-
-

- Εισερχόμενες Κλήσεις -

-

Grandstream UCM · Caller ID

-
-
- -
-
- - Πρόσφατες Κλήσεις - - {log.length > 0 && ( - {log.length} κλήσεις - )} -
- - {log.length === 0 ? ( -
- Δεν έχουν ληφθεί κλήσεις ακόμα. -
- ) : ( -
    - {log.map((entry, i) => ( -
  • 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' }} - > -
    - {entry.customer - ? - {entry.customer.name?.[0]?.toUpperCase()} - - : - } -
    -
    -
    - {entry.customer ? entry.customer.name : entry.caller || '—'} -
    -
    - {entry.customer ? entry.caller : 'Άγνωστος'} -
    -
    -
    - - {formatTime(entry.at)} - - -
    -
  • - ))} -
- )} -
+
+
+

{t('calls.title')}

+

{t('calls.intro')}

+
+
+

{t('calls.log')}

+ {error ?
+ : calls == null ?
+ : calls.length === 0 ?
} title={t('calls.none')} />
+ : ( +
    + {calls.map(c => ( +
  • + +
  • + ))} +
+ )} +
+
+

{t('calls.setup')}

+

{t('calls.setupBody')}

+ {hook} +

{t('calls.setupSecret')}

+
) } diff --git a/manager_dashboard/src/store/phoneStore.js b/manager_dashboard/src/store/phoneStore.js index afec5c7..8feb367 100644 --- a/manager_dashboard/src/store/phoneStore.js +++ b/manager_dashboard/src/store/phoneStore.js @@ -1,11 +1,13 @@ 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) => ({ - activeCall: null, // { caller, ext, at, customer, orders } | null + activeCall: null, log: [], // last 20 calls setActiveCall: (call) => set({ activeCall: call }), 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 diff --git a/nginx-proxy/nginx.conf b/nginx-proxy/nginx.conf index bd43e8c..94f267d 100644 --- a/nginx-proxy/nginx.conf +++ b/nginx-proxy/nginx.conf @@ -143,7 +143,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; @@ -185,7 +186,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; @@ -227,7 +229,8 @@ server { ssl_ciphers HIGH:!aNULL:!MD5; # 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 172.16.0.0/12; allow 192.168.0.0/16; diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json index 00fcf62..564f23f 100644 --- a/packages/i18n/locales/el/errors.json +++ b/packages/i18n/locales/el/errors.json @@ -116,5 +116,8 @@ "media_type": "Ανεβάστε εικόνα JPG, PNG, WebP ή GIF.", "media_too_big": "Η εικόνα είναι πολύ μεγάλη (έως {{max_mb}} MB).", "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός." + }, + "caller_id": { + "key_invalid": "Το κλειδί του τηλεφωνικού κέντρου λείπει ή είναι λάθος." } } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 30e388d..9129eab 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -658,5 +658,25 @@ "pickSlides": "Διαλέξτε τις φωτογραφίες, με τη σειρά (ξανά πάτημα για αφαίρεση)", "upload": "Ανέβασμα εικόνων", "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=<το κλειδί> στη διεύθυνση." } } diff --git a/packages/i18n/locales/el/terminal.json b/packages/i18n/locales/el/terminal.json index 18ec2b2..2c1bb02 100644 --- a/packages/i18n/locales/el/terminal.json +++ b/packages/i18n/locales/el/terminal.json @@ -464,6 +464,13 @@ "arrive": "Ήρθαν: καθίστε τους", "cancel": "Ακύρωση", "noShow": "Δεν ήρθαν" + }, + "call": { + "title": "Εισερχόμενη κλήση", + "unknown": "Άγνωστος καλών", + "takeaway": "Νέα πώληση για παραλαβή", + "visits_one": "{{count}} επίσκεψη · {{spent}}", + "visits_other": "{{count}} επισκέψεις · {{spent}}" } }, "display": { diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json index 8948611..b22a216 100644 --- a/packages/i18n/locales/en/errors.json +++ b/packages/i18n/locales/en/errors.json @@ -116,5 +116,8 @@ "media_type": "Upload a JPG, PNG, WebP or GIF image.", "media_too_big": "The image is too big (at most {{max_mb}} MB).", "qr_url_missing": "Enter the link the QR code opens." + }, + "caller_id": { + "key_invalid": "The phone system's key is missing or wrong." } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index ba26fd1..7356b09 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -658,5 +658,25 @@ "pickSlides": "Pick the photos, in order (tap again to remove)", "upload": "Upload images", "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= to the address." } } diff --git a/packages/i18n/locales/en/terminal.json b/packages/i18n/locales/en/terminal.json index a13abd1..d63fe46 100644 --- a/packages/i18n/locales/en/terminal.json +++ b/packages/i18n/locales/en/terminal.json @@ -464,6 +464,13 @@ "arrive": "They're here: seat them", "cancel": "Cancel", "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": { diff --git a/terminal/src/apps/pos/CallPopup.jsx b/terminal/src/apps/pos/CallPopup.jsx new file mode 100644 index 0000000..899764b --- /dev/null +++ b/terminal/src/apps/pos/CallPopup.jsx @@ -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 ( + + + + }> +
+
+ + {c ? c.name?.[0]?.toUpperCase() : +
+

{c ? c.name : t('pos.call.unknown')}

+

{call.number}{c?.nickname ? ` · ${c.nickname}` : ''}

+
+
+ {c?.notes &&

“{c.notes}”

} + {c && ( +
+

{t('pos.call.visits', { count: c.visit_count, spent: formatMoney(c.total_spent) })}

+ {c.recent_orders.map(o => ( +
+ {formatDate(o.opened_at)}{o.table_name ? ` · ${o.table_name}` : ''}{formatMoney(o.total)} +
+ ))} +
+ )} +
+
+ ) +} diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx index 4b7d3bb..f9b97f3 100644 --- a/terminal/src/apps/pos/PosScreen.jsx +++ b/terminal/src/apps/pos/PosScreen.jsx @@ -22,6 +22,8 @@ import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultS import { findOnline, ONLINE_LISTS } from './logic/online' import { BOOKING_LIST, findBooking } from './logic/bookings' import BookingPanel from './BookingPanel' +import CallPopup from './CallPopup' +import { isFresh } from './logic/calls' import BookingsView from './BookingsView' import { zoneCounts } from './logic/tables' import OnlinePanel from './OnlinePanel' @@ -79,6 +81,14 @@ function Counter({ menu, t }) { ring() 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 => { if (!onlineOn) return ring() @@ -226,6 +236,11 @@ function Counter({ menu, t }) { )} + {call && ( + setCall(null)} + onTakeaway={() => { setCall(null); setMode('sale'); leaveTable(); setOrderType('takeaway') }} /> + )} + {dialog && ( setDialog(null)} onAdd={line => setCart(c => addLine(c, line))} /> diff --git a/terminal/src/apps/pos/logic/calls.js b/terminal/src/apps/pos/logic/calls.js new file mode 100644 index 0000000..9c89461 --- /dev/null +++ b/terminal/src/apps/pos/logic/calls.js @@ -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) +} diff --git a/terminal/tests/pos.test.mjs b/terminal/tests/pos.test.mjs index 94a927d..deeb1f4 100644 --- a/terminal/tests/pos.test.mjs +++ b/terminal/tests/pos.test.mjs @@ -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('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) +}) diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 7dc2e6f..26f5d0b 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -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)) 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 await api('PUT', '/api/platform/modules/customer_display', { token: boss, body: { enabled: true } }).catch(() => {}) await page.goto(`${APP}/settings`) diff --git a/tests/e2e/terminal.mjs b/tests/e2e/terminal.mjs index 2bb73c9..1b2968f 100644 --- a/tests/e2e/terminal.mjs +++ b/tests/e2e/terminal.mjs @@ -732,6 +732,24 @@ try { 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.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 otherDisplay.context().close() drawerServer.close()