diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py
index d5a103e..79f5864 100644
--- a/local_backend/core/errors.py
+++ b/local_backend/core/errors.py
@@ -128,6 +128,7 @@ CODES: dict[str, tuple[int, str]] = {
"reservation.not_found": (404, "Booking {reservation_id} not found."),
"reservation.status_changed": (409, "This booking was changed on another screen in the meantime (it is now {current})."),
"reservation.table_unknown": (404, "Table {table_id} not found."),
+ "reservation.table_kept": (409, "That table is already kept for {name} at {time}."),
"reservation.table_busy": (409, "That table already has an open order. Pick another table, or close that order first."),
"kds.item_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."),
diff --git a/local_backend/routers/connect_orders.py b/local_backend/routers/connect_orders.py
index b455d0f..77f9ae5 100644
--- a/local_backend/routers/connect_orders.py
+++ b/local_backend/routers/connect_orders.py
@@ -370,6 +370,29 @@ def arrive_booking(reservation_id: int, body: ArriveRequest, background: Backgro
return booking_out(r)
+class KeepTableRequest(BaseModel):
+ table_id: Optional[int] = None
+
+
+@router.post("/bookings/{reservation_id}/table")
+def keep_table(reservation_id: int, body: KeepTableRequest, db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
+ """Give a confirmed booking its table ahead (plan step 6.9, from 4.8), or take it back (null).
+ The table then shows RESERVED when the booking is near (routers/tables) and the pickers say
+ it's kept; seating them later offers it first. One table can't be kept for two bookings
+ within two hours of each other."""
+ from services import online_reservations as svc
+ r = _booking(db, reservation_id)
+ if r.status != "pending":
+ raise XeniaError("reservation.status_changed", current=r.status)
+ svc.keep_table(db, r, body.table_id)
+ r.updated_at = utcnow()
+ db.commit()
+ db.refresh(r)
+ broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
+ broadcast_sync("table_list_changed", {})
+ return booking_out(r)
+
+
@router.post("/bookings/{reservation_id}/cancel")
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py
index 1cf57bb..951b5b3 100644
--- a/local_backend/routers/orders.py
+++ b/local_backend/routers/orders.py
@@ -327,6 +327,35 @@ def get_pending_prints(
return {"count": len(pending_jobs), "orders": orders_data}
+@router.get("/menu")
+def ordering_menu(db: Session = Depends(get_db), user: User = Depends(get_current_user)):
+ """What the manager's ordering offers (plan step 6.9): the categories and every product sold
+ in the shop (eating in), with its in-store price now and its choices, in the counter's shape
+ (routers/pos._product_out), so the same product dialog and line ids (4.4) work; service items
+ (cover charge, cutlery…) too, marked `service`. Lines go to POST /{id}/items like the phones'."""
+ from sqlalchemy.orm import selectinload
+ from core import sales_points
+ from models.product import Category, ProductPreferenceSet
+ from routers.pos import _product_out
+ from services import pos_cart
+ if not (holds(user, "ordering.orders.open") or holds(user, "core.dashboard.access")):
+ raise XeniaError("access.denied", key="ordering.orders.open")
+ products = (db.query(Product)
+ .filter(Product.lifecycle_status == "active", Product.system_key.is_(None))
+ .options(selectinload(Product.quick_options), selectinload(Product.options), selectinload(Product.ingredients),
+ selectinload(Product.preference_sets).selectinload(ProductPreferenceSet.choices),
+ selectinload(Product.memberships))
+ .order_by(Product.sort_order, Product.name).all())
+ products = [p for p in products if p.is_service_item or sales_points.is_sold_at(p, "in_store")]
+ prices = pos_cart.unit_prices(db, products, "in_store") if products else []
+ cats = db.query(Category).order_by(Category.sort_order, Category.name).all()
+ return {
+ "categories": [{"id": c.id, "name": c.name, "color": c.color, "parent_id": c.parent_id, "sort_order": c.sort_order} for c in cats],
+ "products": [{**_product_out(p, prices[i]), "service": bool(p.is_service_item), "available": bool(p.is_available)}
+ for i, p in enumerate(products)],
+ }
+
+
@router.get("/{order_id}")
def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)):
order = db.query(Order).filter(Order.id == order_id).first()
diff --git a/local_backend/routers/reservations.py b/local_backend/routers/reservations.py
index ed1c873..bdda718 100644
--- a/local_backend/routers/reservations.py
+++ b/local_backend/routers/reservations.py
@@ -47,15 +47,21 @@ def create_reservation(
email=body.email,
note=body.note,
reserved_for=body.reserved_for,
- table_id=body.table_id,
source=body.source,
online_customer_id=body.online_customer_id,
created_by_user_id=user.id,
status="pending",
)
+ if body.table_id:
+ from services.online_reservations import keep_table
+ keep_table(db, r, body.table_id) # not kept for another booking close by (6.9)
db.add(r)
db.commit()
db.refresh(r)
+ from services.ws_bus import broadcast_sync
+ broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
+ if r.table_id:
+ broadcast_sync("table_list_changed", {})
return _enrich(r)
@@ -123,10 +129,11 @@ def update_reservation(
raise XeniaError("reservation.not_found", reservation_id=reservation_id)
updates = body.model_dump(exclude_none=True)
-
- if "table_id" in updates and updates["table_id"] is not None:
- if not db.query(Table).filter(Table.id == updates["table_id"], Table.is_active == True).first():
- raise XeniaError("table.not_found", status=400)
+ # the table: set, changed or taken back (null) — kept for one booking at a time (6.9)
+ if "table_id" in body.model_fields_set:
+ from services.online_reservations import keep_table
+ keep_table(db, r, body.table_id)
+ updates.pop("table_id", None)
if "status" in updates and updates["status"] not in VALID_STATUSES:
raise XeniaError("validation.choice", field='status', value=updates['status'])
@@ -137,6 +144,9 @@ def update_reservation(
r.updated_at = utcnow()
db.commit()
db.refresh(r)
+ from services.ws_bus import broadcast_sync
+ broadcast_sync("reservation_updated", {"reservation_id": r.id, "status": r.status, "table_id": r.table_id})
+ broadcast_sync("table_list_changed", {})
return _enrich(r)
diff --git a/local_backend/services/online_reservations.py b/local_backend/services/online_reservations.py
index 5fb192e..dce6f03 100644
--- a/local_backend/services/online_reservations.py
+++ b/local_backend/services/online_reservations.py
@@ -102,6 +102,25 @@ def cancel(db, r, status: str, reason: str | None) -> None:
logger.info("Reservation %s cancelled after its food was fired (order %s)", r.id, r.order_id)
+def keep_table(db, r, table_id: int | None) -> None:
+ """A booking's table ahead (plan step 6.9) or none. Refused when the table is kept for another
+ booking within two hours of this one (reservation.table_kept)."""
+ from datetime import timedelta
+ from core.timeutil import venue_strftime
+ from models.reservation import Reservation
+ from models.table import Table
+ if table_id is not None:
+ if db.query(Table).filter(Table.id == table_id, Table.is_active.is_(True)).first() is None:
+ raise XeniaError("reservation.table_unknown", table_id=table_id)
+ clash = (db.query(Reservation).filter(Reservation.id != r.id, Reservation.table_id == table_id,
+ Reservation.status.in_(("pending", "requested")),
+ Reservation.reserved_for > r.reserved_for - timedelta(hours=2),
+ Reservation.reserved_for < r.reserved_for + timedelta(hours=2)).first())
+ if clash is not None:
+ raise XeniaError("reservation.table_kept", name=clash.guest_name, time=venue_strftime(clash.reserved_for, "%H:%M"))
+ r.table_id = table_id
+
+
def table_busy(db, table_id: int, order_id: int | None = None) -> bool:
from models.order import Order
q = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("open", "partially_paid")))
diff --git a/local_backend/tests/test_manager_ordering.py b/local_backend/tests/test_manager_ordering.py
new file mode 100644
index 0000000..bbfb3b8
--- /dev/null
+++ b/local_backend/tests/test_manager_ordering.py
@@ -0,0 +1,40 @@
+"""The manager's ordering (plan step 6.9): the menu it offers, and orders taken, changed, paid and
+closed by the same rules as the phones (prices from line ids, close with unpaid items only when
+the venue allows it)."""
+from tests.test_live import err, owner_h # noqa: F401 (fixtures)
+from tests.test_pos import menu # noqa: F401 (fixtures)
+from tests.test_tablet_orders import day # noqa: F401 (fixtures)
+
+
+def test_the_menu_for_the_manager(client, owner_h, menu, make_user, login):
+ data = client.get("/api/orders/menu", headers=owner_h).json()
+ by = {p["name"]: p for p in data["products"]}
+ assert by["Burger"]["price"] == 10.0 and by["Burger"]["prefs"][0]["name"] == "Cooking"
+ assert by["Cutlery"]["service"] is True and "Old dish" in by and by["Old dish"]["available"] is False
+ cook = login(make_user(role="cook"), client="manager")
+ assert err(client.get("/api/orders/menu", headers=cook)) == "access.denied"
+
+
+def test_taken_changed_paid_and_closed_by_the_phones_rules(client, owner_h, menu, day, monkeypatch):
+ import routers.orders as orders_api
+ from models.settings import PosSettings # noqa: F401
+ monkeypatch.setattr(orders_api, "route_and_print_sync", lambda *a, **kw: [])
+ from models.table import Table
+ from database import SessionLocal # noqa: F401
+ o = client.post("/api/orders/", headers=owner_h, json={"table_id": None, "order_type": "here"}).json()
+ burger = {"product_id": menu["burger"].id, "quantity": 1, "prefs": [{"set_id": menu["cook"].id, "choices": [{"id": menu["well"].id}], "shared": "Fries"}]}
+ cheat = client.post("/api/orders/quote", headers=owner_h, json={"order_id": o["id"], "lines": [{**burger, "unit_price": 0.01}]})
+ assert err(cheat) == "order.line.client_price" # no app sends prices
+ q = client.post("/api/orders/quote", headers=owner_h, json={"order_id": o["id"], "lines": [burger]}).json()
+ assert q["total"] == 10.5
+ r = client.post(f"/api/orders/{o['id']}/items", headers=owner_h, json={"lines": [burger, {"product_id": menu["coffee"].id, "quantity": 2}]})
+ assert r.status_code == 200, r.text
+ items = client.get(f"/api/orders/{o['id']}", headers=owner_h).json()["items"]
+ assert sorted(round(i["unit_price"], 2) for i in items) == [3.0, 10.5]
+ coffee = next(i for i in items if i["product_id"] == menu["coffee"].id)
+ client.post(f"/api/orders/{o['id']}/cancel-items", headers=owner_h, json={"item_ids": [coffee["id"]], "reason": "wrong"})
+ # unpaid → closing is refused (the venue's default): pay first, then close
+ assert err(client.post(f"/api/orders/{o['id']}/close", headers=owner_h)) == "pos.order_unpaid"
+ live = [i["id"] for i in client.get(f"/api/orders/{o['id']}", headers=owner_h).json()["items"] if i["status"] == "active"]
+ assert client.post(f"/api/orders/{o['id']}/pay", headers=owner_h, json={"item_ids": live, "payment_method": "cash"}).status_code == 200
+ assert client.post(f"/api/orders/{o['id']}/close", headers=owner_h).json()["status"] == "closed"
diff --git a/local_backend/tests/test_online_bookings.py b/local_backend/tests/test_online_bookings.py
index dbf8a8f..5653932 100644
--- a/local_backend/tests/test_online_bookings.py
+++ b/local_backend/tests/test_online_bookings.py
@@ -200,3 +200,42 @@ def test_reservation_settings(client, owner_h):
assert r.json()["reservations"]["hours"] == {"4": [["19:00", "23:30"]]} and r.json()["reservations"]["fire_minutes"] == 25
body["reservations"]["party_max"] = 0
assert client.put("/api/connect/fees/ordering", headers=owner_h, json=body).status_code == 422
+
+
+def test_a_confirmed_booking_keeps_its_table_ahead(client, db, counter, menu, cloud, owner_h):
+ """Plan step 6.9 (from 4.8): a confirmed booking can be given a table ahead, so the table shows
+ RESERVED and the pickers see it; one table isn't kept for two bookings close together."""
+ from models.table import Table
+ t5 = Table(number=5, seat_count=4)
+ db.add(t5)
+ db.commit()
+ rid, _ = book(db, menu, cloud_id=711, food=False, minutes=90)
+ assert err(client.post(f"/api/connect/bookings/{rid}/table", headers=counter["h"], json={"table_id": t5.id})) == "reservation.status_changed"
+ client.post(f"/api/connect/bookings/{rid}/confirm", headers=counter["h"])
+ kept = client.post(f"/api/connect/bookings/{rid}/table", headers=counter["h"], json={"table_id": t5.id})
+ assert kept.status_code == 200 and kept.json()["table_label"] == "T5"
+ table = next(t for t in client.get("/api/tables/", headers=owner_h).json() if t["id"] == t5.id)
+ assert table["upcoming_reservation"]["guest_name"] == "Eleni" # RESERVED
+ live = next(t for t in client.get("/api/floor-plans/live", headers=owner_h).json()["tables"] if t["id"] == t5.id)
+ assert live["state"] == "reserved"
+ rid2, _ = book(db, menu, cloud_id=712, food=False, minutes=150)
+ client.post(f"/api/connect/bookings/{rid2}/confirm", headers=counter["h"])
+ assert err(client.post(f"/api/connect/bookings/{rid2}/table", headers=counter["h"], json={"table_id": t5.id})) == "reservation.table_kept"
+ assert client.post(f"/api/connect/bookings/{rid}/table", headers=counter["h"], json={"table_id": None}).json()["table_id"] is None
+ assert client.post(f"/api/connect/bookings/{rid2}/table", headers=counter["h"], json={"table_id": t5.id}).status_code == 200
+
+
+def test_the_managers_booking_dialog_keeps_and_frees_a_table(client, db, owner_h):
+ from core.timeutil import utcnow
+ from datetime import timedelta
+ from models.table import Table
+ t7 = Table(number=7)
+ db.add(t7)
+ db.commit()
+ when = (utcnow() + timedelta(hours=1)).isoformat()
+ a = client.post("/api/reservations/", headers=owner_h, json={"guest_name": "Nikos", "party_size": 2, "reserved_for": when, "table_id": t7.id})
+ assert a.status_code == 201, a.text
+ b = client.post("/api/reservations/", headers=owner_h, json={"guest_name": "Maria", "party_size": 2, "reserved_for": when, "table_id": t7.id})
+ assert err(b) == "reservation.table_kept"
+ freed = client.patch(f"/api/reservations/{a.json()['id']}", headers=owner_h, json={"table_id": None})
+ assert freed.status_code == 200 and freed.json()["table_id"] is None
diff --git a/manager_dashboard/Dockerfile b/manager_dashboard/Dockerfile
index 2007b95..c5210a1 100644
--- a/manager_dashboard/Dockerfile
+++ b/manager_dashboard/Dockerfile
@@ -13,6 +13,7 @@ COPY packages/api/package.json packages/api/
COPY packages/access/package.json packages/access/
COPY packages/signage/package.json packages/signage/
COPY packages/floorplan/package.json packages/floorplan/
+COPY packages/ordering/package.json packages/ordering/
COPY waiter_pwa/package.json waiter_pwa/
COPY manager_dashboard/package.json manager_dashboard/
COPY terminal/package.json terminal/
diff --git a/manager_dashboard/package.json b/manager_dashboard/package.json
index 128ff85..a024e4c 100644
--- a/manager_dashboard/package.json
+++ b/manager_dashboard/package.json
@@ -16,6 +16,7 @@
"@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0",
+ "@xenia/ordering": "^0.0.0",
"@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx
index 52db3cf..83c7f27 100644
--- a/manager_dashboard/src/App.jsx
+++ b/manager_dashboard/src/App.jsx
@@ -14,8 +14,8 @@ import SetupWizard from './pages/SetupWizard'
// Operation
import OverviewPage from './pages/overview/OverviewPage'
-import TablesPage from './pages/TablesPage'
-import OrderDetailPage from './pages/OrderDetailPage'
+import TablesPage from './pages/orders/TablesPage'
+import OrderPage from './pages/orders/OrderPage'
import OnlineOrdersPage from './pages/online/OnlineOrdersPage'
import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage'
@@ -151,7 +151,7 @@ export default function App() {
} />
} />
} />
- } />
+ } />
{/* ── CRM ── */}
} />
diff --git a/manager_dashboard/src/pages/DesktopOrderingTab.jsx b/manager_dashboard/src/pages/DesktopOrderingTab.jsx
deleted file mode 100644
index 729ca67..0000000
--- a/manager_dashboard/src/pages/DesktopOrderingTab.jsx
+++ /dev/null
@@ -1,843 +0,0 @@
-import { useState, useRef, useCallback, useEffect } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-import { LineError, wireLine } from '@xenia/api'
-import ManagerOrderDrawer from './ManagerOrderDrawer'
-
-// ── Constants ─────────────────────────────────────────────────────────────────
-
-const FAV_CAT_ID = '__favorites__'
-const SVC_CAT_ID = '__service__'
-const DECIMAL_UNITS = new Set(['kg', 'liter', 'gram', 'ml'])
-const DECIMAL_UNIT_LABELS = { kg: 'kg', liter: 'L', gram: 'g', ml: 'mL' }
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-function productAllowsQuickAdd(product) {
- if (!product.quick_add_enabled) return false
- for (const ps of (product.preference_sets || [])) {
- if (ps.default_choice_id == null) return false
- }
- return true
-}
-
-function buildQuickAddItem(product) {
- const qty = DECIMAL_UNITS.has(product.unit_type) ? 1.0 : 1
- const selectedOptions = []
- for (const ps of (product.preference_sets || [])) {
- const defaultChoice = ps.choices?.find(c => c.id === ps.default_choice_id)
- if (defaultChoice) {
- selectedOptions.push({ id: defaultChoice.id, name: defaultChoice.name, price_delta: defaultChoice.extra_cost ?? 0 })
- }
- }
- return {
- product_id: product.id,
- quantity: qty,
- unit_type: product.unit_type || 'piece',
- unit_price: product.base_price,
- notes: '',
- selected_options: selectedOptions,
- removed_ingredients: [],
- }
-}
-
-function fmtQty(qty, unitType) {
- const label = DECIMAL_UNIT_LABELS[unitType]
- if (!label) return `×${qty}`
- if (unitType === 'kg' || unitType === 'liter') return `${Number(qty).toFixed(1)}${label}`
- return `${qty}${label}`
-}
-
-function hexToRgba(hex, alpha) {
- if (!hex) return null
- const h = hex.replace('#', '')
- const r = parseInt(h.substring(0, 2), 16)
- const g = parseInt(h.substring(2, 4), 16)
- const b = parseInt(h.substring(4, 6), 16)
- return `rgba(${r},${g},${b},${alpha})`
-}
-
-function buildSections(parent, subcategories, directProducts) {
- const sections = []
- if (directProducts.length > 0) {
- sections.push({ _isGeneral: true, sort_order: parent.general_sort_order, products: directProducts })
- }
- for (const sub of subcategories) {
- sections.push({ ...sub, _isGeneral: false, sort_order: sub.sort_order })
- }
- return sections.sort((a, b) => a.sort_order - b.sort_order)
-}
-
-// ── Product card for the desktop grid ─────────────────────────────────────────
-
-function DesktopProductCard({ product, onOpen, onQuickAdd }) {
- const canQuickAdd = productAllowsQuickAdd(product)
- const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
-
- return (
-
-
- {/* ── LEFT: Category + Product browser ─────────────────────────────── */}
-
-
- {/* Toolbar */}
-
-
- {/* SERVICE chip */}
- {serviceProducts.length > 0 && (
-
selectCategory(SVC_CAT_ID)}
- style={{
- height: 32, padding: '0 14px', borderRadius: 16, border: isSvcActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
- background: isSvcActive ? '#f59e0b' : '#fff7ed', color: isSvcActive ? '#fff' : '#d97706',
- fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
- display: 'flex', alignItems: 'center', gap: 4,
- }}
- >
-
-
-
- Service
-
- )}
- {topLevel.map(cat => {
- const isActive = activeCat === cat.id
- const bg = cat.color
- ? isActive ? cat.color : hexToRgba(cat.color, 0.15)
- : isActive ? '#f59e0b' : '#f8fafc'
- const color = cat.color
- ? isActive ? '#fff' : cat.color
- : isActive ? '#fff' : '#64748b'
- return (
-
selectCategory(cat.id)}
- style={{
- height: 32, padding: '0 14px', borderRadius: 16,
- border: isActive && cat.color ? `2px solid ${cat.color}` : isActive ? '2px solid #f59e0b' : '1px solid #e2e8f0',
- background: bg, color,
- fontSize: 12, fontWeight: 700, cursor: 'pointer', whiteSpace: 'nowrap',
- }}
- >{cat.name}
- )
- })}
-
setViewAllOpen(true)}
- style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', whiteSpace: 'nowrap', flexShrink: 0 }}>
- Όλες →
-
-
-
setSearchOpen(true)}
- style={{ height: 32, padding: '0 12px', borderRadius: 16, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 12, fontWeight: 600, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 5, flexShrink: 0 }}>
-
-
-
-
- Αναζήτηση
-
-
-
- {/* Product area */}
-
-
- {isSvcActive ? (
-
- {serviceProducts.map(p => (
- addToCart(item)} />
- ))}
-
- ) : !hasSubcats ? (
- <>
-
- {directProducts.map(p => (
-
- ))}
-
- {directProducts.length === 0 && (
-
Δεν υπάρχουν προϊόντα
- )}
- >
- ) : (
-
- {sections.map(section => {
- const key = section._isGeneral ? '__general__' : String(section.id)
- const isExpanded = !!expandedSubs[key]
- const sectionProducts = section._isGeneral
- ? section.products
- : regularProducts.filter(p => p.category_id === section.id)
- if (sectionProducts.length === 0) return null
-
- if (section._isGeneral) {
- return (
-
-
- {sectionProducts.map(p => (
-
- ))}
-
-
- )
- }
-
- const accentColor = section.color ?? activeParent?.color ?? null
- return (
-
-
setExpandedSubs(prev => ({ ...prev, [key]: !prev[key] }))}
- style={{
- width: '100%', padding: '10px 14px', background: isExpanded ? '#f8fafc' : 'white',
- border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8, textAlign: 'left',
- }}
- >
- {accentColor && }
- {section.name}
- {sectionProducts.length}
-
-
-
-
- {isExpanded && (
-
-
- {sectionProducts.map(p => (
-
- ))}
-
-
- )}
-
- )
- })}
-
- )}
-
-
-
- {/* ── RIGHT: Cart panel or Drawer panel ────────────────────────────── */}
-
- {drawerOpen ? (
-
{ setDrawerProduct(null); setEditItem(null) }}
- onAdd={handleDrawerAdd}
- courses={courses}
- />
- ) : (
- /* Cart */
-
- {/* Cart header */}
-
-
Νέα Παραγγελία
-
- {cart.length === 0 ? 'Επιλέξτε προϊόντα από τα αριστερά' : `${cart.length} ${cart.length === 1 ? 'προϊόν' : 'προϊόντα'}`}
-
-
-
- {/* Item list */}
-
- {cart.length === 0 ? (
-
-
-
-
-
Το καλάθι είναι άδειο
-
- ) : (
-
- {cart.map(item => {
- const product = products.find(p => p.id === item.product_id)
- return (
- removeFromCart(item._key)}
- onChangeQty={qty => changeCartQty(item._key, qty)}
- onEdit={() => openEditDrawer(item)}
- />
- )
- })}
-
- )}
-
-
- {/* Order note */}
- {cart.length > 0 && (
-
-
- )}
-
- {/* Cart footer */}
-
- {cart.length > 0 && (
-
- Σύνολο
- €{cartTotal.toFixed(2)}
-
- )}
-
addItemsMutation.mutate()}
- disabled={cart.length === 0 || addItemsMutation.isPending}
- style={{
- width: '100%', height: 44, borderRadius: 22,
- background: cart.length === 0 ? '#e2e8f0' : '#f59e0b',
- border: 'none', color: cart.length === 0 ? '#94a3b8' : '#fff',
- fontSize: 15, fontWeight: 700, fontFamily: 'inherit',
- cursor: cart.length === 0 ? 'default' : 'pointer',
- transition: 'background 150ms ease',
- display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
- }}
- >
- {addItemsMutation.isPending ? 'Αποστολή…' : `ΑΠΟΣΤΟΛΗ${cart.length > 0 ? ` (${cart.length})` : ''}`}
-
- {cart.length > 0 && (
-
setCart([])}
- style={{ width: '100%', marginTop: 6, padding: '6px 0', background: 'none', border: 'none', color: '#94a3b8', fontSize: 12, cursor: 'pointer' }}>
- Εκκαθάριση καλαθιού
-
- )}
-
-
- )}
-
-
- {/* View all categories modal */}
- {viewAllOpen && (
- <>
-
setViewAllOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
-
-
- Κατηγορίες
- setViewAllOpen(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: 18 }}>✕
-
-
- {serviceProducts.length > 0 && (
- { selectCategory(SVC_CAT_ID); setViewAllOpen(false) }}
- style={{ padding: '14px 10px', borderRadius: 12, background: '#fff7ed', border: isSvcActive ? '2px solid #f59e0b' : '1px solid #fed7aa', cursor: 'pointer', fontSize: 13, fontWeight: 700, color: '#d97706', textAlign: 'center' }}>
- Service
-
- )}
- {topLevel.map(cat => {
- const isActive = activeCat === cat.id
- return (
- { selectCategory(cat.id); setViewAllOpen(false) }}
- style={{
- padding: '14px 10px', borderRadius: 12, cursor: 'pointer', fontSize: 13, fontWeight: 700, textAlign: 'center',
- background: cat.color || '#f1f5f9',
- color: cat.color ? '#fff' : '#475569',
- border: isActive ? '2px solid #f59e0b' : '1px solid transparent',
- boxShadow: cat.color ? 'inset 0 0 0 100px rgba(0,0,0,0.15)' : 'none',
- }}>
- {cat.name}
-
- )
- })}
-
-
- >
- )}
-
- {/* Search modal */}
- {searchOpen && (
-
setSearchOpen(false)}
- onOpen={p => { setDrawerProduct(p); setSearchOpen(false) }}
- />
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/ManagerOrderDrawer.jsx b/manager_dashboard/src/pages/ManagerOrderDrawer.jsx
deleted file mode 100644
index bc5057b..0000000
--- a/manager_dashboard/src/pages/ManagerOrderDrawer.jsx
+++ /dev/null
@@ -1,854 +0,0 @@
-import { useState, useEffect, useRef } from 'react'
-
-// ── Helpers ───────────────────────────────────────────────────────────────────
-
-const DECIMAL_UNIT_CONFIG = {
- kg: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'kg' },
- liter: { step: 0.05, min: 0.05, presets: [0.10, 0.20, 0.25, 0.50, 0.70, 1.00, 1.50, 2.00, 2.50, 3.00, 4.00, 5.00], offsets: [0.1, 0.2, 0.5, 1.0], label: 'L' },
- gram: { step: 10, min: 10, presets: [50, 100, 150, 200, 250, 300, 400, 500], offsets: [10, 50, 100, 200], label: 'g' },
- ml: { step: 5, min: 5, presets: [25, 50, 100, 150, 200, 250, 300, 500], offsets: [25, 50, 100, 200], label: 'mL' },
-}
-
-function fmtDecimalQty(qty, cfg) {
- if (!cfg) return String(qty)
- if (cfg.label === 'kg' || cfg.label === 'L') {
- const n = Number(qty)
- return n % 1 === 0 ? n.toFixed(1) : (Math.round(n * 100) / 100).toFixed(2).replace(/0$/, '')
- }
- return String(qty)
-}
-
-function buildInitialState(product) {
- const preferenceSets = product.preference_sets || []
- const prefs = {}
- const subChoices = {}
- const sharedSubs = {}
-
- preferenceSets.forEach(ps => {
- const def = ps.default_choice_id != null
- ? ps.choices.find(c => c.id === ps.default_choice_id) ?? null
- : null
- prefs[ps.id] = def
- if (def) {
- if (def.sub_choices?.length > 0) {
- subChoices[def.id] = def.sub_choices.find(s => s.is_default) ?? def.sub_choices[0]
- }
- if (ps.shared_subset?.choices?.length > 0 && !def.disables_subset) {
- sharedSubs[ps.id] = ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]
- }
- }
- })
-
- return { prefs, subChoices, sharedSubs }
-}
-
-const QUICK_NOTES = ['Χωρίς αλάτι', 'Βγάλτε γρήγορα', 'Αλλεργία!', 'Κόψτε σε μικρά κομμάτια', 'Έξτρα χαρτοπετσέτες']
-const PRICE_DELTAS = [-5, -3, -2, -1, -0.5, -0.2, +0.2, +0.5, +1, +2, +3, +5]
-
-// ── Primitive UI ──────────────────────────────────────────────────────────────
-
-function CheckCircle({ selected }) {
- return (
-
- )
-}
-
-function RadioDot({ selected }) {
- return (
-
- )
-}
-
-function Row({ selected, onClick, children, right, left }) {
- return (
-
- {left &&
{left}
}
-
{children}
- {right &&
{right}
}
-
- )
-}
-
-function Stepper({ value, onChange, min = 0, max = 99 }) {
- return (
-
e.stopPropagation()}>
-
onChange(Math.max(min, value - 1))} disabled={value <= min}
- style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value <= min ? 'default' : 'pointer', color: value <= min ? '#94a3b8' : '#1e293b' }}>−
-
{value}
-
onChange(Math.min(max, value + 1))} disabled={value >= max}
- style={{ width: 36, height: 36, border: 'none', background: 'transparent', fontSize: 16, fontWeight: 500, cursor: value >= max ? 'default' : 'pointer', color: value >= max ? '#94a3b8' : '#1e293b' }}>+
-
- )
-}
-
-// ── Option rows ───────────────────────────────────────────────────────────────
-
-function QuickOptionRow({ opt, quickState, setQuickState }) {
- const qty = quickState[opt.id] || 0
- const selected = qty > 0
- return (
-
setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))}
- left={ }
- right={opt.allow_multiple ? (
- e.stopPropagation()}>
- {selected
- ?
setQuickState(s => ({ ...s, [opt.id]: v }))} />
- : { e.stopPropagation(); setQuickState(s => ({ ...s, [opt.id]: 1 })) }}
- style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
-
-
- }
-
- ) : null}
- >
- {opt.name}
- {opt.price > 0 && +{opt.price.toFixed(2)} €
}
-
- )
-}
-
-function ExtraOptionRow({ opt, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
- const sel = extrasState[opt.id]
- const selected = !!sel
- const open = expandedExtra === opt.id
- const hasSubs = opt.sub_choices?.length > 0
- const subLabel = sel ? opt.sub_choices?.find(s => s.name === sel.subName)?.name : null
-
- const toggle = () => {
- if (selected) {
- setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n })
- if (open) setExpandedExtra(null)
- } else {
- const firstSub = hasSubs ? opt.sub_choices[0] : null
- setExtrasState(s => ({ ...s, [opt.id]: { qty: 1, subName: firstSub?.name ?? null } }))
- if (hasSubs) setExpandedExtra(opt.id)
- }
- }
-
- return (
-
-
|
}
- right={
-
e.stopPropagation()}>
- {selected && opt.allow_multiple && (
-
{
- if (v === 0) { setExtrasState(s => { const n = { ...s }; delete n[opt.id]; return n }); return }
- setExtrasState(s => ({ ...s, [opt.id]: { ...sel, qty: v } }))
- }} />
- )}
- {selected && hasSubs && (
- { e.stopPropagation(); setExpandedExtra(open ? null : opt.id) }}
- style={{ width: 30, height: 30, borderRadius: '50%', background: '#f1f5f9', border: '1px solid #e2e8f0', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
-
-
-
-
- )}
-
- }
- >
-
{opt.name}
-
- {(opt.extra_cost ?? 0) !== 0 ? `+${opt.extra_cost.toFixed(2)} €` : 'Included'}
- {subLabel && · {subLabel} }
-
-
- {selected && open && hasSubs && (
-
-
Επιλογή
- {opt.sub_choices.map((sub, si) => {
- const isSel = sel.subName === sub.name
- return (
-
setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={ }>
-
-
{sub.name}
- {(sub.extra_cost ?? 0) !== 0 &&
+{sub.extra_cost.toFixed(2)} €
}
-
-
- )
- })}
-
- )}
-
- )
-}
-
-function IngredientRow({ ing, removedState, setRemovedState }) {
- const removed = !!removedState[ing.id]
- return (
-
setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))}
- right={
-
- {removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
-
- }
- >
- {ing.name}
-
- )
-}
-
-function PrefSetBlock({ ps, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
- const selChoice = prefs[ps.id] ?? null
- const complete = selChoice != null
- && !(selChoice.sub_choices?.length > 0 && subChoices[selChoice.id] == null)
- && !(ps.shared_subset?.choices?.length > 0 && !selChoice.disables_subset && sharedSubs[ps.id] == null)
- const showShared = ps.shared_subset?.choices?.length > 0 && selChoice != null && !selChoice.disables_subset
-
- function selectPref(choice) {
- setPrefs(p => ({ ...p, [ps.id]: choice }))
- if (choice?.sub_choices?.length > 0) {
- setSubChoices(s => ({ ...s, [choice.id]: s[choice.id] ?? (choice.sub_choices.find(x => x.is_default) ?? choice.sub_choices[0]) }))
- }
- if (ps.shared_subset?.choices?.length > 0 && !choice?.disables_subset) {
- setSharedSubs(s => s[ps.id] != null ? s : { ...s, [ps.id]: ps.shared_subset.choices.find(x => x.is_default) ?? ps.shared_subset.choices[0] })
- }
- }
-
- return (
-
-
-
{ps.name}
- {!complete &&
Απαιτείται
}
-
-
- {ps.choices.map(ch => {
- const isSel = selChoice?.id === ch.id
- const hasSubs = ch.sub_choices?.length > 0
- return (
-
-
selectPref(ch)} left={ }
- right={(ch.extra_cost ?? 0) !== 0 ? {ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €
: null}>
- {ch.name}
-
- {isSel && hasSubs && (
-
- {ch.sub_choices.map((sub, si) => {
- const subSel = subChoices[ch.id]?.name === sub.name
- return (
-
setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={ }
- right={(sub.extra_cost ?? 0) !== 0 ? +{sub.extra_cost.toFixed(2)} €
: null}>
- {sub.name}
-
- )
- })}
-
- )}
-
- )
- })}
- {showShared && (
-
-
{ps.shared_subset.name}
- {ps.shared_subset.choices.map((sub, si) => {
- const subSel = sharedSubs[ps.id]?.name === sub.name
- return (
-
setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={ }
- right={(sub.extra_cost ?? 0) !== 0 ? +{sub.extra_cost.toFixed(2)} €
: null}>
- {sub.name}
-
- )
- })}
-
- )}
-
-
- )
-}
-
-// ── Tab content ───────────────────────────────────────────────────────────────
-
-function QuickTab({ product, quickState, setQuickState }) {
- const quickOptions = product.quick_options || []
- if (quickOptions.length === 0) return
Δεν υπάρχουν γρήγορες επιλογές.
- return (
-
- {quickOptions.map(opt => (
-
-
-
- ))}
-
- )
-}
-
-function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
- const options = product.options || []
- if (options.length === 0) return
Δεν υπάρχουν extras.
- return (
-
- {options.map(opt => (
-
- ))}
-
- )
-}
-
-function IngredientsTab({ product, removedState, setRemovedState }) {
- const ingredients = product.ingredients || []
- if (ingredients.length === 0) return
Δεν υπάρχουν υλικά.
- return (
-
-
- Κάντε κλικ για να αφαιρέσετε υλικό.
-
- {ingredients.map(ing => (
-
- ))}
-
- )
-}
-
-function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
- const preferenceSets = product.preference_sets || []
- if (preferenceSets.length === 0) return
Δεν υπάρχουν προτιμήσεις.
- return (
-
- {preferenceSets.map(ps => (
-
- ))}
-
- )
-}
-
-function QuantityTab({ unitCfg, qty, setQty }) {
- const [editing, setEditing] = useState(false)
- const [qtyInput, setQtyInput] = useState('')
- const inputRef = useRef(null)
-
- function clamp(v) { return Math.max(unitCfg.min, Math.round(v * 1000) / 1000) }
-
- return (
-
-
-
-
setQty(q => clamp(q - unitCfg.step))}
- style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>−
- {editing ? (
-
setQtyInput(e.target.value)}
- onBlur={() => { const v = parseFloat(qtyInput); if (!isNaN(v)) setQty(clamp(v)); setEditing(false) }}
- onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
- autoFocus
- style={{ width: 70, height: 48, border: 'none', background: 'transparent', textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', outline: 'none', fontFamily: 'inherit' }}
- />
- ) : (
-
{ setQtyInput(String(qty)); setEditing(true) }}
- style={{ minWidth: 70, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b', cursor: 'text', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 3 }}>
- {fmtDecimalQty(qty, unitCfg)}
- {unitCfg.label}
-
- )}
-
setQty(q => clamp(q + unitCfg.step))}
- style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+
-
-
-
-
ΓΡΗΓΟΡΗ ΕΠΙΛΟΓΗ
-
- {unitCfg.presets.map(v => (
- setQty(v)} style={{
- padding: '8px 4px', borderRadius: 10, border: 'none',
- background: qty === v ? '#f59e0b' : '#f1f5f9',
- color: qty === v ? '#fff' : '#1e293b',
- fontSize: 12, fontWeight: 700, cursor: 'pointer',
- }}>
- {fmtDecimalQty(v, unitCfg)}{unitCfg.label}
-
- ))}
-
-
-
-
ΓΡΗΓΟΡΗ ΠΡΟΣΘΗΚΗ
-
- {unitCfg.offsets.map(off => (
- setQty(q => clamp(q + off))} style={{
- padding: '8px 4px', borderRadius: 10, border: 'none',
- background: 'rgba(34,197,94,0.1)', color: '#16a34a',
- fontSize: 12, fontWeight: 700, cursor: 'pointer',
- }}>+{fmtDecimalQty(off, unitCfg)}{unitCfg.label}
- ))}
- {unitCfg.offsets.map(off => (
- setQty(q => clamp(q - off))} style={{
- padding: '8px 4px', borderRadius: 10, border: 'none',
- background: 'rgba(239,68,68,0.08)', color: '#dc2626',
- fontSize: 12, fontWeight: 700, cursor: 'pointer',
- }}>−{fmtDecimalQty(off, unitCfg)}{unitCfg.label}
- ))}
-
-
-
- )
-}
-
-function PriceAdjustTab({ basePrice, priceAdj, setPriceAdj }) {
- const [editing, setEditing] = useState(false)
- const [rawInput, setRawInput] = useState('')
- const inputRef = useRef(null)
- const effectivePrice = basePrice + priceAdj
-
- function applyDelta(d) {
- setPriceAdj(a => {
- const next = Math.round((a + d) * 100) / 100
- return Math.max(-(basePrice - 0.01), next)
- })
- }
-
- function commitInput() {
- const v = parseFloat(rawInput.replace(',', '.'))
- if (!isNaN(v) && v >= 0.01) setPriceAdj(Math.round((v - basePrice) * 100) / 100)
- setEditing(false)
- }
-
- useEffect(() => { if (editing && inputRef.current) inputRef.current.focus() }, [editing])
-
- return (
-
-
- Αλλαγή τιμής μόνο για αυτό το αντικείμενο.
-
-
- applyDelta(-0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>−
- {editing ? (
- setRawInput(e.target.value)}
- onBlur={commitInput}
- onKeyDown={e => { if (e.key === 'Enter') e.target.blur() }}
- style={{ width: 100, height: 48, border: '2px solid #f59e0b', borderRadius: 12, background: 'white', textAlign: 'center', fontSize: 20, fontWeight: 800, color: '#f59e0b', outline: 'none', fontFamily: 'inherit' }}
- />
- ) : (
- { setRawInput(effectivePrice.toFixed(2)); setEditing(true) }} style={{
- minWidth: 100, height: 48, borderRadius: 12,
- border: `2px solid ${priceAdj !== 0 ? '#f59e0b' : '#e2e8f0'}`,
- background: priceAdj !== 0 ? 'rgba(245,158,11,0.08)' : '#f8fafc',
- color: priceAdj !== 0 ? '#f59e0b' : '#1e293b',
- fontSize: 20, fontWeight: 800, cursor: 'pointer', fontFamily: 'inherit',
- }}>
- {effectivePrice.toFixed(2)} €
-
- )}
- applyDelta(+0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>+
-
- {priceAdj !== 0 && (
-
- Βάση: {basePrice.toFixed(2)} €
- 0 ? '#16a34a' : '#dc2626' }}>{priceAdj > 0 ? '+' : ''}{priceAdj.toFixed(2)} €
- setPriceAdj(0)} style={{ padding: '2px 8px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f1f5f9', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>Επαναφορά
-
- )}
-
- {PRICE_DELTAS.map(d => (
- applyDelta(d)} style={{
- padding: '9px 4px', borderRadius: 10, border: 'none',
- background: d < 0 ? 'rgba(239,68,68,0.08)' : 'rgba(34,197,94,0.08)',
- color: d < 0 ? '#dc2626' : '#16a34a',
- fontSize: 13, fontWeight: 700, cursor: 'pointer',
- }}>
- {d > 0 ? '+' : ''}{d.toFixed(2 - (Number.isInteger(d) ? 2 : 0))} €
-
- ))}
-
-
- )
-}
-
-function NotesTab({ note, setNote }) {
- return (
-
- )
-}
-
-// ── Courses tab ───────────────────────────────────────────────────────────────
-
-function CoursesTab({ courses, courseId, setCourseId }) {
- return (
-
- setCourseId(null)}
- style={{
- padding: '10px 14px', borderRadius: 10, textAlign: 'left',
- background: courseId === null ? '#2563eb' : '#f8fafc',
- color: courseId === null ? '#fff' : '#1e293b',
- border: `2px solid ${courseId === null ? '#2563eb' : '#e2e8f0'}`,
- fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
- }}
- >
- No course (fire immediately)
-
- {courses.map(c => (
- setCourseId(courseId === c.id ? null : c.id)}
- style={{
- padding: '10px 14px', borderRadius: 10, textAlign: 'left',
- background: courseId === c.id ? c.color : '#f8fafc',
- color: courseId === c.id ? '#fff' : '#1e293b',
- border: `2px solid ${courseId === c.id ? c.color : '#e2e8f0'}`,
- fontWeight: 600, fontSize: 14, cursor: 'pointer', fontFamily: 'inherit',
- display: 'flex', alignItems: 'center', gap: 10,
- }}
- >
-
- {c.name}
-
- ))}
-
- )
-}
-
-// ── Main component ────────────────────────────────────────────────────────────
-
-export default function ManagerOrderDrawer({ product, onClose, onAdd, initialState, courses }) {
- const preferenceSets = product?.preference_sets || []
- const quickOptions = product?.quick_options || []
- const options = product?.options || []
- const ingredients = product?.ingredients || []
-
- const unitCfg = product ? (DECIMAL_UNIT_CONFIG[product.unit_type] ?? null) : null
- const isDecimal = !!unitCfg
-
- const hasTabs = {
- quick: quickOptions.length > 0,
- extras: options.length > 0,
- ingredients: ingredients.length > 0,
- prefs: preferenceSets.length > 0,
- quantity: isDecimal,
- }
-
- const firstTab = hasTabs.quick ? 'quick'
- : hasTabs.extras ? 'extras'
- : hasTabs.ingredients ? 'ingredients'
- : hasTabs.prefs ? 'prefs'
- : hasTabs.quantity ? 'quantity'
- : 'notes'
-
- const [activeTab, setActiveTab] = useState(firstTab)
- const [qty, setQty] = useState(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
- const [quickState, setQuickState] = useState({})
- const [extrasState, setExtrasState] = useState({})
- const [expandedExtra, setExpandedExtra] = useState(null)
- const [removedState, setRemovedState] = useState({})
- const [prefs, setPrefs] = useState({})
- const [subChoices, setSubChoices] = useState({})
- const [sharedSubs, setSharedSubs] = useState({})
- const [note, setNote] = useState('')
- const [priceAdj, setPriceAdj] = useState(0)
- const [addAttempted, setAddAttempted] = useState(false)
- const [courseId, setCourseId] = useState(initialState?.courseId ?? null)
-
- // Reset when product changes
- useEffect(() => {
- if (!product) return
- const base = buildInitialState(product)
- if (initialState) {
- setQty(initialState.qty ?? (isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1))
- setQuickState(initialState.quickState ?? {})
- setExtrasState(initialState.extrasState ?? {})
- setRemovedState(initialState.removedState ?? {})
- setPrefs(initialState.prefs ?? base.prefs)
- setSubChoices(initialState.subChoices ?? base.subChoices)
- setSharedSubs(initialState.sharedSubs ?? base.sharedSubs)
- setNote(initialState.note ?? '')
- setPriceAdj(initialState.priceAdj ?? 0)
- setCourseId(initialState.courseId ?? null)
- setActiveTab(initialState.activeTab ?? firstTab)
- } else {
- setQty(isDecimal ? (unitCfg?.presets[0] ?? 0.1) : 1)
- setQuickState({})
- setExtrasState({})
- setRemovedState({})
- setPrefs(base.prefs)
- setSubChoices(base.subChoices)
- setSharedSubs(base.sharedSubs)
- setNote('')
- setPriceAdj(0)
- setCourseId(null)
- setActiveTab(firstTab)
- }
- setExpandedExtra(null)
- setAddAttempted(false)
- }, [product?.id])
-
- // Derived total price
- const totalPrice = (() => {
- if (!product) return 0
- let price = product.base_price
- preferenceSets.forEach(ps => {
- const choice = prefs[ps.id]
- if (!choice) return
- const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
- const sharedSub = (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset) ? (sharedSubs[ps.id] ?? null) : null
- price += (choice.extra_cost ?? 0) + (inlineSub?.extra_cost ?? 0) + (sharedSub?.extra_cost ?? 0)
- })
- quickOptions.forEach(opt => { price += (quickState[opt.id] || 0) * (opt.price ?? 0) })
- options.forEach(opt => {
- const sel = extrasState[opt.id]
- if (!sel) return
- const sub = opt.sub_choices?.find(s => s.name === sel.subName)
- price += ((opt.extra_cost ?? 0) + (sub?.extra_cost ?? 0)) * sel.qty
- })
- return (price + priceAdj) * qty
- })()
-
- function isPrefComplete(ps) {
- const choice = prefs[ps.id]
- if (!choice) return false
- if (choice.sub_choices?.length > 0 && subChoices[choice.id] == null) return false
- if (ps.shared_subset?.choices?.length > 0 && !choice.disables_subset && sharedSubs[ps.id] == null) return false
- return true
- }
- const allPrefsOk = preferenceSets.every(isPrefComplete)
- const extrasSubsMissing = options.some(opt => {
- const sel = extrasState[opt.id]
- return sel && opt.sub_choices?.length > 0 && sel.subName == null
- })
- const canAdd = allPrefsOk && !extrasSubsMissing
-
- function handleAdd() {
- if (!canAdd) {
- setAddAttempted(true)
- if (!allPrefsOk && hasTabs.prefs) setActiveTab('prefs')
- return
- }
-
- const prefChoices = preferenceSets.flatMap(ps => {
- const choice = prefs[ps.id]
- if (!choice) return []
- const inlineSub = choice.sub_choices?.length > 0 ? (subChoices[choice.id] ?? null) : null
- const sharedSub = ps.shared_subset?.choices?.length > 0 && !choice.disables_subset ? (sharedSubs[ps.id] ?? null) : null
- const defaultChoice = ps.default_choice_id != null ? ps.choices.find(c => c.id === ps.default_choice_id) : null
- const isDefaultChoice = defaultChoice && choice.id === defaultChoice.id
- const defaultInlineSub = isDefaultChoice && defaultChoice.sub_choices?.length > 0
- ? (defaultChoice.sub_choices.find(s => s.is_default) ?? defaultChoice.sub_choices[0]) : null
- const defaultSharedSub = isDefaultChoice && ps.shared_subset?.choices?.length > 0 && !choice.disables_subset
- ? (ps.shared_subset.choices.find(s => s.is_default) ?? ps.shared_subset.choices[0]) : null
- const isFullyDefault = isDefaultChoice
- && (!inlineSub || inlineSub.name === defaultInlineSub?.name)
- && (!sharedSub || sharedSub.name === defaultSharedSub?.name)
- if (isFullyDefault) return []
- const entries = [{ id: choice.id, name: choice.name, price_delta: choice.extra_cost ?? 0, type: 'pref' }]
- if (inlineSub) entries.push({ id: null, name: inlineSub.name, price_delta: inlineSub.extra_cost ?? 0, type: 'pref_sub' })
- if (sharedSub) entries.push({ id: null, name: sharedSub.name, price_delta: sharedSub.extra_cost ?? 0, type: 'pref_sub' })
- return entries
- })
-
- const optionEntries = options.flatMap(opt => {
- const sel = extrasState[opt.id]
- if (!sel) return []
- const sub = opt.sub_choices?.find(s => s.name === sel.subName)
- const entries = []
- for (let i = 0; i < sel.qty; i++) {
- entries.push({ id: opt.id, name: opt.name, price_delta: opt.extra_cost ?? 0, type: 'extra' })
- if (sub) entries.push({ id: null, name: sub.name, price_delta: sub.extra_cost ?? 0, type: 'extra_sub' })
- }
- return entries
- })
-
- const quickEntries = quickOptions.flatMap(opt => {
- const q = quickState[opt.id] || 0
- if (q === 0) return []
- return Array.from({ length: q }, () => ({ id: null, name: opt.name, price_delta: opt.price ?? 0, type: 'quick' }))
- })
-
- const removedNames = ingredients.filter(ing => removedState[ing.id]).map(ing => ing.name)
-
- onAdd({
- product_id: product.id,
- quantity: qty,
- unit_price: product.base_price,
- selected_options: [...prefChoices, ...quickEntries, ...optionEntries],
- removed_ingredients: removedNames,
- notes: note,
- price_adjustment: priceAdj !== 0 ? priceAdj : undefined,
- course_id: courseId ?? undefined,
- _drawerState: { qty, quickState, extrasState, removedState, prefs, subChoices, sharedSubs, note, priceAdj, courseId },
- })
- }
-
- const tabs = [
- hasTabs.quick && { id: 'quick', label: 'Quick' },
- hasTabs.extras && { id: 'extras', label: 'Extras' },
- hasTabs.ingredients && { id: 'ingredients', label: 'Υλικά' },
- hasTabs.prefs && { id: 'prefs', label: 'Προτιμήσεις' },
- hasTabs.quantity && { id: 'quantity', label: `Ποσότητα (${unitCfg?.label})` },
- (courses?.length > 0) && { id: 'courses', label: 'Courses' },
- { id: 'notes', label: 'Σημείωση' },
- { id: 'price_adjust', label: '€ Τιμή' },
- ].filter(Boolean)
-
- if (!product) return null
-
- const initials = product.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
-
- return (
-
- {/* Header */}
-
-
-
- {product.image_url
- ?
- :
{initials}
- }
-
-
-
{product.name}
-
- {priceAdj !== 0
- ? <>{product.base_price.toFixed(2)} → {(product.base_price + priceAdj).toFixed(2)} €>
- : <>{product.base_price.toFixed(2)} €>
- }
-
-
-
-
-
-
-
- {/* Tabs bar */}
- {tabs.length > 0 && (
-
- {tabs.map(t => {
- const active = activeTab === t.id
- const isAlert = t.id === 'prefs' && !allPrefsOk && addAttempted
- return (
- setActiveTab(t.id)} style={{
- padding: '6px 10px',
- background: 'none', border: 'none',
- borderBottom: `2px solid ${active ? '#f59e0b' : 'transparent'}`,
- color: isAlert ? '#ef4444' : active ? '#f59e0b' : '#64748b',
- fontSize: 12, fontWeight: active ? 700 : 500,
- fontFamily: 'inherit', cursor: 'pointer',
- whiteSpace: 'nowrap',
- transition: 'color 100ms, border-color 100ms',
- }}>
- {t.label}
-
- )
- })}
-
- )}
-
-
- {/* Scrollable content */}
-
- {activeTab === 'quick' &&
}
- {activeTab === 'extras' &&
}
- {activeTab === 'ingredients' &&
}
- {activeTab === 'prefs' &&
}
- {activeTab === 'quantity' && isDecimal &&
}
- {activeTab === 'courses' && courses?.length > 0 &&
}
- {activeTab === 'notes' &&
}
- {activeTab === 'price_adjust' &&
}
-
-
- {/* Footer: qty stepper + ADD button */}
-
- {isDecimal ? (
-
setActiveTab('quantity')}
- style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0, cursor: 'pointer', padding: '0 14px', gap: 4 }}>
- {fmtDecimalQty(qty, unitCfg)}
- {unitCfg.label}
-
- ) : (
-
-
setQty(q => Math.max(1, q - 1))} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: qty <= 1 ? 'default' : 'pointer', color: qty <= 1 ? '#94a3b8' : '#1e293b' }}>−
-
{qty}
-
setQty(q => q + 1)} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+
-
- )}
-
- ΠΡΟΣΘΗΚΗ
- {totalPrice.toFixed(2)} €
-
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/OrderDetailPage.jsx b/manager_dashboard/src/pages/OrderDetailPage.jsx
deleted file mode 100644
index e68730f..0000000
--- a/manager_dashboard/src/pages/OrderDetailPage.jsx
+++ /dev/null
@@ -1,757 +0,0 @@
-import { useState } from 'react'
-import { useParams, useNavigate } from 'react-router-dom'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-import { Percent } from 'lucide-react'
-import Badge from '../ui/Badge'
-import { ConfirmModal } from '../ui/Modal'
-import PaymentMethodModal from '../ui/PaymentMethodModal'
-import DesktopOrderingTab from './DesktopOrderingTab'
-
-function PrintOrderModal({ onClose, onPrint, printers }) {
- const [printerId, setPrinterId] = useState(printers[0]?.id ?? '')
- function submit() {
- if (!printerId) { toast.error('Επιλέξτε εκτυπωτή'); return }
- onPrint(Number(printerId))
- onClose()
- }
- return (
-
-
-
-
Εκτύπωση παραγγελίας
- ✕
-
-
- Εκτυπωτής
- setPrinterId(e.target.value)}>
- — Επιλέξτε —
- {printers.map(p => {p.name} )}
-
-
-
- Ακύρωση
- Εκτύπωση
-
-
-
- )
-}
-
-function effPrice(item) { return (item.unit_price ?? 0) + (item.price_adjustment ?? 0) }
-function itemTotal(item) {
- return (effPrice(item) * item.quantity).toFixed(2)
-}
-
-const PAYMENT_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 null
- const s = PAYMENT_METHOD_STYLES[method] || { label: method.toUpperCase(), color: '#374151', bg: '#f3f4f6', border: '#d1d5db' }
- return (
-
- {s.label}
-
- )
-}
-
-function formatDate(dt) {
- if (!dt) return '—'
- return new Date(dt).toLocaleString('el-GR', { dateStyle: 'short', timeStyle: 'short' })
-}
-
-const EVENT_LABELS = {
- ORDER_OPENED: 'Άνοιγμα',
- ITEMS_ADDED: 'Προσθήκη',
- PAYMENT: 'Πληρωμή',
- PAYMENT_OFFLINE: 'Πληρωμή (Offline)',
- ORDER_CLOSED: 'Κλείσιμο',
- ORDER_CANCELLED: 'Ακύρωση',
- ITEM_CANCELLED: 'Ακύρωση αντ.',
-}
-
-function AuditTab({ order, waiterMap }) {
- if (!order.audit_logs || order.audit_logs.length === 0) {
- return
Δεν υπάρχουν εγγραφές.
- }
-
- const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i]))
-
- return (
-
- {order.audit_logs.map(log => {
- const isDuplicate = log.is_duplicate === 1 || log.is_duplicate === true
- const isPayment = log.event_type === 'PAYMENT' || log.event_type === 'PAYMENT_OFFLINE'
- const badgeClass = isDuplicate
- ? 'bg-red-100 text-red-700'
- : isPayment ? 'bg-green-100 text-green-700'
- : log.event_type.includes('CANCEL') ? 'bg-red-100 text-red-600'
- : log.event_type === 'ORDER_CLOSED' ? 'bg-gray-100 text-gray-600'
- : 'bg-blue-100 text-blue-700'
- const displayTime = log.offline_at ? formatDate(log.offline_at) : formatDate(log.created_at)
-
- // Resolve item names for ITEMS_ADDED and ITEM_CANCELLED events
- let itemNames = []
- if (log.item_ids && (log.event_type === 'ITEMS_ADDED' || log.event_type === 'ITEM_CANCELLED')) {
- 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 (
-
-
-
- {EVENT_LABELS[log.event_type] ?? log.event_type}
-
- {isDuplicate && (
- ΔΙΠΛΗ
- )}
-
-
-
{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`}
- {log.amount != null && (
-
- €{log.amount.toFixed(2)}
-
- )}
- {log.payment_method && (
-
- )}
- {itemNames.length > 0 && (
-
- {itemNames.map((name, i) => (
- {name}
- ))}
-
- )}
-
-
- {displayTime}
- {log.offline_at && (
- offline
- )}
-
-
- )
- })}
-
- )
-}
-
-// ─── Price Events Tab ────────────────────────────────────────────────────────
-
-const PRICE_EVENT_LABELS = {
- modifier_applied: 'Τροποποιητής',
- deal_triggered: 'Προσφορά',
- deal_offer_shown: 'Προσφορά (εμφανίστηκε)',
- deal_offer_accepted: 'Προσφορά (αποδεκτή)',
- deal_offer_dismissed:'Προσφορά (απορρίφθηκε)',
- waiter_discount: 'Έκπτωση σερβιτόρου',
- free_item_added: 'Δωρεάν αντικείμενο',
-}
-
-const PRICE_EVENT_COLORS = {
- modifier_applied: { bg: '#eff6ff', color: '#1d4ed8', border: '#93c5fd' },
- deal_triggered: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
- deal_offer_shown: { bg: '#fefce8', color: '#a16207', border: '#fde68a' },
- deal_offer_accepted: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
- deal_offer_dismissed:{ bg: '#fef2f2', color: '#b91c1c', border: '#fca5a5' },
- waiter_discount: { bg: '#fdf4ff', color: '#7e22ce', border: '#d8b4fe' },
- free_item_added: { bg: '#f0fdf4', color: '#15803d', border: '#86efac' },
-}
-
-function PriceEventsTab({ orderId }) {
- const { data: events = [], isLoading } = useQuery({
- queryKey: ['price-events', orderId],
- queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
- })
-
- if (isLoading) return (
-
- )
-
- if (events.length === 0) return (
-
-
-
Δεν υπάρχουν συμβάντα τιμολόγησης για αυτή την παραγγελία.
-
- )
-
- return (
-
- {events.map(ev => {
- const label = PRICE_EVENT_LABELS[ev.event_type] ?? ev.event_type
- const style = PRICE_EVENT_COLORS[ev.event_type] ?? { bg: '#f8fafc', color: '#334155', border: '#cbd5e1' }
- const hasDelta = ev.price_before != null && ev.price_after != null
- return (
-
-
-
- {label}
-
-
-
-
- {ev.modifier_name && {ev.modifier_name} }
- {ev.deal_name && {ev.deal_name} }
- {ev.applied_by_username && (
- από {ev.applied_by_username}
- )}
- {hasDelta && (
-
- {ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount?.toFixed(2)}€
-
- ({ev.price_before?.toFixed(2)} → {ev.price_after?.toFixed(2)})
-
-
- )}
-
- {ev.waiter_note && (
-
"{ev.waiter_note}"
- )}
- {ev.conditions_snapshot && Object.keys(ev.conditions_snapshot).length > 0 && (
-
- Συνθήκες
-
- {JSON.stringify(ev.conditions_snapshot, null, 2)}
-
-
- )}
-
-
- {formatDate(ev.applied_at)}
-
-
- )
- })}
-
- )
-}
-
-export default function OrderDetailPage({ orderId: propOrderId, readOnly = false }) {
- const { orderId: paramOrderId } = useParams()
- const orderId = propOrderId ?? paramOrderId
- const navigate = useNavigate()
- const qc = useQueryClient()
-
- const [tab, setTab] = useState('overview')
- const [confirmAction, setConfirmAction] = useState(null) // { type, payload }
- const [showPrintModal, setShowPrintModal] = useState(false)
- const [payPending, setPayPending] = useState(null) // item_ids waiting for method selection
- const [customerSearch, setCustomerSearch] = useState('')
- const [showCustomerDropdown, setShowCustomerDropdown] = useState(false)
-
- const { data: order, isLoading } = useQuery({
- queryKey: ['order', orderId],
- queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data),
- enabled: !!orderId,
- })
-
- const { data: waiters = [] } = useQuery({
- queryKey: ['waiters'],
- queryFn: () => client.get('/api/waiters/').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: printers = [] } = useQuery({
- queryKey: ['printers'],
- queryFn: () => client.get('/api/system/printers').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: rawPriceEvents = [] } = useQuery({
- queryKey: ['price-events', orderId],
- queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data),
- enabled: !!orderId,
- staleTime: 30_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
- }, {})
-
- const printOrder = useMutation({
- mutationFn: (printerId) => client.post(`/api/orders/${orderId}/print`, { printer_id: printerId }),
- onSuccess: () => toast.success('Αποστολή στον εκτυπωτή…'),
- onError: () => toast.error('Σφάλμα εκτύπωσης'),
- })
-
- const waiterMap = Object.fromEntries(waiters.map(w => [w.id, w.nickname || w.full_name || w.username]))
- const assignedIds = new Set((order?.waiters ?? []).map(w => w.waiter_id))
-
- const invalidate = () => {
- qc.invalidateQueries({ queryKey: ['order', orderId] })
- qc.invalidateQueries({ queryKey: ['orders-active'] })
- }
-
- const cancelItem = useMutation({
- mutationFn: (itemId) => client.delete(`/api/orders/${orderId}/items/${itemId}`),
- onSuccess: () => { toast.success('Αντικείμενο ακυρώθηκε'); invalidate() },
- onError: () => toast.error('Σφάλμα ακύρωσης αντικειμένου'),
- })
-
- const cancelOrder = useMutation({
- mutationFn: () => client.delete(`/api/orders/${orderId}`),
- onSuccess: () => { toast.success('Παραγγελία ακυρώθηκε'); navigate('/tables') },
- onError: () => toast.error('Σφάλμα ακύρωσης παραγγελίας'),
- })
-
- const closeOrder = useMutation({
- mutationFn: () => client.post(`/api/orders/${orderId}/close`),
- onSuccess: () => { toast.success('Παραγγελία έκλεισε'); navigate('/tables') },
- onError: () => toast.error('Σφάλμα κλεισίματος'),
- })
-
- const assignWaiter = useMutation({
- mutationFn: (waiter_id) => client.put(`/api/orders/${orderId}/assign-waiter`, { waiter_id }),
- onSuccess: () => { toast.success('Σερβιτόρος προστέθηκε'); invalidate() },
- onError: () => toast.error('Σφάλμα'),
- })
-
- const removeWaiter = useMutation({
- mutationFn: (wid) => client.delete(`/api/orders/${orderId}/waiters/${wid}`),
- onSuccess: () => { toast.success('Σερβιτόρος αφαιρέθηκε'); invalidate() },
- onError: () => toast.error('Σφάλμα'),
- })
-
- const { data: customersData = [] } = useQuery({
- queryKey: ['customers', customerSearch],
- queryFn: () => client.get('/api/customers/', { params: customerSearch ? { search: customerSearch } : {} }).then(r => r.data),
- staleTime: 30_000,
- enabled: showCustomerDropdown,
- })
-
- const assignCustomer = useMutation({
- mutationFn: (customer_id) => client.put(`/api/orders/${orderId}/customer`, { customer_id }),
- onSuccess: (_, customer_id) => { toast.success(customer_id ? 'Πελάτης ανατέθηκε' : 'Πελάτης αφαιρέθηκε'); invalidate(); setShowCustomerDropdown(false); setCustomerSearch('') },
- onError: () => toast.error('Σφάλμα'),
- })
-
- const payItems = useMutation({
- mutationFn: ({ item_ids, payment_method }) => client.post(`/api/orders/${orderId}/pay`, { item_ids, payment_method }),
- onSuccess: () => { toast.success('Πληρώθηκε'); invalidate() },
- onError: () => toast.error('Σφάλμα πληρωμής'),
- })
-
- const tabItem = useMutation({
- mutationFn: (itemId) => client.post(`/api/orders/${orderId}/items/${itemId}/tab`),
- onSuccess: () => { toast.success('Αντικείμενο μεταφέρθηκε στην καρτέλα'); invalidate() },
- onError: (e) => toast.error(e?.response?.data?.detail || 'Σφάλμα'),
- })
-
- function requestPay(item_ids) {
- setPayPending(item_ids)
- }
-
- function confirmPay(method) {
- if (!payPending) return
- payItems.mutate({ item_ids: payPending, payment_method: method })
- setPayPending(null)
- }
-
- function handleConfirm() {
- if (!confirmAction) return
- const { type, payload } = confirmAction
- if (type === 'cancelItem') cancelItem.mutate(payload)
- if (type === 'cancelOrder') cancelOrder.mutate()
- if (type === 'closeOrder') closeOrder.mutate()
- setConfirmAction(null)
- }
-
- if (isLoading) return
Φόρτωση…
- if (!order) return
Παραγγελία δεν βρέθηκε.
-
- const activeItems = order.items.filter(i => i.status === 'active')
- const total = order.items
- .filter(i => i.status !== 'cancelled')
- .reduce((s, i) => s + effPrice(i) * i.quantity, 0)
-
- const isOpen = ['open', 'partially_paid'].includes(order.status)
-
- // The ordering tab needs full height and no outer padding
- if (tab === 'order') {
- return (
-
- {/* Compact header strip */}
-
- {!propOrderId && (
-
navigate(-1)} className="btn btn-ghost text-sm">← Πίσω
- )}
-
- Τραπέζι {order.table_name || order.table_id}
-
-
-
€{total.toFixed(2)}
-
- {/* Tab strip inline */}
-
- {[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό']].map(([key, label]) => (
- setTab(key)}
- style={{
- padding: '6px 14px', fontSize: 13, fontWeight: tab === key ? 700 : 500,
- background: 'none', border: 'none', cursor: 'pointer',
- borderBottom: `2px solid ${tab === key ? '#4f46e5' : 'transparent'}`,
- color: tab === key ? '#4f46e5' : '#64748b',
- }}>
- {label}
-
- ))}
-
-
- {/* Full-height ordering terminal */}
-
-
-
-
- )
- }
-
- return (
-
-
- {!propOrderId && (
-
navigate(-1)} className="btn btn-ghost text-sm">← Πίσω
- )}
-
- {/* Header */}
-
-
-
- Τραπέζι {order.table_name || order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)}
- {order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}
-
-
-
-
- €{total.toFixed(2)}
-
-
-
- {/* Customer assignment */}
-
-
-
Πελάτης
- {order.customer_id && isOpen && !readOnly && (
- assignCustomer.mutate(null)}
- className="text-xs text-gray-400 hover:text-red-500"
- >
- Αφαίρεση
-
- )}
-
-
- {order.customer_id ? (
-
-
👤
-
-
{order.customer_name || `Πελάτης #${order.customer_id}`}
- {order.customer_phone &&
{order.customer_phone}
}
-
-
- ) : isOpen && !readOnly ? (
-
- {!showCustomerDropdown ? (
-
setShowCustomerDropdown(true)}
- style={{ fontSize: 13, color: '#6b7280', border: '1px dashed #d1d5db', borderRadius: 8, padding: '7px 14px', cursor: 'pointer', background: 'white', width: '100%', textAlign: 'left' }}
- >
- + Ανάθεση πελάτη
-
- ) : (
-
-
setCustomerSearch(e.target.value)}
- placeholder="Αναζήτηση πελάτη…"
- style={{ width: '100%', padding: '7px 11px', border: '1.5px solid #3b82f6', borderRadius: 8, fontSize: 13, outline: 'none', boxSizing: 'border-box' }}
- />
-
- {customersData.length === 0 && (
-
Δεν βρέθηκαν πελάτες
- )}
- {customersData.map(c => (
-
assignCustomer.mutate(c.id)}
- style={{ display: 'block', width: '100%', textAlign: 'left', padding: '9px 14px', border: 'none', background: 'none', cursor: 'pointer', fontSize: 13, borderBottom: '1px solid #f3f4f6' }}
- className="hover:bg-blue-50"
- >
- {c.name}
- {c.nickname && «{c.nickname}» }
- {c.phone && {c.phone} }
-
- ))}
-
{ setShowCustomerDropdown(false); setCustomerSearch('') }}
- style={{ display: 'block', width: '100%', padding: '8px 14px', fontSize: 12, color: '#9ca3af', border: 'none', background: 'none', cursor: 'pointer', borderTop: '1px solid #f0f0ef' }}>
- Ακύρωση
-
-
-
- )}
-
- ) : (
-
Χωρίς πελάτη
- )}
-
-
- {/* Tabs */}
-
- {[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => (
- setTab(key)}
- className={`px-4 py-2 text-sm font-medium border-b-2 transition-colors ${tab === key ? 'border-primary-600 text-primary-700' : 'border-transparent text-gray-500 hover:text-gray-700'}`}
- >
- {label}
-
- ))}
-
-
- {tab === 'overview' && <>
- {/* Waiters */}
-
-
Προσωπικό
-
- {order.waiters.map(w => (
-
- {waiterMap[w.waiter_id] || `#${w.waiter_id}`}
- {isOpen && !readOnly && (
- removeWaiter.mutate(w.waiter_id)}
- className="text-gray-400 hover:text-red-500 text-xs leading-none"
- >
- ✕
-
- )}
-
- ))}
- {isOpen && !readOnly && (
-
{ if (e.target.value) assignWaiter.mutate(Number(e.target.value)) }}
- >
- + Πρόσθεσε
- {waiters.filter(w => !assignedIds.has(w.id)).map(w => (
- {w.nickname || w.full_name || w.username}
- ))}
-
- )}
-
-
-
- {/* Items */}
-
-
-
Αντικείμενα
-
- {order.items.length === 0 && (
-
Κανένα αντικείμενο.
- )}
- {order.items.map(item => {
- const isCancelled = item.status === 'cancelled'
- const isClosedItem = item.status === 'closed'
- const badgeStatus = isClosedItem ? 'closed_item' : item.status
- const hasPriceAdj = !!(item.price_adjustment && item.price_adjustment !== 0)
- const isDealItem = !!item.deal_id
- const itemPriceEvents = (priceEventsMap[item.id] ?? []).filter(ev => ['modifier_applied','waiter_discount','free_item_added'].includes(ev.event_type))
- const EVENT_COLORS_ODP = { modifier_applied: '#2563eb', waiter_discount: '#7c3aed', free_item_added: '#16a34a' }
- return (
-
-
-
- {item.product?.name ?? `#${item.product_id}`}
- {item.course_id != null && (
-
- {item.course_id}
-
- )}
- {isDealItem && ΔΩΡΕΑΝ }
-
- {item.notes &&
{item.notes}
}
-
- x{item.quantity} · €{effPrice(item).toFixed(2)}/τμχ
- {hasPriceAdj && (
- €{(item.unit_price ?? 0).toFixed(2)}
- )}
-
- {itemPriceEvents.map((ev, ei) => {
- const evColor = EVENT_COLORS_ODP[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)} € }
-
- )
- })}
- {item.paid_by && (
-
- Πληρώθηκε: {item.paid_by_name ?? waiterMap[item.paid_by] ?? `#${item.paid_by}`}
- {item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''}
- {item.payment_method && (
-
- {' · '}{(PAYMENT_METHOD_STYLES[item.payment_method] || { label: item.payment_method.toUpperCase() }).label}
-
- )}
-
- )}
- {isClosedItem && (
-
Απλήρωτο — κλείστηκε από manager
- )}
-
-
- €{itemTotal(item)}
- {isOpen && !readOnly && item.status === 'active' && (
- <>
- requestPay([item.id])}
- className="btn btn-secondary text-xs px-2 py-1 min-h-0 h-8"
- >
- Πληρωμή
-
- {order.customer_id && (
- tabItem.mutate(item.id)}
- style={{ fontSize: 12, padding: '0 8px', height: 32, borderRadius: 6, border: '1px solid #bfdbfe', background: '#eff6ff', color: '#1d4ed8', cursor: 'pointer', fontWeight: 600, whiteSpace: 'nowrap' }}
- >
- 📋 Καρτέλα
-
- )}
- setConfirmAction({ type: 'cancelItem', payload: item.id })}
- className="btn btn-danger text-xs px-2 py-1 min-h-0 h-8"
- >
- Ακύρωση
-
- >
- )}
- {item.status === 'tabbed' && (
-
- 📋 Καρτέλα
-
- )}
-
-
- )
- })}
-
-
- {/* Actions */}
-
- {isOpen && !readOnly && activeItems.length > 0 && (
- requestPay(activeItems.map(i => i.id))}
- className="btn btn-primary"
- >
- Πληρωμή όλων
-
- )}
- {isOpen && !readOnly && (
- <>
- setConfirmAction({ type: 'closeOrder' })}
- className="btn btn-secondary"
- >
- Κλείσιμο παραγγελίας
-
- setConfirmAction({ type: 'cancelOrder' })}
- className="btn btn-danger"
- >
- Ακύρωση παραγγελίας
-
- >
- )}
- setShowPrintModal(true)}
- className="btn btn-secondary"
- >
- 🖨 Εκτύπωση
-
-
- >}
-
- {tab === 'pricing' && (
-
- )}
-
- {tab === 'audit' && (
-
- )}
-
- {payPending && (
-
setPayPending(null)}
- title={payPending.length === 1 ? 'Τρόπος Πληρωμής;' : `Πληρωμή ${payPending.length} αντικειμένων;`}
- />
- )}
-
- {confirmAction && (
- setConfirmAction(null)}
- />
- )}
-
- {showPrintModal && printers.length > 0 && (
- setShowPrintModal(false)}
- onPrint={(printerId) => printOrder.mutate(printerId)}
- />
- )}
- {showPrintModal && printers.length === 0 && (
-
-
-
Δεν βρέθηκαν ενεργοί εκτυπωτές.
-
setShowPrintModal(false)} className="btn btn-secondary w-full">Κλείσιμο
-
-
- )}
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/TablesPage.jsx b/manager_dashboard/src/pages/TablesPage.jsx
deleted file mode 100644
index 875b3d1..0000000
--- a/manager_dashboard/src/pages/TablesPage.jsx
+++ /dev/null
@@ -1,836 +0,0 @@
-import { useState, useRef, useEffect } from 'react'
-import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
-import { useNavigate } from 'react-router-dom'
-import toast from 'react-hot-toast'
-import client from '../api/client'
-import { useTranslation } from '@xenia/i18n'
-import LiveFloor from './floor/LiveFloor'
-
-function relativeTime(isoStr) {
- if (!isoStr) return ''
- const diffMs = Date.now() - new Date(isoStr).getTime()
- const diffMins = Math.floor(diffMs / 60000)
- if (diffMins < 1) return 'μόλις τώρα'
- if (diffMins < 60) return `πριν ${diffMins}λ`
- const h = Math.floor(diffMins / 60)
- if (h < 24) return `πριν ${h}ω`
- return `πριν ${Math.floor(h / 24)}μ`
-}
-
-function FlagsDetailModal({ flags, tableName, onClose }) {
- return (
-
-
e.stopPropagation()}>
-
-
Σημαίες — {tableName}
-
✕
-
-
- {flags.map(f => (
-
- {f.emoji &&
{f.emoji} }
-
-
{f.name}
- {f.assigned_at && (
-
{relativeTime(f.assigned_at)}
- )}
-
-
- ))}
-
-
-
- )
-}
-
-
-const STATUS_OPTIONS = [
- { value: 'open', label: 'Ανοιχτά' },
- { value: 'partially_paid', label: 'Μερική πληρωμή' },
- { value: 'paid', label: 'Πλήρως πληρωμένο' },
- { value: 'free', label: 'Ελεύθερα' },
-]
-
-const COLORS = {
- open: {
- label: 'Ανοιχτό',
- tint: '#eef7f0', tintStrong: '#d7ecdc',
- accent: '#2f9e5e', ink: '#1f7042',
- },
- partially_paid: {
- label: 'Μερική πληρ.',
- tint: '#f4eefb', tintStrong: '#e3d4f3',
- accent: '#7a44c9', ink: '#57309a',
- },
- paid: {
- label: 'Πλήρως πληρωμένο',
- tint: '#eff6ff', tintStrong: '#dbeafe',
- accent: '#2563eb', ink: '#1d4ed8',
- },
- free: {
- label: 'Ελεύθερο',
- tint: '#f4f4f2', tintStrong: '#dfe2e6',
- accent: '#8a9099', ink: '#5a6169',
- },
-}
-
-function formatEuro(n) {
- return '€' + parseFloat(n).toFixed(2)
-}
-
-function formatDuration(openedAt) {
- const mins = Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
- if (mins < 60) return `${mins}m`
- const h = Math.floor(mins / 60)
- const m = mins % 60
- return m === 0 ? `${h}h` : `${h}h ${m}m`
-}
-
-function occupiedMinsFromDate(openedAt) {
- return Math.floor((Date.now() - new Date(openedAt).getTime()) / 60000)
-}
-
-function orderTotal(items = []) {
- return items
- .filter(i => i.status !== 'cancelled')
- .reduce((s, i) => s + ((i.unit_price ?? 0) + (i.price_adjustment ?? 0)) * i.quantity, 0)
-}
-
-function avatarColor(name) {
- const palette = ['#3758c9', '#7a44c9', '#2f9e5e', '#d94b26', '#8a6d2b', '#0d7a8a', '#c93775']
- let h = 0
- for (let i = 0; i < name.length; i++) h = (h * 31 + name.charCodeAt(i)) >>> 0
- return palette[h % palette.length]
-}
-
-function WaiterBubble({ waiter, size = 26 }) {
- if (waiter.avatarUrl) {
- return (
-
- )
- }
- const parts = waiter.name.trim().split(' ')
- const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
- return (
-
{initials}
- )
-}
-
-// ─── Quick action modal ────────────────────────────────────────────────────────
-
-function QuickActionModal({ table, order, flagDefs, currentFlags, waiters, templates, onClose, onDone }) {
- const qc = useQueryClient()
- const [selectedFlagIds, setSelectedFlagIds] = useState((currentFlags || []).map(f => f.id))
- const [notifyMsg, setNotifyMsg] = useState('')
- const [notifyAll, setNotifyAll] = useState(true)
- const [notifyWaiters, setNotifyWaiters] = useState(false)
- const [sending, setSending] = useState(false)
-
- const setFlagsMut = useMutation({
- mutationFn: () => client.put(`/api/flags/table/${table.id}`, { flag_ids: selectedFlagIds }),
- onSuccess: () => qc.invalidateQueries({ queryKey: ['flag-assignments'] }),
- })
-
- function toggleFlag(id) {
- setSelectedFlagIds(prev => prev.includes(id) ? prev.filter(x => x !== id) : [...prev, id])
- }
-
- async function save() {
- setSending(true)
- try {
- await setFlagsMut.mutateAsync()
- if (notifyWaiters && notifyMsg.trim() && order) {
- const waiterIds = notifyAll ? [] : order.waiters.map(w => w.waiter_id)
- await client.post('/api/notifications/send', {
- body: notifyMsg.trim(),
- target_waiter_ids: waiterIds,
- table_ids: [table.id],
- })
- toast.success('Σημαίες + ειδοποίηση εστάλη!')
- } else {
- toast.success('Σημαίες ενημερώθηκαν')
- }
- onDone()
- onClose()
- } catch {
- toast.error('Σφάλμα')
- } finally {
- setSending(false)
- }
- }
-
- return (
-
-
e.stopPropagation()}>
-
-
⚡ {table.label || `T${table.number}`}
-
✕
-
-
-
Σημαίες
-
- {flagDefs.map(f => {
- const sel = selectedFlagIds.includes(f.id)
- return (
- toggleFlag(f.id)} style={{
- height: 30, padding: '0 12px', borderRadius: 999,
- border: `1.5px solid ${sel ? f.color : '#dfe2e6'}`,
- background: sel ? (f.color + '22') : 'white',
- color: sel ? f.color : '#374151',
- fontSize: 12, fontWeight: sel ? 700 : 500, cursor: 'pointer',
- display: 'flex', alignItems: 'center', gap: 5,
- }}>
- {f.emoji && {f.emoji} }
- {f.name}
-
- )
- })}
-
-
- {order && (
- <>
-
- setNotifyWaiters(e.target.checked)} />
- Ειδοποίησε τους σερβιτόρους
-
-
- {notifyWaiters && (
-
-
- {templates.slice(0, 4).map(t => (
- setNotifyMsg(t.body)} style={{
- height: 26, padding: '0 10px', borderRadius: 6,
- border: `1px solid ${notifyMsg === t.body ? '#3758c9' : '#dfe2e6'}`,
- background: notifyMsg === t.body ? '#eff3ff' : '#f9fafb',
- color: notifyMsg === t.body ? '#3758c9' : '#374151',
- fontSize: 11, cursor: 'pointer', fontFamily: 'inherit', whiteSpace: 'nowrap',
- }}>{t.body}
- ))}
-
-
setNotifyMsg(e.target.value)}
- placeholder="Ή γράψτε μήνυμα…"
- style={{ width: '100%', height: 36, borderRadius: 8, border: '1px solid #dfe2e6', padding: '0 12px', fontSize: 13, fontFamily: 'inherit', boxSizing: 'border-box' }}
- />
-
- )}
- >
- )}
-
-
- Άκυρο
-
- {sending ? 'Αποθήκευση…' : 'Αποθήκευση'}
-
-
-
-
- )
-}
-
-
-function FlagPills({ flags, displayMode = 'both', onOverflowClick }) {
- if (flags.length === 0) return null
- const MAX_VISIBLE = 3
- const visible = flags.slice(0, MAX_VISIBLE)
- const overflow = flags.length - MAX_VISIBLE
-
- return (
-
- {visible.map(f => (
-
- {(displayMode === 'icon' || displayMode === 'both') && f.emoji && {f.emoji} }
- {(displayMode === 'text' || displayMode === 'both') && {f.name} }
-
- ))}
- {overflow > 0 && (
- { e.stopPropagation(); onOverflowClick?.() }}
- title={`+${overflow} ακόμα σημαίες`}
- style={{
- fontSize: 11, fontWeight: 700, borderRadius: 999, padding: '2px 7px',
- background: '#f0f4ff', color: '#3758c9', border: '1px solid #c2cff0',
- whiteSpace: 'nowrap', flexShrink: 0, cursor: 'pointer',
- }}
- >+{overflow}
- )}
-
- )
-}
-
-function TableCardV1({ name, status, amount, openedAt, waiters = [], hasPendingPrint = false, flags = [], flagDisplayMode = 'both', upcomingReservation = null, onClick, onQuickAction, onFlagsClick }) {
- const s = COLORS[status] || COLORS.free
- const [hover, setHover] = useState(false)
- const [pressed, setPressed] = useState(false)
- const occupiedMins = openedAt ? occupiedMinsFromDate(openedAt) : null
-
- return (
-
setHover(true)}
- onMouseLeave={() => { setHover(false); setPressed(false) }}
- onMouseDown={() => setPressed(true)}
- onMouseUp={() => setPressed(false)}
- style={{
- '--cardBg': s.tint,
- position: 'relative', width: '100%', minWidth: 330, height: 200,
- padding: '16px 18px 16px 24px',
- background: s.tint, border: '1px solid ' + s.tintStrong, borderRadius: 14,
- boxShadow: pressed
- ? 'inset 0 2px 4px rgba(16,20,24,0.08)'
- : hover
- ? '0 6px 18px rgba(16,20,24,0.08), 0 2px 4px rgba(16,20,24,0.04)'
- : '0 1px 2px rgba(16,20,24,0.04), 0 1px 1px rgba(16,20,24,0.03)',
- transform: pressed ? 'translateY(1px)' : hover ? 'translateY(-2px)' : 'translateY(0)',
- transition: 'transform 120ms ease, box-shadow 120ms ease',
- cursor: onClick ? 'pointer' : 'default',
- textAlign: 'left', font: 'inherit', color: 'inherit',
- display: 'flex', flexDirection: 'column', outline: 'none', flexShrink: 0,
- }}
- >
-
-
-
{name}
-
-
- {s.label}
-
-
-
- {hasPendingPrint && (
- ⏳
- )}
- {upcomingReservation && (
-
- 🔒 RESERVED · {new Date(upcomingReservation.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
-
- )}
-
-
-
-
-
Total
-
- {amount != null ? formatEuro(amount) : — — }
-
-
-
-
Time
-
= 90 ? 700 : 500,
- color: '#111315',
- }}>
- {openedAt ? formatDuration(openedAt) : — — }
-
-
-
-
- {waiters.length === 0 ? (
-
Unassigned
- ) : waiters.length >= 3 ? (
- <>
-
- {waiters.slice(0, 3).map((w, i) => (
-
-
-
- ))}
-
-
Multiple ({waiters.length})
- >
- ) : (
- waiters.map((w, i) => (
-
-
- {w.shortName}
-
- ))
- )}
- {onQuickAction && (
-
{ e.stopPropagation(); onQuickAction() }}
- title="Γρήγορες ενέργειες"
- style={{
- marginLeft: 'auto', width: 28, height: 28, borderRadius: 8, flexShrink: 0,
- border: '1px solid ' + s.tintStrong, background: 'white',
- display: 'flex', alignItems: 'center', justifyContent: 'center',
- fontSize: 14, cursor: 'pointer', color: '#5a6169',
- }}
- >⚡
- )}
-
-
- )
-}
-
-// ─── Multi-select dropdown ─────────────────────────────────────────────────────
-
-function MultiSelectDropdown({ label, options, selected, onChange, allLabel = 'Όλα' }) {
- const [open, setOpen] = useState(false)
- const ref = useRef(null)
-
- useEffect(() => {
- function handleClick(e) {
- if (ref.current && !ref.current.contains(e.target)) setOpen(false)
- }
- document.addEventListener('mousedown', handleClick)
- return () => document.removeEventListener('mousedown', handleClick)
- }, [])
-
- const allSelected = selected.length === 0
- const displayLabel = allSelected
- ? allLabel
- : selected.length === 1
- ? options.find(o => o.value === selected[0])?.label ?? selected[0]
- : `${selected.length} επιλεγμένα`
-
- function toggle(value) {
- if (selected.includes(value)) {
- onChange(selected.filter(v => v !== value))
- } else {
- onChange([...selected, value])
- }
- }
-
- return (
-
-
setOpen(o => !o)}
- style={{
- height: 36, padding: '0 14px',
- borderRadius: 8, border: '1px solid #dfe2e6',
- background: allSelected ? 'white' : '#f0f4ff',
- color: allSelected ? '#374151' : '#3758c9',
- fontSize: 13, fontWeight: allSelected ? 500 : 600,
- cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 8,
- whiteSpace: 'nowrap', fontFamily: 'inherit',
- boxShadow: open ? '0 0 0 2px #c2cff0' : 'none',
- transition: 'box-shadow 100ms',
- }}
- >
- {label}
- {displayLabel}
- {open ? '▲' : '▼'}
-
-
- {open && (
-
- {/* All option */}
- { onChange([]); setOpen(false) }}
- style={{
- width: '100%', padding: '10px 14px',
- display: 'flex', alignItems: 'center', gap: 10,
- background: allSelected ? '#f0f4ff' : 'white',
- border: 'none', cursor: 'pointer', textAlign: 'left',
- fontSize: 13, fontWeight: allSelected ? 700 : 400,
- color: allSelected ? '#3758c9' : '#374151',
- fontFamily: 'inherit',
- borderBottom: '1px solid #f4f4f2',
- }}
- >
-
- {allSelected && ✓ }
-
- {allLabel}
-
- {options.map(opt => {
- const checked = selected.includes(opt.value)
- return (
- toggle(opt.value)}
- style={{
- width: '100%', padding: '10px 14px',
- display: 'flex', alignItems: 'center', gap: 10,
- background: checked ? '#f9f5ff' : 'white',
- border: 'none', cursor: 'pointer', textAlign: 'left',
- fontSize: 13, fontWeight: checked ? 600 : 400,
- color: checked ? '#57309a' : '#374151',
- fontFamily: 'inherit',
- borderBottom: '1px solid #f9f9f8',
- }}
- >
-
- {checked && ✓ }
-
- {opt.label}
-
- )
- })}
-
- )}
-
- )
-}
-
-// ─── Page ─────────────────────────────────────────────────────────────────────
-
-export default function TablesPage() {
- const { t } = useTranslation('common')
- const [view, setView] = useState('list') // list | map (6.8: the floor plans, live)
- const [statusFilter, setStatusFilter] = useState([])
- const [zoneFilter, setZoneFilter] = useState([])
- const [retryingId, setRetryingId] = useState(null)
- const [quickActionTarget, setQuickActionTarget] = useState(null)
- const [flagsDetail, setFlagsDetail] = useState(null) // { flags, tableName }
- const navigate = useNavigate()
- const queryClient = useQueryClient()
-
- const { data: tables = [], isLoading: tablesLoading } = useQuery({
- queryKey: ['tables'],
- queryFn: () => client.get('/api/tables/').then(r => r.data),
- refetchInterval: 5_000,
- })
-
- const { data: orders = [], isLoading: ordersLoading } = useQuery({
- queryKey: ['orders-active'],
- queryFn: () => client.get('/api/orders/').then(r => r.data),
- refetchInterval: 5_000,
- })
-
- const { data: flagDefs = [] } = useQuery({
- queryKey: ['flag-defs'],
- queryFn: () => client.get('/api/flags/defs').then(r => r.data),
- staleTime: 30_000,
- })
-
- const { data: flagAssignments = [] } = useQuery({
- queryKey: ['flag-assignments'],
- queryFn: () => client.get('/api/flags/assignments').then(r => r.data),
- refetchInterval: 10_000,
- staleTime: 8_000,
- })
-
- // Build map: tableId -> { def, assigned_at }[]
- const flagDefMap = Object.fromEntries(flagDefs.map(f => [f.id, f]))
- const tableFlagsMap = {}
- flagAssignments.forEach(a => {
- if (!tableFlagsMap[a.table_id]) tableFlagsMap[a.table_id] = []
- const def = flagDefMap[a.flag_id]
- if (def) tableFlagsMap[a.table_id].push({ ...def, assigned_at: a.assigned_at })
- })
-
- const { data: waiters = [] } = useQuery({
- queryKey: ['waiters'],
- queryFn: () => client.get('/api/waiters/').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: quickTemplates = [] } = useQuery({
- queryKey: ['quick-templates'],
- queryFn: () => client.get('/api/notifications/templates').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: groups = [] } = useQuery({
- queryKey: ['table-groups'],
- queryFn: () => client.get('/api/tables/groups').then(r => r.data),
- staleTime: 60_000,
- })
-
- const { data: posSettings } = useQuery({
- queryKey: ['pos-settings'],
- queryFn: () => client.get('/api/settings/').then(r => r.data),
- staleTime: 30_000,
- })
- const flagDisplayMode = posSettings?.['flags.display_mode']?.value ?? 'both'
-
- const waiterMap = Object.fromEntries(waiters.map(w => {
- const name = w.full_name || w.nickname || w.username
- const shortName = w.nickname || (w.full_name ? w.full_name.split(' ')[0] : w.username)
- const avatarUrl = w.avatar_url ?? null
- return [w.id, { name, shortName, avatarUrl }]
- }))
-
- const tableCards = tables.map(table => {
- const order = orders.find(o =>
- o.table_id === table.id && ['open', 'partially_paid', 'paid'].includes(o.status)
- )
- const tableStatus = order ? order.status : 'free'
- const hasPendingPrint = order ? order.items.some(i => i.status === 'active' && !i.printed) : false
- const tableFlags = tableFlagsMap[table.id] || []
- return { table, order, tableStatus, hasPendingPrint, tableFlags }
- })
-
- const pendingPrintOrders = tableCards.filter(c => c.hasPendingPrint)
-
- async function retrySingleOrder(orderId) {
- setRetryingId(orderId)
- try {
- const res = await client.post(`/api/orders/${orderId}/retry-print`)
- const results = res.data.print_results ?? []
- const allOk = results.length === 0 || results.every(r => r.success)
- if (allOk) toast.success('Εκτυπώθηκε επιτυχώς')
- else {
- const failed = results.filter(r => !r.success).map(r => r.printer_name).join(', ')
- toast.error(`Αποτυχία: ${failed}`)
- }
- queryClient.invalidateQueries({ queryKey: ['orders-active'] })
- } catch {
- toast.error('Σφάλμα επικοινωνίας')
- } finally {
- setRetryingId(null)
- }
- }
-
- async function retryAllOrders() {
- for (const { order } of pendingPrintOrders) {
- if (order) await retrySingleOrder(order.id)
- }
- }
-
- // Build zone options from groups + "Χωρίς ζώνη"
- const zoneOptions = [
- ...groups.map(g => ({ value: String(g.id), label: g.name })),
- { value: '__none__', label: 'Χωρίς ζώνη' },
- ]
-
- // Apply filters
- const filtered = tableCards.filter(c => {
- const statusOk = statusFilter.length === 0 || statusFilter.includes(c.tableStatus)
- let zoneOk = true
- if (zoneFilter.length > 0) {
- const tableGroupId = c.table.group_id ? String(c.table.group_id) : null
- if (zoneFilter.includes('__none__') && zoneFilter.length === 1) {
- zoneOk = !tableGroupId
- } else if (zoneFilter.includes('__none__')) {
- zoneOk = !tableGroupId || zoneFilter.includes(tableGroupId)
- } else {
- zoneOk = tableGroupId !== null && zoneFilter.includes(tableGroupId)
- }
- }
- return statusOk && zoneOk
- })
-
- if (tablesLoading || ordersLoading) {
- return
Φόρτωση…
- }
-
- return (
-
- {flagsDetail && (
-
setFlagsDetail(null)}
- />
- )}
- {quickActionTarget && (
- setQuickActionTarget(null)}
- onDone={() => queryClient.invalidateQueries({ queryKey: ['flag-assignments'] })}
- />
- )}
-
-
- {['list', 'map'].map(v => (
- setView(v)} data-testid={`tables-view-${v}`}
- className={`px-3 py-1.5 text-label font-medium ${view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2'}`}>
- {t(`floorMap.${v}`)}
-
- ))}
-
-
-
-
-
-
-
- {view === 'map' && navigate(`/orders/${id}`)} />}
-
- {view === 'list' && filtered.length === 0 && (
- Δεν βρέθηκαν τραπέζια.
- )}
-
- {view === 'list' &&
- {filtered.map(({ table, order, tableStatus, hasPendingPrint, tableFlags }) => {
- const waiterNames = order
- ? order.waiters.map(w => waiterMap[w.waiter_id] || { name: `#${w.waiter_id}`, shortName: `#${w.waiter_id}`, avatarUrl: null })
- : []
- const amount = order ? orderTotal(order.items) : null
-
- return (
-
navigate(`/orders/${order.id}`) : undefined}
- onQuickAction={() => setQuickActionTarget({ table, order, currentFlags: tableFlags })}
- onFlagsClick={tableFlags.length > 3 ? () => setFlagsDetail({ flags: tableFlags, tableName: table.label || `T${table.number}` }) : undefined}
- />
- )
- })}
- }
-
- {pendingPrintOrders.length > 0 && (
-
-
-
-
⏳
-
-
Εκκρεμείς Εκτυπώσεις
-
- {pendingPrintOrders.length} παραγγελί{pendingPrintOrders.length !== 1 ? 'ες' : 'α'} δεν έχ{pendingPrintOrders.length !== 1 ? 'ουν' : 'ει'} σταλεί στην κουζίνα/μπαρ
-
-
-
-
- {retryingId !== null ? 'Αποστολή…' : 'Αποστολή Όλων'}
-
-
-
- {pendingPrintOrders.map(({ table, order }) => {
- const unprinted = order.items.filter(i => i.status === 'active' && !i.printed)
- const tableName = table.label || `T${table.number}`
- return (
-
-
- {tableName}
-
-
-
- {unprinted.length} αντικείμενο{unprinted.length !== 1 ? 'α' : ''} εκκρεμούν
-
-
- {unprinted.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
-
-
-
- navigate(`/orders/${order.id}`)}>
- Λεπτομέρειες
-
- retrySingleOrder(order.id)}
- disabled={retryingId === order.id}
- >
- {retryingId === order.id ? '…' : 'Εκτύπωση'}
-
-
-
- )
- })}
-
-
- )}
-
- )
-}
diff --git a/manager_dashboard/src/pages/orders/AddItems.jsx b/manager_dashboard/src/pages/orders/AddItems.jsx
new file mode 100644
index 0000000..5b2d5d1
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/AddItems.jsx
@@ -0,0 +1,135 @@
+// Adding to a table's order from the manager (plan step 6.9), by the phones' rules: the menu
+// (GET /api/orders/menu: in-store prices, the counter's product shape), a tap adds a product (one
+// with a preference to pick opens its choices: the shared dialog, @xenia/ordering), the cart is
+// priced by the server (POST /api/orders/quote with the order, so deals and the order's sales
+// point count), and "Send" adds the lines by id (POST /api/orders/{id}/items; a new order is
+// opened first). Prices are never sent.
+import { useMemo, useState } from 'react'
+import toast from 'react-hot-toast'
+import { Minus, Plus, Search, Send, Trash2 } from 'lucide-react'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import {
+ ProductDialog, addLine, categoriesWithProducts, defaultSelection, needsChoices, productsIn, searchProducts, setLineQty, toLine, unitOf, useQuote,
+} from '@xenia/ordering'
+import { Button, EmptyState, IconButton, Input, Spinner, Textarea, cx } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { sendBody } from './orderLogic'
+
+const SERVICE = '__service__'
+
+export default function AddItems({ orderId, onSent, openOrder }) {
+ const { t } = useTranslation('manager')
+ const { formatMoney } = useFormat()
+ const { data: menu } = useLiveQuery({ queryKey: ['ordering-menu'], queryFn: () => client.get('/api/orders/menu').then(r => r.data),
+ events: ['products_changed', 'pricing.changed'], staleTime: 30_000 })
+ const [category, setCategory] = useState(null)
+ const [query, setQuery] = useState('')
+ const [cart, setCart] = useState([])
+ const [note, setNote] = useState('')
+ const [choosing, setChoosing] = useState(null)
+ const [busy, setBusy] = useState(false)
+
+ const fetchQuote = lines => client.post('/api/orders/quote', { order_id: orderId ?? undefined, order_type: 'here', lines }).then(r => r.data)
+ const { quote, pending, error } = useQuote(fetchQuote, cart, String(orderId ?? 'new'))
+ const products = useMemo(() => (menu?.products ?? []), [menu])
+ const cats = useMemo(() => categoriesWithProducts((menu?.categories ?? []).filter(c => !c.parent_id), products.filter(p => !p.service)), [menu, products])
+ const shown = query.trim() ? searchProducts(products, query)
+ : category === SERVICE ? products.filter(p => p.service)
+ : productsIn(products.filter(p => !p.service), category)
+ const byId = id => products.find(p => p.id === id)
+
+ const tap = p => {
+ if (!p.available) return
+ if (needsChoices(p)) { setChoosing(p); return }
+ const unit = unitOf(p)
+ setCart(c => addLine(c, toLine(p, defaultSelection(p), unit ? unit.start : 1)))
+ }
+ const send = async () => {
+ setBusy(true)
+ try {
+ const id = orderId ?? (await openOrder())
+ const { data } = await client.post(`/api/orders/${id}/items`, sendBody(cart.map(line => ({ line })), note))
+ const failed = (data.print_results ?? []).filter(r => !r.success)
+ if (failed.length) toast.error(t('orders.add.notPrinted', { printers: failed.map(r => r.printer_name).join(', ') }))
+ else toast.success(t('orders.add.sent'))
+ setCart([])
+ setNote('')
+ onSent(id)
+ } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
+ }
+
+ if (!menu) return
+ return (
+
+
+
+
+ setQuery(e.target.value)} placeholder={t('orders.add.search')} aria-label={t('orders.add.search')} className="pl-9" data-testid="order-search" />
+
+
+ {!query.trim() && (
+
+ {[{ id: null, name: t('orders.add.all') }, ...cats, ...(products.some(p => p.service) ? [{ id: SERVICE, name: t('orders.add.service') }] : [])].map(c => (
+ setCategory(c.id)}
+ className={cx('px-3 py-1.5 rounded-full border text-label font-medium', category === c.id ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
+ {c.name}
+
+ ))}
+
+ )}
+ {shown.length === 0 ? : (
+
+ {shown.map(p => (
+ tap(p)} disabled={!p.available} data-testid="order-product" data-id={p.id} data-name={p.name}
+ className={cx('min-h-20 p-2.5 rounded-control border text-left grid content-between gap-1 transition-colors duration-fast',
+ p.available ? 'border-line bg-surface hover:border-accent hover:bg-accent-soft' : 'border-line bg-surface-2 opacity-50 cursor-not-allowed')}>
+ {p.name}
+ {p.available ? formatMoney(p.price) : t('orders.add.soldOut')}{needsChoices(p) ? ' · …' : ''}
+
+ ))}
+
+ )}
+
+
+
{t('orders.add.toSend')}
+ {cart.length === 0 ?
{t('orders.add.empty')}
: (
+
+ {cart.map((line, i) => {
+ const priced = quote?.lines?.[i]
+ const p = byId(line.product_id)
+ const unit = p ? unitOf(p) : null
+ const step = unit ? unit.step : 1
+ return (
+
+
+ {p?.name ?? priced?.name}
+ {priced?.entries?.length > 0 && {priced.entries.map(e => e.name).join(', ')} }
+
+ setCart(c => setLineQty(c, i, line.quantity - step))}>
+ {line.quantity - step <= 0 ? : }
+
+ {unit ? `${line.quantity} ${unit.label}` : line.quantity}
+ setCart(c => setLineQty(c, i, line.quantity + step))}>
+ {priced ? formatMoney(priced.total) : '…'}
+
+ )
+ })}
+
+ )}
+ {error &&
{errorMessage(error, t)}
}
+
+
+ {choosing && setChoosing(null)} onAdd={line => setCart(c => addLine(c, line))} />}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/OrderHistory.jsx b/manager_dashboard/src/pages/orders/OrderHistory.jsx
new file mode 100644
index 0000000..7cebf52
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/OrderHistory.jsx
@@ -0,0 +1,76 @@
+// What happened to a table's order (plan step 6.9): the audit log (opened, lines added, paid,
+// cancelled, closed; a payment counted twice stands out) and the price changes (rules, deals,
+// discounts, by whom).
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { EmptyState, cx } from '@xenia/ui'
+import { Pill } from '../overview/parts'
+import { nameOf } from './orderLogic'
+
+const EVENT_TONE = { PAYMENT: 'success', PAYMENT_OFFLINE: 'success', ORDER_CLOSED: 'neutral', ORDER_CANCELLED: 'danger', ITEM_CANCELLED: 'danger' }
+const ids = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
+
+export function AuditList({ order }) {
+ const { t } = useTranslation('manager')
+ const { formatDateTime, formatMoney } = useFormat()
+ const logs = order.audit_logs ?? []
+ if (!logs.length) return
+ const byId = new Map(order.items.map(i => [i.id, i]))
+ return (
+
+ {logs.map(log => {
+ const dup = !!log.is_duplicate
+ const names = ids(log.item_ids).map(id => byId.get(id)).filter(Boolean).map(i => `${nameOf(i)} ×${i.quantity}`)
+ return (
+
+
+ {t(`orders.history.event.${log.event_type}`, { defaultValue: log.event_type })}
+ {dup && {t('orders.history.duplicate')} }
+
+
+
+ {log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '')}
+ {log.amount != null && {formatMoney(log.amount)} }
+ {log.payment_method && {t(`orders.pay.method.${log.payment_method}`, { defaultValue: log.payment_method })} }
+
+ {names.length > 0 && {names.map((n, i) => {n} )} }
+ {log.note && {log.note} }
+
+
+ {formatDateTime(log.offline_at || log.created_at, 'datetimeShort')}
+ {log.offline_at && {t('orders.history.offline')} }
+
+
+ )
+ })}
+
+ )
+}
+
+export function PriceEventList({ events }) {
+ const { t } = useTranslation('manager')
+ const { formatDateTime, formatMoney } = useFormat()
+ if (!events.length) return
+ return (
+
+ {events.map(ev => (
+
+ {t(`orders.history.price.${ev.event_type}`, { defaultValue: ev.event_type })}
+
+
+ {(ev.modifier_name || ev.deal_name) && {ev.modifier_name || ev.deal_name} }
+ {ev.applied_by_username && {t('orders.history.by', { name: ev.applied_by_username })} }
+ {ev.delta_amount != null && (
+
+ {formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
+ {ev.price_before != null && ev.price_after != null && ({formatMoney(ev.price_before)} → {formatMoney(ev.price_after)}) }
+
+ )}
+
+ {ev.waiter_note && {ev.waiter_note} }
+
+ {formatDateTime(ev.applied_at, 'datetimeShort')}
+
+ ))}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/OrderLines.jsx b/manager_dashboard/src/pages/orders/OrderLines.jsx
new file mode 100644
index 0000000..3fac901
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/OrderLines.jsx
@@ -0,0 +1,151 @@
+// A table's order lines in the manager (plan step 6.9): what was ordered with its choices, who
+// paid what and how, price changes; pick unpaid lines to pay, discount, cancel or put on the
+// customer's tab. The rules are the phones' (a discount needs pricing.discounts.apply, the
+// server checks every key again).
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { Ban, CreditCard, Percent, Printer, Receipt } from 'lucide-react'
+import { useCan } from '@xenia/access'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog, EmptyState, Field, Input, cx } from '@xenia/ui'
+import client from '../../api/client'
+import { Pill } from '../overview/parts'
+import { lineAmount, lineDetails, nameOf, selectable, selectedAmount, shownLines, toggleSelected, unitOf } from './orderLogic'
+
+const STATUS_TONE = { paid: 'success', cancelled: 'danger', tabbed: 'info', closed: 'warning' }
+const EVENT_TONE = { waiter_discount: 'text-accent-ink', free_item_added: 'text-success-ink', modifier_applied: 'text-info-ink' }
+
+export default function OrderLines({ order, open, priceEvents, onPay, onChanged }) {
+ const { t } = useTranslation('manager')
+ const { formatMoney, formatTime } = useFormat()
+ const canDiscount = useCan('pricing.discounts.apply')
+ const [selected, setSelected] = useState([])
+ const [cancelling, setCancelling] = useState(false)
+ const [discounting, setDiscounting] = useState(false)
+ const lines = shownLines(order)
+ const picked = selected.filter(id => order.items.some(i => i.id === id && selectable(i)))
+ const amount = selectedAmount(order, picked)
+ const done = msg => { toast.success(msg); setSelected([]); onChanged() }
+ const onError = err => toast.error(errorMessage(err, t))
+
+ const cancel = useMutation({
+ mutationFn: print => client.post(`/api/orders/${order.id}/cancel-items`, { item_ids: picked, print_cancellation: print }),
+ onSuccess: () => { setCancelling(false); done(t('orders.lines.cancelled', { count: picked.length })) }, onError,
+ })
+ const toTab = useMutation({
+ mutationFn: async () => { for (const id of picked) await client.post(`/api/orders/${order.id}/items/${id}/tab`) },
+ onSuccess: () => done(t('orders.lines.tabbed')), onError: err => { onError(err); onChanged() },
+ })
+
+ return (
+
+ {lines.length === 0 ? : (
+
+ )}
+
+ {open && picked.length > 0 && (
+
+ {t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}
+ setSelected([])}>{t('orders.lines.clear')}
+ {order.customer_id && } loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}}
+ {canDiscount && } onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}}
+ } onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}
+ } onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}
+
+ )}
+
+ {cancelling && (
+ setCancelling(false)} title={t('orders.lines.cancelTitle', { count: picked.length })}
+ description={t('orders.lines.cancelBody')}
+ footer={<>
+ setCancelling(false)}>{t('orders.back')}
+ cancel.mutate(false)} data-testid="cancel-no-print">{t('orders.lines.cancelNoPrint')}
+ } loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}
+ >} />
+ )}
+ {discounting && setDiscounting(false)}
+ onDone={() => { setDiscounting(false); done(t('orders.discount.done')) }} />}
+
+ )
+}
+
+function DiscountDialog({ orderId, itemIds, amount, onClose, onDone }) {
+ const { t } = useTranslation('manager')
+ const { formatMoney } = useFormat()
+ const [pct, setPct] = useState('10')
+ const [note, setNote] = useState('')
+ const value = Number(String(pct).replace(',', '.'))
+ const ok = value > 0 && value <= 100
+ const apply = useMutation({
+ mutationFn: () => client.post(`/api/orders/${orderId}/items/discount`, { item_ids: itemIds, discount_percent: value, note: note.trim() || null }),
+ onSuccess: onDone, onError: err => toast.error(errorMessage(err, t)),
+ })
+ return (
+
+ {t('orders.back')}
+ apply.mutate()} data-testid="discount-apply">{t('orders.discount.apply')}
+ >}>
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/OrderPage.jsx b/manager_dashboard/src/pages/orders/OrderPage.jsx
new file mode 100644
index 0000000..b4e97b3
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/OrderPage.jsx
@@ -0,0 +1,194 @@
+// A table's order in the manager (plan step 6.9; replaces the v1 order page and its desktop
+// ordering tab). Taken, changed, paid and closed by the phones' rules: lines go by id and the
+// server prices them (4.4); paying asks cash or card; "Close" with unpaid lines either takes
+// the payment first or, when the venue allows it (orders.close_with_unpaid), writes them off
+// after saying so. `/orders/new?table=5` is a table without an order: the first "Send" opens it.
+import { useState } from 'react'
+import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
+import { useMutation, useQueryClient } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { ArrowLeft, Ban, CheckCheck, CreditCard, Printer } from 'lucide-react'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog, EmptyState, Select, Spinner, cx } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { useDuration } from '../overview/hooks'
+import { tableName } from '../overview/overviewLogic'
+import { Money, Pill } from '../overview/parts'
+import AddItems from './AddItems'
+import OrderLines from './OrderLines'
+import OrderPeople from './OrderPeople'
+import PayDialog from './PayDialog'
+import { AuditList, PriceEventList } from './OrderHistory'
+import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
+
+const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded', 'kds_order_updated', 'kds_item_updated']
+const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
+const TABS = ['order', 'prices', 'history']
+
+export default function OrderPage() {
+ const { orderId } = useParams()
+ const [params] = useSearchParams()
+ if (orderId === 'new') return
+ return
+}
+
+function useVenue() {
+ const { data } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
+ return venueRules(data)
+}
+
+function Back() {
+ const { t } = useTranslation('manager')
+ const navigate = useNavigate()
+ return
} onClick={() => navigate('/tables')}>{t('orders.toTables')}
+}
+
+function NewOrder({ tableId }) {
+ const { t } = useTranslation('manager')
+ const navigate = useNavigate()
+ const qc = useQueryClient()
+ const { data: tables = [] } = useLiveQuery({ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data), events: ['table_list_changed'] })
+ const table = tables.find(x => x.id === tableId)
+ const open = async () => (await client.post('/api/orders/', { table_id: tableId, order_type: 'here' })).data.id
+ return (
+
+
+
+
+ {t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}
+ {t('overview.tableState.free')}
+
+
{t('orders.newHint')}
+
{
+ qc.invalidateQueries({ queryKey: ['orders-active'] })
+ navigate(`/orders/${id}`, { replace: true })
+ }} />
+
+
+ )
+}
+
+function OrderView({ orderId }) {
+ const { t } = useTranslation('manager')
+ const { formatTime, formatMoney } = useFormat()
+ const since = useDuration()
+ const navigate = useNavigate()
+ const qc = useQueryClient()
+ const venue = useVenue()
+ const [tab, setTab] = useState('order')
+ const [paying, setPaying] = useState(null) // { ids, amount, thenClose, after }
+ const [confirm, setConfirm] = useState(null) // 'close' | 'writeOff' | 'cancel'
+ const [printerId, setPrinterId] = useState('')
+
+ const { data: order, isPending, error } = useLiveQuery({
+ queryKey: ['order', orderId], queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), events: ORDER_EVENTS,
+ })
+ const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
+ const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
+ const { data: priceEvents = [] } = useLiveQuery({
+ queryKey: ['price-events', orderId], queryFn: () => client.get(`/api/pricing/events/order/${orderId}`).then(r => r.data), events: ['order_updated'],
+ })
+
+ const refresh = () => {
+ qc.invalidateQueries({ queryKey: ['order', orderId] })
+ qc.invalidateQueries({ queryKey: ['price-events', orderId] })
+ qc.invalidateQueries({ queryKey: ['orders-active'] })
+ }
+ const onError = err => toast.error(errorMessage(err, t))
+ const close = useMutation({ mutationFn: () => client.post(`/api/orders/${orderId}/close`), onSuccess: () => { setConfirm(null); toast.success(t('orders.closed')); refresh() }, onError })
+ const cancel = useMutation({
+ mutationFn: print => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }),
+ onSuccess: () => { setConfirm(null); toast.success(t('orders.cancelled')); refresh(); navigate('/tables') }, onError,
+ })
+ const print = useMutation({ mutationFn: pid => client.post(`/api/orders/${orderId}/print`, { printer_id: pid }), onSuccess: () => toast.success(t('orders.printing')), onError })
+
+ if (isPending) return
+ if (error || !order) {
+ return
+ }
+
+ const editable = ['open', 'partially_paid', 'paid'].includes(order.status)
+ const sums = totals(order)
+ const due = unpaidIds(order)
+
+ function startClose() {
+ const step = closeStep(order, venue.closeWithUnpaid)
+ if (step === 'payFirst') setPaying({ ids: due, amount: sums.due, thenClose: true })
+ else setConfirm(step)
+ }
+
+ return (
+
+
+
+
+ {order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}
+ {t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}
+ {t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at, order.closed_at ? new Date(order.closed_at).getTime() : undefined) })}
+
+
+ {sums.paid > 0 && {t('orders.paid')} }
+ {sums.paid > 0 && sums.due > 0 && {t('orders.due')} }
+ {t('orders.total')}
+
+
+
+
+
+ {TABS.map(k => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)} )}
+
+
+ {editable && due.length > 0 && } onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}}
+ {editable && } onClick={startClose} data-testid="order-close">{t('orders.close')}}
+ {editable && } onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}}
+ {printers.length > 0 && (
+
+ setPrinterId(e.target.value)} aria-label={t('orders.printer')}
+ placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
+ } disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}
+
+ )}
+
+
+ {tab === 'order' && (
+
+
+ setPaying({ ids, amount, after })} />
+
+
+ {editable &&
}
+
+ )}
+ {tab === 'prices' &&
}
+ {tab === 'history' &&
}
+
+
+ {paying &&
setPaying(null)}
+ onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
+
+ {(confirm === 'close' || confirm === 'writeOff') && (
+ setConfirm(null)} title={t(confirm === 'close' ? 'orders.confirmClose' : 'orders.writeOffTitle')}
+ description={confirm === 'writeOff' ? t('orders.writeOffBody', { count: due.length, amount: formatMoney(sums.due) }) : undefined}
+ footer={<>
+ setConfirm(null)}>{t('orders.back')}
+ {confirm === 'writeOff' && { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')} }
+ close.mutate()} data-testid="order-close-confirm">
+ {confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
+
+ >} />
+ )}
+ {confirm === 'cancel' && (
+ setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
+ footer={<>
+ setConfirm(null)}>{t('orders.back')}
+ cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}
+ } loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}
+ >} />
+ )}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/OrderPeople.jsx b/manager_dashboard/src/pages/orders/OrderPeople.jsx
new file mode 100644
index 0000000..6ca5713
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/OrderPeople.jsx
@@ -0,0 +1,99 @@
+// Who is on a table's order (plan step 6.9): its waiters (add or take one off) and its customer
+// (search and attach one, or take them off; with the customers app on).
+import { useState } from 'react'
+import { useMutation } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { UserRound, X } from 'lucide-react'
+import { useModule } from '@xenia/access'
+import { errorMessage } from '@xenia/api'
+import { useTranslation } from '@xenia/i18n'
+import { Button, IconButton, Input, Select } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { Pill } from '../overview/parts'
+import { addableWaiters, personName } from './orderLogic'
+
+export default function OrderPeople({ order, open, staff, onChanged }) {
+ const { t } = useTranslation('manager')
+ const crm = useModule('crm')
+ const onError = err => toast.error(errorMessage(err, t))
+ const add = useMutation({ mutationFn: id => client.put(`/api/orders/${order.id}/assign-waiter`, { waiter_id: id }), onSuccess: onChanged, onError })
+ const remove = useMutation({ mutationFn: id => client.delete(`/api/orders/${order.id}/waiters/${id}`), onSuccess: onChanged, onError })
+ const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
+ const addable = addableWaiters(staff, order)
+
+ return (
+
+
+
{t('orders.people.staff')}
+
+ {order.waiters.length === 0 &&
{t('orders.people.noStaff')} }
+ {order.waiters.map(w => (
+
+ {name(w.waiter_id)}
+ {open && (
+ remove.mutate(w.waiter_id)}>
+ )}
+
+ ))}
+ {open && addable.length > 0 && (
+
e.target.value && add.mutate(Number(e.target.value))}
+ options={addable.map(s => ({ value: String(s.id), label: personName(s) }))} />
+ )}
+
+
+ {crm && }
+
+ )
+}
+
+function Customer({ order, open, onChanged }) {
+ const { t } = useTranslation('manager')
+ const [searching, setSearching] = useState(false)
+ const [q, setQ] = useState('')
+ const { data: found = [] } = useLiveQuery({
+ queryKey: ['customers', q], enabled: searching, staleTime: 30_000,
+ queryFn: () => client.get('/api/customers/', { params: q ? { search: q } : {} }).then(r => r.data),
+ })
+ const set = useMutation({
+ mutationFn: id => client.put(`/api/orders/${order.id}/customer`, { customer_id: id }),
+ onSuccess: () => { setSearching(false); setQ(''); onChanged() },
+ onError: err => toast.error(errorMessage(err, t)),
+ })
+
+ return (
+
+
{t('orders.people.customer')}
+ {order.customer_id ? (
+
+
+
+ {order.customer_name || `#${order.customer_id}`}
+ {order.customer_phone && {order.customer_phone} }
+
+ {open && set.mutate(null)}> }
+
+ ) : !open ?
{t('orders.people.noCustomer')}
+ : !searching ?
setSearching(true)}>{t('orders.people.customerAdd')}
+ : (
+
+
setQ(e.target.value)} placeholder={t('orders.people.customerSearch')} aria-label={t('orders.people.customerSearch')} />
+
+ {found.length === 0 && {t('orders.people.customerNone')} }
+ {found.map(c => (
+
+ set.mutate(c.id)}>
+ {c.name}
+ {c.phone && {c.phone} }
+
+
+ ))}
+
+
{ setSearching(false); setQ('') }}>{t('orders.back')}
+
+ )}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/PayDialog.jsx b/manager_dashboard/src/pages/orders/PayDialog.jsx
new file mode 100644
index 0000000..eac2ae0
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/PayDialog.jsx
@@ -0,0 +1,50 @@
+// Paying lines of a table's order from the manager (plan step 6.9), as the phones do: how much,
+// then cash or card (card only when the venue takes cards). `thenClose` is the phones'
+// "instant-pay close": the rest is paid and the order closed in one go, for venues that don't
+// close with unpaid items (orders.close_with_unpaid, 4.8).
+import { useState } from 'react'
+import { Banknote, CreditCard } from 'lucide-react'
+import { errorMessage } from '@xenia/api'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, Dialog } from '@xenia/ui'
+import client from '../../api/client'
+
+export default function PayDialog({ orderId, itemIds, amount, card = true, thenClose = false, onClose, onDone }) {
+ const { t } = useTranslation('manager')
+ const { formatMoney } = useFormat()
+ const [busy, setBusy] = useState(null)
+ const [error, setError] = useState(null)
+
+ async function pay(method) {
+ setBusy(method)
+ setError(null)
+ try {
+ await client.post(`/api/orders/${orderId}/pay`, { item_ids: itemIds, payment_method: method })
+ if (thenClose) await client.post(`/api/orders/${orderId}/close`)
+ onDone(method)
+ } catch (err) {
+ setError(errorMessage(err, t))
+ } finally { setBusy(null) }
+ }
+
+ return (
+
{t('orders.back')}}>
+
+
{formatMoney(amount)}
+
+ } loading={busy === 'cash'} disabled={!!busy} onClick={() => pay('cash')} data-testid="pay-cash">
+ {t('orders.pay.cash')}
+
+ } loading={busy === 'card'} disabled={!!busy || !card}
+ onClick={() => pay('card')} data-testid="pay-card" title={card ? undefined : t('orders.pay.noCard')}>
+ {t('orders.pay.card')}
+
+
+ {error &&
{error}
}
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/QuickActions.jsx b/manager_dashboard/src/pages/orders/QuickActions.jsx
new file mode 100644
index 0000000..68be576
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/QuickActions.jsx
@@ -0,0 +1,86 @@
+// A table's quick actions from the Tables page (plan step 6.9): its flags (VIP, birthday…), and
+// a message to the table's waiters or to everyone, from a ready-made text or typed.
+import { useState } from 'react'
+import { useQueryClient } from '@tanstack/react-query'
+import toast from 'react-hot-toast'
+import { errorMessage } from '@xenia/api'
+import { useTranslation } from '@xenia/i18n'
+import { Button, Dialog, Field, Input, Switch, cx } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import { tableName } from '../overview/overviewLogic'
+
+export default function QuickActions({ card, flagDefs, current, onClose }) {
+ const { t } = useTranslation('manager')
+ const qc = useQueryClient()
+ const { table, order } = card
+ const [ids, setIds] = useState(() => current.map(f => f.id))
+ const [notify, setNotify] = useState(false)
+ const [toAll, setToAll] = useState(!order?.waiters?.length)
+ const [message, setMessage] = useState('')
+ const [busy, setBusy] = useState(false)
+ const { data: templates = [] } = useLiveQuery({ queryKey: ['quick-templates'], queryFn: () => client.get('/api/notifications/templates').then(r => r.data), staleTime: 60_000 })
+ const toggle = id => setIds(list => (list.includes(id) ? list.filter(x => x !== id) : [...list, id]))
+
+ async function save() {
+ setBusy(true)
+ try {
+ await client.put(`/api/flags/table/${table.id}`, { flag_ids: ids })
+ if (notify && message.trim()) {
+ await client.post('/api/notifications/send', {
+ body: message.trim(), table_ids: [table.id],
+ target_waiter_ids: toAll ? [] : (order?.waiters ?? []).map(w => w.waiter_id),
+ })
+ toast.success(t('orders.quick.sent'))
+ } else toast.success(t('orders.quick.saved'))
+ qc.invalidateQueries({ queryKey: ['flag-assignments'] })
+ onClose()
+ } catch (err) { toast.error(errorMessage(err, t)) } finally { setBusy(false) }
+ }
+
+ return (
+
+ {t('orders.back')}
+ {t('orders.quick.save')}
+ >}>
+
+
+ {flagDefs.length === 0 ? {t('orders.quick.noFlags')} : (
+
+ {flagDefs.map(f => (
+ toggle(f.id)} data-testid="quick-flag"
+ className={cx('inline-flex items-center gap-1 px-3 py-1 rounded-full border text-label',
+ ids.includes(f.id) ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
+ {f.emoji && {f.emoji} }{f.name}
+
+ ))}
+
+ )}
+
+
+
+ {t('orders.quick.notify')}
+
+ {notify && (
+
+ {templates.length > 0 && (
+
+ {templates.slice(0, 6).map(tp => (
+ setMessage(tp.body)}>{tp.body}
+ ))}
+
+ )}
+ setMessage(e.target.value)} placeholder={t('orders.quick.message')} aria-label={t('orders.quick.message')} />
+ {order?.waiters?.length > 0 && (
+
+
+ {toAll ? t('orders.quick.toAll') : t('orders.quick.toTable')}
+
+ )}
+
+ )}
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/TablesPage.jsx b/manager_dashboard/src/pages/orders/TablesPage.jsx
new file mode 100644
index 0000000..21129a2
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/TablesPage.jsx
@@ -0,0 +1,160 @@
+// The tables now, in the manager (plan step 6.9; the map since 6.8): each table's state, total,
+// time open, waiters, flags and a booking kept for it soon (RESERVED). A table with an order
+// opens its order page; a free one opens a new order there. Quick actions set the table's flags
+// and can tell its waiters (or everyone) a message. Lines that didn't print are listed below.
+// Everything stays current through the live events.
+import { useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { Clock, Lock, Printer, Zap } from 'lucide-react'
+import { useFormat, useTranslation } from '@xenia/i18n'
+import { Button, EmptyState, IconButton, Select, Spinner, cx } from '@xenia/ui'
+import client from '../../api/client'
+import { useLiveQuery } from '../../live/useLiveQuery'
+import LiveFloor from '../floor/LiveFloor'
+import { useDuration } from '../overview/hooks'
+import { TABLE_STATES, durationParts, orderTotal, tableCards, tableName } from '../overview/overviewLogic'
+import { Money, Pill } from '../overview/parts'
+import PendingPrints from '../overview/PendingPrints'
+import { BORDER, SOFT, SOLID } from '../overview/tones'
+import QuickActions from './QuickActions'
+import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
+
+const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
+const STATE_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', free: 'neutral' }
+
+export default function TablesPage() {
+ const { t } = useTranslation('manager')
+ const tc = useTranslation('common').t
+ const navigate = useNavigate()
+ const [view, setView] = useState('list')
+ const [states, setStates] = useState([])
+ const [zone, setZone] = useState('')
+ const [quick, setQuick] = useState(null) // a card
+
+ const { data: tables = [], isPending: loadingTables } = useLiveQuery({
+ queryKey: ['tables'], queryFn: () => client.get('/api/tables/').then(r => r.data),
+ events: ['table_list_changed', 'reservation_updated'], refetchInterval: 60_000,
+ })
+ const { data: orders = [], isPending: loadingOrders } = useLiveQuery({
+ queryKey: ['orders-active'], queryFn: () => client.get('/api/orders/').then(r => r.data), events: ORDER_EVENTS, refetchInterval: 60_000,
+ })
+ const { data: groups = [] } = useLiveQuery({ queryKey: ['table-groups'], queryFn: () => client.get('/api/tables/groups').then(r => r.data), events: ['table_list_changed'] })
+ const { data: flagDefs = [] } = useLiveQuery({ queryKey: ['flag-defs'], queryFn: () => client.get('/api/flags/defs').then(r => r.data), staleTime: 60_000 })
+ const { data: flagRows = [] } = useLiveQuery({ queryKey: ['flag-assignments'], queryFn: () => client.get('/api/flags/assignments').then(r => r.data), events: ['table_flags_changed'] })
+ const { data: staff = [] } = useLiveQuery({ queryKey: ['waiters'], queryFn: () => client.get('/api/waiters/').then(r => r.data), staleTime: 60_000 })
+
+ const cards = tableCards(tables, orders)
+ const shown = filterCards(cards, { states, zone })
+ const flags = flagsByTable(flagDefs, flagRows)
+ const name = id => personName(staff.find(s => s.id === id)) || `#${id}`
+ const toggleState = s => setStates(list => (list.includes(s) ? list.filter(x => x !== s) : [...list, s]))
+
+ if (loadingTables || loadingOrders) return
+
+ return (
+
+
+
+ {['list', 'map'].map(v => (
+ setView(v)} data-testid={`tables-view-${v}`}
+ className={cx('px-3 py-1.5 text-label font-medium', view === v ? 'bg-accent-soft text-accent-ink' : 'bg-surface text-ink-2 hover:bg-surface-2')}>
+ {tc(`floorMap.${v}`)}
+
+ ))}
+
+
+ {view === 'list' && TABLE_STATES.map(s => (
+
toggleState(s)} data-testid={`tables-state-${s}`}
+ className={cx('inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full border text-label font-semibold',
+ states.includes(s) ? `${SOFT[STATE_TONE[s]]} ${BORDER[STATE_TONE[s]]}` : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
+
+ {t(`overview.tableState.${s}`)}
+ {cards.filter(c => c.state === s).length}
+
+ ))}
+
setZone(e.target.value)} aria-label={t('orders.tables.zone')} data-testid="tables-zone">
+ {t('orders.tables.allZones')}
+ {groups.map(g => {g.name} )}
+ {t('orders.tables.noZone')}
+
+
+
+ {view === 'map' && (
+
navigate(`/orders/${id}`)} />
+ )}
+
+ {view === 'list' && (shown.length === 0
+ ?
+ : (
+
+ {shown.map(card => (
+
1 ? groups.find(g => g.id === card.table.group_id)?.name : null} flags={flags[card.table.id] ?? []} waiterName={name}
+ onOpen={() => navigate(cardTarget(card))} onQuick={() => setQuick(card)} />
+ ))}
+
+ ))}
+
+ c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
+
+ {quick && setQuick(null)} />}
+
+ )
+}
+
+function TableCard({ card, zone, flags, waiterName, onOpen, onQuick }) {
+ const { t } = useTranslation('manager')
+ const { formatTime } = useFormat()
+ const since = useDuration()
+ const { table, order, state, pendingPrint } = card
+ const tone = STATE_TONE[state]
+ const booking = table.upcoming_reservation
+ const open = order ? durationParts(order.opened_at) : null
+ const long = !!open && open.h * 60 + open.m >= 90 // the v1 card's "been here a while"
+ return (
+
+
+
+
+
+ {tableName(table)}
+ {zone && {zone} }
+
+ {t(`overview.tableState.${state}`)}
+
+
+ {pendingPrint && {t('orders.tables.notPrinted')} }
+ {booking && (
+
+ {t('orders.tables.reserved', { time: formatTime(booking.reserved_for), name: booking.guest_name })}
+
+ )}
+ {flags.slice(0, 3).map(f => (
+ {f.emoji && {f.emoji} }{f.name}
+ ))}
+ {flags.length > 3 && f.name).join(', ')}>+{flags.length - 3} }
+
+
+
+ {t('orders.total')}
+ {order ? : — }
+
+
+ {t('orders.tables.time')}
+
+ {order ? <> {since(order.opened_at)}> : — }
+
+
+
+
+
+
+ {!order ? (table.seat_count ? t('orders.tables.seats', { count: table.seat_count }) : '')
+ : order.waiters.length ? order.waiters.map(w => waiterName(w.waiter_id)).join(', ') : t('orders.tables.noWaiter')}
+
+
+ {order ? t('orders.tables.view') : t('orders.tables.take')}
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/orderLogic.js b/manager_dashboard/src/pages/orders/orderLogic.js
new file mode 100644
index 0000000..e2d0bf1
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/orderLogic.js
@@ -0,0 +1,105 @@
+// A table's order in the manager, as plain data (plan step 6.9), tested in tests/orders.test.mjs.
+// The rules are the phones': prices come from the server (lines by id, 4.4); closing with unpaid
+// items needs the venue's "close with unpaid items" (orders.close_with_unpaid, 4.8), otherwise
+// the rest is paid first.
+
+export const OPEN_STATUSES = ['open', 'partially_paid', 'paid']
+export const isOpen = order => !!order && OPEN_STATUSES.includes(order.status)
+
+const parse = raw => { try { return raw ? JSON.parse(raw) : [] } catch { return [] } }
+
+/** What a line has: its choices ("Well done, Fries"), what's left out, the note. */
+export function lineDetails(item) {
+ const opts = parse(item.selected_options).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
+ const removed = parse(item.removed_ingredients).map(o => (typeof o === 'string' ? o : o?.name)).filter(Boolean)
+ return { choices: opts, removed, note: item.notes || null }
+}
+
+export const unitOf = item => (item.unit_price ?? 0) + (item.price_adjustment ?? 0)
+export const lineAmount = item => Math.round(unitOf(item) * item.quantity * 100) / 100
+export const nameOf = item => item.product_name || item.product?.name || `#${item.product_id}`
+
+const LIVE = ['active', 'ready', 'paid', 'closed']
+const UNPAID = ['active', 'ready']
+
+/** The order's sums: everything still on it, what's paid, what's due. */
+export function totals(order) {
+ const items = order?.items ?? []
+ const sum = list => Math.round(list.reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
+ const total = sum(items.filter(i => LIVE.includes(i.status)))
+ const paid = sum(items.filter(i => i.status === 'paid'))
+ const due = sum(items.filter(i => UNPAID.includes(i.status)))
+ return { total, paid, due }
+}
+
+export const unpaidIds = order => (order?.items ?? []).filter(i => UNPAID.includes(i.status)).map(i => i.id)
+
+/** Lines in the order they were added; cancelled ones last. */
+export function shownLines(order, { showCancelled = true } = {}) {
+ const items = [...(order?.items ?? [])].sort((a, b) => (a.added_at ?? '').localeCompare(b.added_at ?? '') || a.id - b.id)
+ const live = items.filter(i => i.status !== 'cancelled')
+ return showCancelled ? [...live, ...items.filter(i => i.status === 'cancelled')] : live
+}
+
+/** Selection: only unpaid lines can be paid or cancelled. */
+export function selectable(item) { return UNPAID.includes(item.status) }
+export function toggleSelected(sel, id) { return sel.includes(id) ? sel.filter(x => x !== id) : [...sel, id] }
+export const selectedAmount = (order, sel) => Math.round((order?.items ?? []).filter(i => sel.includes(i.id)).reduce((s, i) => s + lineAmount(i), 0) * 100) / 100
+
+/**
+ * What "Close" does: 'close' (nothing unpaid), 'writeOff' (unpaid lines and the venue allows
+ * closing with them: say so first), or 'payFirst' (the venue doesn't: offer to pay the rest).
+ */
+export function closeStep(order, closeWithUnpaid) {
+ const due = unpaidIds(order).length
+ if (!due) return 'close'
+ return closeWithUnpaid ? 'writeOff' : 'payFirst'
+}
+
+/** The venue's settings rows (GET /api/settings/) → the two that matter here. */
+export function venueRules(settings) {
+ const v = key => settings?.[key]?.value
+ return { closeWithUnpaid: v('orders.close_with_unpaid') === 'true', card: v('payments.card_enabled') !== 'false' }
+}
+
+/** The cart's lines as the server takes them, plus the order's note (POST /api/orders/{id}/items). */
+export function sendBody(cart, note) {
+ return { lines: cart.map(c => c.line), order_note: note?.trim() || null }
+}
+
+/** Waiters to add: the active staff not already on the order. */
+export function addableWaiters(staff = [], order) {
+ const on = new Set((order?.waiters ?? []).map(w => w.waiter_id))
+ return staff.filter(s => s.is_active !== false && !on.has(s.id))
+}
+
+export const personName = p => (p ? p.nickname || p.full_name || p.username : '')
+
+// ── the Tables page ─────────────────────────────────────────────────────────
+
+export const NO_ZONE = 'none'
+
+/** Cards (overviewLogic.tableCards) shown for the chosen states (none = all) and zone
+ * ('' = all, NO_ZONE = tables without a zone, else a zone id as text). */
+export function filterCards(cards, { states = [], zone = '' } = {}) {
+ return cards.filter(c => {
+ if (states.length && !states.includes(c.state)) return false
+ if (zone === NO_ZONE) return !c.table.group_id
+ if (zone) return String(c.table.group_id ?? '') === zone
+ return true
+ })
+}
+
+/** Flags on each table: { tableId: [{ ...flag, assigned_at }] } from the definitions and the assignments. */
+export function flagsByTable(defs = [], assignments = []) {
+ const byId = new Map(defs.map(f => [f.id, f]))
+ const out = {}
+ for (const a of assignments) {
+ const def = byId.get(a.flag_id)
+ if (def) (out[a.table_id] ??= []).push({ ...def, assigned_at: a.assigned_at })
+ }
+ return out
+}
+
+/** Where a table's card goes: its order, or a new order at that table. */
+export const cardTarget = card => (card.order ? `/orders/${card.order.id}` : `/orders/new?table=${card.table.id}`)
diff --git a/manager_dashboard/src/pages/overview/OrderDialog.jsx b/manager_dashboard/src/pages/overview/OrderDialog.jsx
index fce48cb..10793b0 100644
--- a/manager_dashboard/src/pages/overview/OrderDialog.jsx
+++ b/manager_dashboard/src/pages/overview/OrderDialog.jsx
@@ -14,6 +14,8 @@ import { useLiveQuery } from '../../live/useLiveQuery'
import { lineTotal, orderTotal } from './overviewLogic'
import { Money, Pill } from './parts'
import { useDuration } from './hooks'
+import PayDialog from '../orders/PayDialog'
+import { closeStep, selectedAmount, unpaidIds, venueRules } from '../orders/orderLogic'
const ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' }
@@ -27,6 +29,9 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
const [confirm, setConfirm] = useState(null) // { kind: 'cancelItem', itemId } | { kind: 'cancelOrder' } | { kind: 'close' }
const [printCancel, setPrintCancel] = useState(null) // the same, after "yes": ask about the ticket
const [printerId, setPrinterId] = useState('')
+ const [paying, setPaying] = useState(null) // { ids, thenClose } (6.9: cash or card, the venue's close rule)
+ const { data: settings } = useLiveQuery({ queryKey: ['settings'], queryFn: () => client.get('/api/settings/').then(r => r.data), staleTime: 60_000 })
+ const venue = venueRules(settings)
const { data: order, isPending } = useLiveQuery({
queryKey: ['order', orderId],
@@ -52,7 +57,12 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
onSuccess: () => { toast.success(done); refresh(); after?.() },
onError: err => toast.error(errorMessage(err, t)),
})
- const pay = useMutation(run(ids => client.post(`/api/orders/${orderId}/pay`, { item_ids: ids }), t('overview.order.paidDone')))
+ const pay = ids => setPaying({ ids })
+ const startClose = () => {
+ const step = closeStep(order, venue.closeWithUnpaid)
+ if (step === 'payFirst') setPaying({ ids: unpaidIds(order), thenClose: true })
+ else setConfirm({ kind: step === 'writeOff' ? 'writeOff' : 'close' })
+ }
const cancelItem = useMutation(run(({ itemId, print }) => client.delete(`/api/orders/${orderId}/items/${itemId}`, { params: { print_cancellation: print } }), t('overview.order.lineCancelled')))
const cancelOrder = useMutation(run(({ print }) => client.delete(`/api/orders/${orderId}`, { params: { print_cancellation: print } }), t('overview.order.cancelled'), onClose))
const close = useMutation(run(() => client.post(`/api/orders/${orderId}/close`), t('overview.order.closed'), onClose))
@@ -64,7 +74,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
const confirmed = () => {
const c = confirm
setConfirm(null)
- if (c.kind === 'close') close.mutate()
+ if (c.kind === 'close' || c.kind === 'writeOff') close.mutate()
else setPrintCancel(c)
}
const cancelWith = printIt => {
@@ -83,8 +93,8 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
}
description={order ? t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at) }) : undefined}
footer={order &&
- {isOpen && active.length > 0 && pay.mutate(active.map(i => i.id))} loading={pay.isPending} data-testid="order-pay-all">{t('overview.order.payAll')} }
- {isOpen && setConfirm({ kind: 'close' })}>{t('overview.order.close')} }
+ {isOpen && active.length > 0 && pay(active.map(i => i.id))} data-testid="order-pay-all">{t('overview.order.payAll')} }
+ {isOpen && {t('overview.order.close')} }
{isOpen && setConfirm({ kind: 'cancelOrder' })}>{t('overview.order.cancel')} }
{printers.length > 0 && (
@@ -125,7 +135,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
{isOpen && item.status === 'active' && (<>
-
pay.mutate([item.id])}>{t('overview.order.pay')}
+
pay([item.id])}>{t('overview.order.pay')}
setConfirm({ kind: 'cancelItem', itemId: item.id })}>
>)}
@@ -146,16 +156,28 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
)}
{confirm && (
-