From 7767bdb7286ee365e59f7a9534acc7f1965c86ac Mon Sep 17 00:00:00 2001 From: bonamin Date: Thu, 19 Nov 2026 09:06:20 +0200 Subject: [PATCH] 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 --- local_backend/routers/business_day.py | 3 +- local_backend/routers/shifts.py | 3 +- manager_dashboard/src/App.jsx | 4 +- .../src/pages/reports/ProductsReportPage.jsx | 24 - .../src/pages/reports/StorePage.jsx | 30 - .../src/pages/reports/kit/HourChart.jsx | 2 +- .../src/pages/reports/kit/PrintDialog.jsx | 58 ++ .../src/pages/reports/kit/charts.jsx | 45 ++ .../src/pages/reports/kit/reportLogic.js | 6 + .../pages/reports/products/ProductsReport.jsx | 137 +++++ .../restaurant/CategoryPerformance.jsx | 488 ---------------- .../pages/reports/restaurant/OrderHistory.jsx | 151 ----- .../reports/restaurant/ProductPerformance.jsx | 539 ------------------ .../reports/restaurant/RevenueTrends.jsx | 119 ---- .../reports/restaurant/TableAnalytics.jsx | 316 ---------- .../reports/restaurant/TrafficAnalytics.jsx | 131 ----- .../reports/restaurant/WorkDaySummary.jsx | 460 --------------- .../src/pages/reports/store/DaysTab.jsx | 173 ++++++ .../src/pages/reports/store/OrdersTab.jsx | 67 +++ .../src/pages/reports/store/StorePage.jsx | 22 + .../src/pages/reports/store/TablesTab.jsx | 48 ++ .../src/pages/reports/store/TrafficTab.jsx | 50 ++ .../src/pages/reports/store/TrendsTab.jsx | 45 ++ manager_dashboard/tests/reports.test.mjs | 7 +- manager_dashboard/v2.json | 4 +- packages/i18n/locales/el/manager.json | 135 +++++ packages/i18n/locales/en/manager.json | 135 +++++ tests/e2e/manager.mjs | 28 + 28 files changed, 964 insertions(+), 2266 deletions(-) delete mode 100644 manager_dashboard/src/pages/reports/ProductsReportPage.jsx delete mode 100644 manager_dashboard/src/pages/reports/StorePage.jsx create mode 100644 manager_dashboard/src/pages/reports/kit/PrintDialog.jsx create mode 100644 manager_dashboard/src/pages/reports/kit/charts.jsx create mode 100644 manager_dashboard/src/pages/reports/products/ProductsReport.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/CategoryPerformance.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/OrderHistory.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/ProductPerformance.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/RevenueTrends.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/TableAnalytics.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/TrafficAnalytics.jsx delete mode 100644 manager_dashboard/src/pages/reports/restaurant/WorkDaySummary.jsx create mode 100644 manager_dashboard/src/pages/reports/store/DaysTab.jsx create mode 100644 manager_dashboard/src/pages/reports/store/OrdersTab.jsx create mode 100644 manager_dashboard/src/pages/reports/store/StorePage.jsx create mode 100644 manager_dashboard/src/pages/reports/store/TablesTab.jsx create mode 100644 manager_dashboard/src/pages/reports/store/TrafficTab.jsx create mode 100644 manager_dashboard/src/pages/reports/store/TrendsTab.jsx diff --git a/local_backend/routers/business_day.py b/local_backend/routers/business_day.py index fab265a..da50ee4 100644 --- a/local_backend/routers/business_day.py +++ b/local_backend/routers/business_day.py @@ -1,3 +1,4 @@ +from core.access.deps import require from core.timeutil import business_date_of, parse_api_datetime, utcnow from fastapi import APIRouter, Depends, status from sqlalchemy import func @@ -209,7 +210,7 @@ def patch_business_day( def delete_business_day( day_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("core.settings.manage")), ): """Permanently delete a business day. Only allowed when it has no shifts.""" day = db.query(BusinessDay).filter(BusinessDay.id == day_id).first() diff --git a/local_backend/routers/shifts.py b/local_backend/routers/shifts.py index 7c66bc6..43ed30d 100644 --- a/local_backend/routers/shifts.py +++ b/local_backend/routers/shifts.py @@ -1,3 +1,4 @@ +from core.access.deps import require from core.access.check import holds from core.timeutil import utcnow from fastapi import APIRouter, Depends, status @@ -391,7 +392,7 @@ def get_shift( def delete_shift( shift_id: int, db: Session = Depends(get_db), - user: User = Depends(require_manager), + user: User = Depends(require("core.settings.manage")), ): """Permanently delete a shift, its breaks, and all orders opened during that shift.""" from models.order import Order, OrderItem, OrderAuditLog, OrderWaiter diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index caf5c9e..f1d369a 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -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' diff --git a/manager_dashboard/src/pages/reports/ProductsReportPage.jsx b/manager_dashboard/src/pages/reports/ProductsReportPage.jsx deleted file mode 100644 index b99754b..0000000 --- a/manager_dashboard/src/pages/reports/ProductsReportPage.jsx +++ /dev/null @@ -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 ( -
- -
- -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/StorePage.jsx b/manager_dashboard/src/pages/reports/StorePage.jsx deleted file mode 100644 index 2e1bba4..0000000 --- a/manager_dashboard/src/pages/reports/StorePage.jsx +++ /dev/null @@ -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 ( -
- -
- -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/kit/HourChart.jsx b/manager_dashboard/src/pages/reports/kit/HourChart.jsx index f4e8ca6..c80e095 100644 --- a/manager_dashboard/src/pages/reports/kit/HourChart.jsx +++ b/manager_dashboard/src/pages/reports/kit/HourChart.jsx @@ -15,7 +15,7 @@ export default function HourChart({ series, nowHour = null, height = 220 }) { formatMoney(v, { decimals: 0 })} width={56} /> formatMoney(v)} contentStyle={{ background: 'var(--x-surface)', border: '1px solid var(--x-line)', borderRadius: 8, color: 'var(--x-ink)' }} /> - + {data.map(d => nowHour ? 'var(--x-surface-3)' : 'var(--x-accent)'} />)} diff --git a/manager_dashboard/src/pages/reports/kit/PrintDialog.jsx b/manager_dashboard/src/pages/reports/kit/PrintDialog.jsx new file mode 100644 index 0000000..f0ebc8d --- /dev/null +++ b/manager_dashboard/src/pages/reports/kit/PrintDialog.jsx @@ -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 ( + + + + + }> +
+ {modes.length > 1 && ( +
+ {modes.map(m => ( + + ))} +
+ )} + {printers.length === 0 ?

{t('reports.print.noPrinters')}

: ( + + 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 ? : error ? : (<> +
+ + + {refunded > 0 && } + {anyCost && } />} +
+ {top.length > 0 && ( + {METRICS.filter(m => m !== 'trackable_profit' || anyCost).map(m => ( + ))}}> + (metric === 'qty_sold' ? qty(v) : fmt.formatMoney(v))} + rows={top.map(r => ({ key: r.product_id, label: r.product_name, value: r[metric] ?? 0 }))} /> + + )} + + r.product_id} rowTestId="report-product" initialSort={{ key: 'revenue', dir: 'desc' }} limit={500} /> + + )} + {printing && setPrinting(false)} />} + + ) +} + +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 => {r.category_name} }, + { 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 ? {fmt.formatMoney(r.refunded)} : '') }, + ...(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 ? : '') }, + { 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 ( +
+ } onClick={() => setPrinting(true)}>{t('reports.print.button')}} /> + {isPending ? : error ? : (<> + {rows.length > 0 && ( + + 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 })}%` }))} /> + + )} + +
r.category_id ?? 'none'} rowTestId="report-category" initialSort={{ key: 'revenue', dir: 'desc' }} /> + + )} + {printing && setPrinting(false)} />} + + ) +} diff --git a/manager_dashboard/src/pages/reports/restaurant/CategoryPerformance.jsx b/manager_dashboard/src/pages/reports/restaurant/CategoryPerformance.jsx deleted file mode 100644 index 0e44dcd..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/CategoryPerformance.jsx +++ /dev/null @@ -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 `` - }).join('') - return `${slices}` -} - -// ─── 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 `
Εργάσιμη Μέρα${periodLabel}
` - const f = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—' - const t = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—' - return `
Από${f}
Έως${t}
` - } - - 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 `
- - - - - - ` - }).join('') - body = `
${c.category_name}${fmtNum(c.units_sold)}${fmtEUR(c.revenue)}${pctRev}%${pctQty}%
- - ${rows} - -
ΚατηγορίαΤεμ.Έσοδα% Έσ.% Τεμ.
Σύνολο${fmtNum(totalQty)}${fmtEUR(totalRev)}100%100%
` - } 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 `
${c.category_name}${pctRev}% έσ. / ${pctQty}% τεμ.
` - }).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 ` - ${p.name} - ${fmtNum(p.qty)} - ${fmtEUR(p.revenue)} - ${pctProdRev}% - ${pctProdQty}% - ` - }).join('') - - return `
-
- ${c.category_name} - ${fmtEUR(c.revenue)} -
-
${fmtNum(c.units_sold)} τεμ.  ·  ${c.product_count} προϊόντα  ·  ${pctRev}% εσόδων  ·  ${pctQtyOfTotal}% τεμ.
- ${catProducts.length ? ` - - - - ${productRows} -
ΠροϊόνΤεμ.Έσοδα% Έσ.% Τεμ.
` : '
Δεν υπάρχουν πωλήσεις σε αυτή την περίοδο
'} -
` - }).join('') - - body = ` -
-
${donut}
-
${legend}
-
- ${catBlocks}` - } - - const title = printType === 'smart' ? 'Σύνοψη Κατηγοριών' : 'Πλήρης Ανάλυση Κατηγοριών' - const styles = `` - - win.document.write(`${title}${styles} -

${title}

-
- ${periodRow()} -
Κατηγορίες${categories.length}
-
- ${body} - `) - 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 ( -
{ if (e.target === e.currentTarget) onClose() }}> -
-
-

Εκτύπωση Κατηγοριών

- -
-
-
-
Τύπος Εκτύπωσης
-
- {PRINT_TYPES.map(pt => ( - - ))} -
-
-
-
Εκτυπωτής Προορισμού
-
- - -
-
-
- - -
-
-
-
- ) -} - -// ─── 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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- 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"> - Εκτύπωση Σύνοψης - - }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
- {categories.length === 0 ? ( - - ) : ( - <> -
-
- - {[['revenue', 'Έσοδα'], ['profit', 'Κέρδος']].map(([m, label]) => ( - - ))} -
- ) : null - }> - {pieData.length === 0 ? ( -
Δεν υπάρχουν δεδομένα κέρδους
- ) : ( -
- - - - {pieData.map((d, i) => )} - - fmtEUR(v)} />} /> - - -
- )} - -
-
- {categories.map((c, i) => { - const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0 - ? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%' - : null - return ( -
-
- - {c.category_name} -
-
{fmtEUR(c.revenue)}
-
- {c.units_sold} τεμ. · {c.product_count} προϊόντα - {c.pct_rev ?? c.pct}% -
- {(c.trackable_profit || 0) > 0 && ( -
- {fmtEUR(c.trackable_profit)} κέρδος - {margin && {margin}{c.has_gap && ' ⚠'}} -
- )} -
- ) - })} -
-
-
- - - - Κατηγορία - Προϊόντα - Τεμάχια - Έσοδα - {anyHasCost && Κόστος} - {anyHasCost && Κέρδος} - % Εσόδων - {anyHasCost && % Κέρδους} - - - {categories.map((c, i) => { - const margin = c.revenue > 0 && (c.trackable_profit || 0) > 0 - ? ((c.trackable_profit / c.revenue) * 100).toFixed(0) + '%' - : null - return ( - - {c.category_name} - {c.product_count} - {fmtNum(c.units_sold)} - {fmtEUR(c.revenue)} - {anyHasCost && ( - - {(c.total_cost || 0) > 0 ? fmtEUR(c.total_cost) : —} - - )} - {anyHasCost && ( - - {(c.trackable_profit || 0) > 0 ? ( - - {fmtEUR(c.trackable_profit)} - {margin && ({margin}){c.has_gap && ' ⚠'}} - - ) : —} - - )} - {c.pct_rev ?? c.pct}% - {anyHasCost && ( - - {(c.pct_profit || 0) > 0 - ? {c.pct_profit}% - : — - } - - )} - - ) - })} - - - -
- - )} -
- - {showPrintModal && ( - setShowPrintModal(false)} - categories={categories} - allProducts={allProducts} - soldProducts={soldProducts} - printers={printers} - queryParams={queryParams} - periodLabel={periodLabel} - /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/OrderHistory.jsx b/manager_dashboard/src/pages/reports/restaurant/OrderHistory.jsx deleted file mode 100644 index 541ea05..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/OrderHistory.jsx +++ /dev/null @@ -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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - - - - -
- - Παραγγελίες - · - {orders.length} αποτελέσματα - - } - right={ - Κάντε Click για Λεπτομέρειες Παραγγελίας - } - > - {orders.length === 0 ? ( - - ) : ( - <> - - - #ΤραπέζιΆνοιξεΈκλεισε - ΚατάστασηΕίδηΑκυρώσειςΣύνολο - - - {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 ( - setDrillOrder(o)} className={isCancelled ? 'opacity-50' : ''}> - #{o.id} - {o.table_name ?? o.table_id} - {fmtDateTime(o.opened_at)} - {fmtDateTime(o.closed_at)} - - {totalQty} - - {cancelledQty > 0 - ? {cancelledQty} - : —} - - {fmtEUR(total)} - - ) - })} - - - {orders.length > 200 && ( -
- Εμφάνιση πρώτων 200 από {orders.length} παραγγελίες. Περιορίστε τα φίλτρα για λιγότερα αποτελέσματα. -
- )} - - )} -
-
- - {drillOrder && ( - setDrillOrder(null)} /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/ProductPerformance.jsx b/manager_dashboard/src/pages/reports/restaurant/ProductPerformance.jsx deleted file mode 100644 index 22b87c4..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/ProductPerformance.jsx +++ /dev/null @@ -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 ` - ${d[labelKey]} - - ${d[valueKey]}` - }).join('') - - return `${bars}` -} - -// ─── 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 `
Εργάσιμη Μέρα${periodLabel}
` - const f = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—' - const t = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—' - return `
Από${f}
Έως${t}
` - } - - 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 ` - ${p.product_name} - ${fmtNum(p.qty_sold)} - ${fmtEUR(p.revenue)} - ${pctRev}% - ${pctQty}% - ` - }).join('') - tableSection = ` - - ${rows} - -
ΠροϊόνΤεμ.Έσοδα% Έσ.% Τεμ.
Σύνολο${fmtNum(totalQty)}${fmtEUR(totalRev)}100%100%
` - } 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 ` - ${d.name} - - ${fmtEUR(d.revenue)}` - }).join('') - const revH = top5rev.length * (barH + gap) + gap - const chartRevSvg = `${revBars}` - - 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 ` - ${p.name} - ${p.category} - ${fmtNum(p.qty)} - ${fmtEUR(p.revenue)} - ${pctRev}% - ${pctQty}% - ` - }).join('') - - tableSection = ` -
-
Top 5 σε Τεμάχια
- ${chartQty} -
-
-
Top 5 σε Έσοδα
- ${chartRevSvg} -
- - - ${rows} - -
ΠροϊόνΚατηγορίαΤεμ.Έσοδα% Έσ.% Τεμ.
Σύνολο${fmtNum(totalQty)}${fmtEUR(totalRev)}100%100%
` - } - - const title = printType === 'smart' ? 'Έξυπνη Σύνοψη Προϊόντων' : 'Πλήρης Ανάλυση Προϊόντων' - const styles = `` - - win.document.write(`${title}${styles} -

${title}

-
- ${periodRow()} -
Προϊόντα με πωλήσεις${products.length}
- ${printType === 'full' ? `
Σύνολο ενεργών προϊόντων${allProducts.length}
` : ''} -
- ${tableSection} - `) - 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 ( -
{ if (e.target === e.currentTarget) onClose() }}> -
-
-

Εκτύπωση Σύνοψης Προϊόντων

- -
-
-
-
Τύπος Εκτύπωσης
-
- {PRINT_TYPES.map(pt => ( - - ))} -
-
-
-
Εκτυπωτής Προορισμού
-
- - -
- {targetPrinter !== 'browser' && printType === 'full' && ( -

Η Πλήρης Ανάλυση σε θερμικό θα εκτυπώσει μόνο τη λίστα χωρίς γραφήματα.

- )} -
-
- - -
-
-
-
- ) -} - -// ─── 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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - -
- }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
- {(() => { - const chartModes = [ - ['revenue', 'Έσοδα'], - ['units', 'Τεμάχια'], - ...(anyHasCost ? [['profit', 'Κέρδος'], ['dual', 'Έσοδα vs Κέρδος']] : []), - ] - const subtitleMap = { revenue: 'έσοδα', units: 'τεμάχια', profit: 'κέρδος', dual: 'έσοδα vs κέρδος' } - const isDual = chartMode === 'dual' - return ( - - {chartModes.map(([m, label]) => ( - - ))} -
- }> - {top10.length === 0 ? ( - - ) : ( -
- - - - chartMode === 'units' ? String(v) : '€' + v} /> - - { - if (chartMode === 'units') return v + ' τεμ.' - return fmtEUR(v) - }} />} cursor={{ fill: '#f1f5f9' }} /> - {isDual && } - {isDual ? ( - <> - - - - ) : ( - - {top10.map((d, i) => ( - - ))} - - )} - - -
- )} - - ) - })()} - -
- {(() => { - 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 ( - - {hasGap && ( -
- ⚠ - - Μερικά προϊόντα δεν έχουν κόστος — το κέρδος που φαίνεται είναι μερικό. - Ορισμένα έσοδα {fmtEUR(totalUncostedRev)} δεν συμπεριλαμβάνονται στο κέρδος.{' '} - Ορισμός κόστους προϊόντων → - -
- )} - {products.length === 0 ? ( - - ) : ( - - - Προϊόν - Τεμάχια - Έσοδα - {anyHasCost && Κόστος} - Κέρδος - Απόβλητα - % Έσόδων - {anyHasCost && % Κέρδους} - Παραγγελίες - - - {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 ( - - {p.product_name} - {fmtNum(p.qty_sold)} - {fmtEUR(p.revenue)} - {anyHasCost && ( - - {(p.total_cost || 0) > 0 - ? {fmtEUR(p.total_cost)} - : — - } - - )} - - {p.has_gap ? ( - ⚠ χωρίς κόστος - ) : (p.total_cost || 0) === 0 ? ( - — - ) : ( - = 0 ? 'text-green-700' : 'text-red-600'}> - {fmtEUR(p.trackable_profit)} - {margin && ({margin})} - - )} - - - {p.waste_qty > 0 ? ( - - {p.waste_qty} - {p.waste_cost > 0 && ({fmtEUR(p.waste_cost)})} - - ) : —} - - {pctRev.toFixed(1)}% - {anyHasCost && ( - - {pctProfit != null - ? {pctProfit.toFixed(1)}% - : — - } - - )} - {fmtNum(p.order_count)} - - ) - })} - - {products.length > 1 && ( - - - Σύνολο - {fmtEUR(totalRev)} - {anyHasCost && ( - {fmtEUR(totalCost)} - )} - - {hasGap ? ( - {fmtEUR(totalProfit)}{' '}+χωρίς κόστος - ) : totalProfit > 0 ? ( - - {fmtEUR(totalProfit)} - {overallMargin && ({overallMargin})} - - ) : —} - - - 100% - {anyHasCost && ( - - {totalProfit > 0 && !hasGap ? '100%' : '—'} - - )} - - - - )} - - )} -
- ) - })()} -
- - - {showPrintModal && ( - setShowPrintModal(false)} - products={products} - allProducts={allProducts} - printers={printers} - queryParams={queryParams} - periodLabel={periodLabel} - /> - )} - - ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/RevenueTrends.jsx b/manager_dashboard/src/pages/reports/restaurant/RevenueTrends.jsx deleted file mode 100644 index b7f6014..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/RevenueTrends.jsx +++ /dev/null @@ -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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - -
- {GRAN_OPTIONS.map(([g, label]) => ( - - ))} -
-
- -
- g === gran)?.[1] || gran} · ${fmtDateStr(from)} → ${fmtDateStr(to)}`}> - {trends.length === 0 ? ( - - ) : ( -
- - - - - '€' + v} /> - fmtEUR(v)} />} /> - - - {anyHasProfit && } - {gran === 'daily' && } - - -
- )} -
- -
- - - - Περίοδος - Παραγγελίες - Έσοδα - {anyHasProfit && Κέρδος} - {gran === 'daily' && Μέσος 7 ημ.} - - - {trends.map(d => ( - - {gran === 'monthly' ? d.date : fmtDate(d.date)} - {fmtNum(d.orders)} - {fmtEUR(d.revenue)} - {anyHasProfit && ( - - {(d.profit || 0) > 0 - ? - {fmtEUR(d.profit)} - {d.has_gap && ⚠} - - : — - } - - )} - {gran === 'daily' && {fmtEUR(d.rolling7)}} - - ))} - - - -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/TableAnalytics.jsx b/manager_dashboard/src/pages/reports/restaurant/TableAnalytics.jsx deleted file mode 100644 index d92a64e..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/TableAnalytics.jsx +++ /dev/null @@ -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 = `
Εργάσιμη Μέρα${periodLabel}
` - } else { - const fromStr = queryParams.from ? fmtDateStr(queryParams.from.slice(0, 10)) : '—' - const toStr = queryParams.to ? fmtDateStr(queryParams.to.slice(0, 10)) : '—' - periodRow = `
Από${fromStr}
-
Έως${toStr}
` - } - - 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 ` - ${t.table_name} - ${fmtNum(t.order_count)} - ${dur} - ${fmtEUR(t.revenue)} - ` - } - return ` - ${t.table_name} - ${fmtNum(t.order_count)} - ${dur} - ${fmtEUR(avgRev)} - ${fmtEUR(t.revenue)} - ` - }).join('') - - const headers = printType === 'smart' - ? `ΤραπέζιΠαραγγελίεςΜ. ΔιάρκειαΈσοδα` - : `ΤραπέζιΠαραγγελίεςΜ. ΔιάρκειαΜ. / ΕπίσκεψηΈσοδα` - const footCols = printType === 'smart' - ? `Σύνολο${fmtNum(totalOrders)}—${fmtEUR(totalRev)}` - : `Σύνολο${fmtNum(totalOrders)}——${fmtEUR(totalRev)}` - - const title = printType === 'smart' ? 'Σύνοψη Τραπεζιών' : 'Πλήρης Ανάλυση Τραπεζιών' - const styles = `` - - const html = `${title}${styles} -

${title}

-
- ${periodRow} -
Τραπέζια${tables.length}
-
- - ${headers} - ${rows} - ${footCols} -
- ` - - 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 ( -
{ if (e.target === e.currentTarget) onClose() }} - > -
-
-

Εκτύπωση Σύνοψης Τραπεζιών

- -
-
-
-
Τύπος Εκτύπωσης
-
- {PRINT_TYPES.map(pt => ( - - ))} -
-
-
-
Εκτυπωτής Προορισμού
-
- - -
-
-
- - -
-
-
-
- ) -} - -// ─── 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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - -
- }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
- {tables.length === 0 ? ( - - ) : ( - <> - - - - ΤραπέζιΠαραγγελίεςΜέση Διάρκεια - Μέσο / ΕπίσκεψηΣυνολικά ΈσοδαΚύκλοι - - - {tables.map(t => { - const avgRev = t.order_count ? t.revenue / t.order_count : 0 - return ( - - {t.table_name} - {fmtNum(t.order_count)} - {fmtMinutes(t.avg_duration_minutes)} - {fmtEUR(avgRev)} - {fmtEUR(t.revenue)} - {fmtNum(t.order_count)} - - ) - })} - - - - -
- -
- {tables.map(t => { - const intensity = t.revenue / maxRev - return ( -
-
{t.table_name}
-
{fmtEUR(t.revenue)}
-
- ) - })} -
-
-
- - )} -
- - {showPrintModal && ( - setShowPrintModal(false)} - tables={tables} - printers={printers} - queryParams={queryParams} - periodLabel={periodLabel} - /> - )} - - ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/TrafficAnalytics.jsx b/manager_dashboard/src/pages/reports/restaurant/TrafficAnalytics.jsx deleted file mode 100644 index f2d07f6..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/TrafficAnalytics.jsx +++ /dev/null @@ -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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - const maxByHour = Math.max(1, ...byHour.map(h => h.orders)) - const maxByDow = Math.max(1, ...byWeekday.map(d => d.orders)) - - return ( -
- - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
-
- - - - s + h.orders, 0))} icon={TrendingUp} accent /> -
- -
- -
- - - - - - } cursor={{ fill: '#f1f5f9' }} /> - - - -
-
-
- -
- -
- {byWeekday.map((d) => { - const intensity = d.orders / maxByDow - return ( -
-
{d.label}
-
- 0.4 ? 'white' : '#334155' }}> - {d.orders} - -
-
- ) - })} -
-
-
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/restaurant/WorkDaySummary.jsx b/manager_dashboard/src/pages/reports/restaurant/WorkDaySummary.jsx deleted file mode 100644 index 9a63784..0000000 --- a/manager_dashboard/src/pages/reports/restaurant/WorkDaySummary.jsx +++ /dev/null @@ -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 ( - - ) - } - - function handleSave() { - if (!value) return - const iso = new Date(value).toISOString() - mut.mutate(iso) - } - - return ( - - 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)} - /> - - - - ) -} - -// ── 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 ( - <> - - {subtitle} - · - {timeRange} - {day.status === 'closed' && ( - setDay(d => ({ ...d, closed_at: updated.closed_at }))} /> - )} - - } - onClose={onClose} - > - {/* Tabs */} -
- {TABS.map(t => ( - - ))} -
- - {/* Orders tab */} - {tab === 'orders' && ( - orders.length === 0 - ?
Δεν βρέθηκαν παραγγελίες
- : - - #ΤραπέζιΆνοιξεΈκλεισε - ΕίδηΑκυρώσειςΣύνολοΚατάσταση - - - {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 ( - setDrillOrder(o)} className="cursor-pointer"> - #{o.id} - {o.table_name ?? o.table_id} - {fmtDateTime(o.opened_at)} - {o.closed_at ? fmtDateTime(o.closed_at) : '—'} - {totalQty} - - {cancelledQty > 0 - ? {cancelledQty} - : —} - - {fmtEUR(total)} - - - ) - })} - - - )} - - {/* Shifts tab */} - {tab === 'shifts' && ( - shifts.length === 0 - ?
Δεν βρέθηκαν βάρδιες
- : - - Σερβιτόρος - Έναρξη - Λήξη - Διάρκεια - Εισπράχθηκαν - Κατάσταση - - - - {shifts.map(s => ( - setDetailShift(s)} className="cursor-pointer"> - - {fmtDateTime(s.started_at)} - {s.ended_at ? fmtDateTime(s.ended_at) : — ενεργή —} - {fmtDuration(s.started_at, s.ended_at)} - {fmtEUR(s.total_collected)} - - -
- - {!s.is_active && ( - - )} -
- - - ))} - -
- )} -
- - {drillOrder && ( - setDrillOrder(null)} /> - )} - - {detailShift && ( - 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
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - }> - - - - -
- {chartData.length > 0 && ( - -
- - - - - '€' + v} /> - fmtEUR(v)} />} /> - {anyHasCost && } - - {anyHasCost && ( - - )} - - -
-
- )} - -
- - {days.length === 0 ? ( - - ) : ( - - - Εργάσιμη Μέρα - Άνοιξε - Έκλεισε - Διάρκεια - Παραγγελίες - Έσοδα - {anyHasCost && Κόστος} - {anyHasCost && Κέρδος} - Ακυρώσεις - Σερβιτόροι - Κατάσταση - - - - {days.map(d => { - const margin = d.revenue > 0 && (d.trackable_profit || 0) > 0 - ? ((d.trackable_profit / d.revenue) * 100).toFixed(0) + '%' - : null - return ( - setDrillDay(d)} striped> - {fmtDate(d.opened_at)} - {fmtTime(d.opened_at)} - {d.closed_at ? fmtTime(d.closed_at) : '—'} - {fmtDuration(d.opened_at, d.closed_at)} - {fmtNum(d.order_count)} - {fmtEUR(d.revenue)} - {anyHasCost && ( - - {(d.total_cost || 0) > 0 ? fmtEUR(d.total_cost) : —} - - )} - {anyHasCost && ( - - {(d.trackable_profit || 0) > 0 ? ( - - {fmtEUR(d.trackable_profit)} - {margin && !d.has_gap && ({margin})} - {d.has_gap && ⚠} - - ) : —} - - )} - {fmtNum(d.cancellation_count)} - {fmtNum(d.waiter_count)} - - - {d.status === 'closed' && ( - - )} - - - )})} - - - )} - -
-
- - {drillDay && ( - setDrillDay(null)} - onDeleteShift={s => setDeleteShift(s)} - /> - )} - - {deleteDay && ( - deleteDayMutation.mutate(deleteDay.id)} - onCancel={() => setDeleteDay(null)} - /> - )} - - {deleteShift && ( - deleteShiftMutation.mutate(deleteShift.id)} - onCancel={() => setDeleteShift(null)} - /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/store/DaysTab.jsx b/manager_dashboard/src/pages/reports/store/DaysTab.jsx new file mode 100644 index 0000000..9b896ce --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/DaysTab.jsx @@ -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 => {dateOf(d)} }, + { 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 => {fmt.formatMoney(d.revenue)} }, + { 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 ? {fmt.formatMoney(d.refunded)} : '') }, + ...(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 ? : '') }, + ] : []), + { 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 => {t(`reports.store.dayStatus.${d.status}`, { defaultValue: d.status })} }, + ...(owner ? [{ key: 'actions', label: '', sort: false, render: d => (d.status === 'closed' && !d.shift_count ? ( + { e.stopPropagation(); setDeleting(d) }}> + ) : 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 ( +
+ } /> + {isPending ? : error ? : (<> + {list.length > 1 && } + + + + )} + {day && setDay(null)} />} + {deleting && ( + setDeleting(null)} title={t('reports.store.deleteDayTitle', { day: dateOf(deleting) })} description={t('reports.store.deleteDayBody')} + footer={<> + + + } /> + )} + + ) +} + +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 => #{o.id} }, + { 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 ? ( + { e.stopPropagation(); setDropShift(s) }}>) : null) }] : []), + ] + + return ( + + {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 && ( + { setCloseAt(venueWallClock(new Date(day.closed_at), fmt.timeZone)); setEditing(true) }}> + )} + }> +
+ {editing && ( +
+ + + +
+ )} + + {['orders', 'shifts'].map(k => ( + + ))} + + {(tab === 'orders' ? loadingOrders : loadingShifts) ? : tab === 'orders' + ?
+ :
} + + {order && setOrder(null)} />} + {shift && setShift(null)} />} + {dropShift && ( + setDropShift(null)} title={t('reports.store.deleteShiftTitle', { name: dropShift.waiter_name })} description={t('reports.store.deleteShiftBody')} + footer={<> + + + } /> + )} + + ) +} diff --git a/manager_dashboard/src/pages/reports/store/OrdersTab.jsx b/manager_dashboard/src/pages/reports/store/OrdersTab.jsx new file mode 100644 index 0000000..b2c18e7 --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/OrdersTab.jsx @@ -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 => #{o.id} }, + { 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 ? {n} : '' } }, + { 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 ? {fmt.formatMoney(orderTotals(o).refunded)} : '') }, + { key: 'status', label: t('reports.status'), render: o => {t(`overview.orderStatus.${o.status}`, { defaultValue: o.status })} }, + ] + const total = rows.reduce((s, o) => s + orderTotals(o).revenue, 0) + + return ( +
+ } /> +
+ 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 }))]} /> +
+ + )} + {order && setOrder(null)} />} + + ) +} diff --git a/manager_dashboard/src/pages/reports/store/StorePage.jsx b/manager_dashboard/src/pages/reports/store/StorePage.jsx new file mode 100644 index 0000000..2766fb7 --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/StorePage.jsx @@ -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 +} diff --git a/manager_dashboard/src/pages/reports/store/TablesTab.jsx b/manager_dashboard/src/pages/reports/store/TablesTab.jsx new file mode 100644 index 0000000..9c1491d --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/TablesTab.jsx @@ -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 => {r.name} }, + { 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 => {fmt.formatMoney(r.revenue)} }, + { key: 'fees', label: t('reports.fees'), align: 'right', render: r => (r.fees ? fmt.formatMoney(r.fees) : '') }, + ] + return ( +
+ } onClick={() => setPrinting(true)}>{t('reports.print.button')}} /> + {isPending ? : error ? : (<> + +
r.table_id ?? 'none'} initialSort={{ key: 'revenue', dir: 'desc' }} /> + + {rows.length > 1 && ( + + 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 }))} /> + + )} + )} + {printing && setPrinting(false)} />} + + ) +} diff --git a/manager_dashboard/src/pages/reports/store/TrafficTab.jsx b/manager_dashboard/src/pages/reports/store/TrafficTab.jsx new file mode 100644 index 0000000..2028142 --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/TrafficTab.jsx @@ -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 ( +
+ + {isPending ? : error ? : (() => { + 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 (<> +
+ + + + {weekday(busyDay.day)} : '—'} /> +
+ + + 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 }) }))} /> + + ) + })()} +
+ ) +} diff --git a/manager_dashboard/src/pages/reports/store/TrendsTab.jsx b/manager_dashboard/src/pages/reports/store/TrendsTab.jsx new file mode 100644 index 0000000..a3c03d0 --- /dev/null +++ b/manager_dashboard/src/pages/reports/store/TrendsTab.jsx @@ -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 => {label(r.date)} }, + { key: 'orders', label: t('reports.orders'), align: 'right' }, + { key: 'revenue', label: t('reports.revenue'), align: 'right', render: r => {fmt.formatMoney(r.revenue)} }, + { 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 => }] : []), + ...(step === 'daily' ? [{ key: 'rolling7', label: t('reports.trends.avg7'), align: 'right', tip: t('reports.trends.avg7Tip'), render: r => fmt.formatMoney(r.rolling7) }] : []), + ] + return ( +
+ {STEPS.map(s => )}} /> + {isPending ? : error ? : (<> + {rows.length > 1 && ({ label: label(r.date), revenue: r.revenue, profit: r.profit }))} showProfit={anyProfit} />} +
r.date} initialSort={{ key: 'date', dir: 'desc' }} /> + )} + + ) +} diff --git a/manager_dashboard/tests/reports.test.mjs b/manager_dashboard/tests/reports.test.mjs index ee4c79a..fbfc368 100644 --- a/manager_dashboard/tests/reports.test.mjs +++ b/manager_dashboard/tests/reports.test.mjs @@ -2,7 +2,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { - addDays, dayChoices, defaultPeriod, hourSeries, margin, orderTotals, periodParams, periodSlug, quickRange, rangeProblem, ratio, sortRows, + addDays, dayChoices, defaultPeriod, hourSeries, margin, orderTotals, periodParams, periodSlug, printBody, quickRange, rangeProblem, ratio, sortRows, } from '../src/pages/reports/kit/reportLogic.js' test('periods: the default, quick ranges, the parameters sent (venue time), file names', () => { @@ -38,3 +38,8 @@ test('a day by the hour, an order\'s totals, business days newest first', () => assert.equal(orderTotals({ items: [{ status: 'paid', unit_price: 4, price_adjustment: -1, quantity: 2 }, { status: 'cancelled', unit_price: 9, quantity: 1 }] }).revenue, 6) assert.deepEqual(dayChoices([{ id: 1, opened_at: '2026-11-17' }, { id: 2, opened_at: '2026-11-19' }]).map(d => d.id), [2, 1]) }) + +test('a receipt-printer report gets the same period', () => { + assert.deepEqual(printBody({ mode: 'day', dayId: '7' }), { business_day_id: 7, from_dt: null, to_dt: null }) + assert.deepEqual(printBody({ mode: 'range', from: '2026-11-01', to: '2026-11-02' }), { business_day_id: null, from_dt: '2026-11-01T00:00:00', to_dt: '2026-11-02T23:59:59' }) +}) diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json index 51a2992..0528b02 100644 --- a/manager_dashboard/v2.json +++ b/manager_dashboard/v2.json @@ -1,9 +1,9 @@ { "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "paths": [ - "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today" + "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products" ], "strict": [ - "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today" + "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing", "src/pages/staff", "src/pages/schedule", "src/pages/reports/kit", "src/pages/reports/today", "src/pages/reports/store", "src/pages/reports/products" ] } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index 25a4a9c..a5e7cb8 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -2787,6 +2787,141 @@ "noCancels": "καμία", "orders_one": "{{count}} παραγγελία σήμερα", "orders_other": "{{count}} παραγγελίες σήμερα" + }, + "back": "Πίσω", + "save": "Αποθήκευση", + "cost": "Κόστος", + "orders": "Παραγγελίες", + "person": "Άτομο", + "print": { + "button": "Εκτύπωση", + "title": "Εκτύπωση σε εκτυπωτή αποδείξεων", + "kind": "Τι τυπώνεται", + "modes": { + "smart": "Σύνοψη", + "full": "Πλήρης" + }, + "modesHint": { + "smart": "Μόνο όσα πουλήθηκαν, τα περισσότερα πρώτα.", + "full": "Όλα τα προϊόντα, και όσα δεν πουλήθηκαν." + }, + "printer": "Εκτυπωτής", + "noPrinters": "Δεν υπάρχουν εκτυπωτές (Ρυθμίσεις → Εκτύπωση).", + "send": "Εκτύπωση", + "sent": "Στάλθηκε στον εκτυπωτή", + "page": "Εκτύπωση σελίδας", + "back": "Πίσω" + }, + "store": { + "title": "Κατάστημα", + "tabs": { + "days": "Εργάσιμες ημέρες", + "orders": "Παραγγελίες", + "traffic": "Κίνηση", + "trends": "Τάσεις", + "tables": "Τραπέζια" + }, + "day": "Ημέρα", + "hours": "Ώρες", + "cancelled": "Ακυρώσεις", + "staff": "Προσωπικό", + "noDays": "Δεν υπάρχουν εργάσιμες ημέρες σε αυτή την περίοδο.", + "dayStatus": { + "open": "Ανοιχτή", + "closed": "Κλειστή" + }, + "daysCount_one": "{{count}} εργάσιμη ημέρα", + "daysCount_other": "{{count}} εργάσιμες ημέρες", + "daysTip": "Κάθε ημέρα μετράει όλες τις παραγγελίες που άνοιξαν σε αυτή. Πατήστε μια ημέρα για παραγγελίες και βάρδιες.", + "revenueByDay": "Έσοδα ανά εργάσιμη ημέρα", + "deleteDay": "Διαγραφή ημέρας", + "deleteDayTitle": "Διαγραφή της εργάσιμης ημέρας {{day}};", + "deleteDayBody": "Διαγράφεται μόνο ημέρα χωρίς βάρδιες. Δεν αναιρείται.", + "deleteYes": "Οριστική διαγραφή", + "dayDeleted": "Η εργάσιμη ημέρα διαγράφηκε", + "dayTitle": "Εργάσιμη ημέρα · {{day}}", + "dayTabs": { + "orders_one": "{{count}} παραγγελία", + "orders_other": "{{count}} παραγγελίες", + "shifts_one": "{{count}} βάρδια", + "shifts_other": "{{count}} βάρδιες" + }, + "fixClose": "Διόρθωση ώρας κλεισίματος", + "closedAt": "Έκλεισε (ώρα καταστήματος)", + "closeFixed": "Η ώρα κλεισίματος διορθώθηκε", + "from": "Από", + "to": "Έως", + "working": "σε βάρδια", + "length": "Διάρκεια", + "collected": "Εισπράχθηκαν", + "deleteShift": "Διαγραφή βάρδιας", + "deleteShiftTitle": "Διαγραφή της βάρδιας: {{name}};", + "deleteShiftBody": "Η βάρδια και όλες οι παραγγελίες που άνοιξε αυτό το άτομο σε αυτή σβήνονται οριστικά και χάνονται από όλες τις αναφορές. Μόνο για λάθη και δοκιμές.", + "shiftDeleted": "Η βάρδια και οι παραγγελίες της διαγράφηκαν", + "anyStatus": "Κάθε κατάσταση", + "anyone": "Οποιοσδήποτε", + "anyTable": "Κάθε τραπέζι", + "cancelledLines": "Ακυρωμένες γραμμές", + "ordersCount_one": "{{count}} παραγγελία · {{total}}", + "ordersCount_other": "{{count}} παραγγελίες · {{total}}" + }, + "traffic": { + "orders": "Παραγγελίες", + "busiestHour": "Πιο πολυσύχναστη ώρα", + "quietestHour": "Πιο ήσυχη ώρα", + "quietTip": "από τις ώρες με παραγγελίες", + "busiestDay": "Πιο πολυσύχναστη ημέρα", + "ordersN_one": "{{count}} παραγγελία", + "ordersN_other": "{{count}} παραγγελίες", + "byWeekday": "Έσοδα ανά ημέρα εβδομάδας", + "byWeekdayTip": "Κατά εργάσιμη ημέρα: μια παραγγελία στη 01:30 του Σαββάτου μετράει την Παρασκευή." + }, + "trends": { + "title": "Έσοδα στον χρόνο", + "table": "Ανά περίοδο", + "when": "Περίοδος", + "steps": { + "daily": "Ημέρες", + "weekly": "Εβδομάδες", + "monthly": "Μήνες" + }, + "weekOf": "Εβδομάδα {{date}}", + "avg7": "Μέσος όρος 7 ημερών", + "avg7Tip": "Ο μέσος όρος εσόδων αυτής της ημέρας και των έξι προηγούμενων (με πωλήσεις)." + }, + "tables": { + "title": "Τραπέζια", + "tip": "Μόνο ολοκληρωμένες παραγγελίες: ο χρόνος στο τραπέζι είναι από το άνοιγμα ως το κλείσιμο.", + "avgTime": "Μέσος χρόνος", + "avgTimeTip": "Από το άνοιγμα της παραγγελίας ως το κλείσιμο.", + "minutes_one": "{{count}} λεπτό", + "minutes_other": "{{count}} λεπτά", + "perVisit": "Ανά επίσκεψη", + "top": "Τα τραπέζια με τα περισσότερα έσοδα" + }, + "prod": { + "title": "Προϊόντα", + "categories": "Κατηγορίες", + "category": "Κατηγορία", + "allCategories": "Όλες οι κατηγορίες", + "product": "Προϊόν", + "units": "Τεμάχια", + "kinds_one": "{{count}} προϊόν", + "kinds_other": "{{count}} προϊόντα", + "margin": "Περιθώριο", + "waste": "Απώλειες", + "wasteTip": "Πετάχτηκαν στην περίοδο (Απόθεμα → Απώλειες), με το κόστος τους.", + "share": "Μερίδιο εσόδων", + "profitShare": "Μερίδιο κέρδους", + "top": "Τα 10 πρώτα", + "by": { + "revenue": "Έσοδα", + "qty_sold": "Τεμάχια", + "trackable_profit": "Κέρδος" + }, + "all_one": "{{count}} προϊόν", + "all_other": "{{count}} προϊόντα", + "shareTitle": "Έσοδα ανά κατηγορία" } } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index 3bede7c..b878891 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -2787,6 +2787,141 @@ "noCancels": "none", "orders_one": "{{count}} order today", "orders_other": "{{count}} orders today" + }, + "back": "Back", + "save": "Save", + "cost": "Cost", + "orders": "Orders", + "person": "Person", + "print": { + "button": "Print", + "title": "Print on a receipt printer", + "kind": "What to print", + "modes": { + "smart": "Summary", + "full": "Full" + }, + "modesHint": { + "smart": "Only what sold, most first.", + "full": "Every product, unsold ones too." + }, + "printer": "Printer", + "noPrinters": "No printers (Settings → Printing).", + "send": "Print", + "sent": "Sent to the printer", + "page": "Print this page", + "back": "Back" + }, + "store": { + "title": "Venue", + "tabs": { + "days": "Business days", + "orders": "Orders", + "traffic": "Busy times", + "trends": "Trends", + "tables": "Tables" + }, + "day": "Day", + "hours": "Hours", + "cancelled": "Cancelled", + "staff": "Staff", + "noDays": "No business days in this period.", + "dayStatus": { + "open": "Open", + "closed": "Closed" + }, + "daysCount_one": "{{count}} business day", + "daysCount_other": "{{count}} business days", + "daysTip": "Each day counts every order opened in it. Tap a day for its orders and shifts.", + "revenueByDay": "Revenue by business day", + "deleteDay": "Delete this day", + "deleteDayTitle": "Delete the business day of {{day}}?", + "deleteDayBody": "Only an empty day (no shifts) can be deleted. It can't be undone.", + "deleteYes": "Delete for good", + "dayDeleted": "Business day deleted", + "dayTitle": "Business day · {{day}}", + "dayTabs": { + "orders_one": "{{count}} order", + "orders_other": "{{count}} orders", + "shifts_one": "{{count}} shift", + "shifts_other": "{{count}} shifts" + }, + "fixClose": "Correct the closing time", + "closedAt": "Closed at (venue time)", + "closeFixed": "Closing time corrected", + "from": "From", + "to": "To", + "working": "working", + "length": "Length", + "collected": "Collected", + "deleteShift": "Delete this shift", + "deleteShiftTitle": "Delete the shift of {{name}}?", + "deleteShiftBody": "The shift and every order that person opened during it are erased for good, and disappear from every report. Only for mistakes and tests.", + "shiftDeleted": "Shift and its orders deleted", + "anyStatus": "Any status", + "anyone": "Anyone", + "anyTable": "Any table", + "cancelledLines": "Cancelled lines", + "ordersCount_one": "{{count}} order · {{total}}", + "ordersCount_other": "{{count}} orders · {{total}}" + }, + "traffic": { + "orders": "Orders", + "busiestHour": "Busiest hour", + "quietestHour": "Quietest hour", + "quietTip": "of the hours with orders", + "busiestDay": "Busiest weekday", + "ordersN_one": "{{count}} order", + "ordersN_other": "{{count}} orders", + "byWeekday": "Revenue by weekday", + "byWeekdayTip": "By the business date: an order at 01:30 on Saturday counts on Friday." + }, + "trends": { + "title": "Revenue over time", + "table": "By period", + "when": "Period", + "steps": { + "daily": "Days", + "weekly": "Weeks", + "monthly": "Months" + }, + "weekOf": "Week of {{date}}", + "avg7": "7-day average", + "avg7Tip": "The average revenue of this day and the six before it (of the days with sales)." + }, + "tables": { + "title": "Tables", + "tip": "Finished orders only: the time at the table is from opening to closing.", + "avgTime": "Average time", + "avgTimeTip": "From the order's opening to its closing.", + "minutes_one": "{{count}} min", + "minutes_other": "{{count}} min", + "perVisit": "Per visit", + "top": "The tables that earn most" + }, + "prod": { + "title": "Products", + "categories": "Categories", + "category": "Category", + "allCategories": "All categories", + "product": "Product", + "units": "Units", + "kinds_one": "{{count}} product", + "kinds_other": "{{count}} products", + "margin": "Margin", + "waste": "Waste", + "wasteTip": "Thrown away in the period (Inventory → Throwaways), with its cost.", + "share": "Share of revenue", + "profitShare": "Share of profit", + "top": "Top 10", + "by": { + "revenue": "Revenue", + "qty_sold": "Units", + "trackable_profit": "Profit" + }, + "all_one": "{{count}} product", + "all_other": "{{count}} products", + "shareTitle": "Revenue by category" } } } diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index b7b6e29..867f23b 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -25,6 +25,8 @@ const term = await startTerminalVite({ port: 5188, backendUrl: backend.url }) const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {}) const r = reporter('manager: login + bootstrap on @xenia/api / @xenia/access') +const addDaysIso = (key, n) => new Date(Date.parse(`${key}T12:00:00Z`) + n * 86_400_000).toISOString().slice(0, 10) + async function api(method, url, { token, body } = {}) { const res = await fetch(backend.url + url, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, @@ -1186,8 +1188,34 @@ try { await page.waitForFunction(() => document.querySelector('[data-testid="report-today"] h1')?.textContent === 'Σήμερα', null, { timeout: 5000 }).catch(() => {}) r.check(`${rp} Today in Greek`, (await page.locator('[data-testid="report-today"] h1').textContent()) === 'Σήμερα' && (await todayRevenue.textContent()).includes('Έσοδα')) await page.screenshot({ path: path.join(OUT, 'manager-report-today-el.png'), fullPage: true }) + // 6.12b: the venue and products reports, still in Greek for one tab + await page.goto(`${APP}/reports/store?tab=traffic`) + r.check(`${rp} Venue → Busy times in Greek`, await page.getByTestId('traffic-weekdays').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false) + && (await page.locator('[data-testid="report-store"] h1').textContent()) === 'Κατάστημα') await page.getByTestId('user-menu').click() await page.getByRole('menuitemradio', { name: 'English' }).click() + await page.goto(`${APP}/reports/store`) + const dayRow = page.getByTestId('report-day').first() + r.check(`${rp} Venue → Business days lists the days`, await dayRow.waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)) + await dayRow.click() + r.check(`${rp} a day opens with its orders and shifts`, await page.getByTestId('report-day-dialog').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await page.screenshot({ path: path.join(OUT, 'manager-report-day.png'), fullPage: true }) + await page.keyboard.press('Escape') + for (const [tab, testId] of [['orders', 'report-order'], ['trends', 'trend-chart'], ['tables', 'report-period']]) { + await page.getByTestId(`report-tab-${tab}`).click() + r.check(`${rp} Venue → ${tab} opens`, await page.getByTestId(testId).first().waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)) + } + await page.goto(`${APP}/reports/products`) + const prodRevenue = page.getByTestId('products-revenue') + await prodRevenue.waitFor({ timeout: 10_000 }).catch(() => {}) + const venueDay = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Athens' }).format(new Date()) // the venue's date, as the page's default period + const perf = (await api('GET', `/api/reports/products/performance?from=${addDaysIso(venueDay, -29)}T00:00:00&to=${venueDay}T23:59:59`, { token: boss })).products + const perfTotal = perf.reduce((s, p) => s + p.revenue, 0) + r.check(`${rp} Products: the revenue is the backend's (no delivery-fee product)`, (await prodRevenue.textContent()).replace(/[\s,]/g, '').includes(perfTotal.toFixed(2)) + && !perf.some(p => /delivery|αποστολ/i.test(p.product_name)), `${perfTotal} vs ${await prodRevenue.textContent()}`) + await page.getByTestId('report-tab-categories').click() + r.check(`${rp} Products → Categories opens`, await page.getByTestId('categories-share').waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)) + await page.screenshot({ path: path.join(OUT, 'manager-report-categories.png'), fullPage: true }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await page.goto(`${APP}/online-orders`)