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 ( -
onOpen(product)} - style={{ - background: 'white', - border: '1px solid #e2e8f0', - borderRadius: 12, - overflow: 'hidden', - cursor: 'pointer', - display: 'flex', - flexDirection: 'column', - transition: 'box-shadow 120ms ease, border-color 120ms ease', - position: 'relative', - }} - onMouseEnter={e => { e.currentTarget.style.boxShadow = '0 4px 12px rgba(0,0,0,0.08)'; e.currentTarget.style.borderColor = '#cbd5e1' }} - onMouseLeave={e => { e.currentTarget.style.boxShadow = 'none'; e.currentTarget.style.borderColor = '#e2e8f0' }} - > - {/* Thumbnail */} -
- {product.image_url - ? - : {initials} - } -
- - {/* Info */} -
-
- {product.name} -
- {product.tags?.length > 0 && ( -
- {product.tags.slice(0, 2).map(tag => ( - {tag} - ))} -
- )} -
- {Number(product.base_price).toFixed(2)} € - {canQuickAdd && ( - - )} -
-
-
- ) -} - -// ── Service item widget ─────────────────────────────────────────────────────── - -function ServiceItemWidget({ product, customerCount, onAdd }) { - const [qty, setQty] = useState(0) - const hasPrice = product.base_price != null && product.base_price > 0 - - return ( -
-
- {product.name} - - {hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'} - -
-
- - - - {qty} - -
-
- ) -} - -// ── Cart item row ───────────────────────────────────────────────────────────── - -function CartItemRow({ item, product, onRemove, onChangeQty, onEdit }) { - const isDecimal = DECIMAL_UNITS.has(product?.unit_type) - const optionSummary = item.selected_options?.length - ? item.selected_options.map(o => o.name).join(', ') - : null - - return ( -
-
-
- {product?.name ?? `#${item.product_id}`} -
- {optionSummary && ( -
- {optionSummary} -
- )} - {item.notes && ( -
- {item.notes} -
- )} -
- - {/* Qty controls */} - {isDecimal ? ( - - ) : ( -
- - {item.quantity} - -
- )} - - {/* Price */} - - €{((item.unit_price ?? 0) * item.quantity + (item.price_adjustment ?? 0) * item.quantity).toFixed(2)} - - - {/* Edit + Remove */} -
- - -
-
- ) -} - -// ── Search overlay ──────────────────────────────────────────────────────────── - -function SearchOverlay({ products, onClose, onOpen }) { - const [query, setQuery] = useState('') - const inputRef = useRef(null) - - useEffect(() => { - inputRef.current?.focus() - function onKey(e) { if (e.key === 'Escape') onClose() } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, [onClose]) - - const activeProducts = products.filter(p => p.lifecycle_status !== 'archived') - const results = query.trim().length === 0 - ? [] - : activeProducts.filter(p => p.name.toLowerCase().includes(query.trim().toLowerCase())) - - return ( - <> -
-
- {/* Input */} -
- - - - - setQuery(e.target.value)} - placeholder="Αναζήτηση προϊόντος…" - style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, color: '#1e293b', background: 'transparent', fontFamily: 'inherit' }} - /> - -
- - {/* Results */} -
- {query.trim().length === 0 ? ( -

Πληκτρολογήστε για αναζήτηση…

- ) : results.length === 0 ? ( -

Δεν βρέθηκαν προϊόντα για «{query}»

- ) : results.map(p => { - const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase() - return ( - - ) - })} -
-
- - ) -} - -// ── Main component ──────────────────────────────────────────────────────────── - -export default function DesktopOrderingTab({ orderId, tableId, orderStatus }) { - const qc = useQueryClient() - - const { data: productsData, isLoading: productsLoading } = useQuery({ - queryKey: ['products-ordering'], - queryFn: async () => { - const [prodRes, catRes] = await Promise.all([ - client.get('/api/products/'), - client.get('/api/products/categories'), - ]) - return { products: prodRes.data, categories: catRes.data } - }, - staleTime: 5 * 60 * 1000, - }) - - const products = productsData?.products ?? [] - const categories = productsData?.categories ?? [] - - const serviceProducts = products.filter(p => p.is_service_item) - const regularProducts = products.filter(p => !p.is_service_item || p.category_id) - const topLevel = categories.filter(c => !c.parent_id).sort((a, b) => a.sort_order - b.sort_order) - - const initialCatId = topLevel[0]?.id ?? null - const [activeCat, setActiveCat] = useState(null) - const [viewAllOpen, setViewAllOpen] = useState(false) - const [searchOpen, setSearchOpen] = useState(false) - const [expandedSubs, setExpandedSubs] = useState({}) - - // Drawer for product customization - const [drawerProduct, setDrawerProduct] = useState(null) - const [editItem, setEditItem] = useState(null) // { cartKey, product, drawerState } - - // Cart - const [cart, setCart] = useState([]) - const [orderNote, setOrderNote] = useState('') - const [sending, setSending] = useState(false) - - // Customer count (loaded from order) - const { data: orderData } = useQuery({ - queryKey: ['order', orderId], - queryFn: () => client.get(`/api/orders/${orderId}`).then(r => r.data), - enabled: !!orderId, - staleTime: 30_000, - }) - const customerCount = orderData?.customer_count ?? null - - // Courses settings - const { data: posSettings } = useQuery({ - queryKey: ['pos-settings-courses'], - queryFn: () => client.get('/api/settings/').then(r => r.data), - staleTime: 60_000, - }) - const coursesEnabled = posSettings?.['orders.courses_enabled']?.value === 'true' - const courses = coursesEnabled ? (() => { try { return JSON.parse(posSettings?.['orders.courses']?.value || '[]') } catch { return [] } })() : [] - - // Set initial category once products load - useEffect(() => { - if (activeCat === null && topLevel.length > 0) { - const firstId = serviceProducts.length > 0 ? SVC_CAT_ID : topLevel[0]?.id - setActiveCat(firstId ?? null) - } - }, [topLevel.length, serviceProducts.length]) - - function buildDefaultExpanded(catId) { - const subs = categories.filter(c => c.parent_id === catId) - const state = {} - subs.forEach(s => { if (s.auto_expanded) state[String(s.id)] = true }) - return state - } - - function selectCategory(id) { - setActiveCat(id) - setViewAllOpen(false) - setExpandedSubs(id === FAV_CAT_ID || id === SVC_CAT_ID ? {} : buildDefaultExpanded(id)) - } - - const isSvcActive = activeCat === SVC_CAT_ID - - const activeParent = categories.find(c => c.id === activeCat) - const subcategories = activeParent - ? categories.filter(c => c.parent_id === activeCat).sort((a, b) => a.sort_order - b.sort_order) - : [] - const hasSubcats = subcategories.length > 0 - const directProducts = regularProducts.filter(p => p.category_id === activeCat) - const sections = hasSubcats ? buildSections(activeParent, subcategories, directProducts) : [] - - // Cart management - function addToCart(item) { - setCart(prev => { - const { _key: _k, _drawerState: _ds, quantity: _q, ...newCore } = item - const matchIdx = prev.findIndex(existing => { - const { _key, _drawerState, quantity: _eq, ...existCore } = existing - return JSON.stringify(existCore) === JSON.stringify(newCore) - }) - if (matchIdx !== -1) { - const next = [...prev] - next[matchIdx] = { ...next[matchIdx], quantity: next[matchIdx].quantity + (item.quantity ?? 1) } - return next - } - return [...prev, { ...item, _key: Date.now() + Math.random() }] - }) - } - - function handleQuickAdd(product) { - const base = buildQuickAddItem(product) - const item = product.is_service_item ? { ...base, is_service_item: true } : base - addToCart(item) - toast.success(`${product.name} προστέθηκε`, { duration: 800 }) - } - - function removeFromCart(key) { - setCart(prev => prev.filter(i => i._key !== key)) - } - - function changeCartQty(key, newQty) { - if (newQty <= 0) removeFromCart(key) - else setCart(prev => prev.map(i => i._key === key ? { ...i, quantity: newQty } : i)) - } - - function openEditDrawer(cartItem) { - const product = products.find(p => p.id === cartItem.product_id) - if (!product) return - setEditItem({ cartKey: cartItem._key, product, drawerState: cartItem._drawerState }) - setDrawerProduct(null) - } - - function handleDrawerAdd(item) { - if (editItem) { - setCart(prev => prev.map(i => i._key === editItem.cartKey ? { ...item, _key: i._key } : i)) - setEditItem(null) - } else { - const finalItem = drawerProduct?.is_service_item ? { ...item, is_service_item: true } : item - addToCart(finalItem) - setDrawerProduct(null) - } - } - - const cartTotal = cart.reduce((s, i) => s + (i.unit_price ?? 0) * i.quantity + (i.price_adjustment ?? 0) * i.quantity, 0) - const isOpen = ['open', 'partially_paid'].includes(orderStatus) - - const addItemsMutation = useMutation({ - mutationFn: async () => { - let activeOrderId = orderId - if (!activeOrderId) { - const { data: newOrder } = await client.post('/api/orders/', { table_id: tableId }) - activeOrderId = newOrder.id - } - // what was chosen, by id: the server prices it (plan step 4.4) - const res = await client.post(`/api/orders/${activeOrderId}/items`, { - lines: cart.map(({ _key, _drawerState, ...item }) => wireLine(item, products.find(p => p.id === item.product_id))), - order_note: orderNote || null, - }) - return res.data - }, - onSuccess: (data) => { - const printResults = data.print_results ?? [] - const allOk = printResults.length === 0 || printResults.every(r => r.success) - if (!allOk) { - toast.error('Παραγγελία αποθηκεύτηκε αλλά κάποιος εκτυπωτής δεν ανταποκρίθηκε') - } else { - toast.success('Παραγγελία εστάλη επιτυχώς') - } - setCart([]) - setOrderNote('') - qc.invalidateQueries({ queryKey: ['order', orderId] }) - qc.invalidateQueries({ queryKey: ['orders-active'] }) - }, - onError: (err) => { - toast.error(err instanceof LineError - ? `«${err.product}»: το «${err.what}» δεν υπάρχει πια στο μενού` - : err?.response?.data?.detail || 'Σφάλμα αποστολής παραγγελίας') - }, - }) - - // Keyboard shortcut for search - useEffect(() => { - function onKey(e) { - if ((e.ctrlKey || e.metaKey) && e.key === 'f') { e.preventDefault(); setSearchOpen(true) } - if (e.key === 'Escape') { setDrawerProduct(null); setEditItem(null); setSearchOpen(false) } - } - window.addEventListener('keydown', onKey) - return () => window.removeEventListener('keydown', onKey) - }, []) - - if (productsLoading) { - return ( -
- Φόρτωση προϊόντων… -
- ) - } - - if (!isOpen) { - return ( -
- Η παραγγελία δεν είναι ανοιχτή. -
- ) - } - - const activeDrawerProduct = editItem ? editItem.product : drawerProduct - const drawerOpen = !!activeDrawerProduct - - return ( -
- - {/* ── LEFT: Category + Product browser ─────────────────────────────── */} -
- - {/* Toolbar */} -
-
- {/* SERVICE chip */} - {serviceProducts.length > 0 && ( - - )} - {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 ( - - ) - })} - -
- -
- - {/* 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 ( -
- - {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 && ( -
-