Files
xenia-pos-local/manager_dashboard/src/components/NotificationBell.jsx
T
bonaminandClaude Opus 5.5 096bd53dbd feat(backend,manager): the business day opens and closes by itself (opening hours, a time, or only an alert)
- services/day_auto.py: a minute loop (venue time, offline) opens the day when the opening
  hours start (or at business_day.auto_open_time) and closes it when they end (or at
  auto_close_time); 'alert' only tells the managers. Offsets before / after, one day across
  the break or one per span, spans past midnight belong to the day they start, a day closed
  by hand isn't reopened in the same span, a restart catches up the open (until the business
  date changes for 'time') and alerts a missed close instead of doing it late.
- The close runs only when no order of the day is unclosed (Q-10): otherwise a sticky alert
  and a new try every 15 minutes. A locked / expired license turns the open into an alert.
- Sticky notifications: notifications.resolved_at + core.notifications.resolve(); the
  alerts resolve when the day opens / closes (by hand or by itself).
- services/business_days.py: the one open / close path (the routes and the loop); days opened
  or closed by the system have no opener / closer and opened_auto / closed_auto (Alembic 0052).
- Manager: Settings -> Operation "Opening and closing the day"; the bell's action buttons
  ("Open now", "Go to the overview"); Reports -> Days marks days opened / closed by itself.

Plan platform-v2 6F.8.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 13:17:15 +02:00

159 lines
7.3 KiB
React

// The bell in the manager's header (plan step 2.6f, APPS_PLATFORM §10): platform
// notifications (license limits and expiry, support access used, print failures…) from
// GET /api/platform/notifications, in the reader's language (the backend renders `message`).
// - The unread count shows on the bell; it refetches on the live event
// `platform_notification` {id} and after every reconnect ('ready').
// - A NEW warning/critical one also pops up as a toast.
// - Opening an item marks it read; "Mark all as read" does the rest.
// - 6F.8: an item whose params carry an `action` gets a button: 'open_day' opens the business
// day here (POST /api/business-day/open), 'overview' goes to the overview. Those alerts stay
// until their cause is gone (the backend resolves them; a live event refreshes the list).
// Not staff chat (/api/notifications, the chat module), which stays separate.
import { useCallback, useEffect, useRef, useState } from 'react'
import toast from 'react-hot-toast'
import { useNavigate } from 'react-router-dom'
import { Bell, CheckCheck } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation, useFormat } from '@xenia/i18n'
import client from '../api/client'
import { useLiveEvent } from '../live/useLiveEvent'
const DOT = { info: 'bg-info', warning: 'bg-warning', critical: 'bg-danger' }
const FALLBACK_REFRESH_MS = 5 * 60_000
export default function NotificationBell() {
const { t } = useTranslation('manager')
const f = useFormat()
const [data, setData] = useState({ items: [], unread: 0 })
const [open, setOpen] = useState(false)
const ref = useRef(null)
const navigate = useNavigate()
const asked = useRef(0)
const load = useCallback(async () => {
// Loads overlap (the timer, a reconnect, a live event); only the newest may set the list,
// else an answer sent before the event lands after it and hides the new one (seen in e2e).
const mine = ++asked.current
try {
const r = await client.get('/api/platform/notifications', { params: { limit: 30 } })
if (mine === asked.current) setData(r.data)
return r.data
} catch {
return null // the bell stays as it was; the next event or refresh tries again
}
}, [])
useEffect(() => {
load()
const id = setInterval(load, FALLBACK_REFRESH_MS)
return () => clearInterval(id)
}, [load])
useLiveEvent('ready', load)
useLiveEvent('platform_notification', async ev => {
const fresh = await load()
const n = fresh?.items.find(x => x.id === ev?.id)
if (n && n.severity !== 'info') toast(n.message, { icon: '⚠️', duration: 8000 })
})
useEffect(() => {
if (!open) return undefined
const outside = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false) }
const escape = e => { if (e.key === 'Escape') setOpen(false) }
document.addEventListener('mousedown', outside)
document.addEventListener('keydown', escape)
return () => {
document.removeEventListener('mousedown', outside)
document.removeEventListener('keydown', escape)
}
}, [open])
async function markRead(n) {
if (n.read) return
setData(d => ({ unread: Math.max(0, d.unread - 1), items: d.items.map(x => (x.id === n.id ? { ...x, read: true } : x)) }))
await client.post(`/api/platform/notifications/${n.id}/read`).catch(() => {})
}
async function markAll() {
setData(d => ({ unread: 0, items: d.items.map(x => ({ ...x, read: true })) }))
await client.post('/api/platform/notifications/read-all').catch(() => {})
load()
}
async function act(n) {
await markRead(n)
if (n.params?.action === 'overview') { setOpen(false); navigate('/'); return }
if (n.params?.action === 'open_day') {
try {
await client.post('/api/business-day/open', {})
toast.success(t('notifications.dayOpened'))
} catch (err) {
toast.error(errorMessage(err, t))
}
load()
}
}
const badge = data.unread > 9 ? '9+' : String(data.unread)
return (
<div className="relative" ref={ref}>
<button
onClick={() => { setOpen(o => !o); if (!open) load() }}
className="relative flex h-8 w-8 items-center justify-center rounded-lg border border-line bg-surface text-ink-3 transition hover:bg-surface-2 hover:text-ink"
aria-label={data.unread ? t('notifications.bellUnread', { count: data.unread }) : t('notifications.bell')}
aria-haspopup="dialog"
aria-expanded={open}
data-testid="notif-bell"
>
<Bell className="h-3.5 w-3.5" />
{data.unread > 0 && (
<span className="absolute -top-1.5 -right-1.5 min-w-[18px] h-[18px] px-1 rounded-full bg-danger text-danger-fg text-[10px] font-bold leading-[18px] text-center"
data-testid="notif-count">{badge}</span>
)}
</button>
{open && (
<div className="absolute right-0 top-full mt-1.5 w-96 max-w-[calc(100vw-2rem)] rounded-card border border-line bg-surface shadow-popover z-popover"
role="dialog" aria-label={t('notifications.title')} data-testid="notif-panel">
<div className="flex items-center justify-between px-4 py-2.5 border-b border-line">
<span className="text-label font-semibold text-ink">{t('notifications.title')}</span>
{data.unread > 0 && (
<button onClick={markAll} className="inline-flex items-center gap-1 text-caption text-accent-ink hover:underline" data-testid="notif-read-all">
<CheckCheck className="h-3.5 w-3.5" />{t('notifications.markAll')}
</button>
)}
</div>
{data.items.length === 0
? <p className="px-4 py-8 text-center text-label text-ink-3">{t('notifications.empty')}</p>
: (
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
{data.items.map(n => (
<li key={n.id} className="relative">
{n.params?.action && (
<button onClick={() => act(n)} data-testid={`notif-action-${n.id}`}
className="absolute right-3 top-3 z-10 rounded-control border border-line bg-surface px-2.5 py-1 text-caption font-medium text-accent-ink hover:bg-surface-2">
{t(`notifications.actions.${n.params.action}`, { defaultValue: n.params.action })}
</button>
)}
<button onClick={() => markRead(n)} className={`w-full text-left flex gap-3 px-4 py-3 hover:bg-surface-2 ${n.read ? '' : 'bg-accent-soft/40'}`}
data-testid={`notif-${n.id}`} data-read={n.read ? 'true' : 'false'}>
<span className={`mt-1.5 h-2 w-2 shrink-0 rounded-full ${DOT[n.severity] || DOT.info}`} />
<span className={`flex-1 min-w-0 ${n.params?.action ? 'pr-28' : ''}`}>
<span className={`block text-label ${n.read ? 'text-ink-2' : 'text-ink font-medium'}`}>{n.message}</span>
<span className="block text-caption text-ink-3 mt-0.5">
{f.formatRelative(n.last_at)}
{n.count > 1 && ` · ${t('notifications.times', { count: n.count })}`}
</span>
</span>
</button>
</li>
))}
</ul>
)}
</div>
)}
</div>
)
}