feat: the venue and products reports on v2 (platform-v2 step 6.12b)

- Reports -> Venue (src/pages/reports/store): business days (revenue/profit
  trend, each day's times, orders, revenue, fees, refunds, cost, profit; a day
  opens with its orders and shifts, a shift opens the overview's shift dialog;
  the owner corrects a closing time, deletes an empty day or a shift), orders
  (filters by status, person, table; per-order products / fees / refunds),
  busy times (by hour, by weekday of the business date), trends (days, weeks,
  months, the 7-day average), tables (time at the table, per visit, revenue)
- Reports -> Products (src/pages/reports/products): products (units, revenue,
  refunded, cost, profit, margin, waste, share; top 10 by revenue, units or
  profit) and categories (share bars, profit share)
- kit: PrintDialog (receipt printer, summary / full, or print the page),
  TrendChart and BarList on tokens (no chart animation), printBody()
- access: deleting a business day or a shift (which erases its orders) is
  owner-only (core.settings.manage; was any dashboard user)
- v1 StorePage, ProductsReportPage and their seven views removed
- tests: reports.test.mjs (+1), e2e manager.mjs (every tab, a day, products
  revenue = the backend's, Greek)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 09:06:20 +02:00
co-authored by Claude Opus 5.5
parent 4df59c33ef
commit 7767bdb728
28 changed files with 964 additions and 2266 deletions
+2 -2
View File
@@ -46,9 +46,9 @@ import StockPage from './pages/inventory/StockPage'
// Reports
import TodayPage from './pages/reports/today/TodayReport'
import StorePage from './pages/reports/StorePage'
import StorePage from './pages/reports/store/StorePage'
import StaffReportPage from './pages/reports/StaffReportPage'
import ProductsReportPage from './pages/reports/ProductsReportPage'
import ProductsReportPage from './pages/reports/products/ProductsReport'
import PrepZonesPage from './pages/reports/PrepZonesPage'
import ExpensesReportPage from './pages/reports/ExpensesReportPage'
import TechnicalPage from './pages/reports/TechnicalPage'
@@ -1,24 +0,0 @@
import { useState } from 'react'
import { TabBar } from '../../ui/Tabs'
import ProductPerformance from './restaurant/ProductPerformance'
import CategoryPerformance from './restaurant/CategoryPerformance'
const TABS = [
{ id: 'products', label: 'Απόδοση Προϊόντων', Component: ProductPerformance },
{ id: 'categories', label: 'Κατηγορίες', Component: CategoryPerformance },
]
export default function ProductsReportPage() {
const [active, setActive] = useState('products')
const tab = TABS.find(t => t.id === active) || TABS[0]
const { Component } = tab
return (
<div className="flex flex-col h-full min-h-0">
<TabBar tabs={TABS} active={active} onChange={setActive} />
<div className="flex-1 min-h-0 flex flex-col">
<Component key={active} />
</div>
</div>
)
}
@@ -1,30 +0,0 @@
import { useState } from 'react'
import { TabBar } from '../../ui/Tabs'
import WorkDaySummary from './restaurant/WorkDaySummary'
import OrderHistory from './restaurant/OrderHistory'
import TrafficAnalytics from './restaurant/TrafficAnalytics'
import RevenueTrends from './restaurant/RevenueTrends'
import TableAnalytics from './restaurant/TableAnalytics'
const TABS = [
{ id: 'workday', label: 'Ημέρες Λειτουργίας', Component: WorkDaySummary },
{ id: 'orders', label: 'Ιστορικό Παραγγελιών', Component: OrderHistory },
{ id: 'traffic', label: 'Κίνηση', Component: TrafficAnalytics },
{ id: 'trends', label: 'Τάσεις Εσόδων', Component: RevenueTrends },
{ id: 'tables', label: 'Τραπέζια', Component: TableAnalytics },
]
export default function StorePage() {
const [active, setActive] = useState('workday')
const tab = TABS.find(t => t.id === active) || TABS[0]
const { Component } = tab
return (
<div className="flex flex-col h-full min-h-0">
<TabBar tabs={TABS} active={active} onChange={setActive} />
<div className="flex-1 min-h-0 flex flex-col">
<Component key={active} />
</div>
</div>
)
}
@@ -15,7 +15,7 @@ export default function HourChart({ series, nowHour = null, height = 220 }) {
<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}>
<Bar dataKey="revenue" radius={[3, 3, 0, 0]} maxBarSize={44} isAnimationActive={false}>
{data.map(d => <Cell key={d.hour} fill={nowHour != null && d.hour > nowHour ? 'var(--x-surface-3)' : 'var(--x-accent)'} />)}
</Bar>
</BarChart>
@@ -0,0 +1,58 @@
// Print a report on a receipt printer (plan step 6.12b; replaces the v1 print modals): which
// printer, and "Summary" (only what sold) or "Full" (every product, unsold ones too). The
// printout uses the same numbers as the screen (backend services/sales.py). "Print this page"
// uses the browser (to paper or a PDF).
import { useState } from 'react'
import toast from 'react-hot-toast'
import { Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, Select, cx } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
export default function PrintDialog({ endpoint, body, modes = ['smart', 'full'], onClose }) {
const { t } = useTranslation('manager')
const { data: printers = [] } = useLiveQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data.printers), staleTime: 300_000 })
const [printer, setPrinter] = useState('')
const [mode, setMode] = useState(modes[0])
const [busy, setBusy] = useState(false)
const chosen = printer || (printers[0] ? String(printers[0].id) : '')
async function send() {
setBusy(true)
try {
await client.post(endpoint, { ...body, printer_id: Number(chosen), mode })
toast.success(t('reports.print.sent'))
onClose()
} catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
}
return (
<Dialog open size="sm" onClose={onClose} title={t('reports.print.title')}
footer={<>
<Button variant="ghost" onClick={() => { onClose(); setTimeout(() => window.print(), 100) }}>{t('reports.print.page')}</Button>
<Button variant="secondary" onClick={onClose}>{t('reports.print.back')}</Button>
<Button icon={<Printer size={16} />} loading={busy} disabled={!chosen} onClick={send} data-testid="report-print-send">{t('reports.print.send')}</Button>
</>}>
<div className="grid gap-3">
{modes.length > 1 && (
<div className="grid gap-2 sm:grid-cols-2" role="radiogroup" aria-label={t('reports.print.kind')}>
{modes.map(m => (
<button key={m} type="button" role="radio" aria-checked={mode === m} onClick={() => setMode(m)}
className={cx('text-left px-3 py-2 rounded-control border', mode === m ? 'border-accent bg-accent-soft' : 'border-line bg-surface hover:bg-surface-2')}>
<span className={cx('block text-label font-semibold', mode === m ? 'text-accent-ink' : 'text-ink')}>{t(`reports.print.modes.${m}`)}</span>
<span className="block text-caption text-ink-2">{t(`reports.print.modesHint.${m}`)}</span>
</button>
))}
</div>
)}
{printers.length === 0 ? <p className="text-label text-warning-ink">{t('reports.print.noPrinters')}</p> : (
<Field label={t('reports.print.printer')}>
<Select value={chosen} onChange={e => setPrinter(e.target.value)} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
</Field>
)}
</div>
</Dialog>
)
}
@@ -0,0 +1,45 @@
// The reports' charts on the tokens (plan step 6.12b): a revenue (and profit) line over dates,
// and bar lists (top products, weekdays, categories' share) drawn with plain CSS, so they read
// in both themes and print.
import { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts'
import { useFormat, useTranslation } from '@xenia/i18n'
import { cx } from '@xenia/ui'
/** points: [{ label, revenue, profit? }] */
export function TrendChart({ points, showProfit = false, height = 240 }) {
const { t } = useTranslation('manager')
const { formatMoney } = useFormat()
return (
<div style={{ height }} data-testid="trend-chart">
<ResponsiveContainer width="100%" height="100%">
<LineChart data={points} margin={{ top: 8, right: 16, 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} minTickGap={16} />
<YAxis tick={{ fontSize: 11, fill: 'var(--x-ink-3)' }} axisLine={false} tickLine={false} tickFormatter={v => formatMoney(v, { decimals: 0 })} width={64} />
<Tooltip formatter={v => formatMoney(v)} contentStyle={{ background: 'var(--x-surface)', border: '1px solid var(--x-line)', borderRadius: 8, color: 'var(--x-ink)' }} />
{showProfit && <Legend wrapperStyle={{ fontSize: 12 }} />}
<Line type="monotone" dataKey="revenue" name={t('reports.revenue')} stroke="var(--x-accent)" strokeWidth={2} dot={{ r: 2 }} isAnimationActive={false} />
{showProfit && <Line type="monotone" dataKey="profit" name={t('reports.profit')} stroke="var(--x-success)" strokeWidth={2} dot={{ r: 2 }} isAnimationActive={false} connectNulls />}
</LineChart>
</ResponsiveContainer>
</div>
)
}
/** rows: [{ key, label, value, sub? }] → horizontal bars scaled to the largest; `format` for the value. */
export function BarList({ rows, format = v => v, highlight, testId }) {
const max = Math.max(1e-9, ...rows.map(r => r.value))
return (
<ul className="grid gap-1.5" data-testid={testId}>
{rows.map(r => (
<li key={r.key} className="grid grid-cols-[minmax(6rem,12rem)_1fr_auto] items-center gap-2 text-label">
<span className="truncate text-ink" title={r.label}>{r.label}</span>
<span className="h-3 rounded-full bg-surface-2 overflow-hidden">
<span className={cx('block h-full rounded-full', highlight === r.key ? 'bg-success' : 'bg-accent')} style={{ width: `${Math.max(1, (r.value / max) * 100)}%` }} />
</span>
<span className="tabular-nums text-ink-2 text-right min-w-16">{format(r.value)}{r.sub ? <span className="text-ink-3"> · {r.sub}</span> : null}</span>
</li>
))}
</ul>
)
}
@@ -26,6 +26,12 @@ export function periodParams(p) {
return out
}
/** A period → the body of a receipt-printer report (POST /api/reports/print/*). */
export function printBody(p) {
const q = periodParams(p)
return { business_day_id: q.business_day_id ? Number(q.business_day_id) : null, from_dt: q.from ?? null, to_dt: q.to ?? null }
}
/** 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}`)
@@ -0,0 +1,137 @@
// Reports → Products (plan step 6.12b; replaces the v1 product and category performance views):
// what sold, by product and by category, net of refunds (the delivery fee is not a product),
// with cost, profit and margin where products have a cost, and waste; top products as bars;
// export and print on a receipt printer.
import { useState } from 'react'
import { Printer } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Select } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { BarList } from '../kit/charts'
import { ExportButton, Failed, Loading, MoneyCell, Panel, ReportPage, Stat, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import PrintDialog from '../kit/PrintDialog'
import { defaultPeriod, margin, periodParams, periodSlug, printBody, ratio } from '../kit/reportLogic'
export default function ProductsReport() {
const { t } = useTranslation('manager')
const tabs = [
{ id: 'products', label: t('reports.products'), Component: ProductsTab },
{ id: 'categories', label: t('reports.prod.categories'), Component: CategoriesTab },
]
return <ReportPage title={t('reports.prod.title')} tabs={tabs} testId="report-products" />
}
const METRICS = ['revenue', 'qty_sold', 'trackable_profit']
function ProductsTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [category, setCategory] = useState('')
const [metric, setMetric] = useState('revenue')
const [printing, setPrinting] = useState(false)
const params = { ...periodParams(period), ...(category ? { category_id: category } : {}) }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-products', params], queryFn: () => client.get('/api/reports/products/performance', { params }).then(r => r.data.products) })
const { data: cats = [] } = useLiveQuery({ queryKey: ['categories'], queryFn: () => client.get('/api/products/categories').then(r => r.data), staleTime: 60_000 })
const rows = data ?? []
const sold = rows.filter(r => r.qty_sold > 0)
const total = sold.reduce((s, r) => s + r.revenue, 0)
const units = sold.reduce((s, r) => s + r.qty_sold, 0)
const refunded = rows.reduce((s, r) => s + (r.refunded ?? 0), 0)
const profit = rows.reduce((s, r) => s + r.trackable_profit, 0)
const anyCost = rows.some(r => r.total_cost > 0)
const gap = rows.some(r => r.has_gap)
const anyWaste = rows.some(r => r.waste_qty > 0)
const qty = q => fmt.formatNumber(q, { maxDecimals: 3 })
const columns = [
{ key: 'product_name', label: t('reports.prod.product'), render: r => <span className="font-semibold text-ink">{r.product_name}</span> },
{ key: 'qty_sold', label: t('reports.prod.units'), align: 'right', render: r => qty(r.qty_sold) },
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: r => fmt.formatMoney(r.revenue) },
{ key: 'refunded', label: t('reports.refunded'), align: 'right', render: r => (r.refunded ? <span className="text-danger-ink">{fmt.formatMoney(r.refunded)}</span> : '') },
...(anyCost ? [
{ key: 'total_cost', label: t('reports.cost'), align: 'right', render: r => (r.total_cost ? fmt.formatMoney(r.total_cost) : '') },
{ key: 'trackable_profit', label: t('reports.profit'), align: 'right', render: r => (r.total_cost ? <MoneyCell value={r.trackable_profit} partial={r.has_gap} /> : '') },
{ key: 'margin', label: t('reports.prod.margin'), align: 'right', sort: r => margin(r.trackable_profit, r.revenue - r.uncosted_revenue),
render: r => { const m = margin(r.trackable_profit, r.revenue - r.uncosted_revenue); return m != null && r.total_cost ? fmt.formatPercent(m, { maxDecimals: 0 }) : '' } },
] : []),
...(anyWaste ? [{ key: 'waste_qty', label: t('reports.prod.waste'), align: 'right', tip: t('reports.prod.wasteTip'),
render: r => (r.waste_qty ? `${qty(r.waste_qty)}${r.waste_cost ? ` · ${fmt.formatMoney(r.waste_cost)}` : ''}` : '') }] : []),
{ key: 'share', label: t('reports.prod.share'), align: 'right', sort: r => r.revenue, render: r => fmt.formatPercent(ratio(r.revenue, total), { maxDecimals: 1 }) },
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
]
const top = [...sold].sort((a, b) => (b[metric] ?? 0) - (a[metric] ?? 0)).slice(0, 10)
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} right={<span className="flex gap-2">
<ExportButton endpoint="/api/reports/products/export" params={params} filename={`products-${periodSlug(period)}.csv`} />
<Button size="sm" variant="secondary" icon={<Printer size={14} />} onClick={() => setPrinting(true)}>{t('reports.print.button')}</Button>
</span>} />
<Select size="sm" value={category} onChange={e => setCategory(e.target.value)} aria-label={t('reports.prod.category')} className="w-64"
options={[{ value: '', label: t('reports.prod.allCategories') }, ...cats.flatMap(c => [c, ...(c.subcategories ?? [])]).map(c => ({ value: String(c.id), label: c.name }))]} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('reports.revenue')} tip={t('reports.revenueTip')} value={fmt.formatMoney(total)} testId="products-revenue" />
<Stat label={t('reports.prod.units')} value={qty(units)} sub={t('reports.prod.kinds', { count: sold.length })} />
{refunded > 0 && <Stat label={t('reports.refunded')} tone="danger" value={fmt.formatMoney(refunded)} />}
{anyCost && <Stat label={t('reports.profit')} tip={t('reports.profitTip')} tone="success" value={<MoneyCell value={profit} partial={gap} />} />}
</div>
{top.length > 0 && (
<Panel title={t('reports.prod.top')} actions={<span className="flex gap-1">{METRICS.filter(m => m !== 'trackable_profit' || anyCost).map(m => (
<Button key={m} size="sm" variant={metric === m ? 'primary' : 'ghost'} onClick={() => setMetric(m)}>{t(`reports.prod.by.${m}`)}</Button>))}</span>}>
<BarList testId="products-top" format={v => (metric === 'qty_sold' ? qty(v) : fmt.formatMoney(v))}
rows={top.map(r => ({ key: r.product_id, label: r.product_name, value: r[metric] ?? 0 }))} />
</Panel>
)}
<Panel padded={false} title={t('reports.prod.all', { count: rows.length })}>
<Table columns={columns} rows={rows} rowKey={r => r.product_id} rowTestId="report-product" initialSort={{ key: 'revenue', dir: 'desc' }} limit={500} />
</Panel>
</>)}
{printing && <PrintDialog endpoint="/api/reports/print/products" body={printBody(period)} onClose={() => setPrinting(false)} />}
</div>
)
}
function CategoriesTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [printing, setPrinting] = useState(false)
const params = periodParams(period)
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-categories', params], queryFn: () => client.get('/api/reports/categories/performance', { params }).then(r => r.data.categories) })
const rows = data ?? []
const anyCost = rows.some(r => r.total_cost > 0)
const qty = q => fmt.formatNumber(q, { maxDecimals: 3 })
const columns = [
{ key: 'category_name', label: t('reports.prod.category'), render: r => <span className="font-semibold text-ink">{r.category_name}</span> },
{ key: 'product_count', label: t('reports.products'), align: 'right' },
{ key: 'units_sold', label: t('reports.prod.units'), align: 'right', render: r => qty(r.units_sold) },
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: r => fmt.formatMoney(r.revenue) },
{ key: 'refunded', label: t('reports.refunded'), align: 'right', render: r => (r.refunded ? <span className="text-danger-ink">{fmt.formatMoney(r.refunded)}</span> : '') },
...(anyCost ? [
{ key: 'total_cost', label: t('reports.cost'), align: 'right', render: r => (r.total_cost ? fmt.formatMoney(r.total_cost) : '') },
{ key: 'trackable_profit', label: t('reports.profit'), align: 'right', render: r => (r.total_cost ? <MoneyCell value={r.trackable_profit} partial={r.has_gap} /> : '') },
{ key: 'pct_profit', label: t('reports.prod.profitShare'), align: 'right', render: r => (r.pct_profit ? `${fmt.formatNumber(r.pct_profit, { maxDecimals: 1 })}%` : '') },
] : []),
{ key: 'pct_rev', label: t('reports.prod.share'), align: 'right', render: r => `${fmt.formatNumber(r.pct_rev, { maxDecimals: 1 })}%` },
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} right={<Button size="sm" variant="secondary" icon={<Printer size={14} />} onClick={() => setPrinting(true)}>{t('reports.print.button')}</Button>} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
{rows.length > 0 && (
<Panel title={t('reports.prod.shareTitle')}>
<BarList testId="categories-share" format={v => fmt.formatMoney(v)}
rows={rows.map(r => ({ key: r.category_id ?? 'none', label: r.category_name, value: r.revenue, sub: `${fmt.formatNumber(r.pct_rev, { maxDecimals: 1 })}%` }))} />
</Panel>
)}
<Panel padded={false} title={t('reports.prod.categories')}>
<Table columns={columns} rows={rows} rowKey={r => r.category_id ?? 'none'} rowTestId="report-category" initialSort={{ key: 'revenue', dir: 'desc' }} />
</Panel>
</>)}
{printing && <PrintDialog endpoint="/api/reports/print/categories" body={printBody(period)} onClose={() => setPrinting(false)} />}
</div>
)
}
@@ -1,488 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer } from 'recharts'
import { FileText, X, ChevronDown, Loader2 } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateStr, CHART_PALETTE } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
// ─── SVG donut chart (inline, for print window) ───────────────────────────────
function svgDonut(categories, size = 200) {
const total = categories.reduce((s, c) => s + c.revenue, 0)
if (!total) return ''
const cx = size / 2, cy = size / 2, R = size * 0.42, r = size * 0.22
let angle = -Math.PI / 2
const slices = categories.map((c, i) => {
const frac = c.revenue / total
const a0 = angle, a1 = angle + frac * 2 * Math.PI
angle = a1
const x0 = cx + R * Math.cos(a0), y0 = cy + R * Math.sin(a0)
const x1 = cx + R * Math.cos(a1), y1 = cy + R * Math.sin(a1)
const xi0 = cx + r * Math.cos(a0), yi0 = cy + r * Math.sin(a0)
const xi1 = cx + r * Math.cos(a1), yi1 = cy + r * Math.sin(a1)
const large = frac > 0.5 ? 1 : 0
const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
const d = `M${xi0},${yi0} L${x0},${y0} A${R},${R} 0 ${large},1 ${x1},${y1} L${xi1},${yi1} A${r},${r} 0 ${large},0 ${xi0},${yi0} Z`
return `<path d="${d}" fill="${color}" />`
}).join('')
return `<svg width="${size}" height="${size}" xmlns="http://www.w3.org/2000/svg">${slices}</svg>`
}
// ─── Print modal ─────────────────────────────────────────────────────────────
const PRINT_TYPES = [
{ id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Κατηγορίες με τεμάχια, έσοδα και ποσοστό' },
{ id: 'full', label: 'Πλήρης Ανάλυση', desc: 'Κατηγορίες με γράφημα πίτας και αναλυτική εικόνα' },
]
function CategoryPrintModal({ onClose, categories, allProducts, soldProducts, printers, queryParams, periodLabel }) {
const [printType, setPrintType] = useState('smart')
const [targetPrinter, setTargetPrinter] = useState('browser')
const [printing, setPrinting] = useState(false)
const printerOptions = [
{ value: 'browser', label: 'Εκτύπωση μέσω browser (PDF)' },
...printers.map(p => ({ value: String(p.id), label: p.name })),
]
function periodRow() {
if (queryParams.business_day_id)
return `<div class="row"><span>Εργάσιμη Μέρα</span><span>${periodLabel}</span></div>`
const f = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—'
const t = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—'
return `<div class="row"><span>Από</span><span>${f}</span></div><div class="row"><span>Έως</span><span>${t}</span></div>`
}
function handleBrowserPrint() {
const win = window.open('', '_blank', 'width=820,height=800')
if (!win) { onClose(); return }
const totalRev = categories.reduce((s, c) => s + c.revenue, 0)
const totalQty = categories.reduce((s, c) => s + c.units_sold, 0)
let body = ''
if (printType === 'smart') {
const rows = categories.map(c => {
const pctRev = c.pct_rev ?? c.pct ?? 0
const pctQty = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : '0'
return `<tr>
<td>${c.category_name}</td>
<td class="num">${fmtNum(c.units_sold)}</td>
<td class="num">${fmtEUR(c.revenue)}</td>
<td class="num">${pctRev}%</td>
<td class="num">${pctQty}%</td>
</tr>`
}).join('')
body = `<table>
<thead><tr><th>Κατηγορία</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
<tbody>${rows}</tbody>
<tfoot><tr><td>Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
</table>`
} else {
// Build sold-product lookup: product_id → {qty_sold, revenue, category_id}
const soldMap = {}
for (const p of soldProducts) soldMap[p.product_id] = p
// Group allProducts by category_id
const productsByCategory = {}
for (const ap of allProducts) {
if (!productsByCategory[ap.category_id]) productsByCategory[ap.category_id] = []
productsByCategory[ap.category_id].push(ap)
}
const donut = svgDonut(categories)
const legend = categories.map((c, i) => {
const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
const pctRev = c.pct_rev ?? c.pct ?? 0
const pctQty = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : 0
return `<div class="legend-row"><span class="legend-dot" style="background:${color}"></span><span class="legend-name">${c.category_name}</span><span class="legend-val">${pctRev}% έσ. / ${pctQty}% τεμ.</span></div>`
}).join('')
// Full category blocks with per-product breakdown
const catBlocks = categories.map((c, i) => {
const color = c.color || CHART_PALETTE[i % CHART_PALETTE.length]
const pctRev = c.pct_rev ?? c.pct ?? 0
const pctQtyOfTotal = totalQty ? (c.units_sold / totalQty * 100).toFixed(1) : 0
const catProducts = (productsByCategory[c.category_id] || [])
.map(ap => {
const sold = soldMap[ap.id]
return { name: ap.name, qty: sold ? sold.qty_sold : 0, revenue: sold ? sold.revenue : 0 }
})
.filter(p => p.qty > 0)
.sort((a, b) => b.qty - a.qty)
const catTotalQty = catProducts.reduce((s, p) => s + p.qty, 0)
const catTotalRev = catProducts.reduce((s, p) => s + p.revenue, 0)
const productRows = catProducts.map(p => {
const pctProdRev = catTotalRev ? (p.revenue / catTotalRev * 100).toFixed(1) : '0'
const pctProdQty = catTotalQty ? (p.qty / catTotalQty * 100).toFixed(1) : '0'
return `<tr>
<td class="prod-name">${p.name}</td>
<td class="num">${fmtNum(p.qty)}</td>
<td class="num">${fmtEUR(p.revenue)}</td>
<td class="num">${pctProdRev}%</td>
<td class="num">${pctProdQty}%</td>
</tr>`
}).join('')
return `<div class="cat-full-block" style="border-left: 4px solid ${color}">
<div class="cat-full-header">
<span class="cat-full-name">${c.category_name}</span>
<span class="cat-full-rev">${fmtEUR(c.revenue)}</span>
</div>
<div class="cat-full-sub">${fmtNum(c.units_sold)} τεμ. &nbsp;·&nbsp; ${c.product_count} προϊόντα &nbsp;·&nbsp; ${pctRev}% εσόδων &nbsp;·&nbsp; ${pctQtyOfTotal}% τεμ.</div>
${catProducts.length ? `
<table class="prod-table">
<colgroup><col/><col style="width:52px"/><col style="width:64px"/><col style="width:48px"/><col style="width:48px"/></colgroup>
<thead><tr><th>Προϊόν</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
<tbody>${productRows}</tbody>
</table>` : '<div class="no-sales">Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο</div>'}
</div>`
}).join('')
body = `
<div class="chart-row">
<div class="donut-wrap">${donut}</div>
<div class="legend">${legend}</div>
</div>
${catBlocks}`
}
const title = printType === 'smart' ? 'Σύνοψη Κατηγοριών' : 'Πλήρης Ανάλυση Κατηγοριών'
const styles = `<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial, sans-serif; font-size: 12px; color: #000; padding: 24px; max-width: 760px; }
h1 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 12px; font-family: 'Courier New', monospace; }
.meta { margin-bottom: 16px; font-family: 'Courier New', monospace; }
.row { display: flex; justify-content: space-between; padding: 2px 0; }
table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 12px; font-family: 'Courier New', monospace; }
th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; }
td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
.num { text-align: right; font-weight: bold; }
tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
.chart-row { display: flex; align-items: flex-start; gap: 24px; margin: 16px 0; }
.donut-wrap { flex-shrink: 0; }
.legend { display: flex; flex-direction: column; gap: 6px; justify-content: center; }
.legend-row { display: flex; align-items: center; gap: 8px; font-size: 12px; }
.legend-dot { display: inline-block; width: 12px; height: 12px; border-radius: 2px; flex-shrink: 0; }
.legend-name { flex: 1; }
.legend-val { font-weight: bold; min-width: 40px; text-align: right; }
.cards-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 10px; margin-top: 16px; }
.cat-card { padding: 10px 12px; border: 1px solid #e2e8f0; border-radius: 4px; }
.cat-name { font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: .05em; color: #475569; margin-bottom: 4px; }
.cat-rev { font-size: 20px; font-weight: bold; font-family: 'Courier New', monospace; margin-bottom: 2px; }
.cat-sub { font-size: 10px; color: #64748b; }
.cat-full-block { padding: 12px 14px; border: 1px solid #e2e8f0; border-radius: 4px; margin-bottom: 14px; }
.cat-full-header { display: flex; justify-content: space-between; align-items: baseline; margin-bottom: 2px; }
.cat-full-name { font-size: 13px; font-weight: bold; text-transform: uppercase; letter-spacing: .05em; }
.cat-full-rev { font-size: 13px; font-weight: bold; font-family: 'Courier New', monospace; color: #334155; }
.cat-full-sub { font-size: 10px; color: #64748b; margin-bottom: 8px; }
.prod-table { width: 100%; border-collapse: collapse; font-size: 10px; margin-top: 6px; table-layout: fixed; }
.prod-table th, .prod-table td { padding: 2px 4px; border-bottom: 1px dotted #e2e8f0; font-size: 10px; }
.prod-table thead th { border-bottom: 1px solid #cbd5e1; font-size: 9px; text-transform: uppercase; color: #64748b; font-weight: bold; }
.prod-table th.num, .prod-table td.num { text-align: right; font-weight: bold; }
.prod-table th:first-child, .prod-table td:first-child { text-align: left; }
.prod-name { color: #1e293b; }
.no-sales { font-size: 10px; color: #94a3b8; font-style: italic; margin-top: 4px; }
@media print { body { padding: 0; } }
</style>`
win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${styles}</head><body>
<h1>${title}</h1>
<div class="meta">
${periodRow()}
<div class="row"><span>Κατηγορίες</span><span>${categories.length}</span></div>
</div>
${body}
</body></html>`)
win.document.close()
win.focus()
win.print()
onClose()
}
async function handleThermalPrint() {
const body = { printer_id: parseInt(targetPrinter, 10), mode: printType }
if (queryParams.business_day_id) {
body.business_day_id = parseInt(queryParams.business_day_id, 10)
} else {
body.from_dt = queryParams.from
body.to_dt = queryParams.to
}
setPrinting(true)
try {
await client.post('/api/reports/print/categories', body)
toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
onClose()
} catch {
toast.error('Αποτυχία αποστολής στον εκτυπωτή')
} finally {
setPrinting(false)
}
}
function handlePrint() {
if (targetPrinter === 'browser') handleBrowserPrint()
else handleThermalPrint()
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className="relative w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl">
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
<h2 className="text-[15px] font-semibold text-slate-900">Εκτύπωση Κατηγοριών</h2>
<button onClick={onClose} className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"><X className="h-4 w-4" /></button>
</div>
<div className="px-5 py-4 space-y-4 text-[13px] text-slate-700">
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Τύπος Εκτύπωσης</div>
<div className="space-y-2">
{PRINT_TYPES.map(pt => (
<label key={pt.id} className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition ${printType === pt.id ? 'border-sky-400 bg-sky-50' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'}`}>
<input type="radio" name="printType" value={pt.id} checked={printType === pt.id} onChange={() => setPrintType(pt.id)} className="mt-0.5 accent-sky-500" />
<div>
<div className="font-medium text-slate-800">{pt.label}</div>
<div className="text-[12px] text-slate-500">{pt.desc}</div>
</div>
</label>
))}
</div>
</div>
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Εκτυπωτής Προορισμού</div>
<div className="relative">
<select value={targetPrinter} onChange={e => setTargetPrinter(e.target.value)} className="w-full appearance-none rounded-md border border-slate-200 bg-white py-2 pl-3 pr-8 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:border-sky-400 focus:outline-none focus:ring-2 focus:ring-sky-100">
{printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
<ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
</div>
</div>
<div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-2">
<button onClick={onClose} className="inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300">Ακύρωση</button>
<button onClick={handlePrint} disabled={printing} className="inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-60 disabled:pointer-events-none">
{printing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
{printing ? 'Αποστολή...' : 'Εκτύπωση'}
</button>
</div>
</div>
</div>
</div>
)
}
// ─── Main Component ───────────────────────────────────────────────────────────
export default function CategoryPerformance() {
const [mode, setMode] = useState('range')
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [businessDayId, setBusinessDayId] = useState('all')
const [showPrintModal, setShowPrintModal] = useState(false)
const [pieMetric, setPieMetric] = useState('revenue')
const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 })
const { data: allProductsData } = useQuery({ queryKey: ['meta-products'], queryFn: () => client.get('/api/reports/meta/products').then(r => r.data), staleTime: 5 * 60 * 1000 })
const queryParams = {
...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
}
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['category-performance', mode, from, to, businessDayId],
queryFn: () => client.get('/api/reports/categories/performance', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const { data: productsData } = useQuery({
queryKey: ['product-performance-for-cat', mode, from, to, businessDayId],
queryFn: () => client.get('/api/reports/products/performance', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
const printers = printersData?.printers || []
const allProducts = allProductsData?.products || []
const soldProducts = productsData?.products || []
const categories = data?.categories || []
const anyHasCost = categories.some(c => (c.total_cost || 0) > 0)
const pieCategories = pieMetric === 'profit'
? categories.filter(c => (c.trackable_profit || 0) > 0)
: categories
const pieData = pieCategories.map((c, i) => ({
name: c.category_name,
value: pieMetric === 'profit' ? c.trackable_profit : c.revenue,
color: c.color || CHART_PALETTE[i % CHART_PALETTE.length],
}))
const periodLabel = mode === 'workday'
? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
: `${fmtDateStr(from)} → ${fmtDateStr(to)}`
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={6} columns={5} showChart /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<button onClick={() => setShowPrintModal(true)} className="inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12px] font-medium text-slate-600 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900">
<FileText className="h-3.5 w-3.5" />Εκτύπωση Σύνοψης
</button>
}>
<WorkDayDateToggle mode={mode} onChange={setMode} />
{mode === 'workday' ? (
<FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
) : (
<>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</>
)}
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
{categories.length === 0 ? (
<EmptyState title="Δεν υπάρχουν δεδομένα κατηγοριών" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
) : (
<>
<div className="grid grid-cols-12 gap-4">
<div className="col-span-5">
<Panel title={pieMetric === 'profit' ? 'Κατανομή Κέρδους' : 'Κατανομή Εσόδων'} right={
anyHasCost ? (
<div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[11px]">
{[['revenue', 'Έσοδα'], ['profit', 'Κέρδος']].map(([m, label]) => (
<button key={m} onClick={() => setPieMetric(m)} className={`rounded px-2 py-1 font-medium transition ${pieMetric === m ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>{label}</button>
))}
</div>
) : null
}>
{pieData.length === 0 ? (
<div className="flex items-center justify-center py-8 text-[12px] text-slate-400">Δεν υπάρχουν δεδομένα κέρδους</div>
) : (
<div style={{ height: 280 }}>
<ResponsiveContainer width="100%" height="100%">
<PieChart>
<Pie data={pieData} dataKey="value" nameKey="name" innerRadius={60} outerRadius={100} paddingAngle={2}>
{pieData.map((d, i) => <Cell key={i} fill={d.color} />)}
</Pie>
<Tooltip content={<ChartTooltip formatter={v => fmtEUR(v)} />} />
</PieChart>
</ResponsiveContainer>
</div>
)}
</Panel>
</div>
<div className="col-span-7 grid grid-cols-2 gap-4">
{categories.map((c, i) => {
const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0
? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%'
: null
return (
<div key={c.category_id} className="rounded-lg border border-slate-200 bg-white p-5 shadow-[0_1px_0_rgba(15,23,42,0.04)]">
<div className="flex items-center gap-2">
<span className="h-2.5 w-2.5 rounded-sm flex-shrink-0" style={{ backgroundColor: c.color || CHART_PALETTE[i % CHART_PALETTE.length] }} />
<span className="text-[12px] font-semibold uppercase tracking-wider text-slate-700">{c.category_name}</span>
</div>
<div className="mt-3 font-mono text-[24px] font-medium tabular-nums text-slate-900">{fmtEUR(c.revenue)}</div>
<div className="mt-1 flex justify-between text-[11px] text-slate-500">
<span>{c.units_sold} τεμ. · {c.product_count} προϊόντα</span>
<span className="font-mono">{c.pct_rev ?? c.pct}%</span>
</div>
{(c.trackable_profit || 0) > 0 && (
<div className="mt-2 flex items-center justify-between border-t border-slate-100 pt-2">
<span className="text-[11px] font-medium text-green-700">{fmtEUR(c.trackable_profit)} κέρδος</span>
{margin && <span className="text-[10px] text-slate-400">{margin}{c.has_gap && ' ⚠'}</span>}
</div>
)}
</div>
)
})}
</div>
</div>
<div className="mt-4">
<Panel title="Κατηγορίες" padded={false}>
<DataTable>
<THead>
<TH>Κατηγορία</TH>
<TH align="right">Προϊόντα</TH>
<TH align="right">Τεμάχια</TH>
<TH align="right">Έσοδα</TH>
{anyHasCost && <TH align="right">Κόστος</TH>}
{anyHasCost && <TH align="right">Κέρδος</TH>}
<TH align="right">% Εσόδων</TH>
{anyHasCost && <TH align="right">% Κέρδους</TH>}
</THead>
<tbody>
{categories.map((c, i) => {
const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0
? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%'
: null
return (
<TR key={c.category_id} striped>
<TD><span className="inline-flex items-center gap-2 font-medium text-slate-900"><span className="h-2 w-2 rounded-sm flex-shrink-0" style={{ backgroundColor: c.color || CHART_PALETTE[i % CHART_PALETTE.length] }} />{c.category_name}</span></TD>
<TD mono align="right">{c.product_count}</TD>
<TD mono align="right">{fmtNum(c.units_sold)}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(c.revenue)}</TD>
{anyHasCost && (
<TD mono align="right" className="text-slate-600">
{(c.total_cost || 0) > 0 ? fmtEUR(c.total_cost) : <span className="text-slate-300">—</span>}
</TD>
)}
{anyHasCost && (
<TD mono align="right">
{(c.trackable_profit || 0) > 0 ? (
<span className="text-green-700">
{fmtEUR(c.trackable_profit)}
{margin && <span className="ml-1 text-[10px] text-slate-400">({margin}){c.has_gap && ' ⚠'}</span>}
</span>
) : <span className="text-slate-300">—</span>}
</TD>
)}
<TD mono align="right">{c.pct_rev ?? c.pct}%</TD>
{anyHasCost && (
<TD mono align="right">
{(c.pct_profit || 0) > 0
? <span className="text-green-700">{c.pct_profit}%</span>
: <span className="text-slate-300">—</span>
}
</TD>
)}
</TR>
)
})}
</tbody>
</DataTable>
</Panel>
</div>
</>
)}
</div>
{showPrintModal && (
<CategoryPrintModal
onClose={() => setShowPrintModal(false)}
categories={categories}
allProducts={allProducts}
soldProducts={soldProducts}
printers={printers}
queryParams={queryParams}
periodLabel={periodLabel}
/>
)}
</div>
)
}
@@ -1,151 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import OrderDetailModal from '../shared/OrderDetailModal'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateTime } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
const STATUS_OPTIONS = [
{ value: 'all', label: 'Όλες οι Καταστάσεις' },
{ value: 'open', label: 'Ανοιχτή' },
{ value: 'paid', label: 'Πληρωμένη' },
{ value: 'closed', label: 'Κλειστή' },
{ value: 'cancelled', label: 'Ακυρωμένη' },
]
export default function OrderHistory({ initialBusinessDayId } = {}) {
const [mode, setMode] = useState(initialBusinessDayId ? 'workday' : 'range')
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [businessDayId, setBusinessDayId] = useState(initialBusinessDayId ? String(initialBusinessDayId) : 'all')
const [statusF, setStatusF] = useState('all')
const [waiterF, setWaiterF] = useState('all')
const [tableF, setTableF] = useState('all')
const [drillOrder, setDrillOrder] = useState(null)
const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').then(r => r.data), staleTime: 5 * 60 * 1000 })
const { data: tablesData } = useQuery({ queryKey: ['meta-tables'], queryFn: () => client.get('/api/reports/meta/tables').then(r => r.data), staleTime: 5 * 60 * 1000 })
const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
const queryParams = {
...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
...(statusF !== 'all' ? { status: statusF } : {}),
...(waiterF !== 'all' ? { waiter_id: waiterF } : {}),
...(tableF !== 'all' ? { table_id: tableF } : {}),
page_size: 200,
}
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['order-history', mode, from, to, businessDayId, statusF, waiterF, tableF],
queryFn: () => client.get('/api/reports/orders/history', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const waiterOptions = [{ value: 'all', label: 'Όλοι οι Σερβιτόροι' }, ...((waitersData?.waiters || []).map(w => ({ value: String(w.id), label: w.name })))]
const tableOptions = [{ value: 'all', label: 'Όλα τα Τραπέζια' }, ...((tablesData?.tables || []).map(t => ({ value: String(t.id), label: t.name })))]
const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
const orders = Array.isArray(data) ? data : []
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={8} /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<ExportButton endpoint="/api/reports/orders/export" params={queryParams} filename={`orders-${from}-to-${to}.csv`} />
}>
<WorkDayDateToggle mode={mode} onChange={setMode} />
{mode === 'workday' ? (
<FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
) : (
<>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</>
)}
<FilterSelect value={statusF} onChange={setStatusF} options={STATUS_OPTIONS} label="Κατάσταση" />
<FilterSelect value={waiterF} onChange={setWaiterF} options={waiterOptions} label="Σερβιτόρος" />
<FilterSelect value={tableF} onChange={setTableF} options={tableOptions} label="Τραπέζι" />
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
<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={
<span className="text-[11px] text-slate-400 italic">Κάντε Click για Λεπτομέρειες Παραγγελίας</span>
}
>
{orders.length === 0 ? (
<EmptyState title="Δεν βρέθηκαν παραγγελίες" description="Δοκιμάστε διαφορετικό εύρος ημερομηνιών ή φίλτρο κατάστασης." />
) : (
<>
<DataTable>
<THead>
<TH>#</TH><TH>Τραπέζι</TH><TH>Άνοιξε</TH><TH>Έκλεισε</TH>
<TH>Κατάσταση</TH><TH align="right">Είδη</TH><TH align="right">Ακυρώσεις</TH><TH align="right">Σύνολο</TH>
</THead>
<tbody>
{orders.slice(0, 200).map(o => {
const allItems = o.items || []
const activeItems = allItems.filter(i => i.status !== 'cancelled')
const cancelledItems = allItems.filter(i => i.status === 'cancelled')
const totalQty = allItems.reduce((s, i) => s + (i.quantity || 1), 0)
const cancelledQty = cancelledItems.reduce((s, i) => s + (i.quantity || 1), 0)
const total = activeItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
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_name ?? o.table_id}</TD>
<TD mono>{fmtDateTime(o.opened_at)}</TD>
<TD mono>{fmtDateTime(o.closed_at)}</TD>
<TD><StatusBadge status={o.status} /></TD>
<TD mono align="right">{totalQty}</TD>
<TD mono align="right">
{cancelledQty > 0
? <span className="text-red-500 font-semibold">{cancelledQty}</span>
: <span className="text-slate-300">—</span>}
</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(total)}</TD>
</TR>
)
})}
</tbody>
</DataTable>
{orders.length > 200 && (
<div className="border-t border-slate-100 bg-slate-50/50 px-4 py-2 text-center text-[11px] text-slate-500">
Εμφάνιση πρώτων 200 από {orders.length} παραγγελίες. Περιορίστε τα φίλτρα για λιγότερα αποτελέσματα.
</div>
)}
</>
)}
</Panel>
</div>
{drillOrder && (
<OrderDetailModal order={drillOrder} onClose={() => setDrillOrder(null)} />
)}
</div>
)
}
@@ -1,539 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Cell, Legend } from 'recharts'
import { FileText, X, ChevronDown, Loader2 } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDateStr, CHART_PALETTE } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
// ─── SVG bar chart rendered as inline HTML ────────────────────────────────────
// Used inside the browser print window (no Recharts available there).
function svgBarChart(items, valueKey, labelKey, colorFn, width = 680, barH = 18, gap = 6) {
const top5 = [...items].slice(0, 5)
const maxVal = Math.max(1, ...top5.map(d => d[valueKey]))
const labelW = 160
const numW = 70
const barAreaW = width - labelW - numW - 16
const h = top5.length * (barH + gap) + gap
const bars = top5.map((d, i) => {
const y = gap + i * (barH + gap)
const bw = Math.round((d[valueKey] / maxVal) * barAreaW)
const color = colorFn(i)
return `
<text x="${labelW - 6}" y="${y + barH * 0.72}" text-anchor="end" font-size="11" fill="#475569" font-family="Arial,sans-serif">${d[labelKey]}</text>
<rect x="${labelW}" y="${y}" width="${bw}" height="${barH}" rx="3" fill="${color}" />
<text x="${labelW + bw + 4}" y="${y + barH * 0.72}" font-size="10" fill="#64748b" font-family="Arial,sans-serif">${d[valueKey]}</text>`
}).join('')
return `<svg width="${width}" height="${h}" xmlns="http://www.w3.org/2000/svg">${bars}</svg>`
}
// ─── Print modal ─────────────────────────────────────────────────────────────
const PRINT_TYPES = [
{ id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Μόνο προϊόντα με πωλήσεις — σε σειρά ποσότητας' },
{ id: 'full', label: 'Πλήρης Ανάλυση', desc: 'Όλα τα προϊόντα, ακόμα και με 0 πωλήσεις, με αξία + γραφήματα' },
]
function ProductPrintModal({ onClose, products, allProducts, printers, queryParams, periodLabel }) {
const [printType, setPrintType] = useState('smart')
const [targetPrinter, setTargetPrinter] = useState('browser')
const [printing, setPrinting] = useState(false)
const printerOptions = [
{ value: 'browser', label: 'Εκτύπωση μέσω browser (PDF)' },
...printers.map(p => ({ value: String(p.id), label: p.name })),
]
function periodRow() {
if (queryParams.business_day_id)
return `<div class="row"><span>Εργάσιμη Μέρα</span><span>${periodLabel}</span></div>`
const f = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—'
const t = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—'
return `<div class="row"><span>Από</span><span>${f}</span></div><div class="row"><span>Έως</span><span>${t}</span></div>`
}
function handleBrowserPrint() {
const win = window.open('', '_blank', 'width=820,height=800')
if (!win) { onClose(); return }
const soldMap = {}
for (const p of products) soldMap[p.product_id] = p
const totalQty = products.reduce((s, p) => s + p.qty_sold, 0)
const totalRev = products.reduce((s, p) => s + p.revenue, 0)
let tableSection = ''
if (printType === 'smart') {
const sorted = [...products].sort((a, b) => b.qty_sold - a.qty_sold)
const rows = sorted.map(p => {
const pctRev = totalRev ? (p.revenue / totalRev * 100).toFixed(1) : '0'
const pctQty = totalQty ? (p.qty_sold / totalQty * 100).toFixed(1) : '0'
return `<tr>
<td>${p.product_name}</td>
<td class="num">${fmtNum(p.qty_sold)}</td>
<td class="num">${fmtEUR(p.revenue)}</td>
<td class="num">${pctRev}%</td>
<td class="num">${pctQty}%</td>
</tr>`
}).join('')
tableSection = `<table>
<thead><tr><th>Προϊόν</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
<tbody>${rows}</tbody>
<tfoot><tr><td>Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
</table>`
} else {
// Full: merge all products, including 0-sold
const merged = allProducts.map(ap => {
const sold = soldMap[ap.id]
return { name: ap.name, category: ap.category_name, qty: sold ? sold.qty_sold : 0, revenue: sold ? sold.revenue : 0 }
}).sort((a, b) => b.qty - a.qty)
// Top-5 bar charts (qty and revenue)
const top5qty = merged.filter(p => p.qty > 0).slice(0, 5)
const top5rev = merged.filter(p => p.revenue > 0).slice(0, 5).sort((a, b) => b.revenue - a.revenue)
const chartQty = svgBarChart(top5qty, 'qty', 'name', i => CHART_PALETTE[i % CHART_PALETTE.length])
const maxRev = Math.max(1, ...top5rev.map(d => d.revenue))
const labelW = 160, barH = 18, gap = 6, barAreaW = 680 - labelW - 90 - 16
const revBars = top5rev.map((d, i) => {
const y = gap + i * (barH + gap)
const bw = Math.round((d.revenue / maxRev) * barAreaW)
return `
<text x="${labelW - 6}" y="${y + barH * 0.72}" text-anchor="end" font-size="11" fill="#475569" font-family="Arial,sans-serif">${d.name}</text>
<rect x="${labelW}" y="${y}" width="${bw}" height="${barH}" rx="3" fill="${CHART_PALETTE[i % CHART_PALETTE.length]}" />
<text x="${labelW + bw + 4}" y="${y + barH * 0.72}" font-size="10" fill="#64748b" font-family="Arial,sans-serif">${fmtEUR(d.revenue)}</text>`
}).join('')
const revH = top5rev.length * (barH + gap) + gap
const chartRevSvg = `<svg width="680" height="${revH}" xmlns="http://www.w3.org/2000/svg">${revBars}</svg>`
const rows = merged.map(p => {
const pctRev = totalRev && p.revenue ? (p.revenue / totalRev * 100).toFixed(1) : '—'
const pctQty = totalQty && p.qty ? (p.qty / totalQty * 100).toFixed(1) : '—'
return `<tr class="${p.qty === 0 ? 'zero' : ''}">
<td>${p.name}</td>
<td class="cat">${p.category}</td>
<td class="num">${fmtNum(p.qty)}</td>
<td class="num">${fmtEUR(p.revenue)}</td>
<td class="num">${pctRev}%</td>
<td class="num">${pctQty}%</td>
</tr>`
}).join('')
tableSection = `
<div class="chart-section">
<div class="chart-title">Top 5 σε Τεμάχια</div>
${chartQty}
</div>
<div class="chart-section">
<div class="chart-title">Top 5 σε Έσοδα</div>
${chartRevSvg}
</div>
<table>
<thead><tr><th>Προϊόν</th><th>Κατηγορία</th><th class="num">Τεμ.</th><th class="num">Έσοδα</th><th class="num">% Έσ.</th><th class="num">% Τεμ.</th></tr></thead>
<tbody>${rows}</tbody>
<tfoot><tr><td colspan="2">Σύνολο</td><td class="num">${fmtNum(totalQty)}</td><td class="num">${fmtEUR(totalRev)}</td><td class="num">100%</td><td class="num">100%</td></tr></tfoot>
</table>`
}
const title = printType === 'smart' ? 'Έξυπνη Σύνοψη Προϊόντων' : 'Πλήρης Ανάλυση Προϊόντων'
const styles = `<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: Arial, sans-serif; font-size: 12px; color: #000; padding: 24px; max-width: 760px; }
h1 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 12px; font-family: 'Courier New', monospace; }
.meta { margin-bottom: 16px; font-family: 'Courier New', monospace; }
.row { display: flex; justify-content: space-between; padding: 2px 0; }
.chart-section { margin: 16px 0; }
.chart-title { font-size: 11px; font-weight: bold; text-transform: uppercase; letter-spacing: .06em; color: #64748b; margin-bottom: 8px; }
table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 16px; font-family: 'Courier New', monospace; }
th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; letter-spacing: .05em; }
td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
.num { text-align: right; font-weight: bold; }
.cat { color: #555; font-size: 10px; }
.zero { color: #aaa; }
tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
@media print { body { padding: 0; } }
</style>`
win.document.write(`<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${styles}</head><body>
<h1>${title}</h1>
<div class="meta">
${periodRow()}
<div class="row"><span>Προϊόντα με πωλήσεις</span><span>${products.length}</span></div>
${printType === 'full' ? `<div class="row"><span>Σύνολο ενεργών προϊόντων</span><span>${allProducts.length}</span></div>` : ''}
</div>
${tableSection}
</body></html>`)
win.document.close()
win.focus()
win.print()
onClose()
}
async function handleThermalPrint() {
const body = { printer_id: parseInt(targetPrinter, 10), mode: printType }
if (queryParams.business_day_id) {
body.business_day_id = parseInt(queryParams.business_day_id, 10)
} else {
body.from_dt = queryParams.from
body.to_dt = queryParams.to
}
setPrinting(true)
try {
await client.post('/api/reports/print/products', body)
toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
onClose()
} catch {
toast.error('Αποτυχία αποστολής στον εκτυπωτή')
} finally {
setPrinting(false)
}
}
function handlePrint() {
if (targetPrinter === 'browser') handleBrowserPrint()
else handleThermalPrint()
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4" onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}>
<div className="relative w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl">
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
<h2 className="text-[15px] font-semibold text-slate-900">Εκτύπωση Σύνοψης Προϊόντων</h2>
<button onClick={onClose} className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600"><X className="h-4 w-4" /></button>
</div>
<div className="px-5 py-4 space-y-4 text-[13px] text-slate-700">
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Τύπος Εκτύπωσης</div>
<div className="space-y-2">
{PRINT_TYPES.map(pt => (
<label key={pt.id} className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition ${printType === pt.id ? 'border-sky-400 bg-sky-50' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'}`}>
<input type="radio" name="printType" value={pt.id} checked={printType === pt.id} onChange={() => setPrintType(pt.id)} className="mt-0.5 accent-sky-500" />
<div>
<div className="font-medium text-slate-800">{pt.label}</div>
<div className="text-[12px] text-slate-500">{pt.desc}</div>
</div>
</label>
))}
</div>
</div>
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Εκτυπωτής Προορισμού</div>
<div className="relative">
<select value={targetPrinter} onChange={e => setTargetPrinter(e.target.value)} className="w-full appearance-none rounded-md border border-slate-200 bg-white py-2 pl-3 pr-8 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:border-sky-400 focus:outline-none focus:ring-2 focus:ring-sky-100">
{printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
<ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
</div>
{targetPrinter !== 'browser' && printType === 'full' && (
<p className="mt-1.5 text-[11px] text-amber-600">Η Πλήρης Ανάλυση σε θερμικό θα εκτυπώσει μόνο τη λίστα χωρίς γραφήματα.</p>
)}
</div>
<div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-2">
<button onClick={onClose} className="inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300">Ακύρωση</button>
<button onClick={handlePrint} disabled={printing} className="inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-60 disabled:pointer-events-none">
{printing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
{printing ? 'Αποστολή...' : 'Εκτύπωση'}
</button>
</div>
</div>
</div>
</div>
)
}
// ─── Main Component ───────────────────────────────────────────────────────────
export default function ProductPerformance() {
const [mode, setMode] = useState('range')
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [businessDayId, setBusinessDayId] = useState('all')
const [catF, setCatF] = useState('all')
const [chartMode, setChartMode] = useState('revenue')
const [showPrintModal, setShowPrintModal] = useState(false)
// 'revenue' | 'units' | 'profit' | 'dual'
const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
const { data: allProductsData } = useQuery({ queryKey: ['meta-products'], queryFn: () => client.get('/api/reports/meta/products').then(r => r.data), staleTime: 5 * 60 * 1000 })
const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 })
const queryParams = {
...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
...(catF !== 'all' ? { category_id: catF } : {}),
}
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['product-performance', mode, from, to, businessDayId, catF],
queryFn: () => client.get('/api/reports/products/performance', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
const allProducts = allProductsData?.products || []
const printers = printersData?.printers || []
const products = data?.products || []
const totalRev = products.reduce((s, p) => s + p.revenue, 0)
const totalProfit = products.reduce((s, p) => s + (p.trackable_profit || 0), 0)
const anyHasCost = products.some(p => (p.total_cost || 0) > 0)
const top10 = [...products]
.sort((a, b) => {
if (chartMode === 'units') return b.qty_sold - a.qty_sold
if (chartMode === 'profit') return (b.trackable_profit || 0) - (a.trackable_profit || 0)
// revenue and dual: sort by revenue
return b.revenue - a.revenue
})
.slice(0, 10)
.map((p, i) => ({
name: p.product_name,
revenue: p.revenue,
profit: p.has_gap ? null : (p.trackable_profit || 0),
units: p.qty_sold,
color: CHART_PALETTE[i % CHART_PALETTE.length],
}))
const periodLabel = mode === 'workday'
? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
: `${fmtDateStr(from)} → ${fmtDateStr(to)}`
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={7} showChart /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<div className="flex items-center gap-2">
<button onClick={() => setShowPrintModal(true)} className="inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12px] font-medium text-slate-600 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900">
<FileText className="h-3.5 w-3.5" />Εκτύπωση Σύνοψης
</button>
<ExportButton endpoint="/api/reports/products/export" params={queryParams} filename={`products-${from}-to-${to}.csv`} />
</div>
}>
<WorkDayDateToggle mode={mode} onChange={setMode} />
{mode === 'workday' ? (
<FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
) : (
<>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</>
)}
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
{(() => {
const chartModes = [
['revenue', 'Έσοδα'],
['units', 'Τεμάχια'],
...(anyHasCost ? [['profit', 'Κέρδος'], ['dual', 'Έσοδα vs Κέρδος']] : []),
]
const subtitleMap = { revenue: 'έσοδα', units: 'τεμάχια', profit: 'κέρδος', dual: 'έσοδα vs κέρδος' }
const isDual = chartMode === 'dual'
return (
<Panel title="Top 10 Προϊόντα" subtitle={`Ταξινομημένα κατά ${subtitleMap[chartMode] || 'έσοδα'}`} right={
<div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[11px]">
{chartModes.map(([m, label]) => (
<button key={m} onClick={() => setChartMode(m)} className={`rounded px-2 py-1 font-medium transition ${chartMode === m ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>{label}</button>
))}
</div>
}>
{top10.length === 0 ? (
<EmptyState title="Δεν υπάρχουν δεδομένα προϊόντων" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
) : (
<div style={{ height: isDual ? 320 : 280 }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={top10} layout="vertical" margin={{ top: 4, right: 24, bottom: isDual ? 16 : 4, left: 4 }}>
<CartesianGrid horizontal={false} stroke="#f1f5f9" />
<XAxis type="number" tick={{ fontSize: 10, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false}
tickFormatter={v => chartMode === 'units' ? String(v) : '€' + v} />
<YAxis type="category" dataKey="name" tick={{ fontSize: 11, fill: '#475569' }} stroke="#cbd5e1" axisLine={false} tickLine={false} width={140} />
<Tooltip content={<ChartTooltip formatter={(v, name) => {
if (chartMode === 'units') return v + ' τεμ.'
return fmtEUR(v)
}} />} cursor={{ fill: '#f1f5f9' }} />
{isDual && <Legend wrapperStyle={{ fontSize: 11 }} iconType="rect" />}
{isDual ? (
<>
<Bar dataKey="revenue" name="Έσοδα" fill="#60a5fa" radius={[0, 0, 0, 0]} barSize={10} />
<Bar dataKey="profit" name="Κέρδος" fill="#34d399" radius={[0, 3, 3, 0]} barSize={10} />
</>
) : (
<Bar dataKey={chartMode === 'units' ? 'units' : chartMode === 'profit' ? 'profit' : 'revenue'}
radius={[0, 3, 3, 0]} barSize={16}>
{top10.map((d, i) => (
<Cell key={i} fill={chartMode === 'profit' ? '#34d399' : d.color} />
))}
</Bar>
)}
</BarChart>
</ResponsiveContainer>
</div>
)}
</Panel>
)
})()}
<div className="mt-4">
{(() => {
const totalUncostedRev = products.reduce((s, p) => s + (p.uncosted_revenue || 0), 0)
const totalCost = products.reduce((s, p) => s + (p.total_cost || 0), 0)
const hasGap = products.some(p => p.has_gap)
const overallMargin = totalRev > 0 && !hasGap
? ((totalProfit / totalRev) * 100).toFixed(0) + '%'
: null
return (
<Panel
title="Όλα τα Προϊόντα"
subtitle={`${products.length} προϊόντα με πωλήσεις`}
padded={false}
>
{hasGap && (
<div className="mx-4 mt-3 mb-1 flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2.5 text-[12px] text-amber-800">
<span className="shrink-0 font-bold">⚠</span>
<span>
Μερικά προϊόντα δεν έχουν κόστος — το κέρδος που φαίνεται είναι μερικό.
Ορισμένα έσοδα <strong>{fmtEUR(totalUncostedRev)}</strong> δεν συμπεριλαμβάνονται στο κέρδος.{' '}
<a href="/management?tab=products" className="underline hover:text-amber-900">Ορισμός κόστους προϊόντων →</a>
</span>
</div>
)}
{products.length === 0 ? (
<EmptyState title="Δεν βρέθηκαν προϊόντα" description="Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο." />
) : (
<DataTable>
<THead>
<TH>Προϊόν</TH>
<TH align="right">Τεμάχια</TH>
<TH align="right">Έσοδα</TH>
{anyHasCost && <TH align="right">Κόστος</TH>}
<TH align="right">Κέρδος</TH>
<TH align="right">Απόβλητα</TH>
<TH align="right">% Έσόδων</TH>
{anyHasCost && <TH align="right">% Κέρδους</TH>}
<TH align="right">Παραγγελίες</TH>
</THead>
<tbody>
{products.map(p => {
const pctRev = totalRev ? (p.revenue / totalRev * 100) : 0
const pctProfit = totalProfit > 0 && !p.has_gap
? (p.trackable_profit / totalProfit * 100)
: null
const margin = p.revenue > 0 && !p.has_gap && (p.total_cost || 0) > 0
? ((p.trackable_profit / p.revenue) * 100).toFixed(0) + '%'
: null
return (
<TR key={p.product_id} striped>
<TD className="font-medium text-slate-900">{p.product_name}</TD>
<TD mono align="right">{fmtNum(p.qty_sold)}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(p.revenue)}</TD>
{anyHasCost && (
<TD mono align="right">
{(p.total_cost || 0) > 0
? <span className="text-slate-600">{fmtEUR(p.total_cost)}</span>
: <span className="text-slate-300">—</span>
}
</TD>
)}
<TD mono align="right">
{p.has_gap ? (
<span className="text-amber-500 text-[11px]">⚠ χωρίς κόστος</span>
) : (p.total_cost || 0) === 0 ? (
<span className="text-slate-300">—</span>
) : (
<span className={p.trackable_profit >= 0 ? 'text-green-700' : 'text-red-600'}>
{fmtEUR(p.trackable_profit)}
{margin && <span className="ml-1 text-[10px] text-slate-400">({margin})</span>}
</span>
)}
</TD>
<TD mono align="right">
{p.waste_qty > 0 ? (
<span className="text-amber-600">
{p.waste_qty}
{p.waste_cost > 0 && <span className="text-[10px] text-amber-400 ml-1">({fmtEUR(p.waste_cost)})</span>}
</span>
) : <span className="text-slate-300">—</span>}
</TD>
<TD mono align="right">{pctRev.toFixed(1)}%</TD>
{anyHasCost && (
<TD mono align="right">
{pctProfit != null
? <span className="text-green-700">{pctProfit.toFixed(1)}%</span>
: <span className="text-slate-300">—</span>
}
</TD>
)}
<TD mono align="right">{fmtNum(p.order_count)}</TD>
</TR>
)
})}
</tbody>
{products.length > 1 && (
<tfoot>
<TR>
<TD className="font-semibold text-slate-700" colSpan={2}>Σύνολο</TD>
<TD mono align="right" className="font-bold">{fmtEUR(totalRev)}</TD>
{anyHasCost && (
<TD mono align="right" className="font-bold text-slate-600">{fmtEUR(totalCost)}</TD>
)}
<TD mono align="right" className="font-bold">
{hasGap ? (
<span className="text-amber-600">{fmtEUR(totalProfit)}{' '}<span className="text-[10px]">+χωρίς κόστος</span></span>
) : totalProfit > 0 ? (
<span className="text-green-700">
{fmtEUR(totalProfit)}
{overallMargin && <span className="ml-1 text-[10px] text-slate-400">({overallMargin})</span>}
</span>
) : <span className="text-slate-300">—</span>}
</TD>
<TD />
<TD mono align="right" className="font-bold">100%</TD>
{anyHasCost && (
<TD mono align="right" className="font-bold text-green-700">
{totalProfit > 0 && !hasGap ? '100%' : '—'}
</TD>
)}
<TD />
</TR>
</tfoot>
)}
</DataTable>
)}
</Panel>
)
})()}
</div>
</div>
{showPrintModal && (
<ProductPrintModal
onClose={() => setShowPrintModal(false)}
products={products}
allProducts={allProducts}
printers={printers}
queryParams={queryParams}
periodLabel={periodLabel}
/>
)}
</div>
)
}
@@ -1,119 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend, ResponsiveContainer } from 'recharts'
import client from '../../../api/client'
import { FilterBar, FilterDateInput } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, ChartTooltip } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtEUR, fmtNum, fmtDate, fmtDateStr } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
const GRAN_OPTIONS = [['daily', 'Ημερήσια'], ['weekly', 'Εβδομαδιαία'], ['monthly', 'Μηνιαία']]
export default function RevenueTrends() {
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [gran, setGran] = useState('daily')
const queryParams = { from: from + 'T00:00:00', to: to + 'T23:59:59', granularity: gran }
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['revenue-trends', from, to, gran],
queryFn: () => client.get('/api/reports/revenue/trends', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const trends = data?.trends || []
const anyHasProfit = trends.some(d => (d.profit || 0) > 0)
const chartData = trends.map(d => ({
label: gran === 'monthly' ? d.date : fmtDate(d.date),
revenue: d.revenue,
profit: (d.profit || 0) > 0 ? d.profit : undefined,
rolling7: d.rolling7,
}))
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} columns={3} showChart /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
<div className="inline-flex rounded-md border border-slate-200 bg-slate-50 p-0.5 text-[12px]">
{GRAN_OPTIONS.map(([g, label]) => (
<button key={g} onClick={() => setGran(g)} className={`rounded px-2.5 py-1 font-medium transition ${gran === g ? 'bg-white text-slate-900 shadow-sm ring-1 ring-slate-200' : 'text-slate-500'}`}>
{label}
</button>
))}
</div>
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
<Panel title="Τάση Εσόδων" subtitle={`${GRAN_OPTIONS.find(([g]) => g === gran)?.[1] || gran} · ${fmtDateStr(from)} → ${fmtDateStr(to)}`}>
{trends.length === 0 ? (
<EmptyState title="Δεν υπάρχουν δεδομένα εσόδων" description="Δεν υπάρχουν κλειστές παραγγελίες σε αυτή την περίοδο." />
) : (
<div style={{ height: 320 }}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData} margin={{ top: 8, right: 16, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="label" tick={{ fontSize: 10, 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 => fmtEUR(v)} />} />
<Legend wrapperStyle={{ fontSize: 11 }} iconType="rect" />
<Line type="monotone" dataKey="revenue" name="Έσοδα" stroke="#60a5fa" strokeWidth={2.5} dot={{ r: 3, fill: '#60a5fa' }} />
{anyHasProfit && <Line type="monotone" dataKey="profit" name="Κέρδος" stroke="#34d399" strokeWidth={2} dot={{ r: 3, fill: '#34d399' }} connectNulls={false} />}
{gran === 'daily' && <Line type="monotone" dataKey="rolling7" name="Μέσος 7 ημ." stroke="#94a3b8" strokeWidth={1.5} strokeDasharray="4 4" dot={false} />}
</LineChart>
</ResponsiveContainer>
</div>
)}
</Panel>
<div className="mt-4">
<Panel title="Αναλυτικά Στοιχεία" padded={false}>
<DataTable>
<THead>
<TH>Περίοδος</TH>
<TH align="right">Παραγγελίες</TH>
<TH align="right">Έσοδα</TH>
{anyHasProfit && <TH align="right">Κέρδος</TH>}
{gran === 'daily' && <TH align="right">Μέσος 7 ημ.</TH>}
</THead>
<tbody>
{trends.map(d => (
<TR key={d.date} striped>
<TD className="font-medium">{gran === 'monthly' ? d.date : fmtDate(d.date)}</TD>
<TD mono align="right">{fmtNum(d.orders)}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(d.revenue)}</TD>
{anyHasProfit && (
<TD mono align="right">
{(d.profit || 0) > 0
? <span className="text-green-700">
{fmtEUR(d.profit)}
{d.has_gap && <span className="ml-1 text-[10px] text-amber-500">⚠</span>}
</span>
: <span className="text-slate-300">—</span>
}
</TD>
)}
{gran === 'daily' && <TD mono align="right" className="text-slate-500">{fmtEUR(d.rolling7)}</TD>}
</TR>
))}
</tbody>
</DataTable>
</Panel>
</div>
</div>
</div>
)
}
@@ -1,316 +0,0 @@
import { useState } from 'react'
import { useQuery } from '@tanstack/react-query'
import { FileText, X, ChevronDown, Loader2 } from 'lucide-react'
import toast from 'react-hot-toast'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD } from '../shared/TablePrimitives'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtMinutes, fmtDate, fmtTime, fmtDateStr } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
// ─── Print modal ─────────────────────────────────────────────────────────────
const PRINT_TYPES = [
{ id: 'smart', label: 'Έξυπνη Σύνοψη', desc: 'Κατάταξη τραπεζιών με παραγγελίες, μέση διάρκεια και έσοδα' },
{ id: 'full', label: 'Πλήρης Ανάλυση', desc: 'Ίδιο, με επιπλέον μέσο έσοδο ανά επίσκεψη' },
]
function TablePrintModal({ onClose, tables, printers, queryParams, periodLabel }) {
const [printType, setPrintType] = useState('smart')
const [targetPrinter, setTargetPrinter] = useState('browser')
const [printing, setPrinting] = useState(false)
const printerOptions = [
{ value: 'browser', label: 'Εκτύπωση μέσω browser (PDF)' },
...printers.map(p => ({ value: String(p.id), label: p.name })),
]
function handleBrowserPrint() {
const win = window.open('', '_blank', 'width=820,height=750')
if (!win) { onClose(); return }
let periodRow = ''
if (queryParams.business_day_id) {
periodRow = `<div class="row"><span>Εργάσιμη Μέρα</span><span>${periodLabel}</span></div>`
} else {
const fromStr = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—'
const toStr = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—'
periodRow = `<div class="row"><span>Από</span><span>${fromStr}</span></div>
<div class="row"><span>Έως</span><span>${toStr}</span></div>`
}
const totalOrders = tables.reduce((s, t) => s + t.order_count, 0)
const totalRev = tables.reduce((s, t) => s + t.revenue, 0)
const rows = tables.map(t => {
const avgRev = t.order_count ? t.revenue / t.order_count : 0
const dur = t.avg_duration_minutes != null ? fmtMinutes(t.avg_duration_minutes) : '—'
if (printType === 'smart') {
return `<tr>
<td>${t.table_name}</td>
<td class="num">${fmtNum(t.order_count)}</td>
<td class="num">${dur}</td>
<td class="num">${fmtEUR(t.revenue)}</td>
</tr>`
}
return `<tr>
<td>${t.table_name}</td>
<td class="num">${fmtNum(t.order_count)}</td>
<td class="num">${dur}</td>
<td class="num">${fmtEUR(avgRev)}</td>
<td class="num">${fmtEUR(t.revenue)}</td>
</tr>`
}).join('')
const headers = printType === 'smart'
? `<th>Τραπέζι</th><th class="num">Παραγγελίες</th><th class="num">Μ. Διάρκεια</th><th class="num">Έσοδα</th>`
: `<th>Τραπέζι</th><th class="num">Παραγγελίες</th><th class="num">Μ. Διάρκεια</th><th class="num">Μ. / Επίσκεψη</th><th class="num">Έσοδα</th>`
const footCols = printType === 'smart'
? `<td>Σύνολο</td><td class="num">${fmtNum(totalOrders)}</td><td class="num">—</td><td class="num">${fmtEUR(totalRev)}</td>`
: `<td>Σύνολο</td><td class="num">${fmtNum(totalOrders)}</td><td class="num">—</td><td class="num">—</td><td class="num">${fmtEUR(totalRev)}</td>`
const title = printType === 'smart' ? 'Σύνοψη Τραπεζιών' : 'Πλήρης Ανάλυση Τραπεζιών'
const styles = `<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Courier New', monospace; font-size: 12px; color: #000; padding: 24px; max-width: 800px; }
h1 { font-size: 16px; font-weight: bold; border-bottom: 2px solid #000; padding-bottom: 6px; margin-bottom: 12px; }
.meta { margin-bottom: 16px; }
.row { display: flex; justify-content: space-between; padding: 2px 0; }
table { width: 100%; border-collapse: collapse; font-size: 11px; margin-top: 8px; }
th { text-align: left; border-bottom: 1px solid #000; padding: 4px 6px; font-size: 10px; text-transform: uppercase; }
td { padding: 3px 6px; border-bottom: 1px dotted #ccc; }
.num { text-align: right; font-weight: bold; }
tfoot td { border-top: 2px solid #000; border-bottom: none; font-weight: bold; padding-top: 6px; }
@media print { body { padding: 0; } }
</style>`
const html = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${title}</title>${styles}</head><body>
<h1>${title}</h1>
<div class="meta">
${periodRow}
<div class="row"><span>Τραπέζια</span><span>${tables.length}</span></div>
</div>
<table>
<thead><tr>${headers}</tr></thead>
<tbody>${rows}</tbody>
<tfoot><tr>${footCols}</tr></tfoot>
</table>
</body></html>`
win.document.write(html)
win.document.close()
win.focus()
win.print()
onClose()
}
async function handleThermalPrint() {
const body = { printer_id: parseInt(targetPrinter, 10), mode: printType }
if (queryParams.business_day_id) {
body.business_day_id = parseInt(queryParams.business_day_id, 10)
} else {
body.from_dt = queryParams.from
body.to_dt = queryParams.to
}
setPrinting(true)
try {
await client.post('/api/reports/print/tables', body)
toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή')
onClose()
} catch {
toast.error('Αποτυχία αποστολής στον εκτυπωτή')
} finally {
setPrinting(false)
}
}
function handlePrint() {
if (targetPrinter === 'browser') handleBrowserPrint()
else handleThermalPrint()
}
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4"
onMouseDown={e => { if (e.target === e.currentTarget) onClose() }}
>
<div className="relative w-full max-w-md rounded-xl border border-slate-200 bg-white shadow-xl">
<div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
<h2 className="text-[15px] font-semibold text-slate-900">Εκτύπωση Σύνοψης Τραπεζιών</h2>
<button onClick={onClose} className="rounded-md p-1 text-slate-400 transition hover:bg-slate-100 hover:text-slate-600">
<X className="h-4 w-4" />
</button>
</div>
<div className="px-5 py-4 space-y-4 text-[13px] text-slate-700">
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Τύπος Εκτύπωσης</div>
<div className="space-y-2">
{PRINT_TYPES.map(pt => (
<label key={pt.id} className={`flex cursor-pointer items-start gap-3 rounded-lg border p-3 transition ${printType === pt.id ? 'border-sky-400 bg-sky-50' : 'border-slate-200 hover:border-slate-300 hover:bg-slate-50'}`}>
<input type="radio" name="printType" value={pt.id} checked={printType === pt.id} onChange={() => setPrintType(pt.id)} className="mt-0.5 accent-sky-500" />
<div>
<div className="font-medium text-slate-800">{pt.label}</div>
<div className="text-[12px] text-slate-500">{pt.desc}</div>
</div>
</label>
))}
</div>
</div>
<div>
<div className="mb-2 text-[11px] font-medium uppercase tracking-[0.08em] text-slate-500">Εκτυπωτής Προορισμού</div>
<div className="relative">
<select value={targetPrinter} onChange={e => setTargetPrinter(e.target.value)} className="w-full appearance-none rounded-md border border-slate-200 bg-white py-2 pl-3 pr-8 text-[13px] text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] focus:border-sky-400 focus:outline-none focus:ring-2 focus:ring-sky-100">
{printerOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
</select>
<ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
</div>
</div>
<div className="flex items-center justify-end gap-2 border-t border-slate-100 pt-2">
<button onClick={onClose} className="inline-flex items-center justify-center gap-2 rounded-md border border-slate-200 bg-white px-3.5 py-2 text-[13px] font-medium text-slate-700 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:bg-slate-50 hover:border-slate-300">
Ακύρωση
</button>
<button onClick={handlePrint} disabled={printing} className="inline-flex items-center justify-center gap-2 rounded-md bg-sky-500 px-3.5 py-2 text-[13px] font-medium text-white shadow-[0_1px_0_rgba(15,23,42,0.08)] transition hover:bg-sky-600 active:bg-sky-700 disabled:opacity-60 disabled:pointer-events-none">
{printing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileText className="h-3.5 w-3.5" />}
{printing ? 'Αποστολή...' : 'Εκτύπωση'}
</button>
</div>
</div>
</div>
</div>
)
}
// ─── Main Component ───────────────────────────────────────────────────────────
export default function TableAnalytics() {
const [mode, setMode] = useState('range')
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [businessDayId, setBusinessDayId] = useState('all')
const [showPrintModal, setShowPrintModal] = useState(false)
const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 })
const queryParams = {
...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
}
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['table-analytics', mode, from, to, businessDayId],
queryFn: () => client.get('/api/reports/tables/performance', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
const printers = printersData?.printers || []
const tables = data?.tables || []
const maxRev = Math.max(1, ...tables.map(t => t.revenue))
const periodLabel = mode === 'workday'
? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα')
: `${fmtDateStr(from)} → ${fmtDateStr(to)}`
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={10} columns={7} /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<div className="flex items-center gap-2">
<button
onClick={() => setShowPrintModal(true)}
className="inline-flex items-center gap-1.5 rounded-md border border-slate-200 bg-white px-2.5 py-1.5 text-[12px] font-medium text-slate-600 shadow-[0_1px_0_rgba(15,23,42,0.04)] transition hover:border-slate-300 hover:bg-slate-50 hover:text-slate-900"
>
<FileText className="h-3.5 w-3.5" />
Εκτύπωση Σύνοψης
</button>
<ExportButton endpoint="/api/reports/tables/performance" params={queryParams} filename={`tables-${from}-to-${to}.csv`} />
</div>
}>
<WorkDayDateToggle mode={mode} onChange={setMode} />
{mode === 'workday' ? (
<FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
) : (
<>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</>
)}
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
{tables.length === 0 ? (
<EmptyState title="Δεν υπάρχουν δεδομένα τραπεζιών" description="Δεν υπάρχουν κλειστές παραγγελίες σε αυτή την περίοδο." />
) : (
<>
<Panel title="Απόδοση Τραπεζιών" padded={false}>
<DataTable>
<THead>
<TH>Τραπέζι</TH><TH align="right">Παραγγελίες</TH><TH align="right">Μέση Διάρκεια</TH>
<TH align="right">Μέσο / Επίσκεψη</TH><TH align="right">Συνολικά Έσοδα</TH><TH align="right">Κύκλοι</TH>
</THead>
<tbody>
{tables.map(t => {
const avgRev = t.order_count ? t.revenue / t.order_count : 0
return (
<TR key={t.table_id} striped>
<TD className="font-medium text-slate-900">{t.table_name}</TD>
<TD mono align="right">{fmtNum(t.order_count)}</TD>
<TD mono align="right">{fmtMinutes(t.avg_duration_minutes)}</TD>
<TD mono align="right">{fmtEUR(avgRev)}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(t.revenue)}</TD>
<TD mono align="right">{fmtNum(t.order_count)}</TD>
</TR>
)
})}
</tbody>
</DataTable>
</Panel>
<div className="mt-4">
<Panel title="Ένταση Εσόδων" subtitle="Χρώμα κελιού = έσοδα ως προς κορυφαίο τραπέζι">
<div className="grid grid-cols-6 gap-3 sm:grid-cols-8 md:grid-cols-10">
{tables.map(t => {
const intensity = t.revenue / maxRev
return (
<div
key={t.table_id}
className="aspect-square flex flex-col justify-between rounded-md p-2 ring-1 ring-inset ring-slate-200"
style={{ backgroundColor: `rgba(96, 165, 250, ${0.08 + intensity * 0.65})` }}
>
<div className="font-mono text-[11px] font-semibold text-slate-700">{t.table_name}</div>
<div className="font-mono text-[10px] tabular-nums text-slate-700">{fmtEUR(t.revenue)}</div>
</div>
)
})}
</div>
</Panel>
</div>
</>
)}
</div>
{showPrintModal && (
<TablePrintModal
onClose={() => setShowPrintModal(false)}
tables={tables}
printers={printers}
queryParams={queryParams}
periodLabel={periodLabel}
/>
)}
</div>
)
}
@@ -1,131 +0,0 @@
import { useState, useMemo } from 'react'
import { useQuery } from '@tanstack/react-query'
import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'
import { Flame, CalendarDays, Moon, TrendingUp } from 'lucide-react'
import client from '../../../api/client'
import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar'
import { Panel, ChartTooltip } from '../shared/TablePrimitives'
import StatCard from '../shared/StatCard'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import { fmtNum, fmtDate, fmtTime } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
const DOWS = ['Δευ', 'Τρι', 'Τετ', 'Πεμ', 'Παρ', 'Σαβ', 'Κυρ']
const HOURS = Array.from({ length: 14 }, (_, i) => 10 + i)
export default function TrafficAnalytics() {
const [mode, setMode] = useState('range')
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [businessDayId, setBusinessDayId] = useState('all')
const { data: bdData } = useQuery({ queryKey: ['business-days-list'], queryFn: () => client.get('/api/reports/business-days').then(r => r.data), staleTime: 60 * 1000 })
const queryParams = {
...(mode === 'workday' && businessDayId !== 'all' ? { business_day_id: businessDayId } : {}),
...(mode === 'range' ? { from: from + 'T00:00:00', to: to + 'T23:59:59' } : {}),
}
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['traffic', mode, from, to, businessDayId],
queryFn: () => client.get('/api/reports/traffic', { params: queryParams }).then(r => r.data),
staleTime: 60 * 1000,
})
const bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))]
const byHour = useMemo(() => {
const hourMap = {}
;(data?.by_hour || []).forEach(h => { hourMap[h.hour] = h })
return HOURS.map(h => hourMap[h] || { hour: h, orders: 0, revenue: 0 })
}, [data])
const byWeekday = data?.by_weekday || []
const chartData = byHour.map(h => ({
hour: `${String(h.hour).padStart(2, '0')}:00`,
orders: h.orders,
}))
const busiest = [...byHour].sort((a, b) => b.orders - a.orders)[0]
const busiestDow = [...byWeekday].sort((a, b) => b.orders - a.orders)[0]
const quietest = [...byHour].filter(h => h.orders > 0).sort((a, b) => a.orders - b.orders)[0]
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={4} columns={5} showChart /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
const maxByHour = Math.max(1, ...byHour.map(h => h.orders))
const maxByDow = Math.max(1, ...byWeekday.map(d => d.orders))
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar>
<WorkDayDateToggle mode={mode} onChange={setMode} />
{mode === 'workday' ? (
<FilterSelect value={businessDayId} onChange={setBusinessDayId} options={bdOptions} width="w-72" label="Μέρα" />
) : (
<>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</>
)}
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
<div className="grid grid-cols-4 gap-4">
<StatCard label="Πιο Πολυάσχολη Ώρα" value={busiest ? `${String(busiest.hour).padStart(2, '0')}:00` : '—'} icon={Flame} />
<StatCard label="Πιο Πολυάσχολη Μέρα" value={busiestDow?.label || '—'} icon={CalendarDays} />
<StatCard label="Πιο Ήσυχη Ώρα" value={quietest ? `${String(quietest.hour).padStart(2, '0')}:00` : '—'} icon={Moon} />
<StatCard label="Συνολικές Παραγγελίες" value={fmtNum(byHour.reduce((s, h) => s + h.orders, 0))} icon={TrendingUp} accent />
</div>
<div className="mt-4">
<Panel title="Παραγγελίες ανά Ώρα" subtitle="Σε όλες τις μέρες της επιλεγμένης περιόδου">
<div style={{ height: 240 }}>
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 8, right: 8, bottom: 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="hour" tick={{ fontSize: 10, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
<YAxis tick={{ fontSize: 11, fill: '#94a3b8' }} stroke="#cbd5e1" axisLine={false} tickLine={false} />
<Tooltip content={<ChartTooltip />} cursor={{ fill: '#f1f5f9' }} />
<Bar dataKey="orders" fill="#60a5fa" radius={[3, 3, 0, 0]} maxBarSize={36} />
</BarChart>
</ResponsiveContainer>
</div>
</Panel>
</div>
<div className="mt-4">
<Panel title="Παραγγελίες ανά Ημέρα Εβδομάδας" subtitle="Σωρευτικά σε επιλεγμένη περίοδο">
<div className="grid grid-cols-7 gap-3">
{byWeekday.map((d) => {
const intensity = d.orders / maxByDow
return (
<div key={d.day} className="flex flex-col items-center gap-2">
<div className="font-mono text-[11px] font-semibold uppercase tracking-wider text-slate-500">{d.label}</div>
<div
className="flex h-24 w-full items-end justify-center rounded-md pb-2"
style={{ backgroundColor: `rgba(96, 165, 250, ${0.08 + intensity * 0.7})` }}
>
<span className="font-mono text-[13px] font-semibold tabular-nums" style={{ color: intensity > 0.4 ? 'white' : '#334155' }}>
{d.orders}
</span>
</div>
</div>
)
})}
</div>
</Panel>
</div>
</div>
</div>
)
}
@@ -1,460 +0,0 @@
import { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Trash2, Pencil, Check, X as XIcon } from 'lucide-react'
import toast from 'react-hot-toast'
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts'
import client from '../../../api/client'
import { FilterBar, FilterDateInput } from '../shared/FilterBar'
import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives'
import DrillDownModal from '../shared/DrillDownModal'
import OrderDetailModal from '../shared/OrderDetailModal'
import ShiftDetailModal from '../shared/ShiftDetailModal'
import DeleteConfirmModal from '../../../ui/DeleteConfirmModal'
import EmptyState from '../shared/EmptyState'
import SkeletonTable from '../shared/SkeletonTable'
import ExportButton from '../shared/ExportButton'
import { fmtEUR, fmtNum, fmtDate, fmtTime, fmtDuration, fmtDateTime, fmtDateStr } from '../shared/reportDesignTokens'
function today() { return new Date().toISOString().slice(0, 10) }
function monthAgo() { const d = new Date(); d.setDate(d.getDate() - 30); return d.toISOString().slice(0, 10) }
// ── Edit close-time inline control ─────────────────────────────────────────
function EditCloseTime({ day, onSaved }) {
const [editing, setEditing] = useState(false)
const [value, setValue] = useState('')
const qc = useQueryClient()
function startEdit() {
// pre-fill with current closed_at in local datetime-local format
const d = day.closed_at ? new Date(day.closed_at) : new Date()
const pad = n => String(n).padStart(2, '0')
const local = `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`
setValue(local)
setEditing(true)
}
const mut = useMutation({
mutationFn: (iso) => client.patch(`/api/business-day/${day.id}`, { closed_at: iso }).then(r => r.data),
onSuccess: (data) => {
toast.success('Ώρα κλεισίματος ενημερώθηκε')
qc.invalidateQueries({ queryKey: ['business-days'] })
setEditing(false)
onSaved && onSaved(data)
},
onError: (err) => toast.error(err?.response?.data?.detail || 'Σφάλμα ενημέρωσης'),
})
if (!editing) {
return (
<button
onClick={startEdit}
title="Επεξεργασία ώρας κλεισίματος"
className="ml-1 rounded p-0.5 text-slate-400 hover:text-slate-700 hover:bg-slate-100"
>
<Pencil size={13} />
</button>
)
}
function handleSave() {
if (!value) return
const iso = new Date(value).toISOString()
mut.mutate(iso)
}
return (
<span className="inline-flex items-center gap-1 ml-1">
<input
type="datetime-local"
value={value}
onChange={e => setValue(e.target.value)}
className="rounded border border-slate-300 px-1 py-0 text-[11px] font-mono text-slate-700 focus:outline-none focus:ring-1 focus:ring-slate-400"
style={{ height: 22 }}
max={new Date().toISOString().slice(0, 16)}
/>
<button onClick={handleSave} disabled={mut.isPending} className="rounded p-0.5 text-emerald-600 hover:bg-emerald-50" title="Αποθήκευση">
<Check size={14} />
</button>
<button onClick={() => setEditing(false)} className="rounded p-0.5 text-slate-400 hover:bg-slate-100" title="Ακύρωση">
<XIcon size={14} />
</button>
</span>
)
}
// ── Workday drill-down modal ────────────────────────────────────────────────
function WorkDayModal({ day: initialDay, onClose, onDeleteShift }) {
const [day, setDay] = useState(initialDay)
const [tab, setTab] = useState('orders')
const [drillOrder, setDrillOrder] = useState(null)
const [detailShift, setDetailShift] = useState(null)
const { data: ordersData } = useQuery({
queryKey: ['business-day-orders', day.id],
queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: day.id, page_size: 200 } }).then(r => r.data),
staleTime: 0,
})
const { data: shiftsData } = useQuery({
queryKey: ['shifts-for-day', day.id],
queryFn: () => client.get('/api/reports/shifts', { params: { business_day_id: day.id } }).then(r => r.data),
staleTime: 0,
})
const orders = Array.isArray(ordersData) ? ordersData : []
const shifts = shiftsData?.shifts || []
const TABS = [
{ key: 'orders', label: `Παραγγελίες (${orders.length})` },
{ key: 'shifts', label: `Βάρδιες (${shifts.length})` },
]
const hasCost = (day.total_cost || 0) > 0
const hasProfit = (day.trackable_profit || 0) > 0
// Build the rich subtitle
const openDate = fmtDate(day.opened_at)
const closeDate = day.closed_at ? fmtDate(day.closed_at) : null
const openTime = fmtTime(day.opened_at)
const closeTime = day.closed_at ? fmtTime(day.closed_at) : null
const spansDays = closeDate && closeDate !== openDate
const subtitleParts = [
`${fmtEUR(day.revenue)} έσοδα`,
hasCost ? `${fmtEUR(day.total_cost)} Έξοδα` : null,
hasProfit ? `${fmtEUR(day.trackable_profit)} Κέρδος` : null,
].filter(Boolean)
const openLabel = spansDays ? `${openDate} ${openTime}` : openTime
const closeLabel = day.closed_at
? (spansDays ? `${closeDate} ${closeTime}` : closeTime)
: 'ανοιχτή'
const subtitle = subtitleParts.join(' · ')
const timeRange = `${openLabel} – ${closeLabel}`
return (
<>
<DrillDownModal
title={`Εργάσιμη Μέρα · ${fmtDate(day.opened_at)}`}
subtitle={
<span>
{subtitle}
<span className="text-slate-400 mx-1">·</span>
{timeRange}
{day.status === 'closed' && (
<EditCloseTime day={day} onSaved={updated => setDay(d => ({ ...d, closed_at: updated.closed_at }))} />
)}
</span>
}
onClose={onClose}
>
{/* Tabs */}
<div className="flex border-b border-slate-200 px-6">
{TABS.map(t => (
<button
key={t.key}
onClick={() => setTab(t.key)}
className={`px-4 py-2.5 text-[13px] font-medium border-b-2 transition-colors ${tab === t.key ? 'border-slate-800 text-slate-900' : 'border-transparent text-slate-500 hover:text-slate-700'}`}
>
{t.label}
</button>
))}
</div>
{/* Orders tab */}
{tab === 'orders' && (
orders.length === 0
? <div className="py-12 text-center text-slate-400 text-sm">Δεν βρέθηκαν παραγγελίες</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.map(o => {
const allItems = o.items || []
const activeItems = allItems.filter(i => i.status !== 'cancelled')
const cancelledItems = allItems.filter(i => i.status === 'cancelled')
const totalQty = allItems.reduce((s, i) => s + (i.quantity || 1), 0)
const cancelledQty = cancelledItems.reduce((s, i) => s + (i.quantity || 1), 0)
const total = activeItems.reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
return (
<TR key={o.id} striped onClick={() => setDrillOrder(o)} className="cursor-pointer">
<TD mono>#{o.id}</TD>
<TD>{o.table_name ?? o.table_id}</TD>
<TD mono>{fmtDateTime(o.opened_at)}</TD>
<TD mono>{o.closed_at ? fmtDateTime(o.closed_at) : '—'}</TD>
<TD mono align="right">{totalQty}</TD>
<TD mono align="right">
{cancelledQty > 0
? <span className="text-red-500 font-semibold">{cancelledQty}</span>
: <span className="text-slate-300">—</span>}
</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(total)}</TD>
<TD><StatusBadge status={o.status} /></TD>
</TR>
)
})}
</tbody>
</DataTable>
)}
{/* Shifts tab */}
{tab === 'shifts' && (
shifts.length === 0
? <div className="py-12 text-center text-slate-400 text-sm">Δεν βρέθηκαν βάρδιες</div>
: <DataTable>
<THead>
<TH>Σερβιτόρος</TH>
<TH>Έναρξη</TH>
<TH>Λήξη</TH>
<TH align="right">Διάρκεια</TH>
<TH align="right">Εισπράχθηκαν</TH>
<TH>Κατάσταση</TH>
<TH className="w-20" />
</THead>
<tbody>
{shifts.map(s => (
<TR key={s.id} striped onClick={() => setDetailShift(s)} className="cursor-pointer">
<TD><WaiterAvatar name={s.waiter_name} id={s.waiter_id} /></TD>
<TD mono>{fmtDateTime(s.started_at)}</TD>
<TD mono>{s.ended_at ? fmtDateTime(s.ended_at) : <span className="text-sky-600 font-medium">— ενεργή —</span>}</TD>
<TD mono align="right">{fmtDuration(s.started_at, s.ended_at)}</TD>
<TD mono align="right">{fmtEUR(s.total_collected)}</TD>
<TD><StatusBadge status={s.is_active ? 'active' : 'closed'} pulse /></TD>
<TD align="right">
<div className="flex items-center justify-end gap-2">
<button
onClick={e => { e.stopPropagation(); setDetailShift(s) }}
className="rounded border border-slate-200 bg-white px-2 py-0.5 text-[11px] font-medium text-slate-600 hover:bg-slate-50"
>
Λεπτομέρειες
</button>
{!s.is_active && (
<button
onClick={e => { e.stopPropagation(); onDeleteShift(s) }}
className="rounded border border-red-200 bg-white p-0.5 text-red-400 hover:bg-red-50 hover:text-red-600"
title="Διαγραφή βάρδιας"
>
<Trash2 size={13} />
</button>
)}
</div>
</TD>
</TR>
))}
</tbody>
</DataTable>
)}
</DrillDownModal>
{drillOrder && (
<OrderDetailModal order={drillOrder} onClose={() => setDrillOrder(null)} />
)}
{detailShift && (
<ShiftDetailModal
shiftId={detailShift.id}
shiftWaiterId={detailShift.waiter_id}
onClose={() => setDetailShift(null)}
/>
)}
</>
)
}
// ── Main page ───────────────────────────────────────────────────────────────
export default function WorkDaySummary() {
const [from, setFrom] = useState(monthAgo())
const [to, setTo] = useState(today())
const [drillDay, setDrillDay] = useState(null)
const [deleteDay, setDeleteDay] = useState(null)
const [deleteShift, setDeleteShift] = useState(null)
const qc = useQueryClient()
const { data, isLoading, isError, refetch } = useQuery({
queryKey: ['business-days', from, to],
queryFn: () => client.get('/api/reports/business-days', { params: { from: from + 'T00:00:00', to: to + 'T23:59:59' } }).then(r => r.data),
staleTime: 0,
})
const deleteDayMutation = useMutation({
mutationFn: (id) => client.delete(`/api/business-day/${id}`),
onSuccess: () => {
toast.success('Η εργάσιμη μέρα διαγράφηκε')
qc.invalidateQueries({ queryKey: ['business-days'] })
qc.invalidateQueries({ queryKey: ['business-days-list'] })
setDeleteDay(null)
},
onError: (err) => {
toast.error(err?.response?.data?.detail || 'Σφάλμα διαγραφής εργάσιμης μέρας')
setDeleteDay(null)
},
})
const deleteShiftMutation = useMutation({
mutationFn: (id) => client.delete(`/api/shifts/${id}`),
onSuccess: () => {
toast.success('Η βάρδια και οι παραγγελίες της διαγράφηκαν')
qc.invalidateQueries({ queryKey: ['shifts'] })
qc.invalidateQueries({ queryKey: ['shifts-for-day'] })
qc.invalidateQueries({ queryKey: ['business-days'] })
qc.invalidateQueries({ queryKey: ['business-days-list'] })
setDeleteShift(null)
},
onError: (err) => {
toast.error(err?.response?.data?.detail || 'Σφάλμα διαγραφής βάρδιας')
setDeleteShift(null)
},
})
const days = data?.business_days || []
const anyHasCost = days.some(d => (d.total_cost || 0) > 0)
const chartData = [...days].reverse().map(d => ({
date: fmtDate(d.opened_at),
revenue: d.revenue,
profit: (d.trackable_profit || 0) > 0 ? d.trackable_profit : undefined,
}))
if (isLoading) return <div className="flex-1 overflow-y-auto p-6"><SkeletonTable rows={8} columns={9} showChart /></div>
if (isError) return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar><span className="text-[12px] text-slate-500">Αδυναμία φόρτωσης δεδομένων</span></FilterBar>
<div className="flex flex-1 items-center justify-center"><button onClick={() => refetch()} className="rounded-md border border-slate-200 px-4 py-2 text-sm hover:bg-slate-50">Επανάληψη</button></div>
</div>
)
return (
<div className="flex flex-col flex-1 min-h-0">
<FilterBar right={
<ExportButton endpoint="/api/reports/orders/export" params={{ from: from + 'T00:00:00', to: to + 'T23:59:59' }} filename={`workdays-${from}-to-${to}.csv`} />
}>
<FilterDateInput value={from} onChange={setFrom} label="Από" />
<FilterDateInput value={to} onChange={setTo} label="Έως" />
</FilterBar>
<div className="flex-1 overflow-y-auto p-6">
{chartData.length > 0 && (
<Panel title="Έσοδα ανά Εργάσιμη Μέρα" subtitle={`${days.length} μέρες · ${fmtDateStr(from)} → ${fmtDateStr(to)}`}>
<div style={{ height: 240 }}>
<ResponsiveContainer width="100%" height="100%">
<LineChart data={chartData} margin={{ top: 8, right: 16, bottom: anyHasCost ? 16 : 4, left: 4 }}>
<CartesianGrid vertical={false} stroke="#f1f5f9" />
<XAxis dataKey="date" tick={{ fontSize: 10, 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 => fmtEUR(v)} />} />
{anyHasCost && <Legend wrapperStyle={{ fontSize: 11 }} iconType="rect" />}
<Line type="monotone" dataKey="revenue" name="Έσοδα" stroke="#60a5fa" strokeWidth={2} dot={{ r: 3, fill: '#60a5fa' }} activeDot={{ r: 5 }} />
{anyHasCost && (
<Line type="monotone" dataKey="profit" name="Κέρδος" stroke="#34d399" strokeWidth={2} dot={{ r: 3, fill: '#34d399' }} activeDot={{ r: 5 }} connectNulls={false} />
)}
</LineChart>
</ResponsiveContainer>
</div>
</Panel>
)}
<div className="mt-4">
<Panel title="Εργάσιμες Μέρες" padded={false}>
{days.length === 0 ? (
<EmptyState title="Δεν βρέθηκαν εργάσιμες μέρες" description="Δοκιμάστε ευρύτερο εύρος ημερομηνιών." />
) : (
<DataTable>
<THead>
<TH>Εργάσιμη Μέρα</TH>
<TH>Άνοιξε</TH>
<TH>Έκλεισε</TH>
<TH align="right">Διάρκεια</TH>
<TH align="right">Παραγγελίες</TH>
<TH align="right">Έσοδα</TH>
{anyHasCost && <TH align="right">Κόστος</TH>}
{anyHasCost && <TH align="right">Κέρδος</TH>}
<TH align="right">Ακυρώσεις</TH>
<TH align="right">Σερβιτόροι</TH>
<TH>Κατάσταση</TH>
<TH className="w-10" />
</THead>
<tbody>
{days.map(d => {
const margin = d.revenue > 0 && (d.trackable_profit || 0) > 0
? ((d.trackable_profit / d.revenue) * 100).toFixed(0) + '%'
: null
return (
<TR key={d.id} onClick={() => setDrillDay(d)} striped>
<TD className="font-medium text-slate-900">{fmtDate(d.opened_at)}</TD>
<TD mono>{fmtTime(d.opened_at)}</TD>
<TD mono>{d.closed_at ? fmtTime(d.closed_at) : '—'}</TD>
<TD mono align="right">{fmtDuration(d.opened_at, d.closed_at)}</TD>
<TD mono align="right">{fmtNum(d.order_count)}</TD>
<TD mono align="right" className="font-semibold text-slate-900">{fmtEUR(d.revenue)}</TD>
{anyHasCost && (
<TD mono align="right" className="text-slate-600">
{(d.total_cost || 0) > 0 ? fmtEUR(d.total_cost) : <span className="text-slate-300">—</span>}
</TD>
)}
{anyHasCost && (
<TD mono align="right">
{(d.trackable_profit || 0) > 0 ? (
<span className="text-green-700">
{fmtEUR(d.trackable_profit)}
{margin && !d.has_gap && <span className="ml-1 text-[10px] text-slate-400">({margin})</span>}
{d.has_gap && <span className="ml-1 text-[10px] text-amber-500">⚠</span>}
</span>
) : <span className="text-slate-300">—</span>}
</TD>
)}
<TD mono align="right">{fmtNum(d.cancellation_count)}</TD>
<TD mono align="right">{fmtNum(d.waiter_count)}</TD>
<TD><StatusBadge status={d.status} pulse /></TD>
<TD align="right">
{d.status === 'closed' && (
<button
onClick={e => { e.stopPropagation(); setDeleteDay(d) }}
className={`rounded border p-0.5 bg-white ${(d.shift_count ?? 0) === 0 ? 'border-red-200 text-red-400 hover:bg-red-50 hover:text-red-600' : 'border-slate-200 text-slate-300 cursor-not-allowed'}`}
title={(d.shift_count ?? 0) === 0 ? 'Διαγραφή εργάσιμης μέρας' : `Έχει ${d.shift_count} βάρδιες — διαγράψτε τες πρώτα`}
disabled={(d.shift_count ?? 0) > 0}
>
<Trash2 size={13} />
</button>
)}
</TD>
</TR>
)})}
</tbody>
</DataTable>
)}
</Panel>
</div>
</div>
{drillDay && (
<WorkDayModal
day={drillDay}
onClose={() => setDrillDay(null)}
onDeleteShift={s => setDeleteShift(s)}
/>
)}
{deleteDay && (
<DeleteConfirmModal
title={`Διαγραφή Εργάσιμης Μέρας #${deleteDay.id}`}
description={`Η εργάσιμη μέρα της ${fmtDate(deleteDay.opened_at)} θα διαγραφεί μόνιμα. Δεν έχει βάρδιες.`}
onConfirm={() => deleteDayMutation.mutate(deleteDay.id)}
onCancel={() => setDeleteDay(null)}
/>
)}
{deleteShift && (
<DeleteConfirmModal
title={`Διαγραφή Βάρδιας #${deleteShift.id}`}
description={`Η βάρδια του ${deleteShift.waiter_name} (${fmtDateTime(deleteShift.started_at)}) και ΟΛΕΣ οι παραγγελίες της θα διαγραφούν μόνιμα.`}
onConfirm={() => deleteShiftMutation.mutate(deleteShift.id)}
onCancel={() => setDeleteShift(null)}
/>
)}
</div>
)
}
@@ -0,0 +1,173 @@
// Business days (plan step 6.12b): revenue (and profit) per day, and each day with its times,
// orders, revenue, delivery fees, refunds, cost, profit, cancellations and staff. A day opens
// with its orders and shifts (a shift opens its details); the owner can correct a day's closing
// time, delete an empty day or a shift (which erases that shift's orders for good).
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Pencil, Trash2 } from 'lucide-react'
import { useCan } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, IconButton, Input } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { useDuration } from '../../overview/hooks'
import { Pill } from '../../overview/parts'
import ShiftDialog from '../../overview/ShiftDialog'
import { venueWallClock } from '../../overview/overviewLogic'
import { TrendChart } from '../kit/charts'
import OrderDialog from '../kit/OrderDialog'
import { ExportButton, Failed, Loading, MoneyCell, Panel, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod, orderTotals, periodParams, periodSlug } from '../kit/reportLogic'
const STATUS = { open: 'success', closed: 'neutral' }
export default function DaysTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const since = useDuration()
const qc = useQueryClient()
const owner = useCan('core.settings.manage')
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [day, setDay] = useState(null)
const [deleting, setDeleting] = useState(null)
const params = periodParams({ ...period, mode: 'range' })
const { data: days, isPending, error, refetch } = useLiveQuery({
queryKey: ['report-days', params], queryFn: () => client.get('/api/reports/business-days', { params }).then(r => r.data.business_days),
})
const remove = useMutation({
mutationFn: d => client.delete(`/api/business-day/${d.id}`),
onSuccess: () => { toast.success(t('reports.store.dayDeleted')); setDeleting(null); qc.invalidateQueries({ queryKey: ['report-days'] }); qc.invalidateQueries({ queryKey: ['business-days'] }) },
onError: err => toast.error(errorMessage(err, t)),
})
const list = days ?? []
const anyCost = list.some(d => d.total_cost > 0)
const dateOf = d => fmt.formatDateTime(d.opened_at, { weekday: 'short', day: '2-digit', month: '2-digit' })
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)})` },
{ 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) : '') },
{ key: 'refunded', label: t('reports.refunded'), align: 'right', render: d => (d.refunded ? <span className="text-danger-ink">{fmt.formatMoney(d.refunded)}</span> : '') },
...(anyCost ? [
{ key: 'total_cost', label: t('reports.cost'), align: 'right', render: d => (d.total_cost ? fmt.formatMoney(d.total_cost) : '') },
{ key: 'trackable_profit', label: t('reports.profit'), align: 'right', render: d => (d.total_cost ? <MoneyCell value={d.trackable_profit} partial={d.has_gap} /> : '') },
] : []),
{ key: 'cancellation_count', label: t('reports.store.cancelled'), align: 'right' },
{ key: 'waiter_count', label: t('reports.store.staff'), align: 'right' },
{ key: 'status', label: t('reports.status'), render: d => <Pill tone={STATUS[d.status] ?? 'neutral'}>{t(`reports.store.dayStatus.${d.status}`, { defaultValue: d.status })}</Pill> },
...(owner ? [{ key: 'actions', label: '', sort: false, render: d => (d.status === 'closed' && !d.shift_count ? (
<IconButton size="sm" variant="ghost" label={t('reports.store.deleteDay')} onClick={e => { e.stopPropagation(); setDeleting(d) }}><Trash2 size={14} /></IconButton>
) : null) }] : []),
]
const points = [...list].reverse().map(d => ({ label: fmt.formatDateTime(d.opened_at, { day: '2-digit', month: '2-digit' }), revenue: d.revenue, profit: d.total_cost ? d.trackable_profit : null }))
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} allowDay={false}
right={<ExportButton endpoint="/api/reports/orders/export" params={params} filename={`orders-${periodSlug(period)}.csv`} />} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
{list.length > 1 && <Panel title={t('reports.store.revenueByDay')}><TrendChart points={points} showProfit={anyCost} /></Panel>}
<Panel padded={false} title={t('reports.store.daysCount', { count: list.length })} tip={t('reports.store.daysTip')}>
<Table columns={columns} rows={list} onRow={setDay} rowTestId="report-day" empty={t('reports.store.noDays')} />
</Panel>
</>)}
{day && <DayDialog day={day} owner={owner} onClose={() => setDay(null)} />}
{deleting && (
<Dialog open size="sm" onClose={() => setDeleting(null)} title={t('reports.store.deleteDayTitle', { day: dateOf(deleting) })} description={t('reports.store.deleteDayBody')}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('reports.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(deleting)}>{t('reports.store.deleteYes')}</Button>
</>} />
)}
</div>
)
}
function DayDialog({ day: initial, owner, onClose }) {
const { t } = useTranslation('manager')
const fmt = useFormat()
const since = useDuration()
const qc = useQueryClient()
const [day, setDay] = useState(initial)
const [tab, setTab] = useState('orders')
const [order, setOrder] = useState(null)
const [shift, setShift] = useState(null)
const [editing, setEditing] = useState(false)
const [closeAt, setCloseAt] = useState('')
const [dropShift, setDropShift] = useState(null)
const { data: orders = [], isPending: loadingOrders } = useLiveQuery({ queryKey: ['report-day-orders', day.id], queryFn: () => client.get('/api/reports/orders/history', { params: { business_day_id: day.id, page_size: 1000 } }).then(r => r.data) })
const { data: shifts = [], isPending: loadingShifts } = useLiveQuery({ queryKey: ['report-day-shifts', day.id], queryFn: () => client.get('/api/reports/shifts', { params: { business_day_id: day.id } }).then(r => r.data.shifts) })
const fixClose = useMutation({
mutationFn: () => client.patch(`/api/business-day/${day.id}`, { closed_at: `${closeAt}:00` }).then(r => r.data),
onSuccess: d => { setDay(x => ({ ...x, closed_at: d.closed_at })); setEditing(false); toast.success(t('reports.store.closeFixed')); qc.invalidateQueries({ queryKey: ['report-days'] }) },
onError: err => toast.error(errorMessage(err, t)),
})
const removeShift = useMutation({
mutationFn: s => client.delete(`/api/shifts/${s.id}`),
onSuccess: () => { setDropShift(null); toast.success(t('reports.store.shiftDeleted')); ['report-day-shifts', 'report-day-orders', 'report-days'].forEach(k => qc.invalidateQueries({ queryKey: [k] })) },
onError: err => toast.error(errorMessage(err, t)),
})
const orderCols = [
{ key: 'id', label: '#', render: o => <span className="text-ink-2 tabular-nums">#{o.id}</span> },
{ key: 'table_name', label: t('reports.place'), 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: 'products', label: t('reports.products'), align: 'right', sort: o => orderTotals(o).revenue, render: o => fmt.formatMoney(orderTotals(o).revenue) },
{ key: 'status', label: t('reports.status'), render: o => t(`overview.orderStatus.${o.status}`, { defaultValue: o.status }) },
]
const shiftCols = [
{ key: 'waiter_name', label: t('reports.person') },
{ key: 'started_at', label: t('reports.store.from'), render: s => fmt.formatTime(s.started_at) },
{ key: 'ended_at', label: t('reports.store.to'), render: s => (s.ended_at ? fmt.formatTime(s.ended_at) : t('reports.store.working')) },
{ key: 'length', label: t('reports.store.length'), sort: false, render: s => since(s.started_at, s.ended_at ? Date.parse(s.ended_at) : undefined) },
{ key: 'total_collected', label: t('reports.store.collected'), align: 'right', render: s => fmt.formatMoney(s.total_collected) },
...(owner ? [{ key: 'del', label: '', sort: false, render: s => (!s.is_active ? (
<IconButton size="sm" variant="ghost" label={t('reports.store.deleteShift')} onClick={e => { e.stopPropagation(); setDropShift(s) }}><Trash2 size={14} /></IconButton>) : null) }] : []),
]
return (
<Dialog open size="lg" onClose={onClose} title={t('reports.store.dayTitle', { day: fmt.formatDateTime(day.opened_at, 'dateLong') })}
description={<span className="inline-flex flex-wrap items-center gap-2">
{fmt.formatMoney(day.revenue)}{day.fees ? ` + ${fmt.formatMoney(day.fees)} ${t('reports.fees').toLowerCase()}` : ''} · {fmt.formatDateTime(day.opened_at, 'datetimeShort')} – {day.closed_at ? fmt.formatDateTime(day.closed_at, 'datetimeShort') : t('reports.open')}
{owner && day.status === 'closed' && !editing && (
<IconButton size="sm" variant="ghost" label={t('reports.store.fixClose')} onClick={() => { setCloseAt(venueWallClock(new Date(day.closed_at), fmt.timeZone)); setEditing(true) }}><Pencil size={13} /></IconButton>
)}
</span>}>
<div className="grid gap-3" data-testid="report-day-dialog">
{editing && (
<div className="flex flex-wrap items-end gap-2 p-3 rounded-card bg-surface-2">
<label className="grid gap-1 text-caption text-ink-2">{t('reports.store.closedAt')}
<Input type="datetime-local" value={closeAt} onChange={e => setCloseAt(e.target.value)} />
</label>
<Button size="sm" loading={fixClose.isPending} onClick={() => fixClose.mutate()}>{t('reports.save')}</Button>
<Button size="sm" variant="ghost" onClick={() => setEditing(false)}>{t('reports.back')}</Button>
</div>
)}
<span className="flex gap-1" role="tablist">
{['orders', 'shifts'].map(k => (
<Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)}>
{t(`reports.store.dayTabs.${k}`, { count: k === 'orders' ? orders.length : shifts.length })}
</Button>
))}
</span>
{(tab === 'orders' ? loadingOrders : loadingShifts) ? <Loading /> : tab === 'orders'
? <Table columns={orderCols} rows={orders} onRow={setOrder} limit={500} />
: <Table columns={shiftCols} rows={shifts} onRow={setShift} />}
</div>
{order && <OrderDialog order={order} onClose={() => setOrder(null)} />}
{shift && <ShiftDialog shift={shift} mode="stats" onClose={() => setShift(null)} />}
{dropShift && (
<Dialog open size="sm" onClose={() => setDropShift(null)} title={t('reports.store.deleteShiftTitle', { name: dropShift.waiter_name })} description={t('reports.store.deleteShiftBody')}
footer={<>
<Button variant="secondary" onClick={() => setDropShift(null)}>{t('reports.back')}</Button>
<Button variant="danger" loading={removeShift.isPending} onClick={() => removeShift.mutate(dropShift)}>{t('reports.store.deleteYes')}</Button>
</>} />
)}
</Dialog>
)
}
@@ -0,0 +1,67 @@
// Orders (plan step 6.12b): every order of a period or a business day, filtered by status,
// waiter and table; products, delivery fee and refunds per order; a tap opens it; export.
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Select } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { Pill } from '../../overview/parts'
import OrderDialog from '../kit/OrderDialog'
import { ExportButton, Failed, Loading, Panel, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod, orderTotals, periodParams, periodSlug } from '../kit/reportLogic'
const STATUSES = ['open', 'partially_paid', 'paid', 'closed', 'cancelled']
const TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
export default function OrdersTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [filter, setFilter] = useState({ status: '', waiter_id: '', table_id: '' })
const [order, setOrder] = useState(null)
const set = (k, v) => setFilter(f => ({ ...f, [k]: v }))
const { data: waiters = [] } = useLiveQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').then(r => r.data.waiters), staleTime: 300_000 })
const { data: tables = [] } = useLiveQuery({ queryKey: ['meta-tables'], queryFn: () => client.get('/api/reports/meta/tables').then(r => r.data.tables), staleTime: 300_000 })
const params = { ...periodParams(period), ...Object.fromEntries(Object.entries(filter).filter(([, v]) => v)) }
const { data: orders, isPending, error, refetch } = useLiveQuery({
queryKey: ['report-orders', params], queryFn: () => client.get('/api/reports/orders/history', { params: { ...params, page_size: 2000 } }).then(r => r.data),
})
const rows = orders ?? []
const columns = [
{ key: 'id', label: '#', render: o => <span className="tabular-nums text-ink-2">#{o.id}</span> },
{ key: 'table_name', label: t('reports.place'), render: o => o.table_name || t('reports.noTable') },
{ key: 'opened_at', label: t('reports.opened'), render: o => fmt.formatDateTime(o.opened_at, 'datetimeShort') },
{ key: 'closed_at', label: t('reports.closed'), render: o => (o.closed_at ? fmt.formatTime(o.closed_at) : '—') },
{ key: 'opened_by_name', label: t('reports.by') },
{ key: 'cancelled', label: t('reports.store.cancelledLines'), align: 'right', sort: o => (o.items ?? []).filter(i => i.status === 'cancelled').length,
render: o => { const n = (o.items ?? []).filter(i => i.status === 'cancelled').length; return n ? <span className="text-danger-ink">{n}</span> : '' } },
{ 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> },
]
const total = rows.reduce((s, o) => s + orderTotals(o).revenue, 0)
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod}
right={<ExportButton endpoint="/api/reports/orders/export" params={params} filename={`orders-${periodSlug(period)}.csv`} />} />
<div className="flex flex-wrap gap-2">
<Select size="sm" value={filter.status} onChange={e => set('status', e.target.value)} aria-label={t('reports.status')}
options={[{ value: '', label: t('reports.store.anyStatus') }, ...STATUSES.map(s => ({ value: s, label: t(`overview.orderStatus.${s}`) }))]} />
<Select size="sm" value={filter.waiter_id} onChange={e => set('waiter_id', e.target.value)} aria-label={t('reports.person')}
options={[{ value: '', label: t('reports.store.anyone') }, ...waiters.map(w => ({ value: String(w.id), label: w.name }))]} />
<Select size="sm" value={filter.table_id} onChange={e => set('table_id', e.target.value)} aria-label={t('reports.place')}
options={[{ value: '', label: t('reports.store.anyTable') }, ...tables.map(x => ({ value: String(x.id), label: x.group ? `${x.name} · ${x.group}` : x.name }))]} />
</div>
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (
<Panel padded={false} title={t('reports.store.ordersCount', { count: rows.length, total: fmt.formatMoney(total) })}>
<Table columns={columns} rows={rows} onRow={setOrder} rowTestId="report-order" initialSort={{ key: 'id', dir: 'desc' }} limit={300} />
</Panel>
)}
{order && <OrderDialog order={order} onClose={() => setOrder(null)} />}
</div>
)
}
@@ -0,0 +1,22 @@
// Reports → Venue (plan step 6.12b; replaces the v1 StorePage and its five views): business days,
// orders, traffic (hours and weekdays), revenue trends, tables. Every number is counted like the
// other reports (backend services/sales.py): products net of refunds, delivery fees apart.
import { useTranslation } from '@xenia/i18n'
import { ReportPage } from '../kit/parts'
import DaysTab from './DaysTab'
import OrdersTab from './OrdersTab'
import TablesTab from './TablesTab'
import TrafficTab from './TrafficTab'
import TrendsTab from './TrendsTab'
export default function StorePage() {
const { t } = useTranslation('manager')
const tabs = [
{ id: 'days', label: t('reports.store.tabs.days'), Component: DaysTab },
{ id: 'orders', label: t('reports.store.tabs.orders'), Component: OrdersTab },
{ id: 'traffic', label: t('reports.store.tabs.traffic'), Component: TrafficTab },
{ id: 'trends', label: t('reports.store.tabs.trends'), Component: TrendsTab },
{ id: 'tables', label: t('reports.store.tabs.tables'), Component: TablesTab },
]
return <ReportPage title={t('reports.store.title')} tabs={tabs} testId="report-store" />
}
@@ -0,0 +1,48 @@
// Tables (plan step 6.12b): per table, finished orders, the average time at the table, the
// average spend per visit and the revenue; the busiest tables as bars; print on a receipt printer.
import { useState } from 'react'
import { Printer } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { BarList } from '../kit/charts'
import { Failed, Loading, Panel, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import PrintDialog from '../kit/PrintDialog'
import { defaultPeriod, periodParams, printBody } from '../kit/reportLogic'
export default function TablesTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [printing, setPrinting] = useState(false)
const params = periodParams(period)
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-tables', params], queryFn: () => client.get('/api/reports/tables/performance', { params }).then(r => r.data.tables) })
const rows = (data ?? []).map(r => ({ ...r, name: r.table_name ?? t('reports.noTable'), per_visit: r.order_count ? r.revenue / r.order_count : 0 }))
const columns = [
{ key: 'name', label: t('reports.place'), render: r => <span className="font-semibold text-ink">{r.name}</span> },
{ key: 'order_count', label: t('reports.orders'), align: 'right' },
{ key: 'avg_duration_minutes', label: t('reports.tables.avgTime'), align: 'right', tip: t('reports.tables.avgTimeTip'),
render: r => (r.avg_duration_minutes != null ? t('reports.tables.minutes', { count: Math.round(r.avg_duration_minutes) }) : '—') },
{ key: 'per_visit', label: t('reports.tables.perVisit'), align: 'right', render: r => fmt.formatMoney(r.per_visit) },
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: r => <span className="font-semibold">{fmt.formatMoney(r.revenue)}</span> },
{ key: 'fees', label: t('reports.fees'), align: 'right', render: r => (r.fees ? fmt.formatMoney(r.fees) : '') },
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} right={<Button size="sm" variant="secondary" icon={<Printer size={14} />} onClick={() => setPrinting(true)}>{t('reports.print.button')}</Button>} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
<Panel padded={false} title={t('reports.tables.title')} tip={t('reports.tables.tip')}>
<Table columns={columns} rows={rows} rowKey={r => r.table_id ?? 'none'} initialSort={{ key: 'revenue', dir: 'desc' }} />
</Panel>
{rows.length > 1 && (
<Panel title={t('reports.tables.top')}>
<BarList format={v => fmt.formatMoney(v)} rows={[...rows].sort((a, b) => b.revenue - a.revenue).slice(0, 15).map(r => ({ key: r.table_id ?? 'none', label: r.name, value: r.revenue }))} />
</Panel>
)}
</>)}
{printing && <PrintDialog endpoint="/api/reports/print/tables" body={printBody(period)} modes={['smart']} onClose={() => setPrinting(false)} />}
</div>
)
}
@@ -0,0 +1,50 @@
// Traffic (plan step 6.12b): when the venue is busy — orders and revenue by hour of the day
// (venue time) and by weekday (of the business date, so a 01:30 Saturday order counts on Friday).
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { BarList } from '../kit/charts'
import HourChart from '../kit/HourChart'
import { Failed, Loading, Panel, Stat } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod, hourSeries, periodParams } from '../kit/reportLogic'
const hourLabel = h => `${String(h).padStart(2, '0')}:00`
export default function TrafficTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const params = periodParams(period)
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-traffic', params], queryFn: () => client.get('/api/reports/traffic', { params }).then(r => r.data) })
// 16 Nov 2026 is a Monday: weekday d (0 = Monday) by name in the person's language
const weekday = d => fmt.formatDateTime(`2026-11-${String(16 + d).padStart(2, '0')}T12:00:00Z`, { weekday: 'long' })
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (() => {
const hours = data.by_hour.filter(h => h.orders)
const total = data.by_hour.reduce((s, h) => s + h.orders, 0)
const busiest = [...hours].sort((a, b) => b.orders - a.orders)[0]
const quietest = [...hours].sort((a, b) => a.orders - b.orders)[0]
const days = data.by_weekday
const busyDay = [...days].sort((a, b) => b.orders - a.orders)[0]
return (<>
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(12rem,1fr))]">
<Stat label={t('reports.traffic.orders')} value={total} />
<Stat label={t('reports.traffic.busiestHour')} value={busiest ? hourLabel(busiest.hour) : '—'} sub={busiest ? t('reports.traffic.ordersN', { count: busiest.orders }) : undefined} />
<Stat label={t('reports.traffic.quietestHour')} value={quietest ? hourLabel(quietest.hour) : '—'} sub={t('reports.traffic.quietTip')} />
<Stat label={t('reports.traffic.busiestDay')} value={busyDay?.orders ? <span className="capitalize">{weekday(busyDay.day)}</span> : '—'} />
</div>
<Panel title={t('reports.byHour')} tip={t('reports.byHourTip')}><HourChart series={hourSeries(data.by_hour)} /></Panel>
<Panel title={t('reports.traffic.byWeekday')} tip={t('reports.traffic.byWeekdayTip')}>
<BarList testId="traffic-weekdays" format={v => fmt.formatMoney(v)} highlight={busyDay?.orders ? busyDay.day : null}
rows={days.map(d => ({ key: d.day, label: weekday(d.day), value: d.revenue, sub: t('reports.traffic.ordersN', { count: d.orders }) }))} />
</Panel>
</>)
})()}
</div>
)
}
@@ -0,0 +1,45 @@
// Revenue trends (plan step 6.12b): revenue (and profit) by day, week or month of business
// dates, with the 7-day average for days; delivery fees beside the revenue.
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button } from '@xenia/ui'
import client from '../../../api/client'
import { useLiveQuery } from '../../../live/useLiveQuery'
import { TrendChart } from '../kit/charts'
import { Failed, Loading, MoneyCell, Panel, Table } from '../kit/parts'
import { PeriodPicker } from '../kit/Period'
import { defaultPeriod, periodParams } from '../kit/reportLogic'
const STEPS = ['daily', 'weekly', 'monthly']
export default function TrendsTab() {
const { t } = useTranslation('manager')
const fmt = useFormat()
const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday()))
const [step, setStep] = useState('daily')
const params = { ...periodParams({ ...period, mode: 'range' }), granularity: step }
const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-trends', params], queryFn: () => client.get('/api/reports/revenue/trends', { params }).then(r => r.data.trends) })
const label = key => (step === 'monthly' ? fmt.formatDateTime(`${key}-15T12:00:00Z`, { month: 'long', year: 'numeric' })
: step === 'weekly' ? t('reports.trends.weekOf', { date: fmt.formatDateTime(`${key}T12:00:00Z`, { day: '2-digit', month: '2-digit' }) })
: fmt.formatDateTime(`${key}T12:00:00Z`, { weekday: 'short', day: '2-digit', month: '2-digit' }))
const rows = data ?? []
const anyProfit = rows.some(r => r.profit)
const columns = [
{ key: 'date', label: t('reports.trends.when'), render: r => <span className="capitalize">{label(r.date)}</span> },
{ key: 'orders', label: t('reports.orders'), align: 'right' },
{ key: 'revenue', label: t('reports.revenue'), align: 'right', render: r => <span className="font-semibold">{fmt.formatMoney(r.revenue)}</span> },
{ key: 'fees', label: t('reports.fees'), align: 'right', render: r => (r.fees ? fmt.formatMoney(r.fees) : '') },
...(anyProfit ? [{ key: 'profit', label: t('reports.profit'), align: 'right', render: r => <MoneyCell value={r.profit} partial={r.has_gap} /> }] : []),
...(step === 'daily' ? [{ key: 'rolling7', label: t('reports.trends.avg7'), align: 'right', tip: t('reports.trends.avg7Tip'), render: r => fmt.formatMoney(r.rolling7) }] : []),
]
return (
<div className="grid gap-4">
<PeriodPicker value={period} onChange={setPeriod} allowDay={false}
right={<span className="flex gap-1">{STEPS.map(s => <Button key={s} size="sm" variant={step === s ? 'primary' : 'ghost'} onClick={() => setStep(s)}>{t(`reports.trends.steps.${s}`)}</Button>)}</span>} />
{isPending ? <Loading /> : error ? <Failed error={error} retry={refetch} /> : (<>
{rows.length > 1 && <Panel title={t('reports.trends.title')}><TrendChart points={rows.map(r => ({ label: label(r.date), revenue: r.revenue, profit: r.profit }))} showProfit={anyProfit} /></Panel>}
<Panel padded={false} title={t('reports.trends.table')}><Table columns={columns} rows={rows} rowKey={r => r.date} initialSort={{ key: 'date', dir: 'desc' }} /></Panel>
</>)}
</div>
)
}