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 -1
View File
@@ -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",
@@ -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>
)
}
+59 -88
View File
@@ -1,96 +1,67 @@
import { Phone, PhoneIncoming, ChevronRight, Wifi, WifiOff } from 'lucide-react'
// Integrations → Caller ID (plan step 3.5): the call log (GET /api/phone/calls, kept on the
// server, so it survives a reload and shows calls taken while the manager was closed), new calls
// live, a tap opens the caller's card; and how to connect the phone system (the UCM Action URL).
import { useCallback, useEffect, useState } from 'react'
import { PhoneIncoming } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState, Spinner } from '@xenia/ui'
import client from '../api/client'
import { useLiveEvent } from '../live/useLiveEvent'
import usePhoneStore from '../store/phoneStore'
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 (
<div style={{ padding: 32, fontFamily: "'DM Sans','Segoe UI',sans-serif", maxWidth: 680, margin: '0 auto' }}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 28 }}>
<div style={{
width: 40, height: 40, borderRadius: 10,
background: 'linear-gradient(135deg,#064e3b,#065f46)',
border: '1px solid rgba(52,211,153,0.2)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<Phone size={18} color="#34d399" />
</div>
<div>
<h1 style={{ fontSize: 16, fontWeight: 700, color: '#0f172a', margin: 0, letterSpacing: '-0.01em' }}>
Εισερχόμενες Κλήσεις
</h1>
<p style={{ fontSize: 12, color: '#94a3b8', margin: '2px 0 0' }}>Grandstream UCM · Caller ID</p>
</div>
</div>
<div style={{ background: '#fff', border: '1px solid #e2e8f0', borderRadius: 16, overflow: 'hidden' }}>
<div style={{
padding: '12px 16px', borderBottom: '1px solid #f1f5f9',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
}}>
<span style={{ fontSize: 11, fontWeight: 600, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: '0.08em' }}>
Πρόσφατες Κλήσεις
</span>
{log.length > 0 && (
<span style={{ fontSize: 11, color: '#cbd5e1' }}>{log.length} κλήσεις</span>
)}
</div>
{log.length === 0 ? (
<div style={{ padding: '48px 16px', textAlign: 'center', color: '#cbd5e1', fontSize: 13 }}>
Δεν έχουν ληφθεί κλήσεις ακόμα.
</div>
) : (
<ul style={{ listStyle: 'none', margin: 0, padding: 0 }}>
{log.map((entry, i) => (
<li
key={i}
onClick={() => setActiveCall(entry)}
style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '12px 16px',
borderBottom: i < log.length - 1 ? '1px solid #f8fafc' : 'none',
cursor: 'pointer', transition: 'background 0.1s',
}}
onMouseEnter={e => { e.currentTarget.style.background = '#f8fafc' }}
onMouseLeave={e => { e.currentTarget.style.background = 'transparent' }}
>
<div style={{
width: 34, height: 34, borderRadius: 10, flexShrink: 0,
background: entry.customer ? '#fef3c7' : '#f1f5f9',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{entry.customer
? <span style={{ fontSize: 14, fontWeight: 700, color: '#d97706' }}>
{entry.customer.name?.[0]?.toUpperCase()}
</span>
: <PhoneIncoming size={14} color="#94a3b8" />
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b' }}>
{entry.customer ? entry.customer.name : entry.caller || '—'}
</div>
<div style={{ fontSize: 11, color: '#94a3b8', marginTop: 1 }}>
{entry.customer ? entry.caller : 'Άγνωστος'}
</div>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<span style={{ fontSize: 11, color: '#cbd5e1', fontVariantNumeric: 'tabular-nums' }}>
{formatTime(entry.at)}
</span>
<ChevronRight size={12} color="#cbd5e1" />
</div>
</li>
))}
</ul>
)}
</div>
<div className="p-4 md:p-6 grid gap-6 max-w-3xl" data-testid="phone-page">
<header className="grid gap-1">
<h1 className="text-heading font-semibold text-ink">{t('calls.title')}</h1>
<p className="text-body text-ink-2">{t('calls.intro')}</p>
</header>
<section className="rounded-card border border-line bg-surface overflow-hidden" aria-labelledby="calls-h">
<h2 id="calls-h" className="px-4 py-3 border-b border-line text-label font-semibold text-ink-2">{t('calls.log')}</h2>
{error ? <div className="p-6"><EmptyState title={error} /></div>
: calls == null ? <div className="p-6 flex justify-center"><Spinner /></div>
: calls.length === 0 ? <div className="p-6"><EmptyState icon={<PhoneIncoming size={28} />} title={t('calls.none')} /></div>
: (
<ul className="divide-y divide-line" data-testid="call-log">
{calls.map(c => (
<li key={c.call_id}>
<button type="button" onClick={() => setActiveCall(c)} data-testid="call-row"
className="w-full px-4 py-3 flex items-center gap-3 text-left hover:bg-surface-2 transition-colors duration-fast">
<span className="size-9 rounded-full bg-surface-2 text-ink-2 flex items-center justify-center shrink-0 font-semibold">
{c.customer ? c.customer.name?.[0]?.toUpperCase() : <PhoneIncoming size={14} aria-hidden="true" />}
</span>
<span className="flex-1 min-w-0">
<span className="block text-body font-medium text-ink truncate">{c.customer ? c.customer.name : c.number}</span>
<span className="block text-label text-ink-2">{c.customer ? c.number : t('calls.unknown')}{c.ext ? ` · ${t('calls.ext', { ext: c.ext })}` : ''}</span>
</span>
<span className="text-label text-ink-3">{formatDateTime(c.at, 'datetimeShort')}</span>
</button>
</li>
))}
</ul>
)}
</section>
<section className="p-4 rounded-card border border-line bg-surface-2 grid gap-1.5">
<h2 className="text-label font-semibold text-ink">{t('calls.setup')}</h2>
<p className="text-label text-ink-2">{t('calls.setupBody')}</p>
<code className="text-label text-ink break-all bg-surface p-2 rounded-control border border-line">{hook}</code>
<p className="text-caption text-ink-3">{t('calls.setupSecret')}</p>
</section>
</div>
)
}
+4 -2
View File
@@ -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