feat: bump client-services (accumulated feature work + deploy fixes)

Snapshot of in-progress work across local_backend, manager_dashboard,
and waiter_pwa (pricing, chat, fiscal, prep zones, recovery codes, CRM,
inventory, permissions), plus the nginx/docker-compose deploy fixes for
the Unraid + NPM reverse-proxy setup.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-07-19 10:00:14 +03:00
co-authored by Claude Sonnet 5
parent 02ec1aa28f
commit 34ae328b0d
182 changed files with 34874 additions and 3556 deletions
+139 -29
View File
@@ -1,5 +1,6 @@
import { createContext, useContext, useEffect, useRef, useState, useCallback } from 'react'
import { createContext, useContext, useEffect, useState, useCallback } from 'react'
import useAuthStore from '../store/authStore'
import useNotificationSettingsStore from '../store/notificationSettingsStore'
import client from '../api/client'
const NotificationContext = createContext(null)
@@ -8,28 +9,109 @@ export function useNotifications() {
return useContext(NotificationContext)
}
// ─── Persistent banner (one message at a time, stacked) ───────────────────────
// ─── Per-type visual config ────────────────────────────────────────────────
function NotificationBanner({ message, onAck }) {
const TYPE_THEME = {
manager: {
bg: '#1e1b4b', border: '#6366f1', ackBg: '#4f46e5',
labelColor: '#a5b4fc', icon: '📢',
},
kds_order_done: {
bg: '#052e16', border: '#22c55e', ackBg: '#16a34a',
labelColor: '#86efac', icon: '✅',
},
kds_item_done: {
bg: '#052e16', border: '#4ade80', ackBg: '#15803d',
labelColor: '#86efac', icon: '🍽️',
},
kds_call_order: {
bg: '#2d1505', border: '#f97316', ackBg: '#ea580c',
labelColor: '#fed7aa', icon: '🔔',
},
kds_call_general: {
bg: '#2d1505', border: '#f59e0b', ackBg: '#d97706',
labelColor: '#fde68a', icon: '👋',
},
}
function getTheme(messageType) {
return TYPE_THEME[messageType] || TYPE_THEME.manager
}
function isManagerMessage(msg) {
return msg.message_type === 'manager' || !msg.message_type
}
// ─── Rich body renderer — highlights #order, table name, and zone after " - " ─
const HIGHLIGHT = { color: '#7dd3fc', fontWeight: 800 } // light blue bold
function RichBody({ text }) {
if (!text) return null
// Highlighted tokens:
// #digits → order number
// τραπέζι <word> → keep "τραπέζι " plain, highlight the word after it
// " - " <rest> → keep " - " plain, highlight everything after
const parts = []
const re = /(#\d+|τραπέζι \S+| - .+$)/g
let last = 0
let m
while ((m = re.exec(text)) !== null) {
if (m.index > last) parts.push({ t: 'plain', v: text.slice(last, m.index) })
const v = m[0]
if (v.startsWith('τραπέζι ')) {
parts.push({ t: 'plain', v: 'τραπέζι ' })
parts.push({ t: 'hi', v: v.slice(8) })
} else if (v.startsWith(' - ')) {
parts.push({ t: 'plain', v: ' - ' })
parts.push({ t: 'hi', v: v.slice(3) })
} else {
parts.push({ t: 'hi', v })
}
last = m.index + v.length
}
if (last < text.length) parts.push({ t: 'plain', v: text.slice(last) })
return (
<>
{parts.map((p, i) =>
p.t === 'hi'
? <span key={i} style={HIGHLIGHT}>{p.v}</span>
: <span key={i}>{p.v}</span>
)}
</>
)
}
// ─── Persistent banner (one message at a time, stacked) ─────────────────────
function NotificationBanner({ message, onAck, autoDismiss }) {
const tableIds = (() => { try { return JSON.parse(message.table_ids || '[]') } catch { return [] } })()
const theme = getTheme(message.message_type)
useEffect(() => {
if (!autoDismiss) return
const t = setTimeout(() => onAck(message.id), 3000)
return () => clearTimeout(t)
}, [message.id, autoDismiss, onAck])
return (
<div style={{
display: 'flex', alignItems: 'flex-start', gap: 12,
background: '#1e1b4b', border: '1px solid #6366f1',
background: theme.bg, border: `1px solid ${theme.border}`,
borderRadius: 14, padding: '12px 14px',
boxShadow: '0 8px 24px rgba(0,0,0,0.4)',
animation: 'slideIn 0.25s ease',
}}>
<span style={{ fontSize: 22, flexShrink: 0 }}>📢</span>
<span style={{ fontSize: 22, flexShrink: 0 }}>{theme.icon}</span>
<div style={{ flex: 1, minWidth: 0 }}>
{message.sender_name && (
<div style={{ fontSize: 11, fontWeight: 700, color: '#a5b4fc', marginBottom: 2, textTransform: 'uppercase', letterSpacing: 0.5 }}>
{message.sender_name}
{(message.kds_zone || message.sender_name) && (
<div style={{ fontSize: 11, fontWeight: 700, color: theme.labelColor, marginBottom: 2, textTransform: 'uppercase', letterSpacing: 0.5 }}>
{message.kds_zone || message.sender_name}
</div>
)}
<div style={{ fontSize: 15, fontWeight: 600, color: '#e2e8f0', lineHeight: 1.4 }}>
{message.body}
<RichBody text={message.body} />
</div>
{tableIds.length > 0 && (
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 4 }}>
@@ -42,7 +124,7 @@ function NotificationBanner({ message, onAck }) {
style={{
flexShrink: 0, height: 32, padding: '0 12px',
borderRadius: 8, border: 'none',
background: '#4f46e5', color: 'white',
background: theme.ackBg, color: 'white',
fontSize: 12, fontWeight: 700, cursor: 'pointer',
}}
>OK ✓</button>
@@ -52,13 +134,22 @@ function NotificationBanner({ message, onAck }) {
export function NotificationProvider({ children }) {
const { token, user } = useAuthStore()
const { popupMode, persistentPopup } = useNotificationSettingsStore()
const [pendingMessages, setPendingMessages] = useState([])
const [recentMessages, setRecentMessages] = useState([])
// Messages to show as popup banners (filtered by popupMode)
const popupMessages = pendingMessages.filter(msg => {
if (popupMode === 'never') return false
if (popupMode === 'manager_only') return isManagerMessage(msg)
return true
})
const fetchUnread = useCallback(async () => {
if (!token || !user) return
try {
const res = await client.get('/api/messages/unread')
const res = await client.get('/api/notifications/unread')
setPendingMessages(res.data)
} catch { /* offline or unauthenticated — swallow */ }
}, [token, user?.id])
@@ -66,7 +157,7 @@ export function NotificationProvider({ children }) {
const fetchRecent = useCallback(async () => {
if (!token || !user) return
try {
const res = await client.get('/api/messages/recent?limit=10')
const res = await client.get('/api/notifications/recent?limit=10')
setRecentMessages(res.data)
} catch { }
}, [token, user?.id])
@@ -87,7 +178,6 @@ export function NotificationProvider({ children }) {
if (type !== 'message_sent') return
if (!user) return
// Check if this message targets us (empty = broadcast)
const targets = data.target_waiter_ids || []
if (targets.length > 0 && !targets.includes(user.id)) return
@@ -97,52 +187,68 @@ export function NotificationProvider({ children }) {
sender_name: data.sender_name,
body: data.body,
table_ids: data.table_ids,
message_type: data.message_type || 'manager',
kds_zone: data.kds_zone || null,
created_at: data.created_at,
acked_by: [],
}
setPendingMessages(prev => {
if (prev.find(m => m.id === msg.id)) return prev
return [msg, ...prev]
})
setRecentMessages(prev => {
if (prev.find(m => m.id === msg.id)) return prev
return [msg, ...prev].slice(0, 10)
})
// popupMode=never + not persistent → ACK immediately (silent delivery, no badge)
if (popupMode === 'never' && !persistentPopup) {
client.post(`/api/notifications/${msg.id}/ack`).catch(() => {})
return
}
// All other cases: add to pending so bell badge shows and/or popup renders
setPendingMessages(prev => {
if (prev.find(m => m.id === msg.id)) return prev
return [msg, ...prev]
})
}
window.addEventListener('sse-event', onSSEEvent)
return () => window.removeEventListener('sse-event', onSSEEvent)
}, [user?.id])
}, [user?.id, persistentPopup, popupMode])
// Fallback: re-fetch unread when SSE reconnects (catches any messages missed during gap)
// Fallback: re-fetch unread when SSE reconnects
useEffect(() => {
function onSSEConnect() {
fetchUnread()
fetchRecent()
}
// SSEProvider fires this via setOnline — we listen to the connection store indirectly
// through the backend-coming-back-online signal that SSEProvider dispatches
window.addEventListener('sse-reconnected', onSSEConnect)
return () => window.removeEventListener('sse-reconnected', onSSEConnect)
}, [fetchUnread, fetchRecent])
async function ackMessage(messageId) {
try {
await client.post(`/api/messages/${messageId}/ack`)
await client.post(`/api/notifications/${messageId}/ack`)
setPendingMessages(prev => prev.filter(m => m.id !== messageId))
fetchRecent()
} catch { }
}
// Mark all pending as read (used when notification panel opens in never-popup mode)
async function ackAll() {
const ids = [...pendingMessages.map(m => m.id)]
setPendingMessages([])
await Promise.allSettled(ids.map(id => client.post(`/api/notifications/${id}/ack`)))
fetchRecent()
}
const unreadCount = pendingMessages.length
return (
<NotificationContext.Provider value={{ pendingMessages, recentMessages, unreadCount, ackMessage, fetchRecent, fetchUnread }}>
<NotificationContext.Provider value={{ pendingMessages, recentMessages, unreadCount, ackMessage, ackAll, fetchRecent, fetchUnread }}>
{children}
{/* Floating banner stack (max 3 visible) */}
{pendingMessages.length > 0 && (
{/* Floating banner stack — only when popupMode allows */}
{popupMessages.length > 0 && (
<div style={{
position: 'fixed', top: 64, left: 0, right: 0, zIndex: 9999,
padding: '0 12px',
@@ -150,17 +256,21 @@ export function NotificationProvider({ children }) {
pointerEvents: 'none',
}}>
<style>{`@keyframes slideIn { from { transform: translateY(-16px); opacity: 0 } to { transform: translateY(0); opacity: 1 } }`}</style>
{pendingMessages.slice(0, 3).map(msg => (
{popupMessages.slice(0, 3).map(msg => (
<div key={msg.id} style={{ pointerEvents: 'all' }}>
<NotificationBanner message={msg} onAck={ackMessage} />
<NotificationBanner
message={msg}
onAck={ackMessage}
autoDismiss={!persistentPopup}
/>
</div>
))}
{pendingMessages.length > 3 && (
{popupMessages.length > 3 && (
<div style={{
textAlign: 'center', fontSize: 12, color: '#94a3b8',
pointerEvents: 'all',
}}>
+{pendingMessages.length - 3} ακόμα μηνύματα
+{popupMessages.length - 3} ακόμα μηνύματα
</div>
)}
</div>
+158 -91
View File
@@ -2,11 +2,12 @@ import { createContext, useContext, useCallback, useEffect, useRef } from 'react
import { useQueryClient } from '@tanstack/react-query'
import useAuthStore from '../store/authStore'
import useConnectionStore from '../store/connectionStore'
import { useSSE } from '../hooks/useSSE'
import { useWebSocket } from '../hooks/useWebSocket'
import db from '../db/posdb'
import client from '../api/client'
import { flushOfflinePayments } from '../services/offlinePayments'
import { invalidateProductCache } from '../hooks/useProductCache'
import { flushAllOfflineOps } from '../services/offlineOrders'
import useChatStore from '../store/chatStore'
import useKdsReadyStore from '../store/kdsReadyStore'
const SSEContext = createContext(null)
@@ -14,37 +15,32 @@ export function useSSEContext() {
return useContext(SSEContext)
}
const HEARTBEAT_INTERVAL = 30_000
export function SSEProvider({ children }) {
const { token } = useAuthStore()
const { setLost, setOnline } = useConnectionStore()
const { setLost, setOnline, setSseAlive } = useConnectionStore()
const queryClient = useQueryClient()
const sseAlive = useRef(false)
const heartbeatRef = useRef(null)
const wsAlive = useRef(false)
const syncingRef = useRef(false) // prevent concurrent syncs
// Keep setLost/setOnline in refs so heartbeat/event closures are never stale
const setLostRef = useRef(setLost)
const setOnlineRef = useRef(setOnline)
useEffect(() => { setLostRef.current = setLost }, [setLost])
useEffect(() => { setOnlineRef.current = setOnline }, [setOnline])
// ── Snapshot helpers ─────────────────────────────────────────────────────────
// ── Snapshot helpers ──────────────────────────────────────────────────────────
const snapshotTables = useCallback(async () => {
try {
const res = await client.get('/api/tables/')
await db.tables.bulkPut(res.data)
await db.pos_tables.bulkPut(res.data)
} catch { /* offline — snapshot stays as-is */ }
}, [])
const snapshotOrders = useCallback(async () => {
try {
const res = await client.get('/api/orders/active')
const slimOrders = res.data
// Fetch full order details (with items) so emergency mode has them
const fullOrders = await Promise.all(
slimOrders.map(o =>
res.data.map(o =>
client.get(`/api/orders/${o.id}`)
.then(r => ({
...r.data,
@@ -53,36 +49,90 @@ export function SSEProvider({ children }) {
.catch(() => o)
)
)
await db.orders.bulkPut(fullOrders)
await db.pos_orders.bulkPut(fullOrders)
// Purge any IDB orders that are no longer active on the server
const activeIds = new Set(fullOrders.map(o => o.id))
const allIdbIds = await db.pos_orders.toCollection().primaryKeys()
const staleIds = allIdbIds.filter(id => !activeIds.has(id) && typeof id === 'number')
if (staleIds.length > 0) await db.pos_orders.bulkDelete(staleIds)
} catch { /* offline — snapshot stays as-is */ }
useKdsReadyStore.getState().refresh()
}, [])
const snapshotProducts = useCallback(async () => {
try {
const [prodRes, catRes] = await Promise.all([
client.get('/api/products/'),
client.get('/api/products/categories'),
])
await db.products.bulkPut(prodRes.data)
await db.categories.bulkPut(catRes.data)
// Also update React Query cache so AddItemsPage gets it immediately
queryClient.setQueryData(['products'], { products: prodRes.data, categories: catRes.data })
} catch { /* offline — snapshot stays as-is */ }
}, [queryClient])
const snapshotCatalogue = useCallback(async () => {
try {
const [groupsRes, flagDefsRes, flagAssignRes] = await Promise.all([
client.get('/api/tables/groups'),
client.get('/api/flags/defs'),
client.get('/api/flags/assignments'),
])
if (db.table_groups) await db.table_groups.bulkPut(groupsRes.data)
if (db.flag_defs) await db.flag_defs.bulkPut(flagDefsRes.data)
if (db.flag_assignments) {
await db.flag_assignments.clear()
if (flagAssignRes.data.length > 0) await db.flag_assignments.bulkAdd(flagAssignRes.data)
}
} catch { /* offline — snapshot stays as-is */ }
}, [])
const fullRefresh = useCallback(async () => {
await Promise.all([snapshotTables(), snapshotOrders()])
}, [snapshotTables, snapshotOrders])
await Promise.all([snapshotTables(), snapshotOrders(), snapshotCatalogue(), snapshotProducts()])
}, [snapshotTables, snapshotOrders, snapshotCatalogue, snapshotProducts])
// ── SSE event handler ────────────────────────────────────────────────────────
// ── Flush all offline queues in strict sequence order ────────────────────────
const flushOfflineQueue = useCallback(async () => {
if (syncingRef.current) return
syncingRef.current = true
try {
await flushAllOfflineOps()
} finally {
syncingRef.current = false
}
}, [])
// ── Called whenever we confirm the server is reachable again ─────────────────
const handleCameOnline = useCallback(async () => {
const wasOffline = useConnectionStore.getState().status !== 'online'
setOnlineRef.current()
window.dispatchEvent(new Event('sse-reconnected'))
if (wasOffline) {
await flushOfflineQueue()
}
await fullRefresh()
}, [fullRefresh, flushOfflineQueue])
// ── SSE event handler ─────────────────────────────────────────────────────────
const handleEvent = useCallback(async (type, data) => {
// Dispatch for any UI component listening to window events
window.dispatchEvent(new CustomEvent('sse-event', { detail: { type, data } }))
// Incrementally update IndexedDB snapshot
switch (type) {
case 'order_updated':
case 'order_paid': {
// Try to fetch the full order to keep items in the snapshot
case 'order_updated': {
try {
const full = await client.get(`/api/orders/${data.order_id}`)
const o = full.data
await db.orders.put({
await db.pos_orders.put({
...o,
waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [],
})
} catch {
// Fallback: update only the slim fields we know
const existing = await db.orders.get(data.order_id)
await db.orders.put({
const existing = await db.pos_orders.get(data.order_id)
await db.pos_orders.put({
...(existing || {}),
id: data.order_id,
table_id: data.table_id,
@@ -90,47 +140,89 @@ export function SSEProvider({ children }) {
waiter_ids: existing?.waiter_ids || [],
})
}
useKdsReadyStore.getState().refresh()
break
}
case 'order_paid': {
// Do NOT write to IDB — when auto-close is on, order_closed fires immediately
// after order_paid. Writing here races with the delete in order_closed and
// can resurrect the order in IDB after it's been deleted.
useKdsReadyStore.getState().refresh()
break
}
case 'order_closed': {
await db.orders.delete(data.order_id)
await db.pos_orders.delete(data.order_id)
useKdsReadyStore.getState().refresh()
break
}
case 'kds_item_updated':
case 'kds_order_updated': {
try {
const full = await client.get(`/api/orders/${data.order_id}`)
const o = full.data
await db.pos_orders.put({
...o,
waiter_ids: o.waiters?.map(w => w.waiter_id) ?? [],
})
} catch {}
useKdsReadyStore.getState().refresh()
break
}
case 'table_list_changed': {
await snapshotTables()
break
}
case 'table_flags_changed': {
await snapshotCatalogue()
break
}
case 'products_changed': {
invalidateProductCache(queryClient)
await snapshotProducts()
break
}
case 'chat_message': {
const { conversation_id, message_id, sender_id, sender_name, body, sent_at } = data
const { conversations, upsertConversation, incrementUnread } = useChatStore.getState()
const existingConv = conversations.find(c => c.id === conversation_id)
const newMsg = { id: message_id, conversation_id, sender_id, sender_name, body, sent_at, is_deleted: false }
if (existingConv) {
upsertConversation({ ...existingConv, last_message: newMsg })
if (sender_id !== useAuthStore.getState().user?.id) {
incrementUnread(conversation_id)
}
} else {
client.get('/api/chat/conversations')
.then(r => useChatStore.getState().setConversations(r.data || []))
.catch(() => {})
}
break
}
case 'chat_read': {
useChatStore.getState().updateLastRead(data.conversation_id, data.user_id, data.read_at)
break
}
default:
break
}
}, [snapshotTables, queryClient])
}, [snapshotTables, snapshotCatalogue, snapshotProducts, queryClient])
// ── SSE connection lifecycle ─────────────────────────────────────────────────
// ── SSE lifecycle ─────────────────────────────────────────────────────────────
const handleConnect = useCallback(async () => {
sseAlive.current = true
const wasEmergency = useConnectionStore.getState().status === 'emergency'
setOnlineRef.current()
window.dispatchEvent(new Event('sse-reconnected'))
if (wasEmergency) {
const result = await flushOfflinePayments()
if (result.duplicates > 0 || result.failed > 0) {
window.dispatchEvent(new CustomEvent('offline-sync-result', { detail: result }))
}
}
await fullRefresh()
}, [fullRefresh])
wsAlive.current = true
setSseAlive(true)
await handleCameOnline()
}, [handleCameOnline, setSseAlive])
const handleDisconnect = useCallback(() => {
sseAlive.current = false
// Don't immediately setLost — heartbeat is the authoritative check
}, [])
wsAlive.current = false
setSseAlive(false)
// The WS hook will auto-reconnect with exponential backoff.
// Don't immediately declare offline — wait for the axios interceptor
// or visibility handler to confirm the server is truly unreachable.
}, [setSseAlive])
const { reconnect } = useSSE({
const { reconnect } = useWebSocket({
token,
enabled: !!token,
onEvent: handleEvent,
@@ -138,75 +230,50 @@ export function SSEProvider({ children }) {
onDisconnect: handleDisconnect,
})
// ── Heartbeat ────────────────────────────────────────────────────────────────
useEffect(() => {
if (!token) return
async function beat() {
try {
await client.get('/api/system/health')
const currentStatus = useConnectionStore.getState().status
if (currentStatus === 'lost' || currentStatus === 'emergency') {
if (currentStatus === 'emergency') {
const result = await flushOfflinePayments()
if (result.duplicates > 0 || result.failed > 0) {
window.dispatchEvent(new CustomEvent('offline-sync-result', { detail: result }))
}
}
setOnlineRef.current()
reconnect()
await fullRefresh()
}
} catch {
if (!sseAlive.current) {
setLostRef.current()
}
}
}
heartbeatRef.current = setInterval(beat, HEARTBEAT_INTERVAL)
return () => clearInterval(heartbeatRef.current)
// reconnect and fullRefresh are stable (useCallback with no changing deps)
}, [token, reconnect, fullRefresh])
// ── React to failed API requests (immediate detection) ───────────────────────
// ── Auto-offline on any failed API request ────────────────────────────────────
// The axios interceptor fires 'backend-offline' on network errors.
// We act on it immediately — no grace, no modals.
useEffect(() => {
function onBackendOffline() {
if (!sseAlive.current) {
setLostRef.current()
}
setLostRef.current()
}
window.addEventListener('backend-offline', onBackendOffline)
return () => window.removeEventListener('backend-offline', onBackendOffline)
}, [])
// ── Wake-up handshake — fires when tab/app returns from background ────────────
// ── Foreground / visibility handler ──────────────────────────────────────────
// When the phone screen turns back on or the user switches back to the tab,
// immediately probe the server and pull a full refresh.
useEffect(() => {
if (!token) return
async function onVisible() {
if (document.visibilityState !== 'visible') return
try {
await client.get('/api/system/health')
const currentStatus = useConnectionStore.getState().status
if (currentStatus === 'lost' || currentStatus === 'emergency' || currentStatus === 'reconnecting') {
setOnlineRef.current()
if (currentStatus !== 'online') {
reconnect()
await handleCameOnline()
} else if (!wsAlive.current) {
// WS dropped silently while sleeping — re-establish and refresh
setSseAlive(false)
reconnect()
await fullRefresh()
} else if (!sseAlive.current) {
// SSE dropped silently while sleeping — re-establish quietly
reconnect()
} else {
// Was online the whole time — still do a data refresh to catch anything missed
await fullRefresh()
}
} catch {
if (!sseAlive.current) setLostRef.current()
setLostRef.current()
}
}
document.addEventListener('visibilitychange', onVisible)
return () => document.removeEventListener('visibilitychange', onVisible)
}, [token, reconnect, fullRefresh])
}, [token, reconnect, handleCameOnline, fullRefresh])
// ── Initial snapshot on login ─────────────────────────────────────────────────