feat(connect): caller ID as an integration: calls on the signed-in live connection, matched on the server

Plan step 3.5.
- The public /api/phone/ws socket is removed (anyone on the LAN could listen to every
  caller). GET /api/phone/call-event stays public for the Grandstream UCM but is LAN-only in
  the proxy (the 443 blocks' LAN-only location now covers it, in nginx-proxy/nginx.conf and
  install.sh), with an optional shared secret (setting caller_id.secret → &key=).
- Calls are logged (phone_calls, migration 0023), matched to a customer on the server
  (services/caller_id.py: Greek number rules moved from the manager) and published as
  `call_incoming` {call_id, at, number, ext, customer card: visits, spent, last 3 orders} to
  users with caller_id.use and to the counter POS screens. GET /api/phone/calls (the log),
  GET /api/customers/lookup?phone=. Calls older than a minute don't pop up (replays).
- Manager: PhoneListener on the live connection and the shared Dialog (no more downloading
  every customer to match); Integrations → Caller ID shows the server's log live and the UCM
  Action URL. Counter: CallPopup with "New takeaway sale".
- Tests: tests/test_caller_id.py (10), terminal unit test, e2e terminal and manager.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-16 09:06:39 +02:00
co-authored by Claude Opus 5.5
parent 88a9703902
commit dabe807ce0
28 changed files with 609 additions and 501 deletions
@@ -1,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 (
<div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
{[0, 1, 2].map(i => (
<span key={i} style={{
position: 'absolute', width: 80, height: 80, borderRadius: '50%',
border: `2px solid ${color}`, opacity: 0,
animation: `phoneRipple 2s ease-out ${i * 0.6}s infinite`,
}} />
))}
</div>
)
}
/* ─── Known customer modal ────────────────────────────────────────────────── */
function KnownCustomerModal({ call, customer, orders, onClose }) {
const recent = (orders || []).slice(0, 3)
return (
<div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
<div onClick={onClose} style={{
position: 'fixed', inset: 0, zIndex: 9990,
background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
animation: 'fadeIn 0.2s ease',
}} />
<div style={{
position: 'fixed', zIndex: 9991,
top: '50%', left: '50%',
transform: 'translate(-50%,-50%)',
width: '100%', maxWidth: 480, padding: '0 16px',
animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
}}>
<div style={{
background: '#0f1117', borderRadius: 20, overflow: 'hidden',
boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
}}>
<div style={{ height: 3, background: 'linear-gradient(90deg,#d4a853,#f0c87a,#d4a853)' }} />
<div style={{ padding: '24px 24px 20px', position: 'relative' }}>
<button onClick={onClose} style={{
position: 'absolute', top: 20, right: 20,
width: 32, height: 32, borderRadius: 8,
background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
color: '#9ca3af', cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
><X size={14} /></button>
<div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
<div style={{ position: 'relative', width: 44, height: 44 }}>
<RippleRings color="#d4a853" />
<div style={{
width: 44, height: 44, borderRadius: '50%',
background: 'linear-gradient(135deg,#d4a853,#f0c87a)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
position: 'relative', zIndex: 1,
}}><PhoneIncoming size={18} color="#0f1117" /></div>
</div>
<div>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#d4a853', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
<div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)} · {call.caller}</div>
</div>
</div>
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
<div style={{
width: 56, height: 56, borderRadius: 14, flexShrink: 0,
background: 'linear-gradient(135deg,#1e293b,#334155)',
border: '1px solid rgba(212,168,83,0.3)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
fontSize: 22, fontWeight: 700, color: '#d4a853',
}}>{customer.name?.[0]?.toUpperCase() || '?'}</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', lineHeight: 1.2, letterSpacing: '-0.01em' }}>{customer.name}</div>
{customer.nickname && (
<div style={{ fontSize: 13, color: '#d4a853', marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
<Tag size={11} />{customer.nickname}
</div>
)}
</div>
</div>
</div>
<div style={{ height: 1, background: 'rgba(255,255,255,0.06)', margin: '0 24px' }} />
<div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
{customer.email && (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<Mail size={13} color="#6b7280" style={{ flexShrink: 0 }} />
<span style={{ fontSize: 13, color: '#d1d5db' }}>{customer.email}</span>
</div>
)}
{customer.phone && (
<div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
<Phone size={13} color="#6b7280" style={{ flexShrink: 0 }} />
<span style={{ fontSize: 13, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>{customer.phone}</span>
</div>
)}
{customer.notes && (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 2 }}>
<MessageSquare size={13} color="#6b7280" style={{ flexShrink: 0, marginTop: 1 }} />
<span style={{ fontSize: 13, color: '#9ca3af', lineHeight: 1.5, fontStyle: 'italic' }}>"{customer.notes}"</span>
</div>
)}
</div>
<div style={{
margin: '0 24px',
background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
borderRadius: 12, display: 'grid', gridTemplateColumns: '1fr 1fr',
}}>
<div style={{ padding: '12px 16px', borderRight: '1px solid rgba(255,255,255,0.07)' }}>
<div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Επισκέψεις</div>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
<ShoppingBag size={14} color="#d4a853" />{customer.visit_count ?? 0}
</div>
</div>
<div style={{ padding: '12px 16px' }}>
<div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Σύνολο</div>
<div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
<TrendingUp size={14} color="#d4a853" />{formatCurrency(customer.total_spent)}
</div>
</div>
</div>
<div style={{ padding: '16px 24px 0' }}>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', color: '#6b7280', textTransform: 'uppercase', marginBottom: 8 }}>Πρόσφατες Παραγγελίες</div>
{recent.length === 0 ? (
<div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px dashed rgba(255,255,255,0.08)', fontSize: 12, color: '#4b5563', textAlign: 'center' }}>
Δεν υπάρχουν παραγγελίες ακόμα
</div>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{recent.map(order => (
<div key={order.id} style={{
display: 'flex', alignItems: 'center', gap: 10,
padding: '9px 12px', borderRadius: 10,
background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)',
}}>
<Clock size={12} color="#6b7280" style={{ flexShrink: 0 }} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 12, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>
{formatDate(order.opened_at)}
{order.table_name && <span style={{ color: '#6b7280' }}> · {order.table_name}</span>}
</div>
<div style={{ fontSize: 11, color: '#6b7280', marginTop: 1 }}>{order.item_count} είδη</div>
</div>
<div style={{ fontSize: 13, fontWeight: 600, color: '#d4a853', fontVariantNumeric: 'tabular-nums' }}>{formatCurrency(order.total)}</div>
</div>
))}
</div>
)}
</div>
<div style={{ padding: '20px 24px' }}>
<button onClick={onClose} style={{
width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
background: 'rgba(212,168,83,0.12)', color: '#d4a853', fontSize: 13, fontWeight: 600,
letterSpacing: '0.02em', transition: 'all 0.15s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.2)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.12)' }}
>Κλείσιμο</button>
</div>
</div>
</div>
</div>
)
}
/* ─── Unknown caller modal ────────────────────────────────────────────────── */
function UnknownCallerModal({ call, onClose }) {
return (
<div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
<div onClick={onClose} style={{
position: 'fixed', inset: 0, zIndex: 9990,
background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
animation: 'fadeIn 0.2s ease',
}} />
<div style={{
position: 'fixed', zIndex: 9991,
top: '50%', left: '50%',
transform: 'translate(-50%,-50%)',
width: '100%', maxWidth: 360, padding: '0 16px',
animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
}}>
<div style={{
background: '#0f1117', borderRadius: 20, overflow: 'hidden',
boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
}}>
<div style={{ height: 3, background: 'linear-gradient(90deg,#3b82f6,#6366f1,#3b82f6)' }} />
<div style={{ padding: '28px 24px 24px', position: 'relative' }}>
<button onClick={onClose} style={{
position: 'absolute', top: 20, right: 20,
width: 32, height: 32, borderRadius: 8,
background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
color: '#9ca3af', cursor: 'pointer',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
><X size={14} /></button>
<div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
<div style={{ position: 'relative', width: 44, height: 44 }}>
<RippleRings color="#3b82f6" />
<div style={{
width: 44, height: 44, borderRadius: '50%',
background: 'linear-gradient(135deg,#1d4ed8,#3b82f6)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
position: 'relative', zIndex: 1,
}}><PhoneIncoming size={18} color="#fff" /></div>
</div>
<div>
<div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#3b82f6', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
<div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)}</div>
</div>
</div>
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '20px 0 8px' }}>
<div style={{
width: 56, height: 56, borderRadius: 14,
background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}><User size={24} color="#4b5563" /></div>
<div style={{ fontSize: 12, color: '#6b7280' }}>Άγνωστος καλών</div>
<div style={{ fontSize: 28, fontWeight: 700, color: '#f9fafb', letterSpacing: '0.02em', fontVariantNumeric: 'tabular-nums' }}>
{call.caller || '—'}
</div>
{call.ext && <div style={{ fontSize: 12, color: '#6b7280' }}>Εσωτερικό: {call.ext}</div>}
</div>
<div style={{ marginTop: 20 }}>
<button onClick={onClose} style={{
width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
background: 'rgba(59,130,246,0.1)', color: '#3b82f6', fontSize: 13, fontWeight: 600,
transition: 'all 0.15s',
}}
onMouseEnter={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.18)' }}
onMouseLeave={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.1)' }}
>Κλείσιμο</button>
</div>
</div>
</div>
</div>
</div>
)
}
/* ─── PhoneListener ───────────────────────────────────────────────────────── */
export default function PhoneListener() {
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 <CallDialog call={activeCall} onClose={dismissCall} />
}
export function CallDialog({ call, onClose }) {
const { t } = useTranslation('manager')
const { formatMoney, formatTime, formatDate } = useFormat()
const c = call.customer
return (
<>
<style>{`
@keyframes fadeIn { from{opacity:0} to{opacity:1} }
@keyframes slideUp {
from{opacity:0;transform:translate(-50%,calc(-50% + 24px))}
to{opacity:1;transform:translate(-50%,-50%)}
}
@keyframes phoneRipple {
0%{transform:scale(1);opacity:0.6}
100%{transform:scale(2.8);opacity:0}
}
`}</style>
{activeCall.customer
? <KnownCustomerModal call={activeCall} customer={activeCall.customer} orders={activeCall.orders} onClose={dismissCall} />
: <UnknownCallerModal call={activeCall} onClose={dismissCall} />
}
</>
<Dialog open size="md" onClose={onClose} title={t('calls.incoming')}
footer={<Button variant="secondary" onClick={onClose} data-testid="call-close">{t('calls.close')}</Button>}>
<div className="grid gap-4" data-testid="call-popup" data-call={call.call_id}>
<div className="flex items-center gap-3">
<span className="size-12 rounded-full bg-accent-soft text-accent-ink flex items-center justify-center shrink-0">
{c ? <span className="text-title font-semibold">{c.name?.[0]?.toUpperCase()}</span> : <PhoneIncoming size={20} aria-hidden="true" />}
</span>
<div className="min-w-0">
<p className="text-heading font-semibold text-ink truncate" data-testid="call-name">{c ? c.name : t('calls.unknown')}</p>
<p className="text-label text-ink-2">
{call.number}{call.ext ? ` · ${t('calls.ext', { ext: call.ext })}` : ''}{call.at ? ` · ${formatTime(call.at)}` : ''}
</p>
{c?.nickname && <p className="text-label text-accent-ink flex items-center gap-1"><Tag size={12} aria-hidden="true" />{c.nickname}</p>}
</div>
</div>
{c ? (
<>
{c.notes && <p className="p-3 rounded-control bg-warning-soft text-warning-ink text-body">“{c.notes}”</p>}
<div className="grid grid-cols-2 gap-2">
<Stat icon={<ShoppingBag size={14} aria-hidden="true" />} label={t('calls.visits')} value={c.visit_count} />
<Stat icon={<TrendingUp size={14} aria-hidden="true" />} label={t('calls.spent')} value={formatMoney(c.total_spent)} />
</div>
<div className="grid gap-1.5">
<p className="text-label font-medium text-ink-2">{t('calls.recent')}</p>
{c.recent_orders.length === 0 ? <p className="text-label text-ink-3">{t('calls.noOrders')}</p> : c.recent_orders.map(o => (
<div key={o.id} className="flex items-center gap-3 p-2 rounded-control bg-surface-2 text-body">
<span className="flex-1">{formatDate(o.opened_at)}{o.table_name ? ` · ${o.table_name}` : ''} · {t('calls.items', { count: o.item_count })}</span>
<span className="font-medium">{formatMoney(o.total)}</span>
</div>
))}
</div>
</>
) : (
<p className="text-body text-ink-2 flex items-center gap-2"><User size={16} aria-hidden="true" />{t('calls.unknownBody')}</p>
)}
</div>
</Dialog>
)
}
function Stat({ icon, label, value }) {
return (
<div className="p-3 rounded-control border border-line">
<p className="text-caption text-ink-2">{label}</p>
<p className="text-title font-semibold text-ink flex items-center gap-1.5">{icon}{value}</p>
</div>
)
}