feat: one way to count sales in every report; exports for Excel; the report kit and Today on v2 (platform-v2 step 6.12a)

- services/sales.py: sold = active + paid lines; a line's value net of what
  was refunded of it; system lines (the delivery fee) counted apart as fees;
  cost/profit with has_gap. Products, categories, tables, traffic, revenue
  trends, business days (list and current), per-waiter sales, order history
  totals and the printed products/categories/tables reports all use it (they
  used to differ: closed-only vs all orders, fee as a product, refunds never
  subtracted)
- the overview's day summary values lines with their price change (discounts
  were valued at full price)
- services/csv_export.py: UTF-8 BOM, times in venue time with the zone in the
  header, ';' and decimal commas for a Greek venue (',' and '.' otherwise);
  every report export uses it; orders export has products / fees / refunded
- fix: /api/reports/shift/orders with business_day_id crashed (no window)
- manager: src/pages/reports/kit (page with tabs, period picker, panels,
  figures, sortable table, export button, order dialog reusing the order
  page's parts, hour chart on tokens) and reports/today on it; v1 Today removed
- tests: test_sales_accounting.py (a day with a fee and a partial refund adds
  up the same in every report), test_reports_export.py (Excel format),
  reports.test.mjs, e2e manager.mjs (Today, order dialog, export, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 08:51:13 +02:00
co-authored by Claude Opus 5.5
parent 6643614ff6
commit 4df59c33ef
21 changed files with 1197 additions and 558 deletions
@@ -1,9 +0,0 @@
import Today from './restaurant/Today'
export default function TodayPage() {
return (
<div className="flex flex-col h-full min-h-0">
<Today />
</div>
)
}
@@ -0,0 +1,25 @@
// Revenue per hour of the day (plan step 6.12a): one bar per hour; on today's report the hours
// still to come are faint. Colours are the tokens (CSS variables), so dark mode follows.
import { Bar, BarChart, CartesianGrid, Cell, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
import { useFormat } from '@xenia/i18n'
export default function HourChart({ series, nowHour = null, height = 220 }) {
const { formatMoney } = useFormat()
const data = series.map(s => ({ ...s, label: `${String(s.hour).padStart(2, '0')}:00` }))
return (
<div style={{ height }} data-testid="hour-chart">
<ResponsiveContainer width="100%" height="100%">
<BarChart data={data} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="var(--x-line)" />
<XAxis dataKey="label" tick={{ fontSize: 11, fill: 'var(--x-ink-3)' }} axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 11, fill: 'var(--x-ink-3)' }} axisLine={false} tickLine={false} tickFormatter={v => formatMoney(v, { decimals: 0 })} width={56} />
<Tooltip cursor={{ fill: 'var(--x-surface-2)' }} formatter={v => formatMoney(v)}
contentStyle={{ background: 'var(--x-surface)', border: '1px solid var(--x-line)', borderRadius: 8, color: 'var(--x-ink)' }} />
<Bar dataKey="revenue" radius={[3, 3, 0, 0]} maxBarSize={44}>
{data.map(d => <Cell key={d.hour} fill={nowHour != null && d.hour > nowHour ? 'var(--x-surface-3)' : 'var(--x-accent)'} />)}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
)
}
@@ -0,0 +1,52 @@
// An order from a report (plan step 6.12a; replaces the v1 report OrderDetailModal): the same
// lines, price changes and history the order page shows (6.9), read-only, with the order's
// totals (products, the delivery fee, refunds) and a link to the order page.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { ArrowRight } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { AuditList, PriceEventList } from '../../orders/OrderHistory'
import OrderLines from '../../orders/OrderLines'
import { Pill } from '../../overview/parts'
import { Loading } from './parts'
import { orderTotals } from './reportLogic'
const TABS = ['lines', 'prices', 'history']
const TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
export default function OrderDialog({ order: summary, onClose }) {
const { t } = useTranslation('manager')
const { formatMoney, formatDateTime } = useFormat()
const navigate = useNavigate()
const [tab, setTab] = useState('lines')
const { data: order } = useLiveQuery({ queryKey: ['order', summary.id], queryFn: () => client.get(`/api/orders/${summary.id}`).then(r => r.data) })
const { data: events = [] } = useLiveQuery({ queryKey: ['price-events', summary.id], queryFn: () => client.get(`/api/pricing/events/order/${summary.id}`).then(r => r.data) })
const totals = orderTotals(summary)
const place = summary.table_name || order?.table_name
return (
<Dialog open size="lg" onClose={onClose}
title={<span className="flex flex-wrap items-center gap-2">{place ? t('orders.title', { table: place }) : t('orders.titleNoTable', { id: summary.id })}
<Pill tone={TONE[summary.status] ?? 'neutral'}>{t(`overview.orderStatus.${summary.status}`, { defaultValue: summary.status })}</Pill></span>}
description={`#${summary.id} · ${formatDateTime(summary.opened_at, 'datetimeShort')}${summary.closed_at ? ` – ${formatDateTime(summary.closed_at, 'datetimeShort')}` : ''}${summary.opened_by_name ? ` · ${summary.opened_by_name}` : ''}`}
footer={<>
<span className="flex-1 flex flex-wrap gap-x-4 text-label text-ink-2" data-testid="order-dialog-totals">
<span>{t('reports.products')} <b className="text-ink tabular-nums">{formatMoney(totals.revenue)}</b></span>
{totals.fees > 0 && <span>{t('reports.fees')} <b className="text-ink tabular-nums">{formatMoney(totals.fees)}</b></span>}
{totals.refunded > 0 && <span>{t('reports.refunded')} <b className="text-danger-ink tabular-nums">{formatMoney(totals.refunded)}</b></span>}
</span>
<Button variant="ghost" iconEnd={<ArrowRight size={16} />} onClick={() => navigate(`/orders/${summary.id}`)}>{t('reports.openOrder')}</Button>
</>}>
<div className="grid gap-3" data-testid="report-order-dialog">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)}>{t(`reports.orderTabs.${k}`)}</Button>)}
</span>
{!order ? <Loading /> : tab === 'lines' ? <OrderLines order={order} open={false} priceEvents={events} onPay={() => {}} onChanged={() => {}} />
: tab === 'prices' ? <PriceEventList events={events} /> : <AuditList order={order} />}
</div>
</Dialog>
)
}
@@ -0,0 +1,54 @@
// The period a report covers (plan step 6.12a): dates (from – to, with quick choices) or one
// business day. Dates are venue calendar days; the backend reads them in venue time.
import { useId } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Input, Select } from '@xenia/ui'
import { dayChoices, quickRange, rangeProblem } from './reportLogic'
import { useBusinessDays } from './useBusinessDays'
export function PeriodPicker({ value, onChange, allowDay = true, right }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const id = useId()
const today = fmt.venueToday()
const { data: days = [] } = useBusinessDays()
const set = patch => onChange({ ...value, ...patch })
const problem = rangeProblem(value)
const dayLabel = d => `${fmt.formatDateTime(d.opened_at, 'datetimeShort')}${d.status === 'open' ? ` · ${t('reports.open')}` : ''}`
return (
<div className="rounded-card border border-line bg-surface shadow-raised px-4 py-3 flex flex-wrap items-end gap-3" data-testid="report-period">
{allowDay && (
<div className="flex rounded-control border border-line overflow-hidden self-end" role="group" aria-label={t('reports.period')}>
{['range', 'day'].map(m => (
<button key={m} type="button" aria-pressed={value.mode === m} onClick={() => set({ mode: m, dayId: m === 'day' && !value.dayId ? String(days[0]?.id ?? '') : value.dayId })}
className={`px-3 py-1.5 text-label font-medium ${value.mode === m ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2'}`}>
{t(`reports.modes.${m}`)}
</button>
))}
</div>
)}
{value.mode === 'range' ? (<>
<label className="grid gap-1 text-caption text-ink-2" htmlFor={`${id}-from`}>{t('reports.from')}
<Input id={`${id}-from`} type="date" value={value.from} max={today} onChange={e => set({ from: e.target.value })} data-testid="period-from" />
</label>
<label className="grid gap-1 text-caption text-ink-2" htmlFor={`${id}-to`}>{t('reports.to')}
<Input id={`${id}-to`} type="date" value={value.to} max={today} onChange={e => set({ to: e.target.value })} data-testid="period-to" />
</label>
<span className="flex flex-wrap gap-1">
{['today', 'week', 'month', 'thirty'].map(k => (
<Button key={k} size="sm" variant="ghost" onClick={() => set(quickRange(k, today))}>{t(`reports.quick.${k}`)}</Button>
))}
</span>
</>) : (
<label className="grid gap-1 text-caption text-ink-2 min-w-56" htmlFor={`${id}-day`}>{t('reports.businessDay')}
<Select id={`${id}-day`} value={value.dayId} onChange={e => set({ dayId: e.target.value })} data-testid="period-day"
options={dayChoices(days).map(d => ({ value: String(d.id), label: dayLabel(d) }))} placeholder={days.length ? undefined : t('reports.noDays')} />
</label>
)}
<span className="flex-1" />
{right}
{problem && <p role="alert" className="w-full text-label text-danger-ink">{t(`reports.rangeProblem.${problem}`)}</p>}
</div>
)
}
@@ -0,0 +1,155 @@
// The report kit's building blocks (plan step 6.12a): a report's page with tabs, a panel, a big
// figure, a sortable table, loading / error states, the export button. On the tokens, texts in
// `manager:reports.*`, money and dates through useFormat().
import { useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp, Download, Info } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, EmptyState, InfoTip, Spinner, cx } from '@xenia/ui'
import client from '../../../api/client'
import { sortRows } from './reportLogic'
/** A report page: its tabs (kept in the address as ?tab=) over the chosen tab's content. */
export function ReportPage({ title, tabs = [], children, testId }) {
const [params, setParams] = useSearchParams()
const active = tabs.find(t => t.id === params.get('tab'))?.id ?? tabs[0]?.id
const tab = tabs.find(t => t.id === active)
return (
<div className="h-full overflow-y-auto" data-testid={testId}>
<div className="max-w-7xl mx-auto p-4 lg:p-6 grid gap-4">
<header className="flex flex-wrap items-end gap-3">
<h1 className="text-title font-semibold text-ink flex-1 min-w-0">{title}</h1>
{tabs.length > 1 && (
<nav className="flex flex-wrap gap-1" role="tablist">
{tabs.map(t => (
<Button key={t.id} size="sm" variant={t.id === active ? 'primary' : 'ghost'} role="tab" aria-selected={t.id === active}
onClick={() => setParams(p => { const n = new URLSearchParams(p); n.set('tab', t.id); return n }, { replace: true })} data-testid={`report-tab-${t.id}`}>
{t.label}
</Button>
))}
</nav>
)}
</header>
{tab ? <tab.Component key={tab.id} /> : children}
</div>
</div>
)
}
/** A card with a title, an optional tip and actions. */
export function Panel({ title, tip, actions, children, className, padded = true, testId }) {
return (
<section className={cx('rounded-card border border-line bg-surface shadow-raised overflow-hidden', className)} data-testid={testId}>
{(title || actions) && (
<header className="flex flex-wrap items-center gap-2 px-4 py-3 border-b border-line">
<h2 className="flex-1 min-w-0 text-body font-semibold text-ink flex items-center gap-1">{title}{tip && <InfoTip>{tip}</InfoTip>}</h2>
{actions}
</header>
)}
<div className={padded ? 'p-4' : ''}>{children}</div>
</section>
)
}
const TONE = { success: 'text-success-ink', danger: 'text-danger-ink', warning: 'text-warning-ink', info: 'text-info-ink', accent: 'text-accent-ink' }
/** A figure: a label over a value, an optional line under it, a tone for the value. */
export function Stat({ label, value, sub, tip, tone, big = false, testId }) {
return (
<div className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-1 content-start" data-testid={testId}>
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3 flex items-center gap-1">{label}{tip && <InfoTip>{tip}</InfoTip>}</span>
<span className={cx('font-semibold tabular-nums', big ? 'text-display' : 'text-title', TONE[tone] ?? 'text-ink')}>{value}</span>
{sub && <span className="text-caption text-ink-2">{sub}</span>}
</div>
)
}
export function Loading() {
return <div className="py-16 grid place-items-center"><Spinner /></div>
}
export function Failed({ error, retry }) {
const { t } = useTranslation('manager')
return <EmptyState title={t('reports.failed')} description={errorMessage(error, t)}
action={retry ? <Button variant="secondary" onClick={retry}>{t('reports.retry')}</Button> : undefined} />
}
/**
* A sortable table. columns: [{ key, label, align?, render?(row), sort? (key or fn; false = not sortable), tip? }]
* Shows at most `limit` rows ("Showing 100 of 240").
*/
export function Table({ columns, rows, initialSort, onRow, rowTestId, limit = 200, empty, rowKey = r => r.id }) {
const { t, i18n } = useTranslation('manager')
const [sort, setSort] = useState(initialSort ?? null) // { key, dir }
if (!rows.length) return <EmptyState compact title={empty ?? t('reports.nothing')} />
const col = sort && columns.find(c => c.key === sort.key)
const sorted = col ? sortRows(rows, typeof col.sort === 'function' ? col.sort : (col.sort ?? col.key), sort.dir, i18n.language) : rows
const shown = sorted.slice(0, limit)
const flip = c => setSort(s => (s?.key === c.key ? { key: c.key, dir: s.dir === 'desc' ? 'asc' : 'desc' } : { key: c.key, dir: c.align === 'right' ? 'desc' : 'asc' }))
return (
<div className="overflow-x-auto">
<table className="w-full text-label border-collapse">
<thead>
<tr className="bg-surface-2 text-ink-2">
{columns.map(c => (
<th key={c.key} className={cx('px-3 py-2 font-semibold whitespace-nowrap', c.align === 'right' ? 'text-right' : 'text-left')}>
{c.sort === false ? c.label : (
<button type="button" className="inline-flex items-center gap-1 hover:text-ink" onClick={() => flip(c)}>
{c.label}{sort?.key === c.key && (sort.dir === 'desc' ? <ArrowDown size={12} /> : <ArrowUp size={12} />)}
</button>
)}
{c.tip && <InfoTip>{c.tip}</InfoTip>}
</th>
))}
</tr>
</thead>
<tbody className="divide-y divide-line">
{shown.map(r => (
<tr key={rowKey(r)} onClick={onRow ? () => onRow(r) : undefined} data-testid={rowTestId}
className={cx(onRow && 'cursor-pointer hover:bg-surface-2')}>
{columns.map(c => (
<td key={c.key} className={cx('px-3 py-2 align-top', c.align === 'right' && 'text-right tabular-nums')}>{c.render ? c.render(r) : r[c.key]}</td>
))}
</tr>
))}
</tbody>
</table>
{sorted.length > limit && <p className="px-3 py-2 text-caption text-ink-3 border-t border-line">{t('reports.showing', { shown: limit, total: sorted.length })}</p>}
</div>
)
}
/** Money with an optional "includes estimates" mark (a has_gap total is a lower bound). */
export function MoneyCell({ value, partial }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
return (
<span className="inline-flex items-center gap-1">
{formatMoney(value ?? 0)}
{partial && <span title={t('reports.partialTip')} className="text-warning-ink"><Info size={12} aria-label={t('reports.partial')} /></span>}
</span>
)
}
/** Downloads a CSV from a report's export endpoint (venue time, the venue's Excel separators). */
export function ExportButton({ endpoint, params, filename }) {
const { t } = useTranslation('manager')
const [busy, setBusy] = useState(false)
async function run() {
setBusy(true)
try {
const r = await client.get(endpoint, { params, responseType: 'blob' })
const url = URL.createObjectURL(r.data)
const a = document.createElement('a')
a.href = url
a.download = filename
document.body.appendChild(a)
a.click()
a.remove()
setTimeout(() => URL.revokeObjectURL(url), 1000)
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return <Button size="sm" variant="secondary" icon={<Download size={14} />} loading={busy} onClick={run} data-testid="report-export">{t('reports.export')}</Button>
}
@@ -0,0 +1,81 @@
// The report kit's plain data (plan step 6.12a), tested in tests/reports.test.mjs. Periods are
// business days or venue calendar dates; the backend reads a time without an offset as venue
// time (D-11), so a date range is sent as "YYYY-MM-DDT00:00:00" … "YYYY-MM-DDT23:59:59".
const DAY_MS = 86_400_000
const parse = key => Date.UTC(Number(key.slice(0, 4)), Number(key.slice(5, 7)) - 1, Number(key.slice(8, 10)))
export const addDays = (key, n) => new Date(parse(key) + n * DAY_MS).toISOString().slice(0, 10)
/** The period a report starts with: the last 30 days up to today (venue date). */
export const defaultPeriod = today => ({ mode: 'range', from: addDays(today, -29), to: today, dayId: '' })
/** Quick ranges: today, the last 7 / 30 days, this month. */
export function quickRange(kind, today) {
if (kind === 'today') return { from: today, to: today }
if (kind === 'week') return { from: addDays(today, -6), to: today }
if (kind === 'month') return { from: `${today.slice(0, 8)}01`, to: today }
return { from: addDays(today, -29), to: today }
}
/** A period → the query parameters every report endpoint takes. */
export function periodParams(p) {
if (p.mode === 'day') return p.dayId ? { business_day_id: p.dayId } : {}
const out = {}
if (p.from) out.from = `${p.from}T00:00:00`
if (p.to) out.to = `${p.to}T23:59:59`
return out
}
/** A period's part of a file name: "2026-11-01_2026-11-19" or "day-12". */
export const periodSlug = p => (p.mode === 'day' ? `day-${p.dayId || 'all'}` : `${p.from}_${p.to}`)
/** Is the range the right way round (and not more than `maxDays`)? */
export function rangeProblem(p, maxDays = 366) {
if (p.mode !== 'range' || !p.from || !p.to) return null
if (p.from > p.to) return 'order'
if ((parse(p.to) - parse(p.from)) / DAY_MS + 1 > maxDays) return 'long'
return null
}
export const ratio = (part, whole) => (whole ? part / whole : 0)
/** Margin of profit on revenue (null when nothing was sold). */
export const margin = (profit, revenue) => (revenue > 0 ? profit / revenue : null)
/** Rows sorted by a column (numbers numerically, text by the language's rules); stable. */
export function sortRows(rows, key, dir = 'desc', locale) {
const sign = dir === 'asc' ? 1 : -1
return rows.map((r, i) => [r, i]).sort(([a, i], [b, j]) => {
const x = typeof key === 'function' ? key(a) : a[key]
const y = typeof key === 'function' ? key(b) : b[key]
let c
if (x == null && y == null) c = 0
else if (x == null) c = 1
else if (y == null) c = -1
else if (typeof x === 'number' && typeof y === 'number') c = (x - y) * sign
else c = String(x).localeCompare(String(y), locale) * sign
return c || i - j
}).map(([r]) => r)
}
/** The hours a day's chart shows: from `from` to `to` (inclusive), each with its revenue;
* widened to any hour that has sales (an early breakfast, a late night). */
export function hourSeries(byHour = [], { from = 10, to = 23 } = {}) {
const map = new Map(byHour.map(h => [h.hour, h]))
const busy = byHour.filter(h => h.orders || h.revenue).map(h => h.hour)
if (busy.length) { from = Math.min(from, ...busy); to = Math.max(to, ...busy) }
const out = []
for (let h = from; h <= to; h++) out.push({ hour: h, revenue: map.get(h)?.revenue ?? 0, orders: map.get(h)?.orders ?? 0 })
return out
}
/** The order history's totals for an order (the backend's services/sales.py), with a fallback. */
export function orderTotals(o) {
if (o?.totals) return o.totals
const sold = (o?.items ?? []).filter(i => i.status === 'active' || i.status === 'paid')
const revenue = sold.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
return { revenue, fees: 0, takings: revenue, refunded: 0, total_cost: 0, trackable_profit: 0, has_gap: true }
}
/** The business days list → choices for a select, newest first (label filled by the page). */
export const dayChoices = (days = []) => [...days].sort((a, b) => (b.opened_at ?? '').localeCompare(a.opened_at ?? ''))
@@ -0,0 +1,10 @@
// The business days for the period pickers (GET /api/reports/business-days), newest first.
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
export function useBusinessDays() {
return useLiveQuery({
queryKey: ['business-days'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data.business_days),
refetchInterval: 60_000, staleTime: 30_000, // no live event for business days
})
}
@@ -1,234 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell } from 'recharts'
import { TrendingUp, ReceiptText, Clock, Users, Trophy, XCircle, Package, Sunset, PiggyBank, ShoppingBag } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import OrderDetailModal from '../shared/OrderDetailModal'
import { fmtEUR, fmtNum, fmtTime, fmtDateTime } from '../shared/reportDesignTokens'
export default function Today() {
const [drillOrder, setDrillOrder] = useState(null)
const { data: bdData, isLoading: bdLoading } = useQuery({
queryKey: ['business-day-current'],
queryFn: () => client.get('/api/reports/business-days/current').then(r => r.data),
staleTime: 30 * 1000,
refetchInterval: 30 * 1000,
})
const bd = bdData?.business_day
const { data: ordersData, isLoading: ordersLoading } = useQuery({
queryKey: ['today-orders', bd?.id],
queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: bd.id, page_size: 200 } }).then(r => r.data),
enabled: !!bd?.id,
staleTime: 30 * 1000,
refetchInterval: 30 * 1000,
})
const { data: trafficData } = useQuery({
queryKey: ['today-traffic', bd?.id],
queryFn: () => client.get('/api/reports/traffic', { params: { business_day_id: bd.id } }).then(r => r.data),
enabled: !!bd?.id,
staleTime: 30 * 1000,
})
if (bdLoading || ordersLoading) {
return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={8} showChart /></div>
}
if (!bd) {
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar>
<span className="font-mono text-[12px] uppercase tracking-wider text-slate-500">Live snapshot</span>
</FilterBar>
<div className="flex flex-1 items-center justify-center p-12">
<EmptyState
icon={Sunset}
title="Δεν υπάρχει ενεργή εργάσιμη μέρα"
description="Ανοίξτε μια εργάσιμη μέρα από τον Πίνακα Ελέγχου για να ξεκινήσετε."
/>
</div>
</div>
)
}
const orders = Array.isArray(ordersData) ? ordersData : []
const hourlyMap = {}
;(trafficData?.by_hour || []).forEach(h => { hourlyMap[h.hour] = h })
const hours = Array.from({ length: 14 }, (_, i) => 10 + i)
const hourlyChart = hours.map(h => ({
hour: `${String(h).padStart(2, '0')}:00`,
revenue: hourlyMap[h]?.revenue || 0,
}))
const nowH = new Date().getHours()
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<div className="flex items-center gap-2 rounded-md bg-emerald-50 px-2.5 py-1 text-[12px] font-medium text-emerald-700 ring-1 ring-inset ring-emerald-200">
<span className="relative h-1.5 w-1.5 rounded-full bg-emerald-500">
<span className="absolute inset-0 rounded-full bg-emerald-500 animate-ping opacity-75" />
</span>
Εργάσιμη μέρα ανοιχτή · άνοιξε {fmtTime(bd.opened_at)}
</div>
}>
<span className="font-mono text-[12px] uppercase tracking-wider text-slate-500">Ζωντανή Εικόνα</span>
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
<div className="grid grid-cols-12 gap-4">
<div className="col-span-5 rounded-lg border border-slate-200 bg-gradient-to-br from-sky-50 to-white p-6 shadow-[0_1px_0_rgba(15,23,42,0.04)]">
<div className="flex items-center justify-between">
<div className="text-[11px] font-medium uppercase tracking-[0.1em] text-slate-500">Έσοδα Μέχρι Τώρα</div>
<TrendingUp className="h-4 w-4 text-sky-400" />
</div>
<div className="mt-2 font-mono text-[52px] font-medium tabular-nums leading-none tracking-tight text-slate-900">
{fmtEUR(bd.revenue)}
</div>
<div className="mt-3 flex items-center gap-4 text-[12px] text-slate-600">
<span><span className="font-mono font-semibold text-slate-900">{bd.orders_closed}</span> κλειστές παραγγελίες</span>
<span>·</span>
<span><span className="font-mono font-semibold text-slate-900">{fmtEUR(bd.orders_closed ? bd.revenue / bd.orders_closed : 0)}</span> μέσος όρος</span>
</div>
{bd.trackable_profit > 0 && (
<div className="mt-4 flex items-center gap-3 border-t border-sky-100 pt-4">
<div className="flex-1">
<div className="text-[10px] font-medium uppercase tracking-[0.08em] text-slate-400">Μεικτό Κέρδος</div>
<div className="font-mono text-[22px] font-semibold tabular-nums text-green-700">
{fmtEUR(bd.trackable_profit)}
</div>
</div>
{bd.revenue > 0 && (
<div className="rounded-md bg-green-50 px-2.5 py-1 text-[13px] font-semibold text-green-700 ring-1 ring-inset ring-green-200">
{((bd.trackable_profit / bd.revenue) * 100).toFixed(0)}% margin
{bd.has_gap && <span className="ml-1 text-[10px] text-amber-500">⚠ μερικό</span>}
</div>
)}
</div>
)}
</div>
<div className="col-span-7 grid grid-cols-3 gap-4">
<StatCard label="Κλειστές Παραγγελίες" value={fmtNum(bd.orders_closed)} sub="πληρωμένες + κλειστές" icon={ReceiptText} />
<StatCard label="Ανοιχτές Παραγγελίες" value={fmtNum(bd.orders_open)} sub="αναμένουν πληρωμή" icon={Clock} accent />
<StatCard label="Ενεργοί Σερβιτόροι" value={fmtNum(bd.active_waiters)} icon={Users} />
{bd.top_product && (
<StatCard label="Κορυφαίο Προϊόν" value={bd.top_product.name} sub={`${bd.top_product.qty} τεμ.`} icon={Trophy} />
)}
<StatCard
label="Ακυρώσεις"
value={fmtNum(bd.cancellation_events ?? bd.cancellations)}
sub={
(bd.cancellations > 0 || bd.cancelled_items > 0)
? `${fmtNum(bd.cancellations)} παραγγελίες / ${fmtNum(bd.cancelled_items)} είδη`
: 'καμία ακύρωση'
}
icon={XCircle}
/>
{bd.total_cost > 0 && (
<StatCard label="Κόστος Πωλήσεων" value={fmtEUR(bd.total_cost)} sub="κόστος ειδών" icon={ShoppingBag} />
)}
{bd.trackable_profit > 0 && (
<StatCard
label="Μεικτό Κέρδος"
value={fmtEUR(bd.trackable_profit)}
sub={bd.has_gap ? '⚠ μερικό κέρδος' : `${((bd.trackable_profit / bd.revenue) * 100).toFixed(0)}% margin`}
icon={PiggyBank}
/>
)}
</div>
</div>
<div className="mt-4">
<Panel title="Έσοδα ανά Ώρα" subtitle="Μόνο κλειστές παραγγελίες" right={<span className="font-mono text-[11px] uppercase tracking-wider text-slate-500">Σήμερα</span>}>
<div style={{ height: 220 }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={hourlyChart} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="hour" tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} tickFormatter={v => '€' + v} />
<Tooltip content={<ChartTooltip formatter={(v, n) => fmtEUR(v)} />} cursor={{ fill: '#f1f5f9' }} />
<Bar dataKey="revenue" radius={[3, 3, 0, 0]} maxBarSize={48}>
{hourlyChart.map((entry, i) => (
<Cell key={i} fill={parseInt(entry.hour) > nowH ? '#e2e8f0' : '#60a5fa'} />
))}
</Bar>
</BarChart>
</ResponsiveContainer>
</div>
</Panel>
</div>
<div className="mt-4">
<Panel
padded={false}
title={
<span className="flex items-center gap-1.5">
<span>Παραγγελίες Σήμερα</span>
<span className="text-slate-300">·</span>
<span className="font-normal text-slate-500">{orders.length} συνολικά</span>
</span>
}
right={
<div className="flex items-center gap-3">
<span className="text-[11px] text-slate-400 italic">Κάντε Click για Λεπτομέρειες Παραγγελίας</span>
<ExportButton
endpoint="/api/reports/orders/export"
params={{ business_day_id: bd.id }}
filename={`today-orders-${bd.id}.csv`}
/>
</div>
}
>
<DataTable>
<THead>
<TH>#</TH><TH>Τραπέζι</TH><TH>Άνοιξε</TH><TH>Έκλεισε</TH>
<TH align="right">Είδη</TH><TH align="right">Σύνολο</TH><TH align="right">Κέρδος</TH><TH>Κατάσταση</TH>
</THead>
<tbody>
{orders.slice(0, 30).map(o => {
const activeItems = (o.items || []).filter(i => ['active', 'paid'].includes(i.status))
const total = activeItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
const costedItems = activeItems.filter(i => i.unit_cost != null)
const orderProfit = costedItems.length > 0
? costedItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0) - (i.unit_cost ?? 0)) * i.quantity, 0)
: null
const isCancelled = o.status === 'cancelled'
return (
<TR key={o.id} striped onClick={() => setDrillOrder(o)} className={isCancelled ? 'opacity-50' : ''}>
<TD mono>#{o.id}</TD>
<TD>{o.table_id}</TD>
<TD mono>{fmtDateTime(o.opened_at)}</TD>
<TD mono>{fmtDateTime(o.closed_at)}</TD>
<TD mono align="right">{(o.items || []).length}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(total)}</TD>
<TD mono align="right">
{orderProfit != null
? <span className={orderProfit >= 0 ? 'text-green-700' : 'text-red-600'}>{fmtEUR(orderProfit)}</span>
: <span className="text-slate-300">—</span>
}
</TD>
<TD><StatusBadge status={o.status} pulse /></TD>
</TR>
)
})}
</tbody>
</DataTable>
</Panel>
</div>
</div>
{drillOrder && (
<OrderDetailModal order={drillOrder} onClose={() => setDrillOrder(null)} />
)}
</div>
)
}
@@ -0,0 +1,98 @@
// Reports → Today (plan step 6.12a; replaces the v1 "live snapshot"): the open business day as
// it stands — products sold (net of refunds), delivery fees apart, refunds, cost and profit,
// open and finished orders, staff on shift, the best seller, cancellations; revenue per hour;
// every order of the day (tap one for its lines and history), with a CSV export. All numbers
// are counted like every other report (backend services/sales.py) and refresh by themselves.
import { useState } from 'react'
import { Sunset } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { EmptyState } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { Pill } from '../../overview/parts'
import HourChart from '../kit/HourChart'
import OrderDialog from '../kit/OrderDialog'
import { ExportButton, Failed, Loading, MoneyCell, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { hourSeries, margin, orderTotals } from '../kit/reportLogic'
const EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
const TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
export default function TodayPage() {
const { t } = useTranslation('manager')
return <ReportPage title={t('reports.today.title')} testId="report-today"><Today /></ReportPage>
}
function Today() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [order, setOrder] = useState(null)
const { data, isPending, error, refetch } = useLiveQuery({
queryKey: ['report-today'], queryFn: () => client.get('/api/reports/business-days/current').then(r => r.data.business_day),
events: EVENTS, refetchInterval: 60_000,
})
const dayId = data?.id
const { data: orders = [] } = useLiveQuery({
queryKey: ['report-today-orders', dayId], enabled: !!dayId, events: EVENTS,
queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: dayId, page_size: 500 } }).then(r => r.data),
})
const { data: traffic } = useLiveQuery({
queryKey: ['report-today-traffic', dayId], enabled: !!dayId, events: EVENTS,
queryFn: () => client.get('/api/reports/traffic', { params: { business_day_id: dayId } }).then(r => r.data),
})
if (isPending) return <Loading />
if (error) return <Failed error={error} retry={refetch} />
if (!data) return <EmptyState icon={<Sunset size={28} />} title={t('reports.today.closed')} description={t('reports.today.closedHint')} />
const d = data
const finished = d.orders_closed || 0
const m = margin(d.trackable_profit, d.revenue)
const nowHour = Number(fmt.formatDateTime(new Date(), { hour: '2-digit', hourCycle: 'h23' }))
const columns = [
{ key: 'id', label: '#', render: o => <span className="tabular-nums text-ink-2">#{o.id}</span> },
{ key: 'place', label: t('reports.place'), sort: o => o.table_name ?? '', render: o => o.table_name || t('reports.noTable') },
{ key: 'opened_at', label: t('reports.opened'), render: o => fmt.formatTime(o.opened_at) },
{ key: 'closed_at', label: t('reports.closed'), render: o => (o.closed_at ? fmt.formatTime(o.closed_at) : '—') },
{ key: 'waiter', label: t('reports.by'), sort: o => o.opened_by_name ?? '', render: o => o.opened_by_name ?? '' },
{ key: 'products', label: t('reports.products'), align: 'right', sort: o => orderTotals(o).revenue, render: o => fmt.formatMoney(orderTotals(o).revenue) },
{ key: 'fees', label: t('reports.fees'), align: 'right', sort: o => orderTotals(o).fees, render: o => (orderTotals(o).fees ? fmt.formatMoney(orderTotals(o).fees) : '') },
{ key: 'refunded', label: t('reports.refunded'), align: 'right', sort: o => orderTotals(o).refunded,
render: o => (orderTotals(o).refunded ? <span className="text-danger-ink">{fmt.formatMoney(orderTotals(o).refunded)}</span> : '') },
{ key: 'status', label: t('reports.status'), render: o => <Pill tone={TONE[o.status] ?? 'neutral'}>{t(`overview.orderStatus.${o.status}`, { defaultValue: o.status })}</Pill> },
]
return (
<div className="grid gap-4">
<p className="text-label text-ink-2" data-testid="today-day">{t('reports.today.since', { time: fmt.formatDateTime(d.opened_at, 'datetimeShort') })}</p>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat big label={t('reports.revenue')} tip={t('reports.revenueTip')} testId="today-revenue"
value={<MoneyCell value={d.revenue} />}
sub={t('reports.today.finished', { count: finished, avg: fmt.formatMoney(finished ? d.revenue / finished : 0) })} />
{d.fees > 0 && <Stat label={t('reports.fees')} tip={t('reports.feesTip')} value={fmt.formatMoney(d.fees)} testId="today-fees" />}
{d.refunded > 0 && <Stat label={t('reports.refunded')} tip={t('reports.refundedTip')} tone="danger" value={fmt.formatMoney(d.refunded)}
sub={t('reports.today.refunds', { count: d.refunds?.count ?? 0 })} testId="today-refunded" />}
{d.total_cost > 0 && (
<Stat label={t('reports.profit')} tip={t('reports.profitTip')} tone="success" value={<MoneyCell value={d.trackable_profit} partial={d.has_gap} />}
sub={m != null ? t('reports.margin', { pct: fmt.formatPercent(m, { maxDecimals: 0 }) }) : undefined} />
)}
<Stat label={t('reports.today.open')} value={d.orders_open} sub={t('reports.today.openSub')} />
<Stat label={t('reports.today.staff')} value={d.active_waiters} />
{d.top_product && <Stat label={t('reports.today.top')} value={d.top_product.name} sub={t('reports.today.topSub', { qty: d.top_product.qty })} />}
<Stat label={t('reports.today.cancellations')} value={d.cancellation_events ?? 0}
sub={d.cancellations || d.cancelled_items ? t('reports.today.cancelSub', { orders: d.cancellations, items: d.cancelled_items }) : t('reports.today.noCancels')} />
</div>
<Panel title={t('reports.byHour')} tip={t('reports.byHourTip')}>
<HourChart series={hourSeries(traffic?.by_hour)} nowHour={nowHour} />
</Panel>
<Panel padded={false} title={t('reports.today.orders', { count: orders.length })}
actions={<ExportButton endpoint="/api/reports/orders/export" params={{ business_day_id: d.id }} filename={`orders-day-${d.id}.csv`} />}>
<Table columns={columns} rows={orders} onRow={setOrder} rowTestId="today-order" initialSort={{ key: 'id', dir: 'desc' }} />
</Panel>
{order && <OrderDialog order={order} onClose={() => setOrder(null)} />}
</div>
)
}