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>
This commit is contained in:
2026-11-23 13:17:15 +02:00
co-authored by Claude Opus 5.5
parent 7706bf2470
commit 096bd53dbd
21 changed files with 856 additions and 117 deletions
@@ -5,10 +5,15 @@
// `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'
@@ -22,6 +27,7 @@ export default function NotificationBell() {
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 () => {
@@ -74,6 +80,20 @@ export default function NotificationBell() {
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 (
@@ -109,11 +129,17 @@ export default function NotificationBell() {
: (
<ul className="max-h-[60vh] overflow-y-auto divide-y divide-line">
{data.items.map(n => (
<li key={n.id}>
<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">
<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)}
@@ -5,7 +5,7 @@
// Each part shows only with its app on. Dropped from v1: "automatic store schedule" (its switches
// were kept in the browser only and nothing ever read them).
import { useId, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import { useMutation, useQuery } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Plus, RefreshCw, Trash2 } from 'lucide-react'
import { useModule } from '@xenia/access'
@@ -70,9 +70,66 @@ function OrderingSettings() {
<PriceChangeSettings s={s} />
<QuantitySettings s={s} />
<SplitSettings s={s} />
<AutoDaySettings s={s} />
</>)
}
const DAY_MODES = ['off', 'schedule', 'time', 'alert']
const OFFSETS = ['0', '15', '30', '45', '60', '90', '120']
/** The day opens and closes by itself (6F.8, services/day_auto.py): at the opening hours (the
* Schedule page), at a time of its own, or only an alert. Closing waits for every table (Q-10). */
function AutoDaySettings({ s }) {
const { t } = useTranslation('manager')
const a = (k, o) => t(`settings.autoDay.${k}`, o)
const ids = { open: useId(), close: useId(), openTime: useId(), closeTime: useId(), openOff: useId(), closeOff: useId() }
const { data: hours } = useQuery({ queryKey: ['opening-hours'], queryFn: () => client.get('/api/identity/hours').then(r => r.data) })
const mode = which => s.get(`business_day.auto_${which}`, 'off')
const usesHours = ['open', 'close'].some(w => ['schedule', 'alert'].includes(mode(w)))
const noHours = usesHours && hours && !hours.set
const side = which => {
const m = mode(which)
const key = `business_day.auto_${which}`
return (<>
<SettingRow label={a(which)} hint={which === 'close' ? a('closeHint') : a('openHint')} tip={a(`${which}Tip`)} htmlFor={ids[which]}
warning={m !== 'off' && m !== 'time' && noHours ? a('noHours') : undefined}>
<Select id={ids[which]} value={m} disabled={s.saving} data-testid={`setting-${key}`}
onChange={e => s.save(key, e.target.value)}
options={DAY_MODES.map(v => ({ value: v, label: a(`modes.${which}.${v}`) }))} />
</SettingRow>
{m === 'time' && (
<SettingRow label={a(`${which}Time`)} htmlFor={ids[`${which}Time`]}>
<TimeField id={ids[`${which}Time`]} value={s.get(`${key}_time`, which === 'open' ? '09:00' : '23:30')} disabled={s.saving}
testId={`setting-${key}_time`} onSave={v => s.save(`${key}_time`, v)} />
</SettingRow>
)}
{m === 'schedule' && (
<SettingRow label={a(`${which}Offset`)} htmlFor={ids[`${which}Off`]}>
<Select id={ids[`${which}Off`]} value={String(s.get(`${key}_offset_min`, '0'))} disabled={s.saving} data-testid={`setting-${key}_offset_min`}
onChange={e => s.save(`${key}_offset_min`, e.target.value)}
options={OFFSETS.map(n => ({ value: n, label: n === '0' ? a('offsetNone') : a(which === 'open' ? 'before' : 'after', { count: Number(n) }) }))} />
</SettingRow>
)}
</>)
}
return (
<SettingsCard title={a('title')} description={a('intro')} testId="settings-auto-day">
{side('open')}
{side('close')}
{usesHours && <Toggle s={s} k="business_day.auto_ignore_break" fallback="true" label={a('ignoreBreak')} hint={a('ignoreBreakHint')} tip={a('ignoreBreakTip')} />}
</SettingsCard>
)
}
/** HH:MM, saved when a whole time is typed. */
function TimeField({ id, value, disabled, testId, onSave }) {
const [v, setV] = useState(value)
return (
<Input id={id} type="time" value={v} disabled={disabled} data-testid={testId} className="w-32"
onChange={e => { setV(e.target.value); if (/^\d\d:\d\d$/.test(e.target.value) && e.target.value !== value) onSave(e.target.value) }} />
)
}
/** Splitting a bill by amount (6F.6), each level with the ones before. Who may:
* ordering.payments.split_amount ("What each role may do", a person's permissions). */
function SplitSettings({ s }) {
@@ -48,7 +48,14 @@ export default function DaysTab() {
const columns = [
{ key: 'opened_at', label: t('reports.store.day'), render: d => <span className="font-semibold text-ink capitalize">{dateOf(d)}</span> },
{ key: 'times', label: t('reports.store.hours'), sort: false,
render: d => `${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})` },
render: d => (<>
{`${fmt.formatTime(d.opened_at)} – ${d.closed_at ? fmt.formatTime(d.closed_at) : '…'} (${since(d.opened_at, d.closed_at ? Date.parse(d.closed_at) : undefined)})`}
{(d.opened_auto || d.closed_auto) && (
<span className="block text-caption text-ink-3" data-testid="day-auto">
{t(d.opened_auto && d.closed_auto ? 'reports.store.autoBoth' : d.opened_auto ? 'reports.store.autoOpened' : 'reports.store.autoClosed')}
</span>
)}
</>) },
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: d => <span className="font-semibold">{fmt.formatMoney(d.revenue)}</span> },
{ key: 'fees', label: t('reports.fees'), align: 'right', render: d => (d.fees ? fmt.formatMoney(d.fees) : '') },