feat(backend,waiter,terminal,manager): sign-in: ask before signing a waiter's other phone out, usernames on paired screens

- auth.single_session_waiter gains 'ask', the new default (Alembic 0051 moves venues on 'off'
  to it): a second phone gets auth.session_elsewhere {device, since}; Continue retries with
  replace=true and the first phone is signed out at once (live session.ended, reason
  "replaced") and says why on its sign-in page. Only phones count (terminal sessions are
  their own client). refuse_new / end_old unchanged.
- auth.session_ended now carries the reason; the waiter app keeps it until the next sign-in.
- The waiter app sends queued offline ops on every (re)connection, so an order queued on a
  phone that was signed out by another goes out after the next sign-in there (e2e checked).
- auth.terminal_require_username (venue) + Device.require_username (per device, wins):
  GET /api/devices/me/users lists nobody, the screen asks for a username then PIN/password,
  a picked user_id is refused (auth.username_required), "tap" falls back to PIN.
- Manager: Sign-in settings (ask, the new switch), the device dialog's usernames choice.

Plan platform-v2 6F.7.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-23 12:51:37 +02:00
co-authored by Claude Opus 5.5
parent 3eeafb565a
commit 7706bf2470
31 changed files with 494 additions and 41 deletions
+1
View File
@@ -57,6 +57,7 @@ CODES: dict[str, tuple[int, str]] = {
"auth.invalid_credentials": (401, "Wrong username or password."),
"auth.session_ended": (401, "Your session has ended. Please log in again."),
"auth.session_exists": (409, "You're already logged in on another {client}. Log out there first."),
"auth.session_elsewhere": (409, "You're signed in on another device ({device}, since {since}). Continue? It will be signed out."),
"auth.login_mode_not_allowed": (403, "This way of logging in isn't enabled ({mode})."),
"auth.mode_needs_device": (403, "Logging in by {mode} only works on a paired device."),
"auth.username_required": (422, "Enter your username."),
+41 -5
View File
@@ -2,7 +2,11 @@
Sessions
- start(db, user, client, request) creates a row and applies the client's single-session
rule (setting auth.single_session_<client>: off | refuse_new | end_old).
rule (setting auth.single_session_<client>: off | refuse_new | end_old | ask).
`ask` (waiters, the default since 6F.7): a login while signed in elsewhere is refused with
auth.session_elsewhere (where, since when) until the app retries with replace=True; then
the old sessions end with reason "replaced" (their sockets get session.ended at once).
Only the waiter's phones count: a terminal session (the counter) is its own client.
- validate(sid) is called on every authenticated request (routers.deps.decode_token).
Results are cached for CACHE_TTL_S; end()/end_for_user() drop the cache entry at once,
so an ended session is refused on its very next request.
@@ -61,15 +65,32 @@ def _setting(db, key: str, default: str) -> str:
def single_session_rule(db, client: str) -> str:
return _setting(db, f"auth.single_session_{client}", "off") if client in ("manager", "waiter") else "off"
if client == "waiter":
return _setting(db, "auth.single_session_waiter", "ask") # 6F.7: ask is the default
return _setting(db, "auth.single_session_manager", "off") if client == "manager" else "off"
# ── lifecycle ────────────────────────────────────────────────────────────────
def start(db, user, client: str, request=None, *, device=None, expires_at=None):
def device_label(user_agent: str | None) -> str:
"""A short, language-neutral name for where a session runs ("Android · Chrome")."""
ua = user_agent or ""
system = next((name for key, name in (("iPhone", "iPhone"), ("iPad", "iPad"), ("Android", "Android"),
("Windows", "Windows"), ("Macintosh", "Mac"), ("Linux", "Linux"))
if key in ua), "")
browser = next((name for key, name in (("EdgA", "Edge"), ("Edg/", "Edge"), ("Firefox", "Firefox"), ("FxiOS", "Firefox"),
("CriOS", "Chrome"), ("Chrome", "Chrome"), ("Safari", "Safari"))
if key in ua), "")
if "; wv)" in ua:
browser = "app"
return " · ".join(x for x in (system, browser) if x)
def start(db, user, client: str, request=None, *, device=None, expires_at=None, replace: bool = False):
"""Create a session for user (None user_id for the support account). Commits.
`device`: the paired device of a terminal login; its previous sessions are replaced
(a shared screen shows one user at a time)."""
(a shared screen shows one user at a time). `replace`: the person said yes to signing
out their other session (rule `ask`)."""
from models.session import LoginSession
if client not in CLIENTS:
raise ValueError(f"unknown client {client!r}")
@@ -80,6 +101,11 @@ def start(db, user, client: str, request=None, *, device=None, expires_at=None):
LoginSession.ended_at.is_(None)).all()
if active and rule == "refuse_new":
raise XeniaError("auth.session_exists", client=client)
if active and rule == "ask" and not replace:
last = max(active, key=lambda s: s.created_at)
from core.timeutil import iso_z
raise XeniaError("auth.session_elsewhere", client=client, since=iso_z(last.created_at),
device=device_label(last.user_agent) or "?", ip=last.ip or "")
for s in active:
_end_row(s, "replaced")
if device is not None:
@@ -186,7 +212,8 @@ def validate(sid: str | None, db=None) -> Active:
if row is None or row.ended_at is not None:
with _lock:
_cache.pop(sid, None)
raise XeniaError("auth.session_ended")
# why it ended (replaced, logout, idle...): the app can say "you signed in elsewhere"
raise XeniaError("auth.session_ended", reason=(row.end_reason if row is not None else None) or "unknown")
info = Active(row.user_id, row.device_id, row.expires_at)
stale = utcnow() - row.last_seen_at > timedelta(seconds=LAST_SEEN_EVERY_S)
finally:
@@ -233,3 +260,12 @@ def waiter_login_mode(db) -> str:
def waiter_requires_username(db) -> bool:
return _setting(db, "auth.waiter_require_username", "false") == "true"
def terminal_requires_username(db, device=None) -> bool:
"""Paired screens (6F.7): type a username instead of picking a name. The device's own
choice (Device.require_username) wins over the venue's auth.terminal_require_username."""
own = getattr(device, "require_username", None)
if own is not None:
return bool(own)
return _setting(db, "auth.terminal_require_username", "false") == "true"
@@ -0,0 +1,30 @@
"""Sign-in (owner 2026-11-23, plan 6F.7).
- devices.require_username: a paired screen's own choice (NULL = the venue's
auth.terminal_require_username).
- auth.single_session_waiter: 'ask' is the new default; a venue that has the row set to
'off' gets 'ask' too (Q-9). A venue that chose refuse_new / end_old keeps its choice.
Revision ID: 0051_sign_in
Revises: 0050_split_bills
Create Date: 2026-11-23 22:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0051_sign_in'
down_revision = '0050_split_bills'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('devices') as b:
b.add_column(sa.Column('require_username', sa.Boolean(), nullable=True))
op.get_bind().execute(sa.text("update pos_settings set value = 'ask' "
"where key = 'auth.single_session_waiter' and value = 'off'"))
def downgrade() -> None:
with op.batch_alter_table('devices') as b:
b.drop_column('require_username')
+2 -1
View File
@@ -13,7 +13,7 @@ Devices are never deleted: revoked rows keep their token hash so the device is t
`device.revoked` (not "unknown"), and old sessions/audit rows keep a valid device_id.
Read and written through routers/devices.py and core/access/context.py.
"""
from sqlalchemy import JSON, Column, ForeignKey, Integer, String
from sqlalchemy import JSON, Boolean, Column, ForeignKey, Integer, String
from core.timeutil import UTCDateTime, utcnow
from database import Base
@@ -29,6 +29,7 @@ class Device(Base):
app_key = Column(String, nullable=False, index=True) # a kind="app" module with device_app
config = Column(JSON, nullable=True) # app-specific (e.g. KDS prep zone)
login_mode = Column(String, nullable=True) # NULL = site default auth.default_login_mode
require_username = Column(Boolean, nullable=True) # NULL = site default auth.terminal_require_username (6F.7)
token_hash = Column(String, nullable=True, unique=True) # sha256 hex; NULL until the device picks it up
linked_device_id = Column(Integer, ForeignKey("devices.id", ondelete="SET NULL"), nullable=True)
user_agent = Column(String, nullable=True) # from the pairing request
+2 -1
View File
@@ -27,7 +27,8 @@ MODULE = Module(
SettingDef('auth.default_login_mode', 'pin', "How staff log in on paired devices (KDS, counter POS) unless the device sets its own: 'pin' | 'password' | 'tap' | 'none'. Apps that can't use it fall back to their first mode.", type='enum', choices=('pin', 'password', 'tap', 'none')),
SettingDef('auth.waiter_require_username', 'false', 'Waiters must type their username instead of picking their name', type='bool'),
SettingDef('auth.single_session_manager', 'off', "One manager session per user: 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
SettingDef('auth.single_session_waiter', 'off', "One waiter session per user (no double login): 'off' | 'refuse_new' | 'end_old'", type='enum', choices=('off', 'refuse_new', 'end_old')),
SettingDef('auth.single_session_waiter', 'ask', "One waiter session per user, phones only (no double login): 'off' | 'refuse_new' | 'end_old' | 'ask' (the default: the phone asks, yes signs the other one out)", type='enum', choices=('off', 'refuse_new', 'end_old', 'ask')),
SettingDef('auth.terminal_require_username', 'false', 'Paired screens (counter, KDS): type a username instead of picking a name; no names are listed, and "tap" is not used. A device can choose otherwise on the Devices page.', type='bool'),
SettingDef('auth.idle_days', '14', 'Sign people out after this many days without using the app (manager, waiter, paired-device sessions; support has its own 4 h). 0 = never.', type='int'),
SettingDef('system.log_retention_days', '30', 'Days of daily backend log files to keep in data/logs (default 30). Applied at backend start.', type='int'),
SettingDef('venue.language', 'en', 'Default language (en | el) for staff without their own language, and for printed reports/receipts and tickets of zones without one.', type='str'),
+7 -3
View File
@@ -44,7 +44,7 @@ def _check_secret(user, pin, password, db) -> bool:
def do_login(db: Session, request: Request, *, client: str, username: str | None, user_id: int | None,
pin: str | None, password: str | None) -> TokenResponse:
pin: str | None, password: str | None, replace: bool = False) -> TokenResponse:
"""The one login path. Applies the client's login mode, its access key and the
single-session rule, then creates a session (core/sessions.py)."""
if client not in ("manager", "waiter", "terminal"):
@@ -81,7 +81,7 @@ def do_login(db: Session, request: Request, *, client: str, username: str | None
if not holds(user, needed):
raise XeniaError("auth.client_not_allowed", client=client)
row = sessions.start(db, user, client, request)
row = sessions.start(db, user, client, request, replace=replace)
return TokenResponse(access_token=make_token(user, row.id), user=UserOut.model_validate(user))
@@ -104,6 +104,10 @@ def _terminal_login(db: Session, request: Request, *, username, user_id, pin, pa
raise XeniaError("auth.login_mode_not_allowed", mode="password")
if mode == "password" and not password:
raise XeniaError("auth.login_mode_not_allowed", mode="pin")
if sessions.terminal_requires_username(db, device):
if not username:
raise XeniaError("auth.username_required")
user_id = None # usernames only: a picked id isn't enough (6F.7)
q = db.query(User).filter(User.is_active == True) # noqa: E712
user = q.filter(User.username == username).first() if username else (
@@ -122,7 +126,7 @@ def login(body: LoginRequest, request: Request, db: Session = Depends(get_db)):
"""POST {client: "manager"|"waiter"|"terminal", username?, user_id?, pin?, password?}.
"terminal" = a user on a paired device: send the X-Xenia-Device header."""
return do_login(db, request, client=body.client, username=body.username,
user_id=body.user_id, pin=body.pin, password=body.password)
user_id=body.user_id, pin=body.pin, password=body.password, replace=body.replace)
@router.post("/refresh", response_model=TokenResponse)
+12 -2
View File
@@ -151,6 +151,8 @@ def effective_login_mode(db, device) -> str:
can't use that one, the app's first mode (signage etc.: 'none')."""
modes = _app(device.app_key).device_app.login_modes
mode = device.login_mode or sessions._setting(db, "auth.default_login_mode", "pin")
if mode == "tap" and sessions.terminal_requires_username(db, device):
mode = next((m for m in ("pin", "password") if m in modes), mode) # usernames: no name to tap (6F.7)
return mode if mode in modes else modes[0]
@@ -175,6 +177,8 @@ def _out(d: Device, db) -> dict:
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key,
"config": _effective_config(d, db) if d.app_key in registry() else {},
"login_mode": d.login_mode,
"require_username": d.require_username,
"effective_require_username": sessions.terminal_requires_username(db, d),
"effective_login_mode": effective_login_mode(db, d) if d.app_key in registry() else None,
"linked_device_id": d.linked_device_id, "user_agent": d.user_agent,
"paired_at": iso_z(d.paired_at), "paired_by": d.paired_by,
@@ -191,6 +195,7 @@ def _self_out(d: Device, db) -> dict:
return {
"id": d.id, "uuid": d.uuid, "name": d.name, "app_key": d.app_key, "config": _effective_config(d, db),
"login_mode": effective_login_mode(db, d),
"require_username": sessions.terminal_requires_username(db, d),
"linked_device": ({"id": linked.id, "uuid": linked.uuid, "name": linked.name, "app_key": linked.app_key}
if linked is not None and linked.revoked_at is None else None),
"app_status": status, # "ok" | "module.disabled" | "module.not_licensed": show "app disabled"
@@ -249,6 +254,7 @@ class PairApprove(BaseModel):
name: str = Field(min_length=1, max_length=60)
config: Optional[dict] = None
login_mode: Optional[str] = None # None/"" = site default
require_username: Optional[bool] = None # None = site default (6F.7)
linked_device_id: Optional[int] = None
@@ -256,6 +262,7 @@ class DevicePatch(BaseModel):
name: Optional[str] = Field(None, min_length=1, max_length=60)
config: Optional[dict] = None
login_mode: Optional[str] = None # "" or null = back to the site default
require_username: Optional[bool] = None # null = back to the site default (6F.7)
linked_device_id: Optional[int] = None # null/0 = unlink
@@ -285,6 +292,7 @@ def approve_device(body: PairApprove, db: Session = Depends(get_db), user=Depend
d = Device(uuid=uuidlib.uuid4().hex, name=body.name.strip(), app_key=body.app_key,
config=_config(body.app_key, body.config, db),
login_mode=_check_mode(body.app_key, body.login_mode),
require_username=body.require_username,
linked_device_id=_check_link(db, None, body.linked_device_id),
user_agent=row.user_agent, paired_at=now, paired_by=getattr(user, "id", None) or None)
db.add(d)
@@ -307,8 +315,8 @@ def device_users(db: Session = Depends(get_db), device=Depends(require_device())
"""Who can log in on this device (holders of '<app>.access'), for the name picker."""
from core.access.queries import users_with_key
from models.user import User
if effective_login_mode(db, device) == "none":
return []
if effective_login_mode(db, device) == "none" or sessions.terminal_requires_username(db, device):
return [] # usernames on (6F.7): nobody is listed, the screen asks for a username
users = users_with_key(db, f"{device.app_key}.access").order_by(User.full_name).all()
return [{"id": u.id, "full_name": u.full_name, "nickname": u.nickname, "avatar_url": u.avatar_url}
for u in users if u.role != "superadmin"]
@@ -357,6 +365,8 @@ def update_device(device_id: int, body: DevicePatch, db: Session = Depends(get_d
d.config = _config(d.app_key, body.config, db)
if "login_mode" in sent:
d.login_mode = _check_mode(d.app_key, body.login_mode)
if "require_username" in sent:
d.require_username = body.require_username
if "linked_device_id" in sent:
d.linked_device_id = _check_link(db, d.id, body.linked_device_id)
db.commit()
+3
View File
@@ -89,4 +89,7 @@ def update_setting(
timeutil.invalidate() # live: next call re-reads the setting
if key == "venue.language":
i18n.invalidate()
if key in ("auth.default_login_mode", "auth.terminal_require_username"):
from services import ws_bus
ws_bus.notify_device(every_device=True) # paired screens re-read how people sign in (6F.7)
return {"key": setting.key, "value": setting.value}
+1
View File
@@ -8,6 +8,7 @@ class LoginRequest(BaseModel):
user_id: int | None = None # waiter picks their name (when the username isn't required)
pin: str | None = None
password: str | None = None
replace: bool = False # rule "ask": yes, sign my other phone out (6F.7)
class TokenResponse(BaseModel):
+5 -2
View File
@@ -104,7 +104,10 @@ def test_token_is_bound_to_its_key(client, db, venue, make_user, login):
assert r.status_code == 200, r.text
def test_token_is_bound_to_its_session(client, venue, login):
def test_token_is_bound_to_its_session(client, db, venue, login):
from models.settings import PosSettings
db.add(PosSettings(key="auth.single_session_waiter", value="off")) # two phones of one waiter
db.commit()
v = venue
token = approve(client, v["waiter_h"], "ordering.orders.cancel", v["manager"].username).json()["override_token"]
other_phone = login(v["waiter"], client="waiter")
@@ -192,7 +195,7 @@ def test_check_consumes_a_valid_token(db, venue):
from core.access import override
from core.access.check import AccessContext, check
v = venue
row = sessions.start(db, v["waiter"], "waiter")
row = sessions.start(db, v["waiter"], "waiter", replace=True)
token, _ = override.grant(db, key="ordering.orders.cancel", username=v["manager"].username, pin=TEST_PIN,
requester=v["waiter"], sid=row.id)
ctx = AccessContext(user=v["waiter"], session=row.id, override_token=token, target="unit")
+1
View File
@@ -68,6 +68,7 @@ def test_waiter_pin_by_id(client, make_user):
def test_waiter_modes(client, make_user, admin_h):
w = make_user(role="waiter")
_set(client, admin_h, "auth.single_session_waiter", "off") # several logins of one waiter here
_set(client, admin_h, "auth.waiter_login_mode", "password")
r = client.post("/api/auth/login", json={"client": "waiter", "user_id": w.id, "pin": TEST_PIN})
assert r.json()["error"]["code"] == "auth.login_mode_not_allowed"
+101
View File
@@ -0,0 +1,101 @@
"""Sign-in (plan 6F.7): one session per waiter asks before signing the other phone out (the
default), only phones count; usernames on paired screens (venue setting + the device's own)."""
import pytest
from conftest import TEST_PIN
from tests.test_live import err, owner_h, pair # noqa: F401 (fixtures)
ANDROID = "Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0 Mobile Safari/537.36"
def _phone(client, user, **extra):
return client.post("/api/auth/login", headers={"user-agent": ANDROID},
json={"client": "waiter", "user_id": user.id, "pin": TEST_PIN, **extra})
def _h(r):
assert r.status_code == 200, r.text
return {"Authorization": f"Bearer {r.json()['access_token']}"}
@pytest.fixture
def ended(monkeypatch):
from services import ws_bus
got = []
real = ws_bus.end_session
monkeypatch.setattr(ws_bus, "end_session", lambda sid, reason: (got.append(reason), real(sid, reason))[1])
return got
def test_ask_is_the_default_and_says_where(client, make_user, ended):
w = make_user(role="waiter")
first = _h(_phone(client, w))
r = _phone(client, w)
assert r.status_code == 409 and err(r) == "auth.session_elsewhere"
params = r.json()["error"]["params"]
assert params["device"] == "Android · Chrome" and params["since"].endswith("Z")
assert client.get("/api/auth/me", headers=first).status_code == 200 # asking ends nothing
second = _h(_phone(client, w, replace=True))
gone = client.get("/api/auth/me", headers=first)
assert gone.status_code == 401 and err(gone) == "auth.session_ended"
assert gone.json()["error"]["params"]["reason"] == "replaced" # the old phone can say why
assert ended == ["replaced"] # its socket was told at once
assert client.get("/api/auth/me", headers=second).status_code == 200
def test_replace_does_not_bypass_refuse_new(client, make_user, owner_h):
assert client.put("/api/settings/auth.single_session_waiter", headers=owner_h, json={"value": "refuse_new"}).status_code == 200
w = make_user(role="waiter")
_h(_phone(client, w))
r = _phone(client, w, replace=True)
assert r.status_code == 409 and err(r) == "auth.session_exists"
def test_only_phones_count(client, make_user, pair):
owner = make_user(role="owner")
token, dev = pair("pos_counter", "Till")
till = client.post("/api/auth/login", headers={"X-Xenia-Device": token},
json={"client": "terminal", "user_id": owner.id, "pin": TEST_PIN})
assert till.status_code == 200, till.text
_h(_phone(client, owner)) # the counter's session isn't a phone: no question
till_h = {"Authorization": f"Bearer {till.json()['access_token']}", "X-Xenia-Device": token}
assert client.get("/api/auth/me", headers=till_h).status_code == 200
def test_usernames_on_terminals(client, make_user, owner_h, pair):
cashier = make_user(role="owner")
token, dev = pair("pos_counter", "Till")
dh = {"X-Xenia-Device": token}
assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0
assert client.put("/api/settings/auth.terminal_require_username", headers=owner_h, json={"value": "true"}).status_code == 200
assert client.get("/api/devices/me/users", headers=dh).json() == []
assert client.get("/api/devices/me", headers=dh).json()["require_username"] is True
by_id = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "user_id": cashier.id, "pin": TEST_PIN})
assert by_id.status_code == 422 and err(by_id) == "auth.username_required"
wrong = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": "nobody_here", "pin": TEST_PIN})
assert wrong.status_code == 401 and err(wrong) == "auth.invalid_credentials"
ok = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username, "pin": TEST_PIN})
assert ok.status_code == 200, ok.text
# "tap" can't go with usernames: the screen asks for the PIN instead
dev_id = dev.json()["id"]
assert client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"login_mode": "tap"}).status_code == 200
assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "pin"
tap = client.post("/api/auth/login", headers=dh, json={"client": "terminal", "username": cashier.username})
assert tap.status_code == 403 and err(tap) == "auth.login_mode_not_allowed"
# the device's own choice wins over the venue's
out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": False}).json()
assert out["require_username"] is False and out["effective_require_username"] is False
assert client.get("/api/devices/me", headers=dh).json()["login_mode"] == "tap"
assert len(client.get("/api/devices/me/users", headers=dh).json()) > 0
out = client.patch(f"/api/devices/{dev_id}", headers=owner_h, json={"require_username": None}).json()
assert out["require_username"] is None and out["effective_require_username"] is True
def test_device_label():
from core.sessions import device_label
assert device_label(ANDROID) == "Android · Chrome"
assert device_label("Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 Version/17.0 Mobile/15E148 Safari/604.1") == "iPhone · Safari"
assert device_label("Mozilla/5.0 (Linux; Android 14; wv) AppleWebKit/537.36 Chrome/130.0 Mobile Safari/537.36".replace("wv)", "Pixel; wv)")) == "Android · app"
assert device_label(None) == ""
@@ -3,6 +3,8 @@
// auth.default_login_mode (paired devices; a device can choose its own on the Devices page),
// auth.single_session_manager / _waiter, security.autofill_username (the sign-in page) and
// auth.idle_days (sign out after N days without use, 0 = never; owner decision 2026-11-14, 2.99d).
// 6F.7: waiters get 'ask' (the default: the phone asks before signing the other one out; only
// phones count), and auth.terminal_require_username (paired screens list nobody).
// Replaces the v1 "login method" card, whose setting (security.login_method) no longer exists.
import { useId } from 'react'
import { useTranslation } from '@xenia/i18n'
@@ -11,6 +13,7 @@ import { SettingRow, SettingsCard } from './SettingsCard'
import { useSettings } from './useSettings'
const SESSION_RULES = ['off', 'refuse_new', 'end_old']
const WAITER_SESSION_RULES = ['ask', 'off', 'refuse_new', 'end_old']
const IDLE_DAYS = ['7', '14', '30', '60', '90', '0']
export default function SignInSettings() {
@@ -56,11 +59,14 @@ export default function SignInSettings() {
<SettingRow label={t('settings.signIn.device')} htmlFor={idDevice} hint={t('settings.signIn.deviceHint')} tip={t('settings.signIn.deviceTip')}>
{select('auth.default_login_mode', 'pin', opts(['pin', 'password', 'tap', 'none'], 'settings.mode'), idDevice)}
</SettingRow>
<SettingRow label={t('settings.signIn.terminalUsername')} hint={t('settings.signIn.terminalUsernameHint')} tip={t('settings.signIn.terminalUsernameTip')}>
{toggle('auth.terminal_require_username', 'false', t('settings.signIn.terminalUsername'))}
</SettingRow>
<SettingRow label={t('settings.signIn.singleManager')} htmlFor={idSingleManager} tip={t('settings.signIn.singleTip')}>
{select('auth.single_session_manager', 'off', opts(SESSION_RULES, 'settings.session'), idSingleManager)}
</SettingRow>
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter} tip={t('settings.signIn.singleTip')}>
{select('auth.single_session_waiter', 'off', opts(SESSION_RULES, 'settings.session'), idSingleWaiter)}
<SettingRow label={t('settings.signIn.singleWaiter')} htmlFor={idSingleWaiter} hint={t('settings.signIn.singleWaiterHint')} tip={t('settings.signIn.singleWaiterTip')}>
{select('auth.single_session_waiter', 'ask', opts(WAITER_SESSION_RULES, 'settings.session'), idSingleWaiter)}
</SettingRow>
<SettingRow label={t('settings.signIn.idle')} htmlFor={idIdle} hint={t('settings.signIn.idleHint')} tip={t('settings.signIn.idleTip')}>
{select('auth.idle_days', '14', idleOptions, idIdle)}
@@ -277,10 +277,24 @@ function PairDialog({ apps, usage, devices, appName, limitLabel, initialApp, onC
)
}
/** Usernames on this screen (6F.7): the venue's choice, or its own yes / no. */
function usernameOptions(device, t) {
// the venue's value = what applies when the device has no choice of its own
const venue = device.require_username == null ? device.effective_require_username : null
const yes = t('devices.form.usernamesYes')
const no = t('devices.form.usernamesNo')
return [
{ value: '', label: venue == null ? t('devices.signIn.defaultPlain') : t('devices.form.usernamesDefault', { value: venue ? yes : no }) },
{ value: 'true', label: yes },
{ value: 'false', label: no },
]
}
function EditDialog({ device, apps, devices, onClose, onSave }) {
const { t } = useTranslation('manager')
const [name, setName] = useState(device.name)
const [mode, setMode] = useState(device.login_mode || '')
const [usernames, setUsernames] = useState(device.require_username == null ? '' : String(device.require_username))
const [link, setLink] = useState(device.linked_device_id ? String(device.linked_device_id) : '')
const app = apps.find(a => a.key === device.app_key)
const fields = app?.device_app?.config || []
@@ -293,6 +307,7 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
e.preventDefault()
if (!name.trim() || busy) return
run({ name: name.trim(), login_mode: mode || null, linked_device_id: link ? Number(link) : null,
...(modes ? { require_username: usernames === '' ? null : usernames === 'true' } : {}),
...(fields.length ? { config } : {}) })
}
@@ -308,6 +323,12 @@ function EditDialog({ device, apps, devices, onClose, onSave }) {
<Select value={mode} onChange={e => setMode(e.target.value)} options={modes} />
</Field>
)}
{modes && (
<Field label={t('devices.form.usernames')} info={<InfoTip>{t('devices.form.usernamesTip')}</InfoTip>}>
<Select value={usernames} onChange={e => setUsernames(e.target.value)} data-testid="device-usernames"
options={usernameOptions(device, t)} />
</Field>
)}
{targets.length > 0 && (
<Field label={t('devices.form.link')} hint={t('devices.form.linkHint')}>
<Select value={link} onChange={e => setLink(e.target.value)}
+1
View File
@@ -29,6 +29,7 @@
"invalid_credentials": "Λάθος όνομα χρήστη ή κωδικός.",
"session_ended": "Η σύνδεσή σας έληξε. Συνδεθείτε ξανά.",
"session_exists": "Είστε ήδη συνδεδεμένοι σε άλλο {{client}}. Αποσυνδεθείτε πρώτα από εκεί.",
"session_elsewhere": "Είστε συνδεδεμένοι σε άλλη συσκευή ({{device}}, από {{since}}). Συνέχεια; Εκείνη θα αποσυνδεθεί.",
"login_mode_not_allowed": "Αυτός ο τρόπος σύνδεσης δεν είναι ενεργός ({{mode}}).",
"mode_needs_device": "Η σύνδεση με {{mode}} γίνεται μόνο σε συζευγμένη συσκευή.",
"username_required": "Συμπληρώστε το όνομα χρήστη.",
+13 -2
View File
@@ -222,7 +222,12 @@
"linkHint": "Για παράδειγμα μια οθόνη πελάτη που δείχνει την παραγγελία ενός ταμείου πάγκου.",
"full": "{{label}}: η άδεια επιτρέπει {{max}} και χρησιμοποιούνται όλα. Αφαιρέστε μία ή ζητήστε μεγαλύτερη άδεια.",
"noApps": "Καμία εφαρμογή συσκευών δεν είναι ενεργή. Ενεργοποιήστε μία πρώτα από τις Εφαρμογές.",
"signInTip": "PIN ή κωδικός: ο καθένας συνδέεται. Πάτημα στο όνομα: ο καθένας αλλάζει χρήστη χωρίς μυστικό (κοινό ταμείο). Κανένας: η οθόνη δουλεύει χωρίς χρήστη (οθόνη κουζίνας)."
"signInTip": "PIN ή κωδικός: ο καθένας συνδέεται. Πάτημα στο όνομα: ο καθένας αλλάζει χρήστη χωρίς μυστικό (κοινό ταμείο). Κανένας: η οθόνη δουλεύει χωρίς χρήστη (οθόνη κουζίνας).",
"usernames": "Το προσωπικό γράφει το όνομα χρήστη",
"usernamesDefault": "Όπως το κατάστημα ({{value}})",
"usernamesYes": "Ναι",
"usernamesNo": "Όχι, επιλέγουν το όνομά τους",
"usernamesTip": "Ναι: η οθόνη δεν δείχνει κανέναν και ζητά όνομα χρήστη, μετά PIN ή κωδικό. Η «Επιλογή ονόματος» δεν γίνεται μαζί του."
},
"actions": {
"rename": "Μετονομασία",
@@ -389,7 +394,8 @@
"session": {
"off": "Επιτρέπεται σε πολλές συσκευές",
"refuse_new": "Άρνηση δεύτερης σύνδεσης",
"end_old": "Αποσύνδεση της παλιότερης"
"end_old": "Αποσύνδεση της παλιότερης",
"ask": "Ερώτηση, μετά αποσύνδεση του άλλου κινητού"
},
"signIn": {
"title": "Σύνδεση",
@@ -404,8 +410,13 @@
"requireUsernameHint": "Αντί να επιλέγουν το όνομά τους από τη λίστα.",
"device": "Στις συζευγμένες συσκευές (οθόνη κουζίνας, ταμείο πάγκου) το προσωπικό συνδέεται με",
"deviceHint": "Κάθε συσκευή μπορεί να έχει δική της επιλογή στη σελίδα Συσκευές.",
"terminalUsername": "Στις συζευγμένες συσκευές το προσωπικό γράφει το όνομα χρήστη",
"terminalUsernameHint": "Η οθόνη δεν δείχνει ονόματα· η «Επιλογή ονόματος» ζητά τότε PIN. Κάθε συσκευή μπορεί να επιλέξει αλλιώς στη σελίδα Συσκευές.",
"terminalUsernameTip": "Όποιος στέκεται στο ταμείο δεν βλέπει ποιοι δουλεύουν εδώ ούτε δοκιμάζει το PIN συναδέλφου πατώντας ονόματα.",
"singleManager": "Μία σύνδεση ανά υπεύθυνο",
"singleWaiter": "Μία σύνδεση ανά σερβιτόρο",
"singleWaiterHint": "Μετράνε μόνο τα κινητά: η σύνδεση και στο ταμείο επιτρέπεται.",
"singleWaiterTip": "Ερώτηση: το κινητό λέει πού είναι ήδη συνδεδεμένος ο σερβιτόρος και από πότε. Η «Συνέχεια» αποσυνδέει αμέσως εκείνο το κινητό, που δείχνει γιατί. Παραγγελίες που είχε ακόμα να στείλει μένουν σε αυτό και φεύγουν την επόμενη φορά που θα συνδεθεί κάποιος εκεί.",
"singleTip": "Όταν κάποιος είναι ήδη συνδεδεμένος σε άλλη συσκευή: επιτρέπονται και οι δύο, απορρίπτεται η νέα σύνδεση ή αποσυνδέεται η παλιότερη.",
"idle": "Αποσύνδεση μετά από",
"idleHint": "Ημέρες χωρίς χρήση της εφαρμογής (διαχείριση, εφαρμογή σερβιτόρων και συζευγμένες συσκευές). Την επόμενη φορά συνδέονται ξανά.",
+4 -1
View File
@@ -14,7 +14,10 @@
"submit": "Σύνδεση",
"back": "Πίσω",
"empty": "Κανείς δεν μπορεί να συνδεθεί εδώ ακόμη",
"emptyBody": "Δώστε σε κάποιον το δικαίωμα {{app}} στο Προσωπικό, στη διαχείριση."
"emptyBody": "Δώστε σε κάποιον το δικαίωμα {{app}} στο Προσωπικό, στη διαχείριση.",
"username": "Όνομα χρήστη",
"next": "Επόμενο",
"typeUsername": "Γράψτε το όνομα χρήστη σας"
},
"blocked": {
"off": "Η εφαρμογή {{app}} είναι απενεργοποιημένη",
+7 -1
View File
@@ -84,7 +84,13 @@
"username": "Όνομα χρήστη",
"password": "Κωδικός",
"signIn": "Σύνδεση",
"enterPin": "Εισάγετε PIN"
"enterPin": "Εισάγετε PIN",
"elsewhereTitle": "Συνδεδεμένοι σε άλλη συσκευή",
"elsewhereBody": "Είστε συνδεδεμένοι σε άλλη συσκευή ({{device}}) από τις {{time}}. Συνέχεια; Εκείνη θα αποσυνδεθεί.",
"elsewhereContinue": "Συνέχεια",
"elsewhereCancel": "Άκυρο",
"signedOutReplaced": "Αποσυνδεθήκατε: συνδεθήκατε σε άλλη συσκευή.",
"signedOut": "Αποσυνδεθήκατε. Συνδεθείτε ξανά."
},
"card": {
"freeLower": "Ελεύθερο",
+1
View File
@@ -29,6 +29,7 @@
"invalid_credentials": "Wrong username or password.",
"session_ended": "Your session has ended. Please log in again.",
"session_exists": "You're already logged in on another {{client}}. Log out there first.",
"session_elsewhere": "You're signed in on another device ({{device}}, since {{since}}). Continue? It will be signed out.",
"login_mode_not_allowed": "This way of logging in isn't enabled ({{mode}}).",
"mode_needs_device": "Logging in by {{mode}} only works on a paired device.",
"username_required": "Enter your username.",
+13 -2
View File
@@ -222,7 +222,12 @@
"linkHint": "For example a customer display that shows a counter POS's order.",
"full": "{{label}}: the license allows {{max}}, all in use. Remove one or ask for a bigger license.",
"noApps": "No device app is turned on. Turn one on in Apps first.",
"signInTip": "PIN or password: each person signs in. Tap your name: anyone switches user without a secret (a shared counter). None: the screen works without a user (a kitchen display)."
"signInTip": "PIN or password: each person signs in. Tap your name: anyone switches user without a secret (a shared counter). None: the screen works without a user (a kitchen display).",
"usernames": "Staff type their username",
"usernamesDefault": "Venue default ({{value}})",
"usernamesYes": "Yes",
"usernamesNo": "No, they pick their name",
"usernamesTip": "Yes: the screen lists nobody and asks for a username, then the PIN or password. \"Tap your name\" can't be used with it."
},
"actions": {
"rename": "Rename",
@@ -389,7 +394,8 @@
"session": {
"off": "Allowed on several devices",
"refuse_new": "Refuse a second sign-in",
"end_old": "Sign out the older one"
"end_old": "Sign out the older one",
"ask": "Ask, then sign out the other phone"
},
"signIn": {
"title": "Sign-in",
@@ -404,8 +410,13 @@
"requireUsernameHint": "Instead of picking their name from the list.",
"device": "On paired devices (kitchen display, counter POS), staff sign in with",
"deviceHint": "Each device can choose its own on the Devices page.",
"terminalUsername": "On paired devices, staff type their username",
"terminalUsernameHint": "No names are listed on the screen; \"Tap your name\" asks for the PIN instead. Each device can choose otherwise on the Devices page.",
"terminalUsernameTip": "Someone standing at the counter can't see who works here or try a colleague's PIN by tapping names.",
"singleManager": "One session per manager",
"singleWaiter": "One session per waiter",
"singleWaiterHint": "Only phones count: signing in at the counter as well is fine.",
"singleWaiterTip": "Ask: the phone says where the waiter is already signed in and since when. Continue signs that phone out at once, and it shows why. Orders it still had to send stay on it and go out the next time someone signs in there.",
"singleTip": "When someone is already signed in on another device: allow both, refuse the new sign-in, or sign out the older one.",
"idle": "Sign people out after",
"idleHint": "Days without using the app (manager, waiter app and paired devices). They sign in again next time.",
+4 -1
View File
@@ -14,7 +14,10 @@
"submit": "Sign in",
"back": "Back",
"empty": "Nobody can sign in here yet",
"emptyBody": "Give someone the {{app}} permission under Staff in the manager."
"emptyBody": "Give someone the {{app}} permission under Staff in the manager.",
"username": "Username",
"next": "Next",
"typeUsername": "Type your username"
},
"blocked": {
"off": "{{app}} is turned off",
+7 -1
View File
@@ -84,7 +84,13 @@
"username": "Username",
"password": "Password",
"signIn": "Sign in",
"enterPin": "Enter your PIN"
"enterPin": "Enter your PIN",
"elsewhereTitle": "Signed in on another device",
"elsewhereBody": "You're signed in on another device ({{device}}) since {{time}}. Continue? It will be signed out.",
"elsewhereContinue": "Continue",
"elsewhereCancel": "Cancel",
"signedOutReplaced": "Signed out: you signed in on another device.",
"signedOut": "You were signed out. Sign in again."
},
"card": {
"freeLower": "Free",
+31 -3
View File
@@ -5,6 +5,9 @@
// password your name, then your password
// POST /api/auth/login {client: "terminal", user_id, pin|password} with the device header;
// the session belongs to this screen only.
// Usernames (6F.7, me.require_username: the venue's auth.terminal_require_username or the
// device's own choice): nobody is listed; the person types their username, then the PIN or
// password ("tap" never applies then: the server answers pin instead).
import { useCallback, useEffect, useState } from 'react'
import { ArrowLeft } from 'lucide-react'
import { useAccess } from '@xenia/access'
@@ -27,12 +30,14 @@ export default function SignInScreen() {
const [error, setError] = useState('')
const [busy, setBusy] = useState(false)
const mode = me.login_mode
const typeName = !!me.require_username
const loadUsers = useCallback(() => {
if (typeName) { setUsers([]); return }
client.get('/api/devices/me/users', quiet)
.then(r => { setUsers(r.data); setLoadError(null) })
.catch(err => setLoadError(errorMessage(err, t)))
}, [t])
}, [t, typeName])
useEffect(() => { loadUsers() }, [loadUsers, me.login_mode])
useEffect(() => {
const id = setInterval(loadUsers, USERS_REFRESH_MS)
@@ -41,7 +46,8 @@ export default function SignInScreen() {
useLiveEvent('ready', loadUsers)
const login = async secret => {
const { data } = await client.post('/api/auth/login', { client: 'terminal', user_id: picked?.id ?? secret.user_id, ...secret }, quiet)
const who = picked?.username ? { username: picked.username } : { user_id: picked?.id ?? secret.user_id }
const { data } = await client.post('/api/auth/login', { client: 'terminal', ...who, ...secret }, quiet)
signIn(data.access_token)
}
@@ -61,7 +67,11 @@ export default function SignInScreen() {
<p className="text-body text-ink-2">{me.name}{venue?.name ? ` · ${venue.name}` : ''}</p>
</header>
{!picked && (
{!picked && typeName && (
<UsernameForm onSubmit={username => { setError(''); setPicked({ username, full_name: username }) }} />
)}
{!picked && !typeName && (
loadError ? <EmptyState title={loadError} action={<Button variant="secondary" onClick={loadUsers}>{t('common:actions.retry')}</Button>} />
: !users ? <Spinner />
: users.length === 0
@@ -100,6 +110,24 @@ export default function SignInScreen() {
)
}
function UsernameForm({ onSubmit }) {
const { t } = useTranslation('terminal')
const [username, setUsername] = useState('')
const submit = e => {
e.preventDefault()
if (username.trim()) onSubmit(username.trim())
}
return (
<form onSubmit={submit} className="bg-surface border border-line rounded-card shadow-raised p-6 grid gap-4 w-full max-w-sm" data-testid="username-form">
<Field label={t('signIn.username')} hint={t('signIn.typeUsername')}>
<Input value={username} onChange={e => setUsername(e.target.value)} autoFocus autoComplete="off"
autoCapitalize="none" spellCheck={false} data-testid="username-input" />
</Field>
<Button type="submit" disabled={!username.trim()}>{t('signIn.next')}</Button>
</form>
)
}
function PasswordForm({ onSubmit, error }) {
const { t } = useTranslation('terminal')
const [password, setPassword] = useState('')
+15 -5
View File
@@ -189,7 +189,7 @@ try {
await page.getByRole('button', { name: 'Pair a device' }).first().click()
await dlg.getByLabel('Code shown on the device').fill('zz-zz-zz')
await dlg.getByLabel('App to run').selectOption('kds')
await dlg.getByLabel('Name').fill('Kitchen')
await dlg.getByLabel('Name', { exact: true }).fill('Kitchen')
await dlg.getByRole('button', { name: 'Pair a device' }).click()
await page.getByTestId('pair-error').waitFor({ timeout: 5000 }).catch(() => {})
r.check('devices: a wrong code is refused with a message', (await page.getByTestId('pair-error').textContent().catch(() => '')).includes('pairing code is wrong'))
@@ -221,12 +221,15 @@ try {
r.check('devices: the screen opens a live connection with its device token alone (3.1a)', await sock.ready)
await row.getByRole('button', { name: 'Edit' }).click()
r.check('devices: the edit dialog shows the device setting', await dlg.getByLabel('Sign out after').inputValue() === '10')
await dlg.getByLabel('Name').fill('Kitchen 1')
await dlg.getByLabel('Name', { exact: true }).fill('Kitchen 1')
await dlg.getByLabel('Sign out after').selectOption('5')
await dlg.getByTestId('device-usernames').selectOption('true') // 6F.7: this screen asks for usernames
await dlg.getByRole('button', { name: 'Save' }).click()
await page.waitForFunction(() => document.querySelector('[data-testid^="device-"][data-status]')?.textContent.includes('Kitchen 1'), null, { timeout: 8000 }).catch(() => {})
const me2 = await asDevice(deviceToken, '/api/devices/me').then(x => x.json())
r.check('devices: renamed, setting changed', (await row.textContent()).includes('Kitchen 1') && me2.name === 'Kitchen 1' && me2.config?.auto_sign_out_minutes === 5, JSON.stringify(me2))
r.check('6F.7: a device set to "staff type their username" lists nobody', me2.require_username === true
&& (await asDevice(deviceToken, '/api/devices/me/users').then(x => x.json())).length === 0)
await sleep(300)
r.check('devices: the screen is told at once (device.updated)', sock.messages.some(m => m.type === 'device.updated'), JSON.stringify(sock.messages))
@@ -667,11 +670,18 @@ try {
(await api('GET', '/api/platform/bootstrap')).login.manager_mode === 'pin')
await page.screenshot({ path: path.join(OUT, 'manager-settings-sign-in.png'), fullPage: true })
await page.getByTestId('setting-auth.manager_login_mode').selectOption('password')
const sessionDefault = await page.getByTestId('setting-auth.single_session_waiter').inputValue()
r.check('6F.7: one session per waiter is "ask" by default', sessionDefault === 'ask', sessionDefault)
await page.getByTestId('setting-auth.terminal_require_username').click()
await sleep(800)
r.check('6F.7: "staff type their username" on paired devices is saved', await settingValue('auth.terminal_require_username') === 'true')
await page.getByTestId('setting-auth.terminal_require_username').click()
await sleep(800)
await page.getByTestId('setting-auth.single_session_waiter').selectOption('end_old')
await sleep(800)
r.check('settings: one session per waiter → "sign out the older one"', await settingValue('auth.single_session_waiter') === 'end_old' &&
await settingValue('auth.manager_login_mode') === 'password' && await settingValue('auth.waiter_login_mode') === 'pin')
await page.getByTestId('setting-auth.single_session_waiter').selectOption('off')
await page.getByTestId('setting-auth.single_session_waiter').selectOption('ask')
const idleSel = page.getByTestId('setting-auth.idle_days')
const idleDefault = await idleSel.inputValue()
await idleSel.selectOption('30')
@@ -912,7 +922,7 @@ try {
const odlg = o.getByRole('dialog')
await odlg.getByLabel('Code shown on the device').fill(kitchenCode)
await odlg.getByLabel('App to run').selectOption('kds')
await odlg.getByLabel('Name').fill('Kitchen pass')
await odlg.getByLabel('Name', { exact: true }).fill('Kitchen pass')
await odlg.getByLabel('How staff sign in').selectOption('pin')
await odlg.getByRole('button', { name: 'Pair a device' }).click()
await odlg.waitFor({ state: 'detached', timeout: 8000 }).catch(() => {})
@@ -971,7 +981,7 @@ try {
r.check(`${ov} a shift started for a waiter with €20.50 (typed with a comma)`, await ovRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& (await api('GET', '/api/shifts/?active_only=true', { token: boss })).shifts.some(s => s.waiter_id === ovWaiter.id && s.starting_cash === 20.5))
const freeTable = (await api('GET', '/api/tables/', { token: boss })).find(t => !t.open_order_id && !t.current_order_id)
const ovOrder = await api('POST', '/api/orders/', { token: await loginApi('demo_maria', { pin: '3302', client: 'waiter' }), body: { table_id: freeTable.id } })
const ovOrder = await api('POST', '/api/orders/', { token: await loginApi('demo_maria', { pin: '3302', client: 'waiter', replace: true }), body: { table_id: freeTable.id } })
const chip = page.locator(`[data-testid="table-chip"][data-state="open"]`).filter({ hasText: freeTable.label || `T${freeTable.number}` }).first()
r.check(`${ov} a table a waiter opens turns "open" by itself (live)`, await chip.waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await chip.click()
+24
View File
@@ -308,6 +308,30 @@ try {
await api('POST', `/api/auth/sessions/${sid}/end`, { token: boss })
r.check('session ended by a manager → the screen is back at sign-in at once', await shown(page, 'sign-in-screen', 8000))
// ── 6F.7: usernames on paired screens (venue setting, the device's own choice wins) ──
await api('PUT', '/api/settings/auth.terminal_require_username', { token: boss, body: { value: 'true' } })
r.check('6F.7: usernames on → the screen lists nobody and asks for a username (live)',
await shown(page, 'username-form', 8000) && await page.getByTestId('user-grid').count() === 0)
await page.screenshot({ path: path.join(OUT, 'terminal-username.png') })
const byName = async name => {
await page.getByTestId('username-input').fill(name)
await page.getByRole('button', { name: 'Next' }).click()
await page.getByLabel('Password').fill('password')
await page.getByRole('button', { name: 'Sign in' }).click()
}
await byName('nobody_here')
await sleep(1200)
r.check('6F.7: a wrong username is refused', await page.getByTestId('app-kds').count() === 0 && await page.getByTestId('sign-in-screen').count() === 1)
await page.getByRole('button', { name: 'Back' }).click()
await byName('manager')
r.check('6F.7: username + password signs in', await shown(page, 'app-kds'))
await page.getByRole('button', { name: 'Sign out' }).click()
await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { require_username: false } })
r.check('6F.7: the device\'s own "no" wins: the names are back', await shown(page, 'user-grid', 8000))
await api('PATCH', `/api/devices/${kitchen.id}`, { token: boss, body: { require_username: null } })
await api('PUT', '/api/settings/auth.terminal_require_username', { token: boss, body: { value: 'false' } })
await shown(page, 'user-grid', 8000)
// ── app off / on ──────────────────────────────────────────────────────────
await api('PUT', '/api/platform/modules/kds', { token: boss, body: { enabled: false } })
r.check('KDS turned off → "turned off" screen, live', await shown(page, 'blocked-screen', 8000)
+47
View File
@@ -596,6 +596,53 @@ try {
await a.getByRole('button', { name: /Dark theme/ }).click()
await a.reload()
// ── 6F.7: "ask" (the default): the second phone asks; Continue signs the first one out and it
// says why; an order queued offline on the first phone goes out after it signs in again ──
{
await setting(boss, 'auth.single_session_waiter', 'ask')
const busy7 = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
const tq = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busy7.has(x.id))
const status7 = async () => (await api('GET', `/api/tables/${tq.id}/status`, { token: boss })).active_order_id
await a.goto(`${APP}/tables/${tq.id}/add?new=1`)
await addOn(tq.id, plain)
await ctxA.setOffline(true)
await a.getByTestId('cart-open').click()
await waitFor(async () => (await total().innerText().catch(() => '')).includes('offline'), 30_000, 1000)
await a.getByRole('button', { name: /^(SEND|SUMMARY)/ }).last().click()
if (await shown(a, 'summary-total', 3000)) await a.getByRole('button', { name: /SEND/ }).last().click()
await sleep(1500)
// the second phone
await b.reload()
await b.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 })
await pin(b, '3302')
const asked = await shown(b, 'login-elsewhere', 5000)
const askText = await b.getByTestId('login-elsewhere').innerText().catch(() => '')
r.check('6F.7: a second phone asks (where, since when) instead of refusing', asked && /\d\d:\d\d/.test(askText) && !(await tokenOf(b)), askText.replace(/\s+/g, ' '))
await b.screenshot({ path: path.join(OUT, 'waiter-signed-in-elsewhere.png') })
await b.getByTestId('login-elsewhere-continue').click()
await b.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {})
r.check('6F.7: Continue signs this phone in', !!(await tokenOf(b)) && await pathOf(b) !== '/login', await pathOf(b))
// the first phone comes back: signed out, says why, the order still queued
await ctxA.setOffline(false)
const outA = await a.waitForURL(u => u.pathname === '/login', { timeout: 45_000 }).then(() => true).catch(() => false)
const noteA = await a.getByTestId('signed-out-note').innerText({ timeout: 10_000 }).catch(() => '')
r.check('6F.7: the first phone, back online, is signed out and says why', outA && /another device|άλλη συσκευή/.test(noteA), noteA)
await a.screenshot({ path: path.join(OUT, 'waiter-signed-out-replaced.png') })
r.check('6F.7: its order queued offline was not sent with the ended session', !(await status7()))
// it signs in again (asks: the second phone now); the second phone leaves at once (live)
await a.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 10_000 })
await pin(a, '3302')
await a.getByTestId('login-elsewhere-continue').click({ timeout: 5000 })
await a.waitForURL(u => u.pathname !== '/login', { timeout: 10_000 }).catch(() => {})
const outB = await b.waitForURL(u => u.pathname === '/login', { timeout: 10_000 }).then(() => true).catch(() => false)
const noteB = await b.getByTestId('signed-out-note').innerText({ timeout: 5000 }).catch(() => '')
r.check('6F.7: the other phone is signed out at once (live) and says why', outB && /another device|άλλη συσκευή/.test(noteB), noteB)
const flushed = await waitFor(status7, 30_000, 1000)
r.check('6F.7: …and the order queued offline goes out after signing in again', !!flushed)
if (flushed) await api('DELETE', `/api/orders/${flushed}`, { token: boss }).catch(() => {})
await a.goto(`${APP}/tables`)
}
// ── Signing out ends the session on the server: the second phone can sign in ─
await a.getByRole('button', { name: 'demo_maria' }).first().click({ timeout: 10_000 })
await a.getByRole('button', { name: /Sign out/ }).last().click()
+3 -1
View File
@@ -6,6 +6,7 @@
import axios from 'axios'
import { createApiClient } from '@xenia/api'
import { apiBase, storageKey } from '../config/server'
import { noteSignedOut } from '../logic/signedOut'
const client = createApiClient({
axios,
@@ -15,7 +16,8 @@ const client = createApiClient({
onOffline: () => window.dispatchEvent(new Event('backend-offline')),
// A 401 on a normal request = the session ended (expired, ended by a manager, signed in
// elsewhere): sign out. The login and PIN forms opt out with { xenia: { ignoreUnauthorized: true } }.
onUnauthorized: () => {
onUnauthorized: x => {
if (x?.code === 'auth.session_ended') noteSignedOut(x.params?.reason) // 6F.7: the sign-in page says why
localStorage.removeItem(storageKey('token'))
localStorage.removeItem(storageKey('savedUsername'))
window.location.href = '/login'
+15 -3
View File
@@ -7,6 +7,8 @@ import { useWebSocket } from '../hooks/useWebSocket'
import db from '../db/posdb'
import client from '../api/client'
import { flushAllOfflineOps } from '../services/offlineOrders'
import { noteSignedOut } from '../logic/signedOut'
import { storageKey } from '../config/server'
import useChatStore from '../store/chatStore'
import useKdsReadyStore from '../store/kdsReadyStore'
@@ -108,13 +110,13 @@ export function LiveProvider({ children }) {
// ── Called whenever we confirm the server is reachable again ─────────────────
// 6F.7: every (re)connection sends what is still queued, not only after "offline": a phone
// signed out by another one keeps its queued orders, and they go out after the next sign-in
// here even if the connection never looked lost (only unsynced ops are sent, once).
const handleCameOnline = useCallback(async () => {
const wasOffline = useConnectionStore.getState().status !== 'online'
setOnlineRef.current()
window.dispatchEvent(new Event('live-reconnected'))
if (wasOffline) {
await flushOfflineQueue()
}
await fullRefresh()
}, [fullRefresh, flushOfflineQueue])
@@ -124,6 +126,16 @@ export function LiveProvider({ children }) {
window.dispatchEvent(new CustomEvent('live-event', { detail: { type, data } }))
switch (type) {
case 'session.ended': {
// another phone took over (reason "replaced"), a manager ended it, … : say why on the
// sign-in page. Our own sign-out ("logout") already left. Queued orders stay queued.
if (data?.reason === 'logout') break
noteSignedOut(data?.reason || 'unknown')
localStorage.removeItem(storageKey('token'))
localStorage.removeItem(storageKey('savedUsername'))
window.location.href = '/login'
break
}
case 'order_updated': {
try {
const full = await client.get(`/api/orders/${data.order_id}`)
+4
View File
@@ -12,6 +12,7 @@ import { useCallback, useEffect, useRef } from 'react'
import { createLiveClient } from '@xenia/api'
import db from '../db/posdb'
import { wsUrl } from '../config/server'
import client from '../api/client'
const CURSOR_KEY = 'ws_last_seq'
@@ -56,6 +57,9 @@ export function useWebSocket({ token, onEvent, onConnect, onDisconnect, enabled
onEvent: (type, data) => onEventRef.current?.(type, data),
onReady: () => onConnectRef.current?.(),
onDisconnect: () => onDisconnectRef.current?.(),
// the session ended while the phone was away (6F.7): one request gets the 401 with the
// reason, and the client's sign-out runs from there
onRefused: code => { if (code === 'auth.session_ended') client.get('/api/auth/me').catch(() => {}) },
})
liveRef.current = live
live.start()
+25
View File
@@ -0,0 +1,25 @@
// Why the phone was signed out (plan 6F.7): kept until the next sign-in so the sign-in page can
// say it ("Signed out: you signed in on another device"). Set by a 401 that names the reason
// (auth.session_ended {reason}) and by the live socket's session.ended (reason "replaced" the
// moment another phone takes over). A sign-out the waiter asked for ("logout") says nothing.
import { storageKey } from '../config/server'
const KEY = () => storageKey('signedOut')
export function noteSignedOut(reason) {
if (!reason || reason === 'logout') return
try { localStorage.setItem(KEY(), reason) } catch { /* storage unavailable */ }
}
export function signedOutReason() {
try { return localStorage.getItem(KEY()) } catch { return null }
}
export function clearSignedOut() {
try { localStorage.removeItem(KEY()) } catch { /* storage unavailable */ }
}
/** The text key for a reason: "replaced" has its own, the rest a plain "you were signed out". */
export function signedOutText(reason) {
return reason === 'replaced' ? 'login.signedOutReplaced' : 'login.signedOut'
}
+44 -4
View File
@@ -1,12 +1,13 @@
import { useCallback, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useAccess } from '@xenia/access'
import { useTranslation } from '@xenia/i18n'
import { useFormat, useTranslation } from '@xenia/i18n'
import PinPad from '../components/PinPad'
import useAuthStore from '../store/authStore'
import client from '../api/client'
import { apiError } from '../api/errors'
import { assetUrl, deliveryMode, getActiveVenue } from '../config/server'
import { clearSignedOut, signedOutReason, signedOutText } from '../logic/signedOut'
// ─── Waiter card ──────────────────────────────────────────────────────────────
@@ -89,6 +90,9 @@ function WaiterCard({ waiter, onClick }) {
// Sends POST /api/auth/login {client: "waiter", user_id | username, pin | password}. The
// server's refusals (wrong PIN, one session per waiter, no waiter app for this account…)
// are shown in the user's language.
// 6F.7: signed in on another phone (rule "ask", auth.session_elsewhere {device, since}): the
// page asks; Continue sends the same sign-in with replace: true and the other phone is
// signed out at once. Why this phone was signed out (logic/signedOut.js) shows on top.
export default function LoginPage() {
const { t } = useTranslation('waiter')
@@ -107,6 +111,9 @@ export default function LoginPage() {
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const [attempt, setAttempt] = useState(0) // remounts the PIN pad (clears the dots) after a miss
const [elsewhere, setElsewhere] = useState(null) // { secret, device, since }: asking before taking over
const [outReason] = useState(signedOutReason)
const { formatTime } = useFormat()
const loadWaiters = useCallback(() => {
setLoadingWaiters(true)
@@ -129,17 +136,23 @@ export default function LoginPage() {
.finally(() => setLoadingWaiters(false))
}, [typeUsername, mode])
async function signIn(secret) {
async function signIn(secret, replace = false) {
const who = typeUsername ? { username: username.trim() } : { user_id: selectedWaiter?.id }
if (!who.username && who.user_id == null) return
setError('')
setElsewhere(null)
setLoading(true)
try {
const { data } = await client.post('/api/auth/login', { client: 'waiter', ...who, ...secret },
const { data } = await client.post('/api/auth/login', { client: 'waiter', ...who, ...secret, ...(replace ? { replace: true } : {}) },
{ xenia: { ignoreUnauthorized: true, noOverride: true } })
clearSignedOut()
login({ id: data.user.id, username: data.user.username, role: data.user.role }, data.access_token)
navigate('/tables', { replace: true })
} catch (err) {
if (err.xenia?.code === 'auth.session_elsewhere') {
setElsewhere({ secret, device: err.xenia.params?.device, since: err.xenia.params?.since })
return
}
setError(apiError(err, mode === 'password' ? t('login.wrongPassword') : t('login.wrongPin')))
setPassword('')
setAttempt(a => a + 1)
@@ -148,6 +161,15 @@ export default function LoginPage() {
}
}
const outNote = outReason && (
<p data-testid="signed-out-note" role="status" style={{
margin: '0 auto 12px', maxWidth: 480, padding: '10px 14px', borderRadius: 10, fontSize: 14, lineHeight: 1.4,
background: 'var(--bg2)', border: '1px solid var(--x-warning)', color: 'var(--text)', textAlign: 'center',
}}>
{t(signedOutText(outReason))}
</p>
)
const venueSwitch = deliveryMode() === 'native' && (
<button
onClick={() => navigate('/venues')}
@@ -185,6 +207,7 @@ export default function LoginPage() {
{/* Static header — never scrolls */}
<div style={{ flexShrink: 0, padding: '40px 16px 20px', textAlign: 'center' }}>
<h1 className="app-title" style={{ marginBottom: 10 }}>Xenia POS</h1>
{outNote}
<p className="app-subtitle">{t('login.whoAreYou')}</p>
{venueSwitch}
</div>
@@ -231,6 +254,7 @@ export default function LoginPage() {
<div className="page page--centered">
<div className="login-box" data-testid="login-secret" data-mode={mode}>
<h1 className="app-title">XeniaPOS</h1>
{outNote}
{w ? (
/* Selected waiter mini-card */
@@ -278,7 +302,23 @@ export default function LoginPage() {
</>
)}
{mode === 'password' ? (
{elsewhere ? (
<div data-testid="login-elsewhere" role="alertdialog" aria-labelledby="elsewhere-title"
style={{ display: 'grid', gap: 10, marginTop: 12, padding: 14, borderRadius: 12, background: 'var(--bg2)', border: '1px solid var(--border)' }}>
<strong id="elsewhere-title" style={{ fontSize: 16, color: 'var(--text)' }}>{t('login.elsewhereTitle')}</strong>
<p style={{ margin: 0, fontSize: 14, lineHeight: 1.5, color: 'var(--text)' }}>
{t('login.elsewhereBody', { device: elsewhere.device || '?', time: elsewhere.since ? formatTime(elsewhere.since) : '?' })}
</p>
<button className="btn btn--primary btn--lg" disabled={loading} data-testid="login-elsewhere-continue"
onClick={() => signIn(elsewhere.secret, true)}>
{loading ? '…' : t('login.elsewhereContinue')}
</button>
<button className="btn btn--secondary" disabled={loading} data-testid="login-elsewhere-cancel"
onClick={() => { setElsewhere(null); setPassword(''); setAttempt(a => a + 1) }}>
{t('login.elsewhereCancel')}
</button>
</div>
) : mode === 'password' ? (
<form
onSubmit={e => { e.preventDefault(); if (password) signIn({ password }) }}
style={{ display: 'grid', gap: 10, marginTop: 10 }}