diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx index f1d369a..006893f 100644 --- a/manager_dashboard/src/App.jsx +++ b/manager_dashboard/src/App.jsx @@ -47,12 +47,12 @@ import StockPage from './pages/inventory/StockPage' // Reports import TodayPage from './pages/reports/today/TodayReport' import StorePage from './pages/reports/store/StorePage' -import StaffReportPage from './pages/reports/StaffReportPage' +import StaffReportPage from './pages/reports/staff/StaffReport' 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' -import MiscPage from './pages/reports/MiscPage' +import PrepZonesPage from './pages/reports/prepzones/PrepZonesReport' +import ExpensesReportPage from './pages/reports/expenses/ExpensesReport' +import TechnicalPage from './pages/reports/technical/TechnicalReport' +import MiscPage from './pages/reports/misc/MiscReport' // Other import { AppsPage, IntegrationsPage } from './pages/platform/ModulesPage' diff --git a/manager_dashboard/src/pages/reports/ExpensesReportPage.jsx b/manager_dashboard/src/pages/reports/ExpensesReportPage.jsx deleted file mode 100644 index 4a511f4..0000000 --- a/manager_dashboard/src/pages/reports/ExpensesReportPage.jsx +++ /dev/null @@ -1,439 +0,0 @@ -import { useState, useMemo } from 'react' -import { useQuery } from '@tanstack/react-query' -import { FileText, AlertCircle, CheckCircle, Clock } from 'lucide-react' -import client from '../../api/client' -import { FilterBar, FilterSelect } from './shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD } from './shared/TablePrimitives' -import StatCard from './shared/StatCard' -import EmptyState from './shared/EmptyState' -import SkeletonTable from './shared/SkeletonTable' -import { fmtEUR, fmtDate } from './shared/reportDesignTokens' - -const CATEGORY_LABELS = { - food: 'Τρόφιμα', - beverage: 'Ποτά', - supplies: 'Αναλώσιμα', - utilities: 'Κοινόχρηστα', - rent: 'Ενοίκιο', - salary: 'Μισθοί', - maintenance: 'Συντήρηση', - other: 'Άλλο', -} - -const STATUS_META = { - due: { label: 'Εκκρεμεί', bg: '#fef2f2', color: '#dc2626' }, - partial: { label: 'Μερική', bg: '#fff7ed', color: '#c2410c' }, - paid: { label: 'Πληρώθηκε', bg: '#eef7f0', color: '#1f7042' }, -} - -// 12 distinct colours for combined view supplier segments -const SUPPLIER_COLORS = [ - '#3b82f6','#10b981','#f59e0b','#ef4444','#8b5cf6', - '#06b6d4','#f97316','#84cc16','#ec4899','#14b8a6', - '#a78bfa','#fb923c', -] - -function fmtCat(cat) { - return CATEGORY_LABELS[cat] || cat || '—' -} - -// ── Breakdown section ───────────────────────────────────────────────────────── - -const BREAKDOWN_VIEWS = [ - { key: 'category', label: 'ΑΝΑ ΚΑΤΗΓΟΡΙΑ' }, - { key: 'contact', label: 'ΑΝΑ ΕΠΑΦΗ' }, - { key: 'combined', label: 'ΣΥΝΔΙΑΣΤΙΚΑ' }, -] - -function BreakdownToggle({ value, onChange }) { - return ( -
- {BREAKDOWN_VIEWS.map(v => ( - - ))} -
- ) -} - -function BreakdownByCategoryRow({ cat, total }) { - return ( -
-
{fmtCat(cat.category)}
-
-
0 ? (cat.total / total) * 100 : 0}%` }} /> -
-
-
{fmtEUR(cat.total)}
- {cat.due > 0 &&
{fmtEUR(cat.due)} εκκρεμεί
} -
-
- ) -} - -function BreakdownByContactRow({ name, total, due, grandTotal }) { - return ( -
-
{name}
-
-
0 ? (total / grandTotal) * 100 : 0}%`, - background: '#10b981', - }} /> -
-
-
{fmtEUR(total)}
- {due > 0 &&
{fmtEUR(due)} εκκρεμεί
} -
-
- ) -} - -function BreakdownCombinedRow({ cat, segments, supplierColorMap, grandTotal }) { - const catTotal = segments.reduce((s, sg) => s + sg.amount, 0) - if (catTotal === 0) return null - return ( -
-
{fmtCat(cat)}
-
- {segments.map(sg => ( - sg.amount > 0 ? ( -
0 ? (sg.amount / grandTotal) * 100 : 0}%`, - background: supplierColorMap[sg.name] || '#94a3b8', - transition: 'width 300ms', - }} - /> - ) : null - ))} -
-
-
{fmtEUR(catTotal)}
-
-
- ) -} - -function BreakdownSection({ expenses, summary }) { - const [view, setView] = useState('category') - - // By contact - const byContact = useMemo(() => { - const map = {} - for (const e of expenses) { - const key = e.contact_name || '(χωρίς προμηθευτή)' - if (!map[key]) map[key] = { name: key, total: 0, due: 0 } - map[key].total += e.total_amount - map[key].due += e.due_amount - } - return Object.values(map).sort((a, b) => b.total - a.total) - }, [expenses]) - - // By combined (category × contact stacked) - const { combinedRows, supplierColorMap, allSuppliers } = useMemo(() => { - const catMap = {} - const suppSet = new Set() - for (const e of expenses) { - const cat = e.category || 'other' - const supp = e.contact_name || '(χωρίς)' - suppSet.add(supp) - if (!catMap[cat]) catMap[cat] = {} - catMap[cat][supp] = (catMap[cat][supp] || 0) + e.total_amount - } - const allSupps = [...suppSet] - const colorMap = {} - allSupps.forEach((s, i) => { colorMap[s] = SUPPLIER_COLORS[i % SUPPLIER_COLORS.length] }) - - const rows = Object.entries(catMap) - .map(([cat, suppAmounts]) => ({ - cat, - segments: allSupps.map(s => ({ name: s, amount: suppAmounts[s] || 0 })), - })) - .sort((a, b) => { - const ta = a.segments.reduce((s, sg) => s + sg.amount, 0) - const tb = b.segments.reduce((s, sg) => s + sg.amount, 0) - return tb - ta - }) - - return { combinedRows: rows, supplierColorMap: colorMap, allSuppliers: allSupps } - }, [expenses]) - - const grandTotal = expenses.reduce((s, e) => s + e.total_amount, 0) - const catGrandTotal = (summary?.by_category || []).reduce((s, c) => s + c.total, 0) - - const hasData = expenses.length > 0 || (summary?.by_category?.length > 0) - if (!hasData) return null - - return ( -
-
-
-
- {view === 'category' ? 'Ανά Κατηγορία' : view === 'contact' ? 'Ανά Επαφή / Προμηθευτή' : 'Συνδιαστική Ανάλυση'} -
- -
- - {view === 'category' && ( -
- {(summary?.by_category || []) - .sort((a, b) => b.total - a.total) - .map(cat => ( - - ))} -
- )} - - {view === 'contact' && ( -
- {byContact.map(row => ( - - ))} - {byContact.length === 0 && ( -
Δεν υπάρχουν δεδομένα.
- )} -
- )} - - {view === 'combined' && ( - <> -
- {combinedRows.map(row => ( - - ))} - {combinedRows.length === 0 && ( -
Δεν υπάρχουν δεδομένα.
- )} -
- {allSuppliers.length > 0 && ( -
- {allSuppliers.map(s => ( -
-
- {s} -
- ))} -
- )} - - )} -
-
- ) -} - -// ── Detail modal ────────────────────────────────────────────────────────────── - -function ExpenseDetailModal({ expense, onClose }) { - return ( -
{ if (e.target === e.currentTarget) onClose() }} - > -
-
-
-
{expense.description}
-
{fmtCat(expense.category)} · {fmtDate(expense.created_at)}
-
- -
-
-
- {[ - { label: 'Σύνολο', value: fmtEUR(expense.total_amount), color: '#111315' }, - { label: 'Πληρώθηκε', value: fmtEUR(expense.paid_amount), color: '#1f7042' }, - { label: 'Εκκρεμεί', value: fmtEUR(expense.due_amount), color: expense.due_amount > 0 ? '#dc2626' : '#1f7042' }, - ].map(s => ( -
-
{s.label}
-
{s.value}
-
- ))} -
- - {expense.contact_name && ( -
- Προμηθευτής: {expense.contact_name} -
- )} - - {expense.due_date && ( -
- Ημ. λήξης: {fmtDate(expense.due_date)} -
- )} - - {expense.notes && ( -
- {expense.notes} -
- )} - - {expense.payments.length > 0 && ( -
-
Πληρωμές
-
- {expense.payments.map(p => ( -
- {fmtDate(p.paid_at)}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''} - {fmtEUR(p.amount)} -
- ))} -
-
- )} -
-
-
- ) -} - -// ── Main page ───────────────────────────────────────────────────────────────── - -export default function ExpensesPage() { - const [statusF, setStatusF] = useState('all') - const [categoryF, setCategoryF] = useState('all') - const [selectedExpense, setSelectedExpense] = useState(null) - - const queryParams = { - ...(statusF !== 'all' ? { status: statusF } : {}), - ...(categoryF !== 'all' ? { category: categoryF } : {}), - } - - const { data: expenses = [], isLoading, isError, refetch } = useQuery({ - queryKey: ['expenses-report', statusF, categoryF], - queryFn: () => client.get('/api/expenses/', { params: queryParams }).then(r => r.data), - staleTime: 30_000, - }) - - const { data: summary } = useQuery({ - queryKey: ['expenses-summary'], - queryFn: () => client.get('/api/expenses/summary').then(r => r.data), - staleTime: 30_000, - }) - - const allCategories = [...new Set(expenses.map(e => e.category).filter(Boolean))] - const categoryOptions = [ - { value: 'all', label: 'Όλες οι Κατηγορίες' }, - ...allCategories.map(c => ({ value: c, label: fmtCat(c) })), - ] - const statusOptions = [ - { value: 'all', label: 'Όλες Κατάσταση' }, - { value: 'due', label: 'Εκκρεμείς' }, - { value: 'partial', label: 'Μερική Πληρωμή' }, - { value: 'paid', label: 'Πληρωμένες' }, - ] - - const totalAmount = expenses.reduce((s, e) => s + e.total_amount, 0) - const paidAmount = expenses.reduce((s, e) => s + e.paid_amount, 0) - const dueAmount = expenses.reduce((s, e) => s + e.due_amount, 0) - const dueCount = expenses.filter(e => e.status !== 'paid').length - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
- -
-
- ) - - return ( -
- - - - - -
- {/* Summary stat cards */} -
- - - 0 ? `${dueCount} εκκρεμείς` : 'όλα πληρωμένα'} /> - -
- - - - {/* Expense list */} - - {expenses.length === 0 ? ( - - ) : ( - - - Περιγραφή - Κατηγορία - Προμηθευτής - Σύνολο - Εκκρεμεί - Κατάσταση - Ημερομηνία - - - {expenses.map(e => { - const meta = STATUS_META[e.status] || STATUS_META.due - return ( - setSelectedExpense(e)} - > - {e.description} - {fmtCat(e.category)} - {e.contact_name || '—'} - {fmtEUR(e.total_amount)} - 0 ? 'text-rose-600 font-semibold' : 'text-slate-400'}> - {e.due_amount > 0 ? fmtEUR(e.due_amount) : '—'} - - - - {meta.label} - - - {fmtDate(e.created_at)} - - ) - })} - - - )} - -
- - {selectedExpense && ( - setSelectedExpense(null)} /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/MiscPage.jsx b/manager_dashboard/src/pages/reports/MiscPage.jsx deleted file mode 100644 index 25649b7..0000000 --- a/manager_dashboard/src/pages/reports/MiscPage.jsx +++ /dev/null @@ -1,24 +0,0 @@ -import { useState } from 'react' -import { TabBar } from '../../ui/Tabs' -import CancellationsLog from './operations/CancellationsLog' -import DiscountsLog from './operations/DiscountsLog' - -const TABS = [ - { id: 'cancellations', label: 'Ακυρώσεις', Component: CancellationsLog }, - { id: 'discounts', label: 'Εκπτώσεις', Component: DiscountsLog }, -] - -export default function MiscPage() { - const [active, setActive] = useState('cancellations') - const tab = TABS.find(t => t.id === active) || TABS[0] - const { Component } = tab - - return ( -
- -
- -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/PrepZonesPage.jsx b/manager_dashboard/src/pages/reports/PrepZonesPage.jsx deleted file mode 100644 index f8ad3e6..0000000 --- a/manager_dashboard/src/pages/reports/PrepZonesPage.jsx +++ /dev/null @@ -1,524 +0,0 @@ -import { useState, useMemo } from 'react' -import { useQuery } from '@tanstack/react-query' -import { ConciergeBell, Printer, Download, PrinterIcon, X, ChevronDown, ChevronUp } from 'lucide-react' -import toast from 'react-hot-toast' -import client from '../../api/client' -import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from './shared/FilterBar' -import StatCard from './shared/StatCard' -import SkeletonTable from './shared/SkeletonTable' -import { DataTable, THead, TH, TR, TD } from './shared/TablePrimitives' -import { fmtNum, fmtEUR, fmtDate, 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) } - -// ── CSV export (client-side) ────────────────────────────────────────────────── - -function downloadCSV(filename, rows, headers) { - const escape = v => `"${String(v ?? '').replace(/"/g, '""')}"` - const lines = [ - headers.map(escape).join(','), - ...rows.map(r => r.map(escape).join(',')), - ] - const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8;' }) - const url = URL.createObjectURL(blob) - const a = document.createElement('a') - a.href = url; a.download = filename; a.click() - URL.revokeObjectURL(url) -} - -// ── Print modal ─────────────────────────────────────────────────────────────── - -function PrintModal({ zone, queryParams, periodLabel, onClose }) { - const [targetPrinter, setTargetPrinter] = useState('browser') - const [printing, setPrinting] = useState(false) - - const { data: printersData } = useQuery({ - queryKey: ['printers-list'], - queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), - staleTime: 60_000, - }) - const printers = printersData?.printers || [] - - const printerOptions = [ - { value: 'browser', label: 'Εκτύπωση μέσω browser (PDF)' }, - ...printers.map(p => ({ value: String(p.id), label: p.name })), - ] - - function handleBrowserPrint() { - const items = [...zone.all_products].sort((a, b) => b.count - a.count) - const totalItems = items.reduce((s, i) => s + i.count, 0) - - const rows = items.map(item => { - const dots = '.'.repeat(Math.max(2, 42 - item.name.length - String(item.count).length)) - return `${item.name}${dots} ${item.count}` - }).join('') - - const html = `Ζώνη: ${zone.name} - - -

ΖΩΝΗ ΠΡΟΕΤΟΙΜΑΣΙΑΣ: ${zone.name.toUpperCase()}

-
Περίοδος: ${periodLabel}
- - -${rows} - -
ΠροϊόνΠοσότητα
ΣΥΝΟΛΟ ΕΙΔΩΝ${totalItems}
-` - - const win = window.open('', '_blank', 'width=800,height=600') - win.document.write(html) - win.document.close() - win.focus() - win.print() - onClose() - } - - async function handleThermalPrint() { - setPrinting(true) - try { - const body = { - printer_id: parseInt(targetPrinter, 10), - zone_id: zone.id, - ...queryParams, - } - await client.post('/api/reports/print/prep-zone', body) - toast.success(`Αποστολή στον εκτυπωτή…`) - onClose() - } catch { - toast.error('Αποτυχία εκτύπωσης') - } finally { - setPrinting(false) - } - } - - const isBrowser = targetPrinter === 'browser' - - return ( -
{ if (e.target === e.currentTarget) onClose() }} - > -
-
-
-
Εκτύπωση Σύνοψης
-
Ζώνη: {zone.name} · {periodLabel}
-
- -
- -
- {/* Preview of shopping list */} -
- {zone.all_products.slice(0, 20).map(p => { - const dots = '.'.repeat(Math.max(2, 34 - p.name.length - String(p.count).length)) - return
{p.name}{dots}{p.count}
- })} - {zone.all_products.length > 20 && ( -
…+{zone.all_products.length - 20} ακόμα
- )} -
- - {/* Printer target */} -
- - -
- - {/* Action button */} - -
-
-
- ) -} - -// ── Zone multi-select filter ────────────────────────────────────────────────── - -function ZoneFilter({ zones, selected, onChange }) { - const allSelected = selected.length === 0 || selected.length === zones.length - - function toggleAll() { onChange([]) } - function toggle(id) { - if (allSelected) { - onChange([id]) - } else { - const next = selected.includes(id) ? selected.filter(z => z !== id) : [...selected, id] - onChange(next.length === zones.length ? [] : next) - } - } - - return ( -
- Ζώνες: - - {zones.map(z => { - const on = !allSelected && selected.includes(z.id) - return ( - - ) - })} -
- ) -} - -// ── Zone detail card ────────────────────────────────────────────────────────── - -function ZoneDetailCard({ zone, queryParams, periodLabel }) { - const [showPrintModal, setShowPrintModal] = useState(false) - const [ordersExpanded, setOrdersExpanded] = useState(false) - - function handleCSVItems() { - downloadCSV( - `prep-zone-${zone.name}-items.csv`, - zone.all_products.map(p => [p.name, p.count, p.value]), - ['Προϊόν', 'Ποσότητα', 'Αξία (€)'], - ) - } - - function handleCSVOrders() { - downloadCSV( - `prep-zone-${zone.name}-orders.csv`, - zone.all_orders.map(o => [o.order_id, o.table, o.opened_at ? new Date(o.opened_at).toLocaleString('el-GR') : '', o.items_count, o.value]), - ['Αρ. Παραγγελίας', 'Τραπέζι', 'Ώρα', 'Τεμάχια', 'Αξία (€)'], - ) - } - - return ( - <> -
- {/* Zone header bar */} -
-
-
- - {zone.name} - {zone.notification_name && zone.notification_name !== zone.name && ( - ({zone.notification_name}) - )} -
- {zone.printers.length > 0 && ( -
- - {zone.printers.map(p => p.name).join(', ')} -
- )} -
- -
- {/* Stats */} -
-
Συνολικά Είδη
-
{fmtNum(zone.item_count)}
-
-
-
Αξία
-
{fmtEUR(zone.total_value)}
-
- - {/* Actions */} -
- -
-
-
- - {zone.item_count === 0 ? ( -
- Δεν βρέθηκαν παραγγελίες για αυτή την ζώνη στο επιλεγμένο διάστημα. -
- ) : ( -
- {/* Items table */} -
-
- Είδη ({zone.all_products.length}) -
- -
- - - Προϊόν - Ποσότητα - Αξία - - - {zone.all_products.map((p, i) => ( - - {p.name} - {fmtNum(p.count)} - {fmtEUR(p.value)} - - ))} - - - - {/* Orders section */} -
- - {ordersExpanded && ( - - )} -
- {ordersExpanded && ( - - - # - Τραπέζι - Ώρα - Τεμάχια - Αξία - - - {zone.all_orders.map(o => ( - - #{o.order_id} - {o.table} - - {o.opened_at ? new Date(o.opened_at).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' }) : '—'} - - {fmtNum(o.items_count)} - {fmtEUR(o.value)} - - ))} - - - )} -
-
- )} -
- - {showPrintModal && ( - setShowPrintModal(false)} - /> - )} - - ) -} - -// ── Main page ───────────────────────────────────────────────────────────────── - -export default function PrepZonesPage() { - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - const [selectedZoneIds, setSelectedZoneIds] = useState([]) // [] = all - - const { data: bdData } = useQuery({ - queryKey: ['business-days-list'], - queryFn: () => client.get('/api/reports/business-days').then(r => r.data), - staleTime: 60_000, - }) - - 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: ['prep-zones-report', mode, from, to, businessDayId], - queryFn: () => client.get('/api/reports/prep-zones', { params: queryParams }).then(r => r.data), - staleTime: 60_000, - }) - - const bdOptions = [ - { value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, - ...((bdData?.business_days || []).map(bd => ({ - value: String(bd.id), - label: `${fmtDate(bd.opened_at)}`, - }))), - ] - - const allZones = data?.zones || [] - - const visibleZones = useMemo(() => { - if (selectedZoneIds.length === 0) return allZones - return allZones.filter(z => selectedZoneIds.includes(z.id)) - }, [allZones, selectedZoneIds]) - - const totalItems = visibleZones.reduce((s, z) => s + z.item_count, 0) - const totalValue = visibleZones.reduce((s, z) => s + z.total_value, 0) - const busyZone = visibleZones.reduce((best, z) => (!best || z.item_count > best.item_count ? z : best), null) - - const periodLabel = useMemo(() => { - if (mode === 'workday' && businessDayId !== 'all') { - const bd = (bdData?.business_days || []).find(b => String(b.id) === businessDayId) - return bd ? fmtDate(bd.opened_at) : `Εργάσιμη #${businessDayId}` - } - return `${from} – ${to}` - }, [mode, businessDayId, from, to, bdData]) - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
- -
-
- ) - - return ( -
- - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - - {/* Zone multi-select */} - {allZones.length > 1 && ( -
- -
- )} - -
- {/* Summary stats */} -
- - - -
- - {allZones.length === 0 ? ( -
- -

Δεν βρέθηκαν ζώνες προετοιμασίας

-

Δημιουργήστε ζώνες από το Management → Prep Zones.

-
- ) : ( -
- {visibleZones.map(zone => ( - - ))} -
- )} -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/StaffReportPage.jsx b/manager_dashboard/src/pages/reports/StaffReportPage.jsx deleted file mode 100644 index a943411..0000000 --- a/manager_dashboard/src/pages/reports/StaffReportPage.jsx +++ /dev/null @@ -1,37 +0,0 @@ -import { useState } from 'react' -import { useNavigate } from 'react-router-dom' -import { TabBar } from '../../ui/Tabs' -import ShiftsOverview from './staff/ShiftsOverview' -import Payments from './staff/Payments' -import Activity from './staff/Activity' -import StaffLeaderboard from './staff/StaffLeaderboard' - -const TABS = [ - { id: 'shifts', label: 'Βάρδιες', Component: ShiftsOverview }, - { id: 'payments', label: 'Πληρωμές', Component: Payments }, - { id: 'activity', label: 'Δραστηριότητα', Component: Activity }, - { id: 'leaderboard', label: 'Κατάταξη', Component: StaffLeaderboard }, -] - -export default function StaffReportPage() { - const [active, setActive] = useState('shifts') - const navigate = useNavigate() - const tab = TABS.find(t => t.id === active) || TABS[0] - const { Component } = tab - - // ShiftsOverview uses onNavigate to drill into order history — redirect to Store page - function handleNavigate({ parent, sub, ...rest }) { - if (parent === 'restaurant' && sub === 'orders') { - navigate('/reports/store') - } - } - - return ( -
- -
- -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/TechnicalPage.jsx b/manager_dashboard/src/pages/reports/TechnicalPage.jsx deleted file mode 100644 index 6fe195d..0000000 --- a/manager_dashboard/src/pages/reports/TechnicalPage.jsx +++ /dev/null @@ -1,30 +0,0 @@ -import { useState } from 'react' -import { TabBar } from '../../ui/Tabs' -import PrinterHistory from './operations/PrinterHistory' -import PrinterHealthLog from './operations/PrinterHealthLog' -import LogsPanel from './operations/LogsPanel' -import { useCan } from '@xenia/access' -import { useTranslation } from '@xenia/i18n' - -const TABS = [ - { id: 'printer-history', label: 'Ιστορικό Εκτυπωτή', Component: PrinterHistory }, - { id: 'printer-health', label: 'Υγεία Εκτυπωτή', Component: PrinterHealthLog }, -] - -export default function TechnicalPage() { - const { t } = useTranslation('manager') - const canLogs = useCan('core.settings.manage') // the files carry names and IPs: owner-level - const tabs = canLogs ? [...TABS, { id: 'logs', label: t('logs.tab'), Component: LogsPanel }] : TABS - const [active, setActive] = useState('printer-history') - const tab = tabs.find(x => x.id === active) || tabs[0] - const { Component } = tab - - return ( -
- -
- -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/expenses/ExpensesReport.jsx b/manager_dashboard/src/pages/reports/expenses/ExpensesReport.jsx new file mode 100644 index 0000000..f9cd6aa --- /dev/null +++ b/manager_dashboard/src/pages/reports/expenses/ExpensesReport.jsx @@ -0,0 +1,96 @@ +// Reports → Expenses (plan step 6.12c; replaces the v1 expenses report): what the venue spent in +// a period (by the day each expense was entered), paid and still due; split by category or by +// supplier; every expense, a tap shows its payments. Entering expenses is Finance → Expenses. +import { useState } from 'react' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog, Select } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { Pill } from '../../overview/parts' +import { BarList } from '../kit/charts' +import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts' +import { PeriodPicker } from '../kit/Period' +import { defaultPeriod } from '../kit/reportLogic' + +const STATUS_TONE = { paid: 'success', partial: 'warning', due: 'danger' } +const CATEGORIES = ['supplier', 'utilities', 'rent', 'maintenance', 'staff', 'equipment', 'other'] // as Finance → Expenses saves them (models/expenses.py) + +export default function ExpensesReport() { + const { t } = useTranslation('manager') + return +} + +function Expenses() { + const { t } = useTranslation('manager') + const fmt = useFormat() + const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday())) + const [status, setStatus] = useState('') + const [category, setCategory] = useState('') + const [split, setSplit] = useState('category') + const [open, setOpen] = useState(null) + const params = { ...(status ? { status } : {}), ...(category ? { category } : {}) } + const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-expenses', params], queryFn: () => client.get('/api/expenses/', { params }).then(r => r.data) }) + const catName = c => t(`reports.exp.categories.${c}`, { defaultValue: c }) + const inPeriod = e => { const d = fmt.venueDateKey(e.created_at); return (!period.from || d >= period.from) && (!period.to || d <= period.to) } + const rows = (data ?? []).filter(inPeriod) + const sum = k => rows.reduce((s, e) => s + (e[k] ?? 0), 0) + const groups = Object.values(rows.reduce((m, e) => { + const k = split === 'category' ? e.category : (e.contact_name || t('reports.exp.noSupplier')) + m[k] = m[k] ?? { key: k, label: split === 'category' ? catName(k) : k, value: 0, due: 0 } + m[k].value += e.total_amount + m[k].due += e.due_amount + return m + }, {})).sort((a, b) => b.value - a.value) + const columns = [ + { key: 'created_at', label: t('reports.exp.date'), render: e => fmt.formatDate(e.created_at) }, + { key: 'description', label: t('reports.exp.what'), render: e => {e.description} }, + { key: 'category', label: t('reports.prod.category'), sort: e => catName(e.category), render: e => catName(e.category) }, + { key: 'contact_name', label: t('reports.exp.supplier'), render: e => e.contact_name || '' }, + { key: 'total_amount', label: t('reports.exp.total'), align: 'right', render: e => fmt.formatMoney(e.total_amount) }, + { key: 'due_amount', label: t('reports.exp.due'), align: 'right', render: e => (e.due_amount ? {fmt.formatMoney(e.due_amount)} : '') }, + { key: 'status', label: t('reports.status'), render: e => {t(`reports.exp.status.${e.status}`, { defaultValue: e.status })} }, + ] + return ( +
+ + setCategory(e.target.value)} aria-label={t('reports.prod.category')} + options={[{ value: '', label: t('reports.prod.allCategories') }, ...CATEGORIES.map(c => ({ value: c, label: catName(c) }))]} /> + } /> + {isPending ? : error ? : (<> +
+ + + +
+ {groups.length > 0 && ( + {['category', 'supplier'].map(s => ( + ))}}> + fmt.formatMoney(v)} rows={groups.map(g => ({ ...g, sub: g.due ? t('reports.exp.dueSub', { amount: fmt.formatMoney(g.due) }) : undefined }))} /> + + )} + + + + )} + {open && ( + setOpen(null)} title={open.description} + description={`${catName(open.category)}${open.contact_name ? ` · ${open.contact_name}` : ''} · ${fmt.formatDate(open.created_at)}`} + footer={}> +
+

{t('reports.exp.total')}: {fmt.formatMoney(open.total_amount)} · {t('reports.exp.paid')}: {fmt.formatMoney(open.paid_amount)}{open.due_amount ? <> · {t('reports.exp.due')}: {fmt.formatMoney(open.due_amount)} : null}

+ {open.due_date &&

{t('reports.exp.dueDate', { date: fmt.formatDate(open.due_date) })}

} + {open.notes &&

{open.notes}

} +

{t('reports.exp.payments')}

+ {open.payments?.length ? ( +
    + {open.payments.map(p =>
  • {fmt.formatDate(p.paid_at)}{p.paid_by_name ? ` · ${p.paid_by_name}` : ''}{p.notes ? ` · ${p.notes}` : ''}{fmt.formatMoney(p.amount)}
  • )} +
+ ) :

{t('reports.exp.noPayments')}

} +
+
+ )} + + ) +} diff --git a/manager_dashboard/src/pages/reports/kit/reportLogic.js b/manager_dashboard/src/pages/reports/kit/reportLogic.js index 4da754d..c57b54c 100644 --- a/manager_dashboard/src/pages/reports/kit/reportLogic.js +++ b/manager_dashboard/src/pages/reports/kit/reportLogic.js @@ -85,3 +85,27 @@ export function orderTotals(o) { /** The business days list → choices for a select, newest first (label filled by the page). */ export const dayChoices = (days = []) => [...days].sort((a, b) => (b.opened_at ?? '').localeCompare(a.opened_at ?? '')) + +/** A CSV built in the browser with the server's Excel rules (services/csv_export.py): a UTF-8 + * mark; for Greek, ';' between columns and decimal commas. rows: arrays of cells. */ +export function csvText(header, rows, language = 'en') { + const [sep, dec] = language === 'el' ? [';', ','] : [',', '.'] + const cell = v => { + let s = v == null ? '' : typeof v === 'number' ? (Number.isInteger(v) ? String(v) : v.toFixed(2).replace('.', dec)) : String(v) + if (s.includes(sep) || s.includes('"') || s.includes('\n')) s = `"${s.replace(/"/g, '""')}"` + return s + } + return String.fromCharCode(0xFEFF) + [header, ...rows].map(r => r.map(cell).join(sep)).join('\r\n') +} + +/** Download text as a file. */ +export function download(text, filename) { + const url = URL.createObjectURL(new Blob([text], { type: 'text/csv;charset=utf-8' })) + const a = document.createElement('a') + a.href = url + a.download = filename + document.body.appendChild(a) + a.click() + a.remove() + setTimeout(() => URL.revokeObjectURL(url), 1000) +} diff --git a/manager_dashboard/src/pages/reports/misc/MiscReport.jsx b/manager_dashboard/src/pages/reports/misc/MiscReport.jsx new file mode 100644 index 0000000..4fc1569 --- /dev/null +++ b/manager_dashboard/src/pages/reports/misc/MiscReport.jsx @@ -0,0 +1,104 @@ +// Reports → Cancellations and discounts (plan step 6.12c; replaces the v1 "misc" logs): every +// cancelled line (what, how much, who sent it, who cancelled it, why) and every discount given +// (on what, how much, by whom, why), with totals per person; exports for Excel. +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 { ExportButton, Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts' +import { PeriodPicker } from '../kit/Period' +import { defaultPeriod, periodParams, periodSlug } from '../kit/reportLogic' + +export default function MiscReport() { + const { t } = useTranslation('manager') + const tabs = [ + { id: 'cancellations', label: t('reports.misc.cancellations'), Component: CancellationsTab }, + { id: 'discounts', label: t('reports.misc.discounts'), Component: DiscountsTab }, + ] + return +} + +function CancellationsTab() { + 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-cancellations', params], queryFn: () => client.get('/api/reports/cancellations', { params }).then(r => r.data) }) + const rows = data?.cancellations ?? [] + const byPerson = Object.values(rows.reduce((m, c) => { + const k = c.cancelled_by || c.waiter_name || '—' + m[k] = m[k] ?? { key: k, label: k, value: 0, n: 0 } + m[k].value += c.value + m[k].n += 1 + return m + }, {})) + const columns = [ + { key: 'cancelled_at', label: t('reports.misc.when'), render: c => fmt.formatDateTime(c.cancelled_at, 'datetimeShort') }, + { key: 'product_name', label: t('reports.prod.product'), render: c => {c.product_name} }, + { key: 'quantity', label: t('reports.prod.units'), align: 'right', render: c => fmt.formatNumber(c.quantity, { maxDecimals: 3 }) }, + { key: 'value', label: t('reports.misc.value'), align: 'right', render: c => fmt.formatMoney(c.value) }, + { key: 'table', label: t('reports.place') }, + { key: 'waiter_name', label: t('reports.misc.sentBy') }, + { key: 'cancelled_by', label: t('reports.misc.cancelledBy') }, + { key: 'cancel_reason', label: t('reports.misc.reason'), render: c => c.cancel_reason || '' }, + ] + return ( +
+ } /> + {isPending ? : error ? : (<> +
+ + +
+ {byPerson.length > 1 && ( + + fmt.formatMoney(v)} rows={byPerson.sort((a, b) => b.value - a.value).map(p => ({ ...p, sub: t('reports.misc.lines', { count: p.n }) }))} /> + + )} + +
+ + )} + + ) +} + +function DiscountsTab() { + 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-discounts', params], queryFn: () => client.get('/api/reports/discounts', { params }).then(r => r.data) }) + const rows = data?.discounts ?? [] + const columns = [ + { key: 'applied_at', label: t('reports.misc.when'), render: d => fmt.formatDateTime(d.applied_at, 'datetimeShort') }, + { key: 'order_id', label: '#', render: d => #{d.order_id} }, + { key: 'table_name', label: t('reports.place'), render: d => d.table_name || t('reports.noTable') }, + { key: 'discount_value', label: t('reports.misc.discount'), align: 'right', + render: d => (d.discount_type === 'percent' ? `${fmt.formatNumber(d.discount_value, { maxDecimals: 1 })}%` : fmt.formatMoney(d.discount_value)) }, + { key: 'discount_amount', label: t('reports.misc.amount'), align: 'right', render: d => {fmt.formatMoney(d.discount_amount)} }, + { key: 'order_total_before', label: t('reports.misc.before'), align: 'right', render: d => (d.order_total_before != null ? fmt.formatMoney(d.order_total_before) : '') }, + { key: 'applied_by_name', label: t('reports.misc.givenBy') }, + { key: 'reason', label: t('reports.misc.reason'), render: d => d.reason || '' }, + ] + return ( +
+ + {isPending ? : error ? : (<> +
+ + +
+ {data.by_waiter?.length > 0 && ( + + fmt.formatMoney(v)} rows={data.by_waiter.map(w => ({ key: w.waiter_id, label: w.waiter_name, value: w.total_value, sub: t('reports.misc.times', { count: w.count }) }))} /> + + )} + +
+ + )} + + ) +} diff --git a/manager_dashboard/src/pages/reports/operations/CancellationsLog.jsx b/manager_dashboard/src/pages/reports/operations/CancellationsLog.jsx deleted file mode 100644 index 22ad8a8..0000000 --- a/manager_dashboard/src/pages/reports/operations/CancellationsLog.jsx +++ /dev/null @@ -1,116 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { XCircle, TrendingDown, Repeat, CheckCircle2 } from 'lucide-react' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar } from '../shared/TablePrimitives' -import StatCard from '../shared/StatCard' -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) } - -export default function CancellationsLog() { - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - const [waiterF, setWaiterF] = useState('all') - - const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').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' } : {}), - ...(waiterF !== 'all' ? { waiter_id: waiterF } : {}), - } - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['cancellations', mode, from, to, businessDayId, waiterF], - queryFn: () => client.get('/api/reports/cancellations', { 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 bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))] - - const cancellations = data?.cancellations || [] - const totalValue = data?.total_value || 0 - - const itemCounts = {} - cancellations.forEach(c => { itemCounts[c.product_name] = (itemCounts[c.product_name] || 0) + c.quantity }) - const topItem = Object.entries(itemCounts).sort((a, b) => b[1] - a[1])[0] - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - - -
-
- - - -
- - - {cancellations.length === 0 ? ( - - ) : ( - <> - -
- - - - - {cancellations.map(c => ( - - - - - - - - - - - ))} - - - - - - - - )} - - - - ) -} diff --git a/manager_dashboard/src/pages/reports/operations/DiscountsLog.jsx b/manager_dashboard/src/pages/reports/operations/DiscountsLog.jsx deleted file mode 100644 index b2b74fe..0000000 --- a/manager_dashboard/src/pages/reports/operations/DiscountsLog.jsx +++ /dev/null @@ -1,191 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { Tag } from 'lucide-react' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar } from '../shared/TablePrimitives' -import StatCard from '../shared/StatCard' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import { fmtEUR, fmtNum, fmtDate, fmtTime, 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) } - -export default function DiscountsLog() { - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - const [waiterF, setWaiterF] = useState('all') - - const { data: waitersData } = useQuery({ - queryKey: ['meta-waiters'], - queryFn: () => client.get('/api/reports/meta/waiters').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' } : {}), - ...(waiterF !== 'all' ? { applied_by: waiterF } : {}), - } - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['discounts', mode, from, to, businessDayId, waiterF], - queryFn: () => client.get('/api/reports/discounts', { 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 bdOptions = [ - { value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, - ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` }))), - ] - - const discounts = data?.discounts || [] - const byWaiter = data?.by_waiter || [] - const totalValue = data?.total_discount_value ?? 0 - const orderCount = data?.order_count ?? 0 - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
- -
-
- ) - - return ( -
- - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - - -
- {/* Summary cards */} -
- - - -
- - {/* By waiter summary */} - {byWaiter.length > 1 && ( - - -
- - - - - - - {byWaiter.map(w => ( - - - - - - - ))} - - - - )} - - {/* Full log */} - - {discounts.length === 0 ? ( - - ) : ( - - - - - - - - - - - - {discounts.map(d => { - const typeLabel = d.discount_type === 'percent' - ? `${d.discount_value}%` - : fmtEUR(d.discount_value) - const isItemLevel = d.item_id != null - return ( - - - - - - - - - - ) - })} - - {discounts.length > 1 && ( - - - - - - - )} - - )} - - - - ) -} diff --git a/manager_dashboard/src/pages/reports/operations/PrinterHealthLog.jsx b/manager_dashboard/src/pages/reports/operations/PrinterHealthLog.jsx deleted file mode 100644 index 0748c3a..0000000 --- a/manager_dashboard/src/pages/reports/operations/PrinterHealthLog.jsx +++ /dev/null @@ -1,110 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, StatusBadge } from '../shared/TablePrimitives' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import ExportButton from '../shared/ExportButton' -import { 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) } - -export default function PrinterHealthLog() { - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [printerF, setPrinterF] = useState('all') - - const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').then(r => r.data), staleTime: 5 * 60 * 1000 }) - - const queryParams = { - from: from + 'T00:00:00', - to: to + 'T23:59:59', - ...(printerF !== 'all' ? { printer_id: printerF } : {}), - } - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['printer-health', from, to, printerF], - queryFn: () => client.get('/api/reports/printers/history', { params: queryParams }).then(r => r.data), - staleTime: 60 * 1000, - }) - - const printerOptions = [{ value: 'all', label: 'Όλοι οι Εκτυπωτές' }, ...((printersData?.printers || []).map(p => ({ value: String(p.id), label: p.name })))] - - const logs = data?.logs || [] - const succeeded = logs.filter(j => j.success).length - const failed = logs.filter(j => !j.success).length - const rate = logs.length ? (succeeded / logs.length * 100) : 100 - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - }> - - - - - -
-
-
-
-
Επιτυχημένες
-
{fmtNum(succeeded)}
-
-
-
Αποτυχημένες
-
{fmtNum(failed)}
-
-
-
Επιτυχία %
-
{rate.toFixed(1)}%
-
-
-
- - - {logs.length === 0 ? ( - - ) : ( - <> - -
- - - - {logs.slice(0, 100).map(j => ( - - - - - - - - ))} - - - {logs.length > 100 && ( -
- Εμφάνιση πρώτων 100 από {logs.length} εργασίες. -
- )} - - )} - - - - ) -} diff --git a/manager_dashboard/src/pages/reports/operations/PrinterHistory.jsx b/manager_dashboard/src/pages/reports/operations/PrinterHistory.jsx deleted file mode 100644 index 825eb70..0000000 --- a/manager_dashboard/src/pages/reports/operations/PrinterHistory.jsx +++ /dev/null @@ -1,530 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { Printer, AlertCircle, Hash, Euro, 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, StatusBadge } from '../shared/TablePrimitives' -import StatCard from '../shared/StatCard' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import ExportButton from '../shared/ExportButton' -import { fmtNum, fmtEUR, fmtDate, fmtTime, 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) } - -// ─── Print Summary Modal ──────────────────────────────────────────────────── - -const PRINT_TYPES = [ - { - id: 'quick', - label: 'Γρήγορη Σύνοψη', - desc: 'Συγκεντρωτικά στατιστικά — λίγο χαρτί', - }, - { - id: 'orders', - label: 'Όλες οι Παραγγελίες', - desc: 'Κάθε παραγγελία με σύνολο, χωρίς ανάλυση ειδών', - }, - { - id: 'detailed', - label: 'Πλήρης Ανάλυση', - desc: 'Κάθε παραγγελία + όλα τα είδη — καταναλώνει πολύ χαρτί', - }, -] - -function PrintSummaryModal({ onClose, logs, stats, printers, printerF, queryParams }) { - const [printType, setPrintType] = useState('quick') - const [targetPrinter, setTargetPrinter] = useState('browser') - const [itemBreakdown, setItemBreakdown] = useState(false) - const [printing, setPrinting] = useState(false) - - const printerOptions = [ - { value: 'browser', label: 'Εκτύπωση μέσω browser' }, - ...printers.map(p => ({ value: String(p.id), label: p.name })), - ] - - async function handlePrint() { - if (targetPrinter !== 'browser') { - await handleThermalPrint() - return - } - handleBrowserPrint() - } - - async function handleThermalPrint() { - const printerTargetId = printerF === 'all' ? 0 : parseInt(printerF, 10) - - const body = { - printer_target_id: printerTargetId, - printer_id: parseInt(targetPrinter, 10), - mode: printType, - item_breakdown: itemBreakdown, - } - - if (queryParams.business_day_id) { - body.business_day_id = parseInt(queryParams.business_day_id, 10) - } else { - body.from_dt = queryParams.from || (new Date(Date.now() - 30 * 86400000).toISOString().slice(0, 10) + 'T00:00:00') - body.to_dt = queryParams.to || (new Date().toISOString().slice(0, 10) + 'T23:59:59') - } - - setPrinting(true) - try { - await client.post('/api/reports/print/printer', body) - toast.success('Η εκτύπωση στάλθηκε στον εκτυπωτή') - onClose() - } catch { - toast.error('Αποτυχία αποστολής στον εκτυπωτή') - } finally { - setPrinting(false) - } - } - - function handleBrowserPrint() { - const win = window.open('', '_blank', 'width=820,height=750') - if (!win) { onClose(); return } - - // ── Group logs by printer ────────────────────────────────────────────── - // For "all printers" we produce one section per printer. - // For a single selected printer the single section is the same format. - const printerMap = {} - for (const j of logs) { - const key = j.printer_name - if (!printerMap[key]) { - printerMap[key] = { name: key, printJobs: 0, orderIds: new Set(), totalItems: 0, totalValue: 0, orders: [] } - } - const g = printerMap[key] - g.printJobs += 1 - g.orderIds.add(j.order_id) - const itemQty = (j.items || []).reduce((s, i) => s + i.quantity, 0) - g.totalItems += itemQty - if (j.order_total != null) g.totalValue += j.order_total - g.orders.push(j) - } - - // De-dup order totals per printer group (same order_id → count once) - for (const g of Object.values(printerMap)) { - const seen = {} - g.totalValue = 0 - for (const j of g.orders) { - if (j.success && j.order_total != null && !seen[j.order_id]) { - seen[j.order_id] = true - g.totalValue += j.order_total - } - } - } - - const groups = Object.values(printerMap) - const filterLabel = printerF === 'all' - ? 'Όλοι οι Εκτυπωτές' - : (printers.find(p => String(p.id) === printerF)?.name || printerF) - - // ── Period label ─────────────────────────────────────────────────────── - let periodRow = '' - if (queryParams.business_day_id) { - periodRow = `
Εργάσιμη Μέρα${stats.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}
` - } - - // ── Titles per mode ──────────────────────────────────────────────────── - const titles = { - quick: 'Γρήγορη Ανάλυση Εκτυπώσεων', - orders: 'Ανάλυση Εκτυπώσεων με Παραγγελίες', - detailed: 'Αναλυτικό Ιστορικό Εκτυπώσεων', - } - - // ── Render one printer block ─────────────────────────────────────────── - function renderPrinterBlock(g) { - const orderCount = g.orderIds.size - const statsBlock = ` -
- Εκτυπωτής${g.name} -
-
-
Εκτυπώσεις${fmtNum(g.printJobs)}
-
Παραγγελίες${fmtNum(orderCount)}
-
Είδη${fmtNum(g.totalItems)}
-
Αξία Ειδών${fmtEUR(g.totalValue)}
- ` - - if (printType === 'quick') { - return `
${statsBlock}
` - } - - if (printType === 'orders') { - // Unique orders only - const seenOrders = {} - const orderLines = g.orders - .filter(j => j.success) - .filter(j => { if (seenOrders[j.order_id]) return false; seenOrders[j.order_id] = true; return true }) - .map(j => { - const itemQty = (j.items || []).reduce((s, i) => s + i.quantity, 0) - return `
- #${j.order_id} · ${j.table || '—'} - ${itemQty} είδη - ${j.order_total != null ? fmtEUR(j.order_total) : '—'} -
` - }).join('') - return `
${statsBlock}
${orderLines}
` - } - - // detailed — full log, each entry is a print job - const jobBlocks = g.orders.map(j => { - const result = j.success ? '✓ Επιτυχία' : '✗ Αποτυχία' - const itemRows = (j.items || []).map(i => - `
${i.name}×${i.quantity}
` - ).join('') - return ` -
-
- #${j.order_id} · ${j.table || '—'} - ${fmtDateTime(j.printed_at)} · ${result} -
- ${itemRows} - ${j.order_total != null ? `
Σύνολο Παραγγελίας${fmtEUR(j.order_total)}
` : ''} -
` - }).join('') - - return `
${statsBlock}
${jobBlocks}
` - } - - // ── Summary footer (multi-printer only) ─────────────────────────────── - function renderSummary() { - if (groups.length <= 1) return '' - const totJobs = groups.reduce((s, g) => s + g.printJobs, 0) - const totOrders = groups.reduce((s, g) => s + g.orderIds.size, 0) - const totItems = groups.reduce((s, g) => s + g.totalItems, 0) - const totValue = groups.reduce((s, g) => s + g.totalValue, 0) - return ` -
-
Σύνολο Όλων των Εκτυπωτών
-
Εκτυπώσεις${fmtNum(totJobs)}
-
Παραγγελίες${fmtNum(totOrders)}
-
Είδη${fmtNum(totItems)}
-
Αξία Ειδών${fmtEUR(totValue)}
-
` - } - - // ── Product breakdown (optional) ─────────────────────────────────────── - function renderItemBreakdown() { - if (!itemBreakdown) return '' - // Merge item counts across all printer groups - const combined = {} - for (const g of groups) { - for (const j of g.orders) { - if (!j.success) continue - for (const i of (j.items || [])) { - if (!combined[i.name]) combined[i.name] = { qty: 0 } - combined[i.name].qty += i.quantity - } - } - } - if (!Object.keys(combined).length) return '' - const sorted = Object.entries(combined).sort((a, b) => b[1].qty - a[1].qty) - return ` -
-
Ανάλυση Προϊόντων
- ${sorted.map(([name, d]) => ` -
- ${name} - ${d.qty} -
`).join('')} -
` - } - - const styles = ` - - ` - - const htmlBody = ` -

${titles[printType] || 'Αναφορά Εκτυπωτή'}

-
-
Εκτυπωτής${filterLabel}
- ${periodRow} -
Σύνολο Εγγραφών${logs.length}
-
- ${groups.map(renderPrinterBlock).join('')} - ${renderSummary()} - ${renderItemBreakdown()} - ` - - win.document.write(`Ιστορικό Εκτυπωτή${styles}${htmlBody}`) - win.document.close() - win.focus() - win.print() - onClose() - } // end handleBrowserPrint - - return ( -
{ if (e.target === e.currentTarget) onClose() }} - > -
-
-

Εκτύπωση Σύνοψης

- -
- -
-
-
Τύπος Εκτύπωσης
-
- {PRINT_TYPES.map(pt => ( - - ))} -
-
- - - -
-
Εκτυπωτής Προορισμού
-
- - -
-
- -
- - -
-
-
-
- ) -} - -// ─── Main Component ───────────────────────────────────────────────────────── - -export default function PrinterHistory() { - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - const [printerF, setPrinterF] = useState('all') - const [showPrintModal, setShowPrintModal] = useState(false) - - const { data: printersData } = useQuery({ queryKey: ['meta-printers'], queryFn: () => client.get('/api/reports/meta/printers').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' } : {}), - ...(printerF !== 'all' ? { printer_id: printerF } : {}), - } - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['printer-history', mode, from, to, businessDayId, printerF], - queryFn: () => client.get('/api/reports/printers/history', { params: queryParams }).then(r => r.data), - staleTime: 60 * 1000, - }) - - const printers = printersData?.printers || [] - const printerOptions = [{ value: 'all', label: 'Όλοι οι Εκτυπωτές' }, ...printers.map(p => ({ value: String(p.id), label: p.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 logs = data?.logs || [] - const total = data?.total || 0 - const failed = data?.failed || 0 - // total_amount comes pre-computed from the backend (unique orders, no double-counting reprints) - const totalAmount = data?.total_amount ?? null - - // Derived stats for StatCards + Print modal - const itemCounts = {} - const waiterCounts = {} - let totalItemQty = 0 - - logs.forEach(l => { - if (l.waiter) waiterCounts[l.waiter] = (waiterCounts[l.waiter] || 0) + 1 - ;(l.items || []).forEach(i => { - itemCounts[i.name] = (itemCounts[i.name] || 0) + i.quantity - totalItemQty += i.quantity - }) - }) - - const topItem = Object.entries(itemCounts).sort((a, b) => b[1] - a[1])[0] - const periodLabel = mode === 'workday' - ? (bdOptions.find(o => o.value === businessDayId)?.label || 'Εργάσιμη Μέρα') - : `${fmtDateStr(from)} → ${fmtDateStr(to)}` - - const stats = { total, failed, totalAmount, itemCounts, waiterCounts, totalItemQty, periodLabel, topItem } - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - -
- }> - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - - -
-
- - 0 ? 'ελέγξτε τον εκτυπωτή' : 'όλα καλά'} icon={AlertCircle} /> - - -
- - - {logs.length === 0 ? ( - - ) : ( - <> - -
- - - - {logs.slice(0, 100).map(j => ( - - - - - - - - - ))} - - - {logs.length > 100 && ( -
- Εμφάνιση πρώτων 100 από {logs.length} εργασίες. -
- )} - - )} - - - - {showPrintModal && ( - setShowPrintModal(false)} - logs={logs} - stats={stats} - printers={printers} - printerF={printerF} - queryParams={queryParams} - /> - )} - - ) -} diff --git a/manager_dashboard/src/pages/reports/prepzones/PrepZonesReport.jsx b/manager_dashboard/src/pages/reports/prepzones/PrepZonesReport.jsx new file mode 100644 index 0000000..915e33e --- /dev/null +++ b/manager_dashboard/src/pages/reports/prepzones/PrepZonesReport.jsx @@ -0,0 +1,106 @@ +// Reports → Prep zones (plan step 6.12c; replaces the v1 prep zones report): what each zone (the +// kitchen, the bar…) prepared in a period — items, their value, every product with its count and +// every order — so the owner sees each station's load. Download a zone's products or orders for +// Excel, or print a zone's summary on a receipt printer. +import { useState } from 'react' +import { ChevronDown, ChevronRight, Download, Printer } from 'lucide-react' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, cx } from '@xenia/ui' +import client from '../../../api/client' +import { useLiveQuery } from '../../../live/useLiveQuery' +import { Pill } from '../../overview/parts' +import { BarList } from '../kit/charts' +import { Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts' +import { PeriodPicker } from '../kit/Period' +import PrintDialog from '../kit/PrintDialog' +import { csvText, defaultPeriod, download, periodParams, periodSlug, printBody } from '../kit/reportLogic' + +export default function PrepZonesReport() { + const { t } = useTranslation('manager') + return +} + +function Zones() { + const { t } = useTranslation('manager') + const fmt = useFormat() + const [period, setPeriod] = useState(() => defaultPeriod(fmt.venueToday())) + const [only, setOnly] = useState([]) // zone ids shown; [] = all + const params = periodParams(period) + const { data, isPending, error, refetch } = useLiveQuery({ queryKey: ['report-prep-zones', params], queryFn: () => client.get('/api/reports/prep-zones', { params }).then(r => r.data.zones) }) + const zones = data ?? [] + const shown = only.length ? zones.filter(z => only.includes(z.id)) : zones + const toggle = id => setOnly(o => (o.includes(id) ? o.filter(x => x !== id) : [...o, id])) + return ( +
+ + {isPending ? : error ? : (<> + {zones.length > 1 && ( +
+ + {zones.map(z => ( + + ))} +
+ )} + {zones.length > 1 && ( + + fmt.formatNumber(v, { maxDecimals: 3 })} rows={shown.map(z => ({ key: z.id, label: z.name, value: z.item_count, sub: fmt.formatMoney(z.total_value) }))} /> + + )} + {shown.map(z => )} + )} +
+ ) +} + +function ZoneCard({ zone: z, period }) { + const { t, i18n } = useTranslation('manager') + const fmt = useFormat() + const [orders, setOrders] = useState(false) + const [printing, setPrinting] = useState(false) + const lang = i18n.language + const slug = `${z.name}-${periodSlug(period)}`.replace(/[^\p{L}\p{N}_-]+/gu, '-') + const products = () => download(csvText([t('reports.prod.product'), t('reports.prod.units'), t('reports.misc.value')], z.all_products.map(p => [p.name, p.count, p.value]), lang), `zone-products-${slug}.csv`) + const ordersCsv = () => download(csvText(['#', t('reports.place'), t('reports.opened'), t('reports.prod.units'), t('reports.misc.value')], + z.all_orders.map(o => [o.order_id, o.table, fmt.formatDateTime(o.opened_at, 'datetimeShort'), o.items_count, o.value]), lang), `zone-orders-${slug}.csv`) + const productCols = [ + { key: 'name', label: t('reports.prod.product'), render: p => {p.name} }, + { key: 'count', label: t('reports.prod.units'), align: 'right', render: p => fmt.formatNumber(p.count, { maxDecimals: 3 }) }, + { key: 'value', label: t('reports.misc.value'), align: 'right', render: p => fmt.formatMoney(p.value) }, + ] + const orderCols = [ + { key: 'order_id', label: '#', render: o => #{o.order_id} }, + { key: 'table', label: t('reports.place') }, + { key: 'opened_at', label: t('reports.opened'), render: o => fmt.formatDateTime(o.opened_at, 'datetimeShort') }, + { key: 'items_count', label: t('reports.prod.units'), align: 'right', render: o => fmt.formatNumber(o.items_count, { maxDecimals: 3 }) }, + { key: 'value', label: t('reports.misc.value'), align: 'right', render: o => fmt.formatMoney(o.value) }, + ] + return ( + {z.name} + {z.notification_name && {z.notification_name}} + {z.printers.map(p => )}} + actions={ + + + + }> +
+ + + +
+
ΏραΠαραγγελία #ΤραπέζιΣερβιτόροςΕίδοςΑξίαΑκυρώθηκε απόΛόγος
{fmtDateTime(c.cancelled_at)}#{c.order_id}{c.table}{c.product_name} ×{c.quantity}{fmtEUR(c.value)}{c.cancelled_by || —}{c.cancel_reason || —}
Σύνολο Ακυρωθέντων{fmtEUR(totalValue)} -
ΣερβιτόροςΑριθμόςΣύνολοΜέσος / Έκπτωση
{fmtNum(w.count)}{fmtEUR(w.total_value)}{fmtEUR(w.count > 0 ? w.total_value / w.count : 0)}
Ημ/νίαΠαραγγελίαΣερβιτόροςΤύποςΤιμή πρινΠοσό ΈκπτωσηςΑιτία
{fmtDateTime(d.applied_at)} - - #{d.order_id} - {d.table_name && · {d.table_name}} - - {isItemLevel && ( - ΑΝΤΙΚ. - )} - - - {typeLabel} - - - {d.order_total_before != null ? fmtEUR(d.order_total_before) : '—'} - - − {fmtEUR(d.discount_amount)} - - {d.reason || —} -
Σύνολο− {fmtEUR(totalValue)} -
ΏραΕκτυπωτήςΠαραγγελία #ΑποτέλεσμαΣφάλμα
{fmtDateTime(j.printed_at)}{j.printer_name}#{j.order_id} - {j.error_message || —} -
Ώρα ΕκτύπωσηςΕκτυπωτήςΠαραγγελία #ΤραπέζιΕίδηΑποτέλεσμα
{fmtDateTime(j.printed_at)}{j.printer_name}#{j.order_id}{j.table} - {(j.items || []).slice(0, 3).map((i, idx) => ( - {i.name} ×{i.quantity}{idx < Math.min((j.items || []).length, 3) - 1 ? ', ' : ''} - ))} - {(j.items || []).length > 3 && +{(j.items || []).length - 3} ακόμα} -
p.name} initialSort={{ key: 'count', dir: 'desc' }} empty={t('reports.zones.nothing')} /> + {z.all_orders.length > 0 && ( +
+ + {orders &&
o.order_id} initialSort={{ key: 'opened_at', dir: 'desc' }} />} + + )} + {printing && setPrinting(false)} />} + + ) +} diff --git a/manager_dashboard/src/pages/reports/shared/DrillDownModal.jsx b/manager_dashboard/src/pages/reports/shared/DrillDownModal.jsx deleted file mode 100644 index bd4db50..0000000 --- a/manager_dashboard/src/pages/reports/shared/DrillDownModal.jsx +++ /dev/null @@ -1,47 +0,0 @@ -import { useEffect } from 'react' -import { X, ChevronLeft } from 'lucide-react' - -export default function DrillDownModal({ title, subtitle, onClose, onBack, children }) { - useEffect(() => { - const onKey = (e) => { if (e.key === 'Escape') onClose() } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [onClose]) - - return ( -
-
e.stopPropagation()} - > -
-
- {onBack && ( - - )} -
-
{title}
- {subtitle &&
{subtitle}
} -
-
- -
-
{children}
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/EmptyState.jsx b/manager_dashboard/src/pages/reports/shared/EmptyState.jsx deleted file mode 100644 index d9e3334..0000000 --- a/manager_dashboard/src/pages/reports/shared/EmptyState.jsx +++ /dev/null @@ -1,14 +0,0 @@ -import { Inbox } from 'lucide-react' - -export default function EmptyState({ icon: Icon = Inbox, title, description, action }) { - return ( -
-
- -
-
{title}
- {description &&
{description}
} - {action &&
{action}
} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/ExportButton.jsx b/manager_dashboard/src/pages/reports/shared/ExportButton.jsx deleted file mode 100644 index 450140f..0000000 --- a/manager_dashboard/src/pages/reports/shared/ExportButton.jsx +++ /dev/null @@ -1,42 +0,0 @@ -import { useState } from 'react' -import { Download, Loader2 } from 'lucide-react' -import toast from 'react-hot-toast' -import client from '../../../api/client' - -export default function ExportButton({ endpoint, params = {}, filename = 'export.csv' }) { - const [loading, setLoading] = useState(false) - - async function handleClick() { - setLoading(true) - try { - const response = await client.get(endpoint, { - params, - responseType: 'blob', - }) - const url = URL.createObjectURL(response.data) - const a = document.createElement('a') - a.href = url - a.download = filename - a.click() - URL.revokeObjectURL(url) - } catch { - toast.error('Αποτυχία εξαγωγής') - } finally { - setLoading(false) - } - } - - return ( - - ) -} diff --git a/manager_dashboard/src/pages/reports/shared/FilterBar.jsx b/manager_dashboard/src/pages/reports/shared/FilterBar.jsx deleted file mode 100644 index 04f5c8f..0000000 --- a/manager_dashboard/src/pages/reports/shared/FilterBar.jsx +++ /dev/null @@ -1,347 +0,0 @@ -import { useState, useRef, useEffect, useCallback } from 'react' -import { INPUT_CLASS } from '../../../ui/tokens' - -export function FilterBar({ children, right }) { - return ( -
-
{children}
- {right &&
{right}
} -
- ) -} - -// ── Searchable custom dropdown ───────────────────────────────────────────────── - -export function FilterSelect({ value, onChange, options, label, icon: Icon }) { - const [open, setOpen] = useState(false) - const [query, setQuery] = useState('') - const containerRef = useRef(null) - const inputRef = useRef(null) - const listRef = useRef(null) - - const selected = options.find(o => o.value === value) - - const filtered = query.trim() - ? options.filter(o => o.label.toLowerCase().includes(query.toLowerCase())) - : options - - // Close on outside click - useEffect(() => { - function handler(e) { - if (containerRef.current && !containerRef.current.contains(e.target)) { - setOpen(false) - setQuery('') - } - } - if (open) document.addEventListener('mousedown', handler) - return () => document.removeEventListener('mousedown', handler) - }, [open]) - - // Focus search input when opening - useEffect(() => { - if (open && inputRef.current) inputRef.current.focus() - }, [open]) - - function handleSelect(val) { - onChange(val) - setOpen(false) - setQuery('') - } - - function handleKeyDown(e) { - if (e.key === 'Escape') { setOpen(false); setQuery('') } - } - - // Dropdown position: flip up if near bottom of viewport - const [dropUp, setDropUp] = useState(false) - const openDropdown = useCallback(() => { - if (containerRef.current) { - const rect = containerRef.current.getBoundingClientRect() - setDropUp(rect.bottom + 280 > window.innerHeight) - } - setOpen(true) - }, []) - - return ( -
- {/* Trigger button */} - - - {/* Dropdown panel */} - {open && ( -
- {/* Search box — only shown when there are enough options */} - {options.length > 6 && ( -
-
- - - - setQuery(e.target.value)} - placeholder="Αναζήτηση…" - className="flex-1 bg-transparent text-[12px] text-slate-700 placeholder-slate-400 outline-none" - /> - {query && ( - - )} -
-
- )} - - {/* Options list */} -
    - {filtered.length === 0 ? ( -
  • Δεν βρέθηκαν αποτελέσματα
  • - ) : ( - filtered.map(o => { - const isActive = o.value === value - return ( -
  • - -
  • - ) - }) - )} -
-
- )} -
- ) -} - -// ── Date input ───────────────────────────────────────────────────────────────── - -const GR_MONTHS = ['Ιανουάριος','Φεβρουάριος','Μάρτιος','Απρίλιος','Μάιος','Ιούνιος','Ιούλιος','Αύγουστος','Σεπτέμβριος','Οκτώβριος','Νοέμβριος','Δεκέμβριος'] -const GR_DAYS = ['Κυ','Δε','Τρ','Τε','Πε','Πα','Σα'] - -function fmtGR(value) { - if (!value) return '' - const [y, m, d] = value.split('-') - if (!y || !m || !d) return value - return `${d}/${m}/${y}` -} - -function CalendarDropdown({ value, onCommit, onClose }) { - const today = new Date() - const initYear = value ? parseInt(value.slice(0, 4)) : today.getFullYear() - const initMonth = value ? parseInt(value.slice(5, 7)) - 1 : today.getMonth() - - const [viewYear, setViewYear] = useState(initYear) - const [viewMonth, setViewMonth] = useState(initMonth) - - const selectedY = value ? parseInt(value.slice(0, 4)) : null - const selectedM = value ? parseInt(value.slice(5, 7)) - 1 : null - const selectedD = value ? parseInt(value.slice(8, 10)) : null - - function prevMonth(e) { - e.stopPropagation() - if (viewMonth === 0) { setViewMonth(11); setViewYear(y => y - 1) } - else setViewMonth(m => m - 1) - } - function nextMonth(e) { - e.stopPropagation() - if (viewMonth === 11) { setViewMonth(0); setViewYear(y => y + 1) } - else setViewMonth(m => m + 1) - } - - // Build grid: first cell = weekday of 1st of month (0=Sun) - const firstDow = new Date(viewYear, viewMonth, 1).getDay() - const daysInMonth = new Date(viewYear, viewMonth + 1, 0).getDate() - const cells = [] - for (let i = 0; i < firstDow; i++) cells.push(null) - for (let d = 1; d <= daysInMonth; d++) cells.push(d) - - function selectDay(e, day) { - e.stopPropagation() - const mm = String(viewMonth + 1).padStart(2, '0') - const dd = String(day).padStart(2, '0') - onCommit(`${viewYear}-${mm}-${dd}`) - onClose() - } - - const todayY = today.getFullYear() - const todayM = today.getMonth() - const todayD = today.getDate() - - return ( -
e.preventDefault()} - onClick={e => e.stopPropagation()} - > - {/* Month navigation */} -
- - - {GR_MONTHS[viewMonth]} {viewYear} - - -
- - {/* Day-of-week headers */} -
- {GR_DAYS.map(d => ( -
{d}
- ))} -
- - {/* Day cells */} -
- {cells.map((day, i) => { - if (!day) return
- const isSelected = day === selectedD && viewMonth === selectedM && viewYear === selectedY - const isToday = day === todayD && viewMonth === todayM && viewYear === todayY - return ( - - ) - })} -
-
- ) -} - -export function FilterDateInput({ value, onChange, label }) { - const [open, setOpen] = useState(false) - const containerRef = useRef(null) - - useEffect(() => { - if (!open) return - function handler(e) { - if (containerRef.current && !containerRef.current.contains(e.target)) { - setOpen(false) - } - } - document.addEventListener('mousedown', handler) - return () => document.removeEventListener('mousedown', handler) - }, [open]) - - return ( -
- - - {open && ( - setOpen(false)} - /> - )} -
- ) -} - -// ── Work Day / Date Range toggle ─────────────────────────────────────────────── - -export function WorkDayDateToggle({ mode, onChange }) { - return ( -
- {[ - { id: 'workday', label: 'Εργάσιμη Μέρα' }, - { id: 'range', label: 'Εύρος Ημερομηνιών' }, - ].map((opt) => ( - - ))} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/OrderDetailModal.jsx b/manager_dashboard/src/pages/reports/shared/OrderDetailModal.jsx deleted file mode 100644 index c553ae6..0000000 --- a/manager_dashboard/src/pages/reports/shared/OrderDetailModal.jsx +++ /dev/null @@ -1,320 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { X } from 'lucide-react' -import { fmtEUR, fmtDateTime } from './reportDesignTokens' -import client from '../../../api/client' - -// ── Status badge ──────────────────────────────────────────────────────────── -const STATUS_META = { - active: { label: 'Ενεργό', bg: '#eff6ff', text: '#1d4ed8' }, - paid: { label: 'Πληρωμένο', bg: '#f0fdf4', text: '#15803d' }, - cancelled: { label: 'Ακυρωμένο', bg: '#fef2f2', text: '#b91c1c' }, - closed: { label: 'Κλειστό (απλήρωτο)', bg: '#fffbeb', text: '#b45309' }, - open: { label: 'Ανοιχτή', bg: '#eff6ff', text: '#1d4ed8' }, - partially_paid: { label: 'Μερική πλ.', bg: '#fffbeb', text: '#b45309' }, -} -function StatusPill({ status }) { - const m = STATUS_META[status] || { label: status, bg: '#f9fafb', text: '#374151' } - return ( - - {m.label} - - ) -} - -// ── Payment method chip ───────────────────────────────────────────────────── -const PAY_METHOD_STYLES = { - cash: { label: 'ΜΕΤΡΗΤΑ', color: '#15803d', bg: '#f0fdf4', border: '#86efac' }, - card: { label: 'ΚΑΡΤΑ', color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' }, - transfer: { label: 'ΤΡΑΠΕΖΙΚΗ', color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' }, - treat: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' }, - comp: { label: 'ΚΕΡΑΣΤΗΚΕ', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' }, -} -function PayMethodChip({ method }) { - if (!method) return — - const s = PAY_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' } - return ( - - {s.label} - - ) -} - -// ── Audit event labels ────────────────────────────────────────────────────── -const EVENT_LABELS = { - ORDER_OPENED: { label: 'Άνοιγμα', bg: '#eff6ff', text: '#1d4ed8' }, - ITEMS_ADDED: { label: 'Προσθήκη', bg: '#eff6ff', text: '#1d4ed8' }, - PAYMENT: { label: 'Πληρωμή', bg: '#f0fdf4', text: '#15803d' }, - PAYMENT_OFFLINE: { label: 'Πληρωμή (Offline)', bg: '#fffbeb', text: '#b45309' }, - ORDER_CLOSED: { label: 'Κλείσιμο', bg: '#f9fafb', text: '#374151' }, - ORDER_CANCELLED: { label: 'Ακύρωση', bg: '#fef2f2', text: '#b91c1c' }, - ITEM_CANCELLED: { label: 'Ακύρωση αντ.', bg: '#fef2f2', text: '#b91c1c' }, - PAYMENT_REVERTED:{ label: 'Αναίρεση Πληρωμής', bg: '#fffbeb', text: '#b45309' }, -} - -function AuditTimeline({ logs, itemsById }) { - if (!logs || logs.length === 0) { - return

Δεν υπάρχουν εγγραφές

- } - return ( -
- {logs.map(log => { - const meta = EVENT_LABELS[log.event_type] || { label: log.event_type, bg: '#f9fafb', text: '#374151' } - const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true - const displayTime = log.offline_at ? fmtDateTime(log.offline_at) : fmtDateTime(log.created_at) - - let itemNames = [] - if (log.item_ids && itemsById) { - try { - const ids = JSON.parse(log.item_ids) - itemNames = ids.map(id => { - const item = itemsById[id] - return item ? `${item.product?.name ?? `#${item.product_id}`} ×${item.quantity}` : null - }).filter(Boolean) - } catch { /* ignore */ } - } - - return ( -
-
- - {meta.label} - - {isDuplicate &&
ΔΙΠΛΗ
} -
-
-
- {log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '—')} - {log.amount != null && ( - - {fmtEUR(log.amount)} - - )} - {log.payment_method && } -
- {itemNames.length > 0 && ( -
- {itemNames.map((name, i) => ( - - {name} - - ))} -
- )} -
-
- {displayTime} - {log.offline_at &&
offline
} -
-
- ) - })} -
- ) -} - -// ── Items tab ─────────────────────────────────────────────────────────────── -function ItemsTab({ order, priceEventsMap = {} }) { - const itemsFiltered = order.items || [] - const billableItems = itemsFiltered.filter(i => i.status !== 'cancelled') - const effPrice = i => (i.unit_price ?? 0) + (i.price_adjustment ?? 0) - const closedTotal = billableItems.filter(i => i.status === 'closed').reduce((s, i) => s + effPrice(i) * i.quantity, 0) - const total = billableItems.reduce((s, i) => s + effPrice(i) * i.quantity, 0) - - if (itemsFiltered.length === 0) { - return

Κανένα αντικείμενο

- } - - // Column widths: [item info] [ordered by] [paid by] [pay type] [total] - const GRID = '1fr 150px 150px 110px 80px' - - const EVENT_COLORS = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' } - - return ( -
- {/* Header */} -
- Προϊόν - Παρήγγειλε - Πλήρωσε - Τρόπος - Σύνολο -
- - {itemsFiltered.map(item => { - const isCancelled = item.status === 'cancelled' - const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0) - const isDealItem = !!item.deal_id - const itemEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type)) - return ( -
-
- {/* Item info */} -
-
- {item.product?.name ?? `#${item.product_id}`} - {isDealItem && ΔΩΡΕΑΝ} -
-
- ×{item.quantity} - {fmtEUR(effPrice(item))} - {hasPriceAdj && ( - {fmtEUR(item.unit_price)} - )} - -
- {itemEvents.map((ev, ei) => { - const evColor = EVENT_COLORS[ev.event_type] || '#8a9099' - const evLabel = ev.modifier_name || ev.deal_name || (ev.event_type === 'waiter_discount' ? 'Έκπτωση' : ev.event_type === 'free_item_added' ? 'Δωρεάν' : ev.event_type) - return ( -
- ↳ - {evLabel} - {ev.delta_amount != null && {ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €} -
- ) - })} -
- - {/* Ordered by */} -
-
{item.added_by_name ?? '—'}
- {item.added_at &&
{fmtDateTime(item.added_at)}
} -
- - {/* Paid by */} -
- {item.paid_by_name - ? <> -
{item.paid_by_name}
- {item.paid_at &&
{fmtDateTime(item.paid_at)}
} - - : — - } -
- - {/* Pay type */} -
- -
- - {/* Total */} -
- {fmtEUR(effPrice(item) * item.quantity)} -
-
-
- ) - })} - - {/* Totals footer */} -
- {closedTotal > 0 && ( - - Απλήρωτα κλειστά: {fmtEUR(closedTotal)} - - )} - Σύνολο - {fmtEUR(total)} -
-
- ) -} - -// ── Main modal ────────────────────────────────────────────────────────────── -export default function OrderDetailModal({ order, onClose }) { - const [tab, setTab] = useState('items') - - const { data: rawPriceEvents = [] } = useQuery({ - queryKey: ['price-events', order?.id], - queryFn: () => client.get(`/api/pricing/events/order/${order.id}`).then(r => r.data), - enabled: !!order?.id, - staleTime: 60_000, - }) - const priceEventsMap = rawPriceEvents.reduce((acc, ev) => { - if (!acc[ev.order_item_id]) acc[ev.order_item_id] = [] - acc[ev.order_item_id].push(ev) - return acc - }, {}) - - if (!order) return null - - const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i])) - - const TABS = [ - { key: 'items', label: `Αντικείμενα (${(order.items || []).length})` }, - { key: 'audit', label: 'Ιστορικό Συναλλαγών' }, - ] - - return ( -
-
e.stopPropagation()} - > - {/* Header */} -
-
-
- Παραγγελία #{order.id} - -
-
- {order.table_name ? `Τραπέζι ${order.table_name}` : order.table_id ? `Τραπέζι #${order.table_id}` : ''} - {order.notes && · Σημ: {order.notes}} -
-
- -
- - {/* Opener / closer strip */} -
- {[ - { label: 'Άνοιξε', name: order.opened_by_name, time: order.opened_at }, - { label: 'Έκλεισε', name: order.closed_by_name, time: order.closed_at }, - ].map(cell => ( -
-
{cell.label}
-
{cell.name ?? '—'}
- {cell.time &&
{fmtDateTime(cell.time)}
} -
- ))} -
- - {/* Tabs */} -
- {TABS.map(t => ( - - ))} -
- - {/* Tab content */} -
- {tab === 'items' && } - {tab === 'audit' && } -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/ShiftDetailModal.jsx b/manager_dashboard/src/pages/reports/shared/ShiftDetailModal.jsx deleted file mode 100644 index 4ea3ab7..0000000 --- a/manager_dashboard/src/pages/reports/shared/ShiftDetailModal.jsx +++ /dev/null @@ -1,431 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { X } from 'lucide-react' -import client from '../../../api/client' -import { fmtEUR, fmtDateTime, fmtTime, fmtDate } from './reportDesignTokens' - -function fmtDur(ms) { - const totalMin = Math.round(ms / 60000) - const h = Math.floor(totalMin / 60) - const m = totalMin % 60 - return h > 0 ? `${h}ω ${m}λ` : `${m}λ` -} - -// ── Breaks timeline bar ────────────────────────────────────────────────────── -function BreaksTimeline({ started_at, ended_at, breaks }) { - if (!breaks || breaks.length === 0) return null - - const start = new Date(started_at).getTime() - const end = ended_at ? new Date(ended_at).getTime() : Date.now() - const total = end - start - if (total <= 0) return null - - return ( -
-
- Διαλείμματα -
-
- {/* work = whole bar base */} - {breaks.map((b, i) => { - const bs = new Date(b.started_at).getTime() - const be = b.ended_at ? new Date(b.ended_at).getTime() : Date.now() - const left = Math.max(0, ((bs - start) / total) * 100) - const width = Math.min(100 - left, ((be - bs) / total) * 100) - return ( -
- ) - })} -
-
- {breaks.map(b => { - const bs = new Date(b.started_at).getTime() - const be = b.ended_at ? new Date(b.ended_at).getTime() : Date.now() - return ( - - ◼{' '} - {fmtTime(b.started_at)} – {b.ended_at ? fmtTime(b.ended_at) : 'ενεργό'} · {fmtDur(be - bs)} - - ) - })} -
-
- ) -} - -// ── Order-status distribution bar ─────────────────────────────────────────── -function StatusDistributionBar({ counts }) { - const total = counts.all || 1 - const segments = [ - { key: 'both', color: '#16a34a', label: 'Πλήρης' }, - { key: 'paid', color: '#2563eb', label: 'Πληρώθηκε' }, - { key: 'ordered', color: '#ca8a04', label: 'Παρήγγειλε' }, - { key: 'unpaid', color: '#ea580c', label: 'Ανοιχτό' }, - { key: 'cancelled', color: '#dc2626', label: 'Ακύρωση' }, - ].filter(s => counts[s.key] > 0) - - if (segments.length === 0) return null - - return ( -
- {/* bar */} -
- {segments.map(s => ( -
- ))} -
- {/* legend with % */} -
- {segments.map(s => ( - - - {s.label}: {counts[s.key]} ({Math.round(counts[s.key] / total * 100)}%) - - ))} -
-
- ) -} - -// ── colour rules ──────────────────────────────────────────────────────────── -function classify(item, shiftWaiterId) { - if (item.status === 'cancelled') - return { key: 'cancelled', label: 'Ακυρώθηκε', dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#991b1b' } - - const orderedByMe = item.added_by_id === shiftWaiterId - const paidToMe = item.paid_by_id === shiftWaiterId - const isPaid = item.status === 'paid' - - if (orderedByMe && paidToMe && isPaid) - return { key: 'both', label: 'Πλήρης Παραγγελία', dot: '#16a34a', bg: '#f0fdf4', border: '#bbf7d0', text: '#15803d' } - if (!orderedByMe && paidToMe && isPaid) - return { key: 'paid', label: 'Μόνο Πληρώθηκε', dot: '#2563eb', bg: '#eff6ff', border: '#bfdbfe', text: '#1d4ed8' } - if (orderedByMe && isPaid && !paidToMe) - return { key: 'ordered', label: 'Μόνο Παρήγγειλε', dot: '#ca8a04', bg: '#fefce8', border: '#fef08a', text: '#854d0e' } - if (orderedByMe && !isPaid) - return { key: 'unpaid', label: 'Ανοιχτό ακόμη', dot: '#ea580c', bg: '#fff7ed', border: '#fed7aa', text: '#c2410c' } - return { key: 'anomaly', label: 'Πρόβλημα', dot: '#dc2626', bg: '#fef2f2', border: '#fecaca', text: '#b91c1c' } -} - -const FILTER_OPTIONS = [ - { key: 'all', label: 'Όλα' }, - { key: 'both', label: 'Πλήρης Παραγγελία' }, - { key: 'paid', label: 'Μόνο Πληρώθηκε' }, - { key: 'ordered', label: 'Μόνο Παρήγγειλε' }, - { key: 'unpaid', label: 'Ανοιχτό ακόμη' }, - { key: 'cancelled', label: 'Ακυρώθηκε' }, - { key: 'anomaly', label: 'Πρόβλημα' }, -] - -const LEGEND = [ - { dot: '#16a34a', label: 'Πλήρης Παραγγελία' }, - { dot: '#2563eb', label: 'Μόνο Πληρώθηκε' }, - { dot: '#ca8a04', label: 'Μόνο Παρήγγειλε' }, - { dot: '#ea580c', label: 'Ανοιχτό ακόμη' }, - { dot: '#dc2626', label: 'Ακυρώθηκε / Πρόβλημα' }, -] - -function fmtMins(mins) { - if (mins == null) return '—' - const h = Math.floor(mins / 60) - const m = mins % 60 - return h > 0 ? `${h}ω ${m}λ` : `${m}λ` -} - -function ItemRow({ item, shiftWaiterId }) { - const c = classify(item, shiftWaiterId) - const isCancelled = item.status === 'cancelled' - return ( -
-
-
-
- - {item.product_name} - ×{item.quantity} - - - {fmtEUR(item.subtotal)} - -
-
- - Παρήγγειλε: {item.added_by_name ?? '—'} - {item.added_at ? · {fmtDateTime(item.added_at)} : null} - - {!isCancelled && ( - - Πληρώθηκε: {item.paid_by_name ?? '—'} - {item.paid_at ? · {fmtDateTime(item.paid_at)} : null} - {item.payment_method ? ({item.payment_method}) : null} - - )} -
-
- {c.label} -
-
-
- ) -} - -function OrderGroup({ order, shiftWaiterId, activeFilter }) { - const visibleItems = order.items.filter(item => { - if (activeFilter === 'all') return true - return classify(item, shiftWaiterId).key === activeFilter - }) - if (visibleItems.length === 0) return null - - const groupTotal = visibleItems - .filter(i => i.status === 'paid') - .reduce((s, i) => s + i.subtotal, 0) - - return ( -
-
-
- Παραγγελία #{order.order_id} - {order.table_name && · Τραπέζι {order.table_name}} -
-
- {order.opener_name && ( - - Άνοιξε: {order.opener_name} - {order.opened_at ? {fmtTime(order.opened_at)} : null} - - )} - {order.closer_name && ( - - Έκλεισε: {order.closer_name} - {order.closed_at ? {fmtTime(order.closed_at)} : null} - - )} - {groupTotal > 0 && ( - {fmtEUR(groupTotal)} - )} -
-
- {visibleItems.map(item => ( - - ))} -
- ) -} - -export default function ShiftDetailModal({ shiftId, shiftWaiterId, onClose }) { - const [activeFilter, setActiveFilter] = useState('all') - - const { data: summary, isLoading, isError } = useQuery({ - queryKey: ['shift-detail', shiftId], - queryFn: () => client.get(`/api/shifts/${shiftId}/summary`).then(r => r.data), - staleTime: 30 * 1000, - }) - - const counts = { all: 0, both: 0, paid: 0, ordered: 0, unpaid: 0, cancelled: 0, anomaly: 0 } - const waiterIdToUse = shiftWaiterId ?? summary?.waiter_id - if (summary?.orders) { - for (const o of summary.orders) { - for (const item of o.items) { - counts.all++ - const key = classify(item, waiterIdToUse).key - if (key in counts) counts[key]++ - } - } - } - - return ( -
-
e.stopPropagation()} - > - {/* Header */} -
-
-
Λεπτομέρειες Βάρδιας
- {summary && ( -
- {summary.waiter_name} · {fmtDate(summary.started_at)} · {fmtTime(summary.started_at)}–{summary.ended_at ? fmtTime(summary.ended_at) : 'ενεργή'} -
- )} -
- -
- - {isLoading &&
Φόρτωση…
} - {isError &&
Σφάλμα φόρτωσης δεδομένων
} - - {summary && ( - <> - {/* KPI grid — 2 rows × 4 cols */} - {(() => { - const totalOrders = summary.orders?.length ?? 0 - const durationHours = summary.duration_hours ?? (summary.duration_minutes != null ? summary.duration_minutes / 60 : null) - const durationLabel = durationHours != null - ? (() => { const h = Math.floor(durationHours); const m = Math.round((durationHours - h) * 60); return h > 0 ? `${h}ω ${m}λ` : `${m}λ` })() - : fmtMins(summary.duration_minutes) - const row1 = [ - { label: 'Διάρκεια Βάρδιας', value: durationLabel }, - { label: 'Μισθός / Ώρα', value: summary.hourly_rate_snapshot != null ? fmtEUR(summary.hourly_rate_snapshot) : '—' }, - { label: 'Πληρωμή Βάρδιας', value: summary.shift_pay != null ? fmtEUR(summary.shift_pay) : 'Δεν παρακολουθείται', accent: summary.shift_pay != null ? '#059669' : undefined }, - { label: 'Αρχικά Μετρητά', value: summary.starting_cash != null ? fmtEUR(summary.starting_cash) : '—' }, - ] - const discrepancy = summary.cash_discrepancy - const discLabel = discrepancy == null - ? '—' - : Math.abs(discrepancy) < 0.005 - ? '✓ Εντάξει' - : discrepancy < 0 - ? `Έλλειμμα ${fmtEUR(Math.abs(discrepancy))}` - : `Πλεόνασμα +${fmtEUR(discrepancy)}` - const discAccent = discrepancy == null - ? undefined - : Math.abs(discrepancy) < 0.005 - ? '#16a34a' - : discrepancy > 0 - ? '#16a34a' // surplus → green - : '#dc2626' // shortage → red - - const cancelEvents = summary.cancellation_events ?? 0 - const cancelItemsQty = summary.orders - ? summary.orders.reduce((s, o) => s + o.items.filter(i => i.status === 'cancelled').reduce((ss, i) => ss + i.quantity, 0), 0) - : 0 - - const cashSales = summary.cash_sales ?? summary.total_collected ?? 0 - const cardSales = summary.card_sales ?? 0 - const totalRev = cashSales + cardSales - const collectLabel = cardSales > 0 - ? `${fmtEUR(cashSales)} + ${fmtEUR(cardSales)}` - : fmtEUR(cashSales) - - const row2 = [ - { label: 'Σύνολο Παραγγελιών', value: String(totalOrders) }, - { label: 'Εισπράξεις (μετρητά + κάρτα)', value: collectLabel, accent: '#2f9e5e' }, - { - label: 'Ακυρώσεις', - value: cancelEvents > 0 ? `${cancelEvents} / ${cancelItemsQty} είδη` : '—', - accent: cancelEvents > 0 ? '#dc2626' : undefined, - }, - { label: 'Ταμείο', value: discLabel, accent: discAccent }, - ] - return ( -
- {[row1, row2].map((row, ri) => ( -
- {row.map(k => ( -
-
{k.label}
-
{k.value}
-
- ))} -
- ))} -
- ) - })()} - - {/* Breaks timeline (hidden when no breaks) */} - - - {/* Status distribution bar */} -
- -
- - {/* Filter bar */} -
- {FILTER_OPTIONS.map(opt => { - const isCancelOpt = opt.key === 'cancelled' - const isActive = activeFilter === opt.key - return ( - - ) - })} -
- - {/* Orders + items */} -
- {summary.orders.length === 0 ? ( -

- Δεν υπάρχουν αντικείμενα για αυτή τη βάρδια -

- ) : ( - summary.orders.map(o => ( - - )) - )} - {summary.orders.length > 0 && - !summary.orders.some(o => o.items.some(i => - activeFilter === 'all' || classify(i, waiterIdToUse).key === activeFilter - )) && ( -

- Δεν υπάρχουν αντικείμενα για αυτό το φίλτρο -

- )} -
- - )} -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/SkeletonTable.jsx b/manager_dashboard/src/pages/reports/shared/SkeletonTable.jsx deleted file mode 100644 index f041bb1..0000000 --- a/manager_dashboard/src/pages/reports/shared/SkeletonTable.jsx +++ /dev/null @@ -1,30 +0,0 @@ -export default function SkeletonTable({ rows = 8, columns = 5, showChart = false }) { - return ( -
- {showChart && ( -
-
-
-
- )} -
-
-
-
-
- {Array.from({ length: rows }).map((_, i) => ( -
- {Array.from({ length: columns }).map((_, j) => ( -
- ))} -
- ))} -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/StatCard.jsx b/manager_dashboard/src/pages/reports/shared/StatCard.jsx deleted file mode 100644 index 21b88ab..0000000 --- a/manager_dashboard/src/pages/reports/shared/StatCard.jsx +++ /dev/null @@ -1,20 +0,0 @@ -export default function StatCard({ label, value, sub, icon: Icon, accent, size = 'md' }) { - const sizes = { - sm: { val: 'text-2xl', pad: 'p-4' }, - md: { val: 'text-[28px]', pad: 'p-5' }, - lg: { val: 'text-4xl', pad: 'p-6' }, - } - const s = sizes[size] || sizes.md - return ( -
-
-
{label}
- {Icon && } -
-
- {value ?? '—'} -
- {sub &&
{sub}
} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/TablePrimitives.jsx b/manager_dashboard/src/pages/reports/shared/TablePrimitives.jsx deleted file mode 100644 index fda8e7f..0000000 --- a/manager_dashboard/src/pages/reports/shared/TablePrimitives.jsx +++ /dev/null @@ -1,136 +0,0 @@ -import { STATUS_STYLES, avatarColor } from '../../../ui/tokens' - -export function Panel({ title, subtitle, right, children, padded = true }) { - return ( -
- {(title || right) && ( -
-
- {title &&
{title}
} - {subtitle &&
{subtitle}
} -
- {right} -
- )} -
{children}
-
- ) -} - -export function DataTable({ children, className = '' }) { - return ( -
-
- {children} -
-
- ) -} - -export function THead({ children }) { - return ( - - {children} - - ) -} - -export function TH({ children, className = '', align = 'left' }) { - return ( - - {children} - - ) -} - -export function TR({ children, onClick, highlight, striped, className = '' }) { - return ( - - {children} - - ) -} - -export function TD({ children, className = '', mono, align = 'left', colSpan }) { - return ( - - {children} - - ) -} - -export function StatusBadge({ status, pulse }) { - const s = STATUS_STYLES[status] || STATUS_STYLES.closed - const label = status ? status.replace('_', ' ').replace('-', ' ') : 'unknown' - return ( - - - {pulse && (status === 'active' || status === 'open') && ( - - )} - - {label} - - ) -} - -export function WaiterAvatar({ name, id }) { - const cls = avatarColor(id ?? name ?? '0') - const initials = name - ? name.split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase() - : '?' - return ( -
-
- {initials} -
- {name || '—'} -
- ) -} - -export function ChartTooltip({ active, payload, label, formatter, labelFormatter }) { - if (!active || !payload?.length) return null - return ( -
- {label != null && ( -
- {labelFormatter ? labelFormatter(label) : label} -
- )} - {payload.map((p, i) => ( -
- - {p.name}: - - {formatter ? formatter(p.value, p.name) : p.value} - -
- ))} -
- ) -} - -export function ErrorState({ message, onRetry }) { - return ( -
-
{message || 'Something went wrong'}
- {onRetry && ( - - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/shared/reportDesignTokens.js b/manager_dashboard/src/pages/reports/shared/reportDesignTokens.js deleted file mode 100644 index 03593a2..0000000 --- a/manager_dashboard/src/pages/reports/shared/reportDesignTokens.js +++ /dev/null @@ -1,3 +0,0 @@ -// Re-export shim — all tokens have moved to src/ui/tokens.js. -// Existing report subpage imports continue to work unchanged. -export * from '../../../ui/tokens' diff --git a/manager_dashboard/src/pages/reports/staff/Activity.jsx b/manager_dashboard/src/pages/reports/staff/Activity.jsx deleted file mode 100644 index bc0941c..0000000 --- a/manager_dashboard/src/pages/reports/staff/Activity.jsx +++ /dev/null @@ -1,275 +0,0 @@ -import { useState, useMemo } from 'react' -import { useQuery } from '@tanstack/react-query' -import { - BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, - ResponsiveContainer, Legend, ComposedChart, Line, -} from 'recharts' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar } from '../shared/TablePrimitives' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import { fmtEUR, 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 METRICS = [ - { key: 'orders', label: 'ΠΑΡΑΓΓΕΛΙΕΣ', color: '#60a5fa' }, - { key: 'items', label: 'ΕΙΔΗ', color: '#34d399' }, - { key: 'cancellations', label: 'ΑΚΥΡΩΣΕΙΣ', color: '#f87171' }, - { key: 'total', label: 'ΕΣΟΔΑ', color: '#a78bfa' }, - { key: 'hours_worked', label: 'ΩΡΕΣ', color: '#fb923c', rightAxis: true }, -] - -function fmtHours(h) { - if (h == null) return '—' - const hrs = Math.floor(h) - const mins = Math.round((h - hrs) * 60) - if (mins === 0) return `${hrs}ω` - return `${hrs}ω ${mins}λ` -} - -function CustomTooltip({ active, payload, label }) { - if (!active || !payload?.length) return null - return ( -
-
{label}
- {payload.map(p => ( -
- {p.name} - - {p.dataKey === 'total' ? fmtEUR(p.value) - : p.dataKey === 'hours_worked' ? fmtHours(p.value) - : fmtNum(p.value)} - -
- ))} -
- ) -} - -export default function Activity() { - const [waiterId, setWaiterId] = useState('all') - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - const [activeMetrics, setActiveMetrics] = useState(new Set(['orders', 'items', 'cancellations', 'total'])) - const [stacked, setStacked] = useState(false) - - const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').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 = { - ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}), - ...(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: ['shifts-activity', waiterId, mode, from, to, businessDayId], - queryFn: () => client.get('/api/reports/shift/orders', { 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 bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))] - - const waiters = data?.waiters || [] - - const chartData = useMemo(() => waiters.map(w => ({ - name: w.waiter_name || `#${w.waiter_id}`, - shortName: (w.waiter_name || '').split(' ')[0] || `#${w.waiter_id}`, - orders: w.orders || 0, - items: w.items || 0, - cancellations: w.cancellations || 0, - total: Math.round((w.total || 0) * 100) / 100, - hours_worked: w.hours_worked || 0, - })), [waiters]) - - function toggleMetric(key) { - setActiveMetrics(prev => { - const next = new Set(prev) - if (next.has(key)) { if (next.size > 1) next.delete(key) } - else next.add(key) - return next - }) - } - - const showRightAxis = activeMetrics.has('hours_worked') - const leftMetrics = METRICS.filter(m => !m.rightAxis && activeMetrics.has(m.key)) - const hasRevenue = activeMetrics.has('total') - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
- {waiters.length > 0 && ( - - - -
- } - > - {/* Metric checkboxes */} -
- {METRICS.map(m => { - const active = activeMetrics.has(m.key) - return ( - - ) - })} -
- -
- - - - hasRevenue && leftMetrics.length === 1 ? `€${v}` : v} - /> - {showRightAxis && ( - `${v}ω`} - /> - )} - v.length > 12 ? v.slice(0, 11) + '…' : v} - /> - } cursor={{ fill: '#f1f5f9' }} /> - {METRICS.filter(m => !m.rightAxis && activeMetrics.has(m.key)).map(m => ( - - ))} - {activeMetrics.has('hours_worked') && ( - - )} - - -
- - )} - -
- - {waiters.length === 0 ? ( - - ) : ( - - - Σερβιτόρος - Παραγγελίες - Είδη - Ακυρώσεις - Ώρες - Συνολική Αξία - - - {[...waiters].sort((a, b) => (b.total || 0) - (a.total || 0)).map(w => ( - - - {fmtNum(w.orders)} - {fmtNum(w.items)} - - {w.cancellations > 0 - ? {fmtNum(w.cancellations)} - : —} - - {fmtHours(w.hours_worked)} - {fmtEUR(w.total)} - - ))} - - - )} - -
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/staff/Payments.jsx b/manager_dashboard/src/pages/reports/staff/Payments.jsx deleted file mode 100644 index 47c0762..0000000 --- a/manager_dashboard/src/pages/reports/staff/Payments.jsx +++ /dev/null @@ -1,125 +0,0 @@ -import { useState } from 'react' -import { useQuery } from '@tanstack/react-query' -import { Wallet, HandCoins, Coins } from 'lucide-react' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput, WorkDayDateToggle } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar } from '../shared/TablePrimitives' -import StatCard from '../shared/StatCard' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import ExportButton from '../shared/ExportButton' -import { fmtEUR, 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) } - -export default function Payments() { - const [waiterId, setWaiterId] = useState('all') - const [mode, setMode] = useState('range') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [businessDayId, setBusinessDayId] = useState('all') - - const { data: waitersData } = useQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').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 = { - ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}), - ...(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: ['shifts-payments', waiterId, mode, from, to, businessDayId], - queryFn: () => client.get('/api/reports/shifts', { 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 bdOptions = [{ value: 'all', label: 'Όλες οι Εργάσιμες Μέρες' }, ...((bdData?.business_days || []).map(bd => ({ value: String(bd.id), label: `${fmtDate(bd.opened_at)} · ${fmtTime(bd.opened_at)}` })))] - - const shifts = data?.shifts || [] - const totals = shifts.reduce((acc, s) => { - acc.starting += s.starting_cash || 0 - acc.collected += s.total_collected || 0 - acc.owed += s.net_to_deliver || 0 - return acc - }, { starting: 0, collected: 0, owed: 0 }) - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - }> - - - {mode === 'workday' ? ( - - ) : ( - <> - - - - )} - - -
-
- - - -
- - - {shifts.length === 0 ? ( - - ) : ( - - - Σερβιτόρος - Βάρδια - Αρχικά Μετρητά - Εισπράχθηκαν - Σύνολο στην Τσέπη - Κατάσταση - - - {shifts.map(s => ( - - - - {fmtDate(s.started_at)} · {fmtTime(s.started_at)}–{s.ended_at ? fmtTime(s.ended_at) : 'now'} - - {fmtEUR(s.starting_cash)} - {fmtEUR(s.total_collected)} - {fmtEUR(s.net_to_deliver)} - - - ))} - - Σύνολα - {fmtEUR(totals.starting)} - {fmtEUR(totals.collected)} - {fmtEUR(totals.owed)} - - - - - )} - -
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/staff/ShiftsOverview.jsx b/manager_dashboard/src/pages/reports/staff/ShiftsOverview.jsx deleted file mode 100644 index 68c16d1..0000000 --- a/manager_dashboard/src/pages/reports/staff/ShiftsOverview.jsx +++ /dev/null @@ -1,277 +0,0 @@ -import { useState } from 'react' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { UserRoundX, ChevronRight, ExternalLink, Trash2, Eye } from 'lucide-react' -import toast from 'react-hot-toast' -import ShiftDetailModal from '../shared/ShiftDetailModal' -import DeleteConfirmModal from '../../../ui/DeleteConfirmModal' -import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, LabelList } from 'recharts' -import client from '../../../api/client' -import { FilterBar, FilterSelect, FilterDateInput } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, StatusBadge, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives' -import StatCard from '../shared/StatCard' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import ExportButton from '../shared/ExportButton' -import { fmtEUR, fmtDateTime, fmtDuration, 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) -} - -export default function ShiftsOverview({ onNavigate } = {}) { - const [waiterId, setWaiterId] = useState('all') - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - const [expanded, setExpanded] = useState(null) - const [detailShift, setDetailShift] = useState(null) // { id, waiter_id } - const [deleteShift, setDeleteShift] = useState(null) // shift object to delete - - const qc = useQueryClient() - - const { data: waitersData } = useQuery({ - queryKey: ['meta-waiters'], - queryFn: () => client.get('/api/reports/meta/waiters').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 bdById = Object.fromEntries((bdData?.business_days || []).map(bd => [String(bd.id), bd])) - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['shifts', waiterId, from, to], - queryFn: () => client.get('/api/reports/shifts', { - params: { - ...(waiterId !== 'all' ? { waiter_id: waiterId } : {}), - from: from + 'T00:00:00', - to: to + 'T23:59:59', - }, - }).then(r => r.data), - staleTime: 0, - }) - - const deleteShiftMutation = useMutation({ - mutationFn: (id) => client.delete(`/api/shifts/${id}`), - onSuccess: () => { - toast.success('Η βάρδια διαγράφηκε') - qc.invalidateQueries({ queryKey: ['shifts'] }) - qc.invalidateQueries({ queryKey: ['business-days-list'] }) - setDeleteShift(null) - }, - onError: (err) => { - toast.error(err?.response?.data?.detail || 'Σφάλμα διαγραφής βάρδιας') - setDeleteShift(null) - }, - }) - - const waiterOptions = [ - { value: 'all', label: 'Όλοι οι Σερβιτόροι' }, - ...((waitersData?.waiters || []).map(w => ({ value: String(w.id), label: w.name }))), - ] - - const shifts = data?.shifts || [] - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
- -
-
- ) - - return ( -
- - }> - - - - - -
- - {shifts.length === 0 ? ( - - ) : ( - - - Σερβιτόρος - Έναρξη - Λήξη - Διάρκεια - Αμοιβή/ώρα - Αποδοχές - Αρχικά Μετρητά - Εισπράχθηκαν - Οφείλει - Ταμείο - Ακυρώσεις - Αξία Ακυρ. - Κατάσταση - - - - {shifts.map(s => { - const isOpen = expanded === s.id - return [ - setExpanded(isOpen ? null : s.id)} - highlight={isOpen} - striped - > - - {fmtDateTime(s.started_at)} - - {s.ended_at - ? fmtDateTime(s.ended_at) - : — ενεργή —} - - {fmtDuration(s.started_at, s.ended_at)} - - {s.hourly_rate_snapshot != null - ? fmtEUR(s.hourly_rate_snapshot) - : —} - - - {s.shift_pay != null - ? {fmtEUR(s.shift_pay)} - : Δεν παρακολουθείται} - - {fmtEUR(s.starting_cash)} - - {fmtEUR(s.cash_sales ?? s.total_collected)} - {(s.card_sales ?? 0) > 0 && ( - +{fmtEUR(s.card_sales)} κάρτα - )} - - {fmtEUR(s.net_to_deliver)} - - {s.counted_cash_end != null ? (() => { - const d = s.cash_discrepancy - const isClean = d == null || Math.abs(d) < 0.005 - const isSurplus = d != null && d > 0.005 - const colorClass = isClean ? 'text-emerald-600 font-semibold' - : isSurplus ? 'text-emerald-600 font-semibold' - : 'text-red-600 font-semibold' - return ( - - {fmtEUR(s.counted_cash_end)} - {d != null && Math.abs(d) >= 0.005 && ( - - {isSurplus ? `+${fmtEUR(d)}` : `−${fmtEUR(Math.abs(d))}`} - - )} - - ) - })() : ( - — - )} - - - {s.cancellations > 0 - ? {s.cancellations} - : —} - - - {s.cancellation_value > 0 - ? {fmtEUR(s.cancellation_value)} - : —} - - - -
- - {!s.is_active && ( - - )} - -
- - , - isOpen && ( - - -
- - {'Εργάσιμη Μέρα: '} - {s.business_day_id ? (() => { - const bd = bdById[String(s.business_day_id)] - const label = bd - ? `#${s.business_day_id} · ${fmtDate(bd.opened_at)} ${fmtTime(bd.opened_at)}` - : `#${s.business_day_id}` - return onNavigate ? ( - - ) : {label} - })() : '—'} - - Σημειώσεις: {s.notes || '—'} -
- - - ), - ] - })} - -
- )} -
-
- - {detailShift && ( - setDetailShift(null)} - /> - )} - - {deleteShift && ( - deleteShiftMutation.mutate(deleteShift.id)} - onCancel={() => setDeleteShift(null)} - /> - )} -
- ) -} diff --git a/manager_dashboard/src/pages/reports/staff/StaffLeaderboard.jsx b/manager_dashboard/src/pages/reports/staff/StaffLeaderboard.jsx deleted file mode 100644 index edcf5d3..0000000 --- a/manager_dashboard/src/pages/reports/staff/StaffLeaderboard.jsx +++ /dev/null @@ -1,150 +0,0 @@ -import { useState, useMemo } from 'react' -import { useQuery } from '@tanstack/react-query' -import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts' -import client from '../../../api/client' -import { FilterBar, FilterDateInput } from '../shared/FilterBar' -import { Panel, DataTable, THead, TH, TR, TD, WaiterAvatar, ChartTooltip } from '../shared/TablePrimitives' -import EmptyState from '../shared/EmptyState' -import SkeletonTable from '../shared/SkeletonTable' -import { fmtEUR, fmtNum, avatarColor, 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 PODIUM_HEIGHTS = ['h-44', 'h-32', 'h-24'] -const PODIUM_COLORS = [ - 'bg-gradient-to-b from-amber-200 to-amber-100 ring-amber-300', - 'bg-gradient-to-b from-slate-200 to-slate-100 ring-slate-300', - 'bg-gradient-to-b from-orange-200 to-orange-100 ring-orange-300', -] -const MEDAL_LABEL = ['1ος', '2ος', '3ος'] -const PODIUM_ORDER = [1, 0, 2] - -export default function StaffLeaderboard() { - const [from, setFrom] = useState(monthAgo()) - const [to, setTo] = useState(today()) - - const { data, isLoading, isError, refetch } = useQuery({ - queryKey: ['shifts-leaderboard', from, to], - queryFn: () => client.get('/api/reports/shifts', { params: { from: from + 'T00:00:00', to: to + 'T23:59:59' } }).then(r => r.data), - staleTime: 60 * 1000, - }) - - const ranked = useMemo(() => { - const shifts = data?.shifts || [] - const map = new Map() - shifts.forEach(s => { - const cur = map.get(s.waiter_id) || { waiter_id: s.waiter_id, waiter_name: s.waiter_name, shifts: 0, orders: 0, value: 0 } - cur.shifts += 1 - cur.value += s.total_collected || 0 - map.set(s.waiter_id, cur) - }) - return [...map.values()] - .map(r => ({ ...r, avg_per_shift: r.shifts ? r.value / r.shifts : 0 })) - .sort((a, b) => b.value - a.value) - }, [data]) - - const top3 = ranked.slice(0, 3) - - const chartData = ranked.map(r => ({ - name: (r.waiter_name || '').split(' ')[0], - value: Math.round(r.value), - })) - - if (isLoading) return
- if (isError) return ( -
- Αδυναμία φόρτωσης δεδομένων -
-
- ) - - return ( -
- - - - {ranked.length} σερβιτόροι · άθροισμα περιόδου - - -
- - {top3.length === 0 ? ( - - ) : ( -
- {PODIUM_ORDER.map(rank => { - const r = top3[rank] - if (!r) return
- const initials = (r.waiter_name || '').split(' ').map(p => p[0]).slice(0, 2).join('').toUpperCase() - const cls = avatarColor(r.waiter_id) - return ( -
-
-
- {initials} -
-
{r.waiter_name}
-
{r.shifts} βάρδιες
-
-
-
{MEDAL_LABEL[rank]}
-
{fmtEUR(r.value)}
-
-
- ) - })} -
- )} - - -
-
- - - - Θέση - Σερβιτόρος - Βάρδιες - Συνολικά Έσοδα - Μέσος / Βάρδια - - - {ranked.map((r, i) => ( - - - {i + 1} - - - {r.shifts} - {fmtEUR(r.value)} - {fmtEUR(r.avg_per_shift)} - - ))} - - - -
- -
- - - - - - fmtEUR(v)} />} cursor={{ fill: '#f1f5f9' }} /> - - - -
-
-
-
-
- ) -} diff --git a/manager_dashboard/src/pages/reports/staff/StaffReport.jsx b/manager_dashboard/src/pages/reports/staff/StaffReport.jsx new file mode 100644 index 0000000..05e7cad --- /dev/null +++ b/manager_dashboard/src/pages/reports/staff/StaffReport.jsx @@ -0,0 +1,181 @@ +// Reports → Staff (plan step 6.12c; replaces the v1 shifts / payments / activity / leaderboard +// views): every shift with its pay and cash; the cash each shift hands over; and sales by person +// (counted like every report: net of refunds, the delivery fee apart), ranked. +import { useState } from 'react' +import { useMutation, useQueryClient } from '@tanstack/react-query' +import toast from 'react-hot-toast' +import { Trash2 } from 'lucide-react' +import { useCan } from '@xenia/access' +import { errorMessage } from '@xenia/api' +import { useFormat, useTranslation } from '@xenia/i18n' +import { Button, Dialog, IconButton, Select } 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 { BarList } from '../kit/charts' +import { ExportButton, Failed, Loading, Panel, ReportPage, Stat, Table } from '../kit/parts' +import { PeriodPicker } from '../kit/Period' +import { defaultPeriod, periodParams, periodSlug, ratio } from '../kit/reportLogic' + +export default function StaffReport() { + const { t } = useTranslation('manager') + const tabs = [ + { id: 'shifts', label: t('reports.staff.tabs.shifts'), Component: ShiftsTab }, + { id: 'cash', label: t('reports.staff.tabs.cash'), Component: CashTab }, + { id: 'people', label: t('reports.staff.tabs.people'), Component: PeopleTab }, + ] + return +} + +function usePeople() { + return useLiveQuery({ queryKey: ['meta-waiters'], queryFn: () => client.get('/api/reports/meta/waiters').then(r => r.data.waiters), staleTime: 300_000 }) +} + +function PersonFilter({ value, onChange }) { + const { t } = useTranslation('manager') + const { data: people = [] } = usePeople() + return ( + setPrinter(e.target.value)} aria-label={t('reports.print.printer')} className="w-48" + options={[{ value: '', label: t('reports.tech.allPrinters') }, ...printers.map(p => ({ value: String(p.id), label: p.name }))]} /> + + + } /> + {isPending ? : error ? : (<> +
+ + + + {data.total_amount != null && } +
+ {perPrinter.length > 0 && ( + + ({ ...p, sub: p.failed ? t('reports.tech.failedSome', { count: p.failed }) : t('reports.tech.noneFailed') }))} /> + + )} + + + + )} + {printing && setPrinting(false)} />} + + ) +} diff --git a/manager_dashboard/tests/reports.test.mjs b/manager_dashboard/tests/reports.test.mjs index fbfc368..bc03d48 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, printBody, quickRange, rangeProblem, ratio, sortRows, + addDays, csvText, 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', () => { @@ -43,3 +43,10 @@ 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' }) }) + +test('a CSV built in the browser follows the Excel rules', () => { + const en = csvText(['Product', 'Value'], [['Freddo, iced', 3.5], ['Tea', 2]]) + assert.equal(en.charCodeAt(0), 0xFEFF) + assert.deepEqual(en.slice(1).split('\r\n'), ['Product,Value', '"Freddo, iced",3.50', 'Tea,2']) + assert.deepEqual(csvText(['Π', 'Τιμή'], [['Φρέντο', 3.5]], 'el').slice(1).split('\r\n'), ['Π;Τιμή', 'Φρέντο;3,50']) +}) diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json index 0528b02..b0a887f 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/pages/reports/store", "src/pages/reports/products" + "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/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" ], "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/pages/reports/store", "src/pages/reports/products" + "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", "src/pages/reports/staff", "src/pages/reports/misc", "src/pages/reports/technical", "src/pages/reports/prepzones", "src/pages/reports/expenses" ] } diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json index a5e7cb8..47e6b5e 100644 --- a/packages/i18n/locales/el/manager.json +++ b/packages/i18n/locales/el/manager.json @@ -2799,11 +2799,17 @@ "kind": "Τι τυπώνεται", "modes": { "smart": "Σύνοψη", - "full": "Πλήρης" + "full": "Πλήρης", + "quick": "Γρήγορη σύνοψη", + "orders": "Κάθε παραγγελία", + "detailed": "Κάθε παραγγελία και είδος" }, "modesHint": { "smart": "Μόνο όσα πουλήθηκαν, τα περισσότερα πρώτα.", - "full": "Όλα τα προϊόντα, και όσα δεν πουλήθηκαν." + "full": "Όλα τα προϊόντα, και όσα δεν πουλήθηκαν.", + "quick": "Μόνο σύνολα: λίγο χαρτί.", + "orders": "Κάθε παραγγελία με το σύνολό της.", + "detailed": "Κάθε παραγγελία με όλα τα είδη: πολύ χαρτί." }, "printer": "Εκτυπωτής", "noPrinters": "Δεν υπάρχουν εκτυπωτές (Ρυθμίσεις → Εκτύπωση).", @@ -2922,6 +2928,140 @@ "all_one": "{{count}} προϊόν", "all_other": "{{count}} προϊόντα", "shareTitle": "Έσοδα ανά κατηγορία" + }, + "staff": { + "title": "Προσωπικό", + "tabs": { + "shifts": "Βάρδιες", + "cash": "Παράδοση ταμείου", + "people": "Πωλήσεις ανά άτομο" + }, + "shiftsCount_one": "{{count}} βάρδια", + "shiftsCount_other": "{{count}} βάρδιες", + "payTotal": "Αμοιβή για αυτές τις βάρδιες: {{amount}}", + "pay": "Αμοιβή", + "payTip": "Ώρες × η ωριαία αμοιβή τη στιγμή της βάρδιας.", + "handOver": "Για παράδοση", + "handOverTip": "Αρχικά μετρητά + μετρητά που εισπράχθηκαν − μετρητά που επιστράφηκαν: όσα πρέπει να είναι στο συρτάρι.", + "difference": "Διαφορά", + "differenceTip": "Όσα μετρήθηκαν στο τέλος μείον όσα έπρεπε να υπάρχουν (− λείπουν, + περισσεύουν).", + "shift": "Βάρδια", + "starting": "Αρχικά μετρητά", + "cash": "Μετρητά", + "card": "Κάρτα", + "counted": "Μετρήθηκαν", + "open": "Ανοιχτή", + "ended": "Έληξε", + "cashTitle": "Ταμείο ανά βάρδια", + "hours": "Ώρες", + "sales": "Πωλήσεις", + "salesTip": "Όσα έστειλε κάθε άτομο (προϊόντα, μείον επιστροφές· τα έξοδα αποστολής χωριστά), όποιος κι αν πληρώθηκε.", + "perHour": "Ανά ώρα", + "ranking": "Ποιος πούλησε περισσότερο", + "people_one": "{{count}} άτομο", + "people_other": "{{count}} άτομα" + }, + "misc": { + "title": "Ακυρώσεις και εκπτώσεις", + "cancellations": "Ακυρώσεις", + "discounts": "Εκπτώσεις", + "when": "Πότε", + "value": "Αξία", + "sentBy": "Το έστειλε", + "cancelledBy": "Το ακύρωσε", + "reason": "Γιατί", + "cancelledLines": "Ακυρωμένες γραμμές", + "cancelledValue": "Η αξία τους", + "notSales": "δεν μετρούν στις πωλήσεις", + "byWhom": "Ανά άτομο", + "lines_one": "{{count}} γραμμή", + "lines_other": "{{count}} γραμμές", + "discount": "Έκπτωση", + "amount": "Ποσό", + "before": "Παραγγελία πριν", + "givenBy": "Την έδωσε", + "discountsGiven": "Εκπτώσεις που δόθηκαν", + "onOrders_one": "σε {{count}} παραγγελία", + "onOrders_other": "σε {{count}} παραγγελίες", + "discountTotal": "Σύνολο εκπτώσεων", + "alreadyOff": "έχουν ήδη αφαιρεθεί από τα έσοδα", + "times_one": "{{count}} φορά", + "times_other": "{{count}} φορές" + }, + "tech": { + "title": "Τεχνικά", + "printing": "Εκτυπώσεις", + "allPrinters": "Όλοι οι εκτυπωτές", + "items": "Στο δελτίο", + "result": "Αποτέλεσμα", + "printed": "Τυπώθηκε", + "failed": "Απέτυχε", + "tickets": "Δελτία που στάλθηκαν", + "failedN": "Απέτυχαν", + "checkPrinter": "ελέγξτε τον εκτυπωτή", + "allGood": "όλα τυπώθηκαν", + "reliability": "Τυπώθηκαν με την πρώτη", + "reliabilityTip": "Το ποσοστό των προσπαθειών που τυπώθηκαν. Όσα αποτυγχάνουν ξαναδοκιμάζονται μέχρι να τυπωθούν (Ρυθμίσεις → Εκτύπωση).", + "ordersValue": "Αξία παραγγελιών", + "ordersValueTip": "Η αξία των παραγγελιών αυτών των δελτίων, κάθε παραγγελία μία φορά.", + "perPrinter": "Δελτία ανά εκτυπωτή", + "failedSome_one": "{{count}} απέτυχε", + "failedSome_other": "{{count}} απέτυχαν", + "noneFailed": "κανένα δεν απέτυχε", + "jobs_one": "{{count}} δελτίο", + "jobs_other": "{{count}} δελτία" + }, + "zones": { + "title": "Ζώνες προετοιμασίας", + "which": "Ζώνες που φαίνονται", + "all": "Όλες οι ζώνες", + "load": "Τι ετοίμασε κάθε ζώνη", + "loadTip": "Είδη που έφτιαξε κάθε ζώνη στην περίοδο (προϊόν σε δύο ζώνες μετράει και στις δύο).", + "items": "Είδη", + "value": "Η αξία τους", + "valueTip": "Η τιμή που πουλήθηκαν αυτά τα είδη.", + "nothing": "Τίποτα δεν ετοιμάστηκε εδώ σε αυτή την περίοδο.", + "orders_one": "{{count}} παραγγελία", + "orders_other": "{{count}} παραγγελίες", + "productsCsv": "Προϊόντα (Excel)", + "ordersCsv": "Παραγγελίες (Excel)" + }, + "exp": { + "title": "Δαπάνες", + "spent": "Δαπανήθηκαν", + "count_one": "{{count}} δαπάνη", + "count_other": "{{count}} δαπάνες", + "paid": "Πληρώθηκαν", + "due": "Οφείλονται", + "split": "Πού πήγαν", + "by": { + "category": "Ανά κατηγορία", + "supplier": "Ανά προμηθευτή" + }, + "dueSub": "οφείλονται {{amount}}", + "noSupplier": "Χωρίς προμηθευτή", + "list": "Όλες οι δαπάνες", + "date": "Καταχωρήθηκε", + "what": "Τι", + "supplier": "Προμηθευτής", + "total": "Σύνολο", + "status": { + "due": "Οφείλεται", + "partial": "Μερικώς", + "paid": "Πληρώθηκε" + }, + "categories": { + "supplier": "Προμηθευτές", + "utilities": "Κοινή χρεία", + "rent": "Ενοίκιο", + "maintenance": "Συντήρηση", + "staff": "Προσωπικό", + "equipment": "Εξοπλισμός", + "other": "Άλλο" + }, + "dueDate": "Λήξη {{date}}", + "payments": "Πληρωμές", + "noPayments": "Δεν έχει πληρωθεί τίποτα ακόμα." } } } diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json index b878891..c5744f2 100644 --- a/packages/i18n/locales/en/manager.json +++ b/packages/i18n/locales/en/manager.json @@ -2799,11 +2799,17 @@ "kind": "What to print", "modes": { "smart": "Summary", - "full": "Full" + "full": "Full", + "quick": "Quick summary", + "orders": "Every order", + "detailed": "Every order and item" }, "modesHint": { "smart": "Only what sold, most first.", - "full": "Every product, unsold ones too." + "full": "Every product, unsold ones too.", + "quick": "Totals only: little paper.", + "orders": "Each order with its total.", + "detailed": "Each order with every item: a lot of paper." }, "printer": "Printer", "noPrinters": "No printers (Settings → Printing).", @@ -2922,6 +2928,140 @@ "all_one": "{{count}} product", "all_other": "{{count}} products", "shareTitle": "Revenue by category" + }, + "staff": { + "title": "Staff", + "tabs": { + "shifts": "Shifts", + "cash": "Cash handover", + "people": "Sales by person" + }, + "shiftsCount_one": "{{count}} shift", + "shiftsCount_other": "{{count}} shifts", + "payTotal": "Pay for these shifts: {{amount}}", + "pay": "Pay", + "payTip": "Hours × the hourly pay at the time of the shift.", + "handOver": "To hand over", + "handOverTip": "Starting cash + cash taken − cash refunded: what should be in the drawer.", + "difference": "Difference", + "differenceTip": "What was counted at the end minus what should have been there (− short, + over).", + "shift": "Shift", + "starting": "Starting cash", + "cash": "Cash taken", + "card": "Card taken", + "counted": "Counted", + "open": "Open", + "ended": "Ended", + "cashTitle": "Cash per shift", + "hours": "Hours", + "sales": "Sales", + "salesTip": "What each person sent (products, net of refunds; the delivery fee apart), whoever was paid.", + "perHour": "Per hour", + "ranking": "Who sold most", + "people_one": "{{count}} person", + "people_other": "{{count}} people" + }, + "misc": { + "title": "Cancellations and discounts", + "cancellations": "Cancellations", + "discounts": "Discounts", + "when": "When", + "value": "Value", + "sentBy": "Sent by", + "cancelledBy": "Cancelled by", + "reason": "Why", + "cancelledLines": "Lines cancelled", + "cancelledValue": "Their value", + "notSales": "not counted as sales", + "byWhom": "By person", + "lines_one": "{{count}} line", + "lines_other": "{{count}} lines", + "discount": "Discount", + "amount": "Amount off", + "before": "Order before", + "givenBy": "Given by", + "discountsGiven": "Discounts given", + "onOrders_one": "on {{count}} order", + "onOrders_other": "on {{count}} orders", + "discountTotal": "Total off", + "alreadyOff": "already taken off the revenue", + "times_one": "{{count}} time", + "times_other": "{{count}} times" + }, + "tech": { + "title": "Technical", + "printing": "Printing", + "allPrinters": "All printers", + "items": "On the ticket", + "result": "Result", + "printed": "Printed", + "failed": "Failed", + "tickets": "Tickets sent", + "failedN": "Failed", + "checkPrinter": "check the printer", + "allGood": "all printed", + "reliability": "Printed first time", + "reliabilityTip": "The share of attempts that printed. Failed tickets are tried again until they print (Settings → Printing).", + "ordersValue": "Orders' value", + "ordersValueTip": "The value of the orders these tickets belong to, each order once.", + "perPrinter": "Tickets per printer", + "failedSome_one": "{{count}} failed", + "failedSome_other": "{{count}} failed", + "noneFailed": "none failed", + "jobs_one": "{{count}} ticket", + "jobs_other": "{{count}} tickets" + }, + "zones": { + "title": "Prep zones", + "which": "Zones shown", + "all": "All zones", + "load": "What each zone prepared", + "loadTip": "Items made by each zone in the period (a product in two zones counts in both).", + "items": "Items", + "value": "Their value", + "valueTip": "What those items were sold for.", + "nothing": "Nothing prepared here in this period.", + "orders_one": "{{count}} order", + "orders_other": "{{count}} orders", + "productsCsv": "Products (Excel)", + "ordersCsv": "Orders (Excel)" + }, + "exp": { + "title": "Expenses", + "spent": "Spent", + "count_one": "{{count}} expense", + "count_other": "{{count}} expenses", + "paid": "Paid", + "due": "Still due", + "split": "Where it went", + "by": { + "category": "By category", + "supplier": "By supplier" + }, + "dueSub": "{{amount}} due", + "noSupplier": "No supplier", + "list": "Every expense", + "date": "Entered", + "what": "What", + "supplier": "Supplier", + "total": "Total", + "status": { + "due": "Due", + "partial": "Partly paid", + "paid": "Paid" + }, + "categories": { + "supplier": "Supplies", + "utilities": "Utilities", + "rent": "Rent", + "maintenance": "Maintenance", + "staff": "Staff", + "equipment": "Equipment", + "other": "Other" + }, + "dueDate": "Due by {{date}}", + "payments": "Payments", + "noPayments": "Nothing paid yet." } } } diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs index 867f23b..3237a94 100644 --- a/tests/e2e/manager.mjs +++ b/tests/e2e/manager.mjs @@ -1216,6 +1216,27 @@ try { 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 }) + // 6.12c: staff, cancellations and discounts, technical, prep zones, expenses + const opens = async (url, testId, what) => { + await page.goto(`${APP}${url}`) + r.check(`${rp} ${what} opens`, await page.getByTestId(testId).first().waitFor({ timeout: 10_000 }).then(() => true).catch(() => false)) + } + await opens('/reports/staff', 'report-shift', 'Staff → Shifts (rows)') + await page.getByTestId('report-shift').first().click() + r.check(`${rp} a shift opens its details`, await page.getByTestId('shift-dialog').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await page.keyboard.press('Escape') + await page.getByTestId('report-tab-cash').click() + r.check(`${rp} Staff → Cash handover`, await page.getByTestId('staff-handover').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await page.getByTestId('report-tab-people').click() + r.check(`${rp} Staff → Sales by person ranks people`, await page.getByTestId('staff-ranking').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await page.screenshot({ path: path.join(OUT, 'manager-report-staff.png'), fullPage: true }) + await opens('/reports/misc', 'cancellations-count', 'Cancellations') + await page.getByTestId('report-tab-discounts').click() + r.check(`${rp} Discounts opens`, await page.getByTestId('report-period').waitFor({ timeout: 8000 }).then(() => true).catch(() => false)) + await opens('/reports/technical', 'printing-total', 'Technical → Printing') + await opens('/reports/prep-zones', 'report-period', 'Prep zones') + await opens('/reports/expenses', 'expenses-total', 'Expenses') + await page.screenshot({ path: path.join(OUT, 'manager-report-expenses.png'), fullPage: true }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await page.goto(`${APP}/online-orders`)