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
+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'
+16 -4
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 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 }}