feat: tables and orders in the manager on v2 (platform-v2 step 6.9)

- manager: new pages/orders/ (Tables page cards + quick actions, order page with
  lines, multi-select pay/discount/cancel/tab, staff + customer, price changes,
  history, the menu + cart beside it); a free table opens a new order on first
  Send; v1 TablesPage, OrderDetailPage, DesktopOrderingTab, ManagerOrderDrawer
  and PaymentMethodModal removed
- ordering by line id like the phones: GET /api/orders/menu (the counter's
  product shape, in-store prices); the product dialog, cart rules and quote hook
  move to packages/ordering (@xenia/ordering), shared by counter, menu tablet,
  manager
- close follows orders.close_with_unpaid (pay first, or write off after saying
  so) on the order page and the overview's quick view; paying asks cash or card
- a confirmed booking can keep its table ahead (manager, phones, counter):
  POST /api/connect/bookings/{id}/table, reservations create/PATCH; refused with
  reservation.table_kept within 2 h of another booking
- tests: test_manager_ordering.py, online bookings +2, manager orders.test.mjs,
  @xenia/ordering, e2e manager.mjs (take, change, pay-first close, RESERVED)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 21:58:46 +02:00
co-authored by Claude Opus 5.5
parent f4aae6abbc
commit 070c9cf625
56 changed files with 2339 additions and 3846 deletions
+1
View File
@@ -128,6 +128,7 @@ CODES: dict[str, tuple[int, str]] = {
"reservation.not_found": (404, "Booking {reservation_id} not found."), "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.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_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."), "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_not_found": (404, "Item {item_id} not found on this order."),
"kds.item_claimed": (409, "{name} is already on this item."), "kds.item_claimed": (409, "{name} is already on this item."),
+23
View File
@@ -370,6 +370,29 @@ def arrive_booking(reservation_id: int, body: ArriveRequest, background: Backgro
return booking_out(r) 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") @router.post("/bookings/{reservation_id}/cancel")
def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks, def cancel_booking(reservation_id: int, body: CancelRequest, background: BackgroundTasks,
db: Session = Depends(get_db), user=Depends(_BOOKINGS)): db: Session = Depends(get_db), user=Depends(_BOOKINGS)):
+29
View File
@@ -327,6 +327,35 @@ def get_pending_prints(
return {"count": len(pending_jobs), "orders": orders_data} 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}") @router.get("/{order_id}")
def get_order(order_id: int, db: Session = Depends(get_db), user: User = Depends(get_current_user)): 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() order = db.query(Order).filter(Order.id == order_id).first()
+15 -5
View File
@@ -47,15 +47,21 @@ def create_reservation(
email=body.email, email=body.email,
note=body.note, note=body.note,
reserved_for=body.reserved_for, reserved_for=body.reserved_for,
table_id=body.table_id,
source=body.source, source=body.source,
online_customer_id=body.online_customer_id, online_customer_id=body.online_customer_id,
created_by_user_id=user.id, created_by_user_id=user.id,
status="pending", 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.add(r)
db.commit() db.commit()
db.refresh(r) 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) return _enrich(r)
@@ -123,10 +129,11 @@ def update_reservation(
raise XeniaError("reservation.not_found", reservation_id=reservation_id) raise XeniaError("reservation.not_found", reservation_id=reservation_id)
updates = body.model_dump(exclude_none=True) updates = body.model_dump(exclude_none=True)
# the table: set, changed or taken back (null) — kept for one booking at a time (6.9)
if "table_id" in updates and updates["table_id"] is not None: if "table_id" in body.model_fields_set:
if not db.query(Table).filter(Table.id == updates["table_id"], Table.is_active == True).first(): from services.online_reservations import keep_table
raise XeniaError("table.not_found", status=400) keep_table(db, r, body.table_id)
updates.pop("table_id", None)
if "status" in updates and updates["status"] not in VALID_STATUSES: if "status" in updates and updates["status"] not in VALID_STATUSES:
raise XeniaError("validation.choice", field='status', value=updates['status']) raise XeniaError("validation.choice", field='status', value=updates['status'])
@@ -137,6 +144,9 @@ def update_reservation(
r.updated_at = utcnow() r.updated_at = utcnow()
db.commit() db.commit()
db.refresh(r) 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) return _enrich(r)
@@ -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) 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: def table_busy(db, table_id: int, order_id: int | None = None) -> bool:
from models.order import Order from models.order import Order
q = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("open", "partially_paid"))) q = db.query(Order).filter(Order.table_id == table_id, Order.status.in_(("open", "partially_paid")))
@@ -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"
@@ -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 assert r.json()["reservations"]["hours"] == {"4": [["19:00", "23:30"]]} and r.json()["reservations"]["fire_minutes"] == 25
body["reservations"]["party_max"] = 0 body["reservations"]["party_max"] = 0
assert client.put("/api/connect/fees/ordering", headers=owner_h, json=body).status_code == 422 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
+1
View File
@@ -13,6 +13,7 @@ COPY packages/api/package.json packages/api/
COPY packages/access/package.json packages/access/ COPY packages/access/package.json packages/access/
COPY packages/signage/package.json packages/signage/ COPY packages/signage/package.json packages/signage/
COPY packages/floorplan/package.json packages/floorplan/ COPY packages/floorplan/package.json packages/floorplan/
COPY packages/ordering/package.json packages/ordering/
COPY waiter_pwa/package.json waiter_pwa/ COPY waiter_pwa/package.json waiter_pwa/
COPY manager_dashboard/package.json manager_dashboard/ COPY manager_dashboard/package.json manager_dashboard/
COPY terminal/package.json terminal/ COPY terminal/package.json terminal/
+1
View File
@@ -16,6 +16,7 @@
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0", "@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/signage": "^0.0.0", "@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
+3 -3
View File
@@ -14,8 +14,8 @@ import SetupWizard from './pages/SetupWizard'
// Operation // Operation
import OverviewPage from './pages/overview/OverviewPage' import OverviewPage from './pages/overview/OverviewPage'
import TablesPage from './pages/TablesPage' import TablesPage from './pages/orders/TablesPage'
import OrderDetailPage from './pages/OrderDetailPage' import OrderPage from './pages/orders/OrderPage'
import OnlineOrdersPage from './pages/online/OnlineOrdersPage' import OnlineOrdersPage from './pages/online/OnlineOrdersPage'
import FeesPage from './pages/online/FeesPage' import FeesPage from './pages/online/FeesPage'
import QrCodesPage from './pages/online/QrCodesPage' import QrCodesPage from './pages/online/QrCodesPage'
@@ -151,7 +151,7 @@ export default function App() {
<Route path="online-orders" element={<OnlineOrdersPage />} /> <Route path="online-orders" element={<OnlineOrdersPage />} />
<Route path="online/fees" element={<FeesPage />} /> <Route path="online/fees" element={<FeesPage />} />
<Route path="online/qr" element={<QrCodesPage />} /> <Route path="online/qr" element={<QrCodesPage />} />
<Route path="orders/:orderId" element={<OrderDetailPage />} /> <Route path="orders/:orderId" element={<OrderPage />} />
{/* ── CRM ── */} {/* ── CRM ── */}
<Route path="crm/contacts" element={<ContactsPage />} /> <Route path="crm/contacts" element={<ContactsPage />} />
@@ -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 (
<div
onClick={() => 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 */}
<div style={{
width: '100%', aspectRatio: '16/9', maxHeight: 80,
background: '#f1f5f9', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
{product.image_url
? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 22, fontWeight: 700, color: '#94a3b8', letterSpacing: -1 }}>{initials}</span>
}
</div>
{/* Info */}
<div style={{ padding: '8px 10px 10px', flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', lineHeight: 1.3, display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
{product.name}
</div>
{product.tags?.length > 0 && (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 3 }}>
{product.tags.slice(0, 2).map(tag => (
<span key={tag} style={{ fontSize: 10, fontWeight: 600, padding: '1px 6px', background: '#f1f5f9', borderRadius: 99, color: '#64748b', border: '1px solid #e2e8f0' }}>{tag}</span>
))}
</div>
)}
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginTop: 'auto' }}>
<span style={{ fontSize: 14, fontWeight: 700, color: '#f59e0b' }}>{Number(product.base_price).toFixed(2)} €</span>
{canQuickAdd && (
<button
onClick={e => { e.stopPropagation(); onQuickAdd(product) }}
style={{
width: 30, height: 30, borderRadius: '50%',
background: '#fff7ed', border: '1.5px solid #fed7aa',
cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center',
color: '#f59e0b',
}}
>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none">
<path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.8" strokeLinecap="round"/>
</svg>
</button>
)}
</div>
</div>
</div>
)
}
// ── Service item widget ───────────────────────────────────────────────────────
function ServiceItemWidget({ product, customerCount, onAdd }) {
const [qty, setQty] = useState(0)
const hasPrice = product.base_price != null && product.base_price > 0
return (
<div style={{
background: 'white', border: '1px solid #e2e8f0', borderRadius: 12,
padding: '12px 14px', display: 'flex', flexDirection: 'column', gap: 8,
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
<span style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', flex: 1, minWidth: 0 }}>{product.name}</span>
<span style={{ fontSize: 12, color: hasPrice ? '#f59e0b' : '#94a3b8', fontWeight: 600, flexShrink: 0 }}>
{hasPrice ? `${Number(product.base_price).toFixed(2)} €` : 'no charge'}
</span>
</div>
<div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<button onClick={() => setQty(q => Math.max(0, q - 1))}
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: qty === 0 ? '#f8fafc' : 'rgba(245,158,11,0.1)', color: qty === 0 ? '#94a3b8' : '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>−</button>
<button onClick={() => setQty(Math.max(1, customerCount ?? 1))} title={`Ορισμός σε ${customerCount ?? 1}`}
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round">
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/>
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>
</svg>
</button>
<button onClick={() => setQty(q => q + 1)}
style={{ width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0', background: 'rgba(245,158,11,0.1)', color: '#f59e0b', fontSize: 18, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700 }}>+</button>
<span style={{ fontSize: 20, fontWeight: 800, color: qty === 0 ? '#94a3b8' : '#1e293b', flex: 1, textAlign: 'center' }}>{qty}</span>
<button
disabled={qty === 0}
onClick={() => {
if (qty === 0) return
onAdd({
product_id: product.id,
quantity: qty,
unit_type: 'piece',
unit_price: product.base_price ?? 0,
notes: '',
selected_options: [],
removed_ingredients: [],
is_service_item: true,
})
setQty(0)
}}
style={{
padding: '6px 14px', borderRadius: 8, border: 'none',
background: qty === 0 ? '#f1f5f9' : '#f59e0b',
color: qty === 0 ? '#94a3b8' : '#fff',
fontSize: 12, fontWeight: 700, cursor: qty === 0 ? 'default' : 'pointer',
}}
>ADD</button>
</div>
</div>
)
}
// ── 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 (
<div style={{ display: 'flex', alignItems: 'flex-start', gap: 8, padding: '8px 0', borderBottom: '1px solid #f1f5f9' }}>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{product?.name ?? `#${item.product_id}`}
</div>
{optionSummary && (
<div style={{ fontSize: 11, color: '#94a3b8', marginTop: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{optionSummary}
</div>
)}
{item.notes && (
<div style={{ fontSize: 11, color: '#f59e0b', marginTop: 1, fontStyle: 'italic', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
{item.notes}
</div>
)}
</div>
{/* Qty controls */}
{isDecimal ? (
<button onClick={onEdit} style={{ fontSize: 12, fontWeight: 700, color: '#f59e0b', background: '#fff7ed', border: '1px solid #fed7aa', borderRadius: 6, padding: '2px 8px', cursor: 'pointer', whiteSpace: 'nowrap' }}>
{fmtQty(item.quantity, product?.unit_type)}
</button>
) : (
<div style={{ display: 'flex', alignItems: 'center', gap: 4, flexShrink: 0 }}>
<button onClick={() => onChangeQty(item.quantity - 1)}
style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: item.quantity <= 1 ? '#ef4444' : '#475569', fontSize: 14, fontWeight: 700 }}>
{item.quantity <= 1
? <svg width="10" height="10" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
: '−'}
</button>
<span style={{ fontSize: 13, fontWeight: 700, color: '#1e293b', minWidth: 16, textAlign: 'center' }}>{item.quantity}</span>
<button onClick={() => onChangeQty(item.quantity + 1)}
style={{ width: 24, height: 24, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f8fafc', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#16a34a', fontSize: 14, fontWeight: 700 }}>+</button>
</div>
)}
{/* Price */}
<span style={{ fontSize: 13, fontWeight: 700, color: '#475569', minWidth: 50, textAlign: 'right', flexShrink: 0 }}>
€{((item.unit_price ?? 0) * item.quantity + (item.price_adjustment ?? 0) * item.quantity).toFixed(2)}
</span>
{/* Edit + Remove */}
<div style={{ display: 'flex', gap: 3, flexShrink: 0 }}>
<button onClick={onEdit}
style={{ padding: '2px 7px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f8fafc', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>
Επεξ.
</button>
<button onClick={onRemove}
style={{ width: 24, height: 24, borderRadius: '50%', border: 'none', background: 'none', color: '#94a3b8', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
</div>
)
}
// ── 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 (
<>
<div onClick={onClose} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
<div style={{
position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
zIndex: 201, width: 'min(580px, 90vw)',
background: 'white', borderRadius: 16,
boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
overflow: 'hidden', display: 'flex', flexDirection: 'column',
maxHeight: '60vh',
}}>
{/* Input */}
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '14px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" style={{ color: '#94a3b8', flexShrink: 0 }}>
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
<input
ref={inputRef}
value={query}
onChange={e => setQuery(e.target.value)}
placeholder="Αναζήτηση προϊόντος…"
style={{ flex: 1, border: 'none', outline: 'none', fontSize: 16, color: '#1e293b', background: 'transparent', fontFamily: 'inherit' }}
/>
<button onClick={onClose} style={{ background: '#f1f5f9', border: 'none', borderRadius: '50%', width: 30, height: 30, display: 'flex', alignItems: 'center', justifyContent: 'center', cursor: 'pointer', color: '#64748b' }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{/* Results */}
<div style={{ flex: 1, overflowY: 'auto' }}>
{query.trim().length === 0 ? (
<p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Πληκτρολογήστε για αναζήτηση…</p>
) : results.length === 0 ? (
<p style={{ textAlign: 'center', color: '#94a3b8', padding: '20px', fontSize: 14 }}>Δεν βρέθηκαν προϊόντα για «{query}»</p>
) : results.map(p => {
const initials = p.name.trim().split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase()
return (
<button key={p.id} onClick={() => { onOpen(p); onClose() }}
style={{ display: 'flex', alignItems: 'center', gap: 12, width: '100%', padding: '10px 16px', background: 'none', border: 'none', cursor: 'pointer', borderBottom: '1px solid #f1f5f9', textAlign: 'left' }}
onMouseEnter={e => { e.currentTarget.style.background = '#f8fafc' }}
onMouseLeave={e => { e.currentTarget.style.background = 'none' }}
>
<div style={{ width: 38, height: 38, borderRadius: 8, flexShrink: 0, background: '#f1f5f9', overflow: 'hidden', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
{p.image_url
? <img src={p.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 12, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: '#1e293b', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{p.name}</div>
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>{Number(p.base_price).toFixed(2)} €</div>
</div>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ color: '#cbd5e1', flexShrink: 0 }}>
<path d="M9 18l6-6-6-6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
)
})}
</div>
</div>
</>
)
}
// ── 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 (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
Φόρτωση προϊόντων…
</div>
)
}
if (!isOpen) {
return (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 200, color: '#94a3b8', fontSize: 14 }}>
Η παραγγελία δεν είναι ανοιχτή.
</div>
)
}
const activeDrawerProduct = editItem ? editItem.product : drawerProduct
const drawerOpen = !!activeDrawerProduct
return (
<div style={{ display: 'flex', height: '100%', minHeight: 0, gap: 0 }}>
{/* ── LEFT: Category + Product browser ─────────────────────────────── */}
<div style={{ flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0, borderRight: '1px solid #e2e8f0' }}>
{/* Toolbar */}
<div style={{ padding: '10px 12px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0, background: '#f8fafc' }}>
<div style={{ flex: 1, display: 'flex', gap: 6, overflowX: 'auto', scrollbarWidth: 'none' }}>
{/* SERVICE chip */}
{serviceProducts.length > 0 && (
<button onClick={() => 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,
}}
>
<svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
<path d="M3 11l19-9-9 19-2-8-8-2z"/>
</svg>
Service
</button>
)}
{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 (
<button key={cat.id} onClick={() => 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}</button>
)
})}
<button onClick={() => 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 }}>
Όλες →
</button>
</div>
<button onClick={() => 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 }}>
<svg width="13" height="13" viewBox="0 0 24 24" fill="none">
<circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="2.2"/>
<path d="M16.5 16.5L21 21" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
Αναζήτηση
</button>
</div>
{/* Product area */}
<div style={{ flex: 1, overflowY: 'auto', padding: '12px 14px' }}>
{isSvcActive ? (
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))', gap: 10 }}>
{serviceProducts.map(p => (
<ServiceItemWidget key={p.id} product={p} customerCount={customerCount} onAdd={item => addToCart(item)} />
))}
</div>
) : !hasSubcats ? (
<>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
{directProducts.map(p => (
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
))}
</div>
{directProducts.length === 0 && (
<div style={{ textAlign: 'center', color: '#94a3b8', padding: '40px 0', fontSize: 14 }}>Δεν υπάρχουν προϊόντα</div>
)}
</>
) : (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{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 (
<div key={key}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
{sectionProducts.map(p => (
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
))}
</div>
</div>
)
}
const accentColor = section.color ?? activeParent?.color ?? null
return (
<div key={key} style={{ border: '1px solid #e2e8f0', borderRadius: 12, overflow: 'hidden' }}>
<button
onClick={() => 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 && <span style={{ width: 10, height: 10, borderRadius: '50%', background: accentColor, flexShrink: 0 }} />}
<span style={{ flex: 1, fontSize: 13, fontWeight: 700, color: '#1e293b' }}>{section.name}</span>
<span style={{ fontSize: 11, color: '#94a3b8', marginRight: 4 }}>{sectionProducts.length}</span>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${isExpanded ? 180 : 0}deg)`, transition: 'transform 180ms', color: '#94a3b8', flexShrink: 0 }}>
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
</button>
{isExpanded && (
<div style={{ padding: '10px 12px 12px', background: '#fafbfc', borderTop: '1px solid #f1f5f9' }}>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(140px, 1fr))', gap: 10 }}>
{sectionProducts.map(p => (
<DesktopProductCard key={p.id} product={p} onOpen={setDrawerProduct} onQuickAdd={handleQuickAdd} />
))}
</div>
</div>
)}
</div>
)
})}
</div>
)}
</div>
</div>
{/* ── RIGHT: Cart panel or Drawer panel ────────────────────────────── */}
<div style={{ width: 320, flexShrink: 0, display: 'flex', flexDirection: 'column', minHeight: 0 }}>
{drawerOpen ? (
<ManagerOrderDrawer
key={activeDrawerProduct.id}
product={activeDrawerProduct}
initialState={editItem?.drawerState}
onClose={() => { setDrawerProduct(null); setEditItem(null) }}
onAdd={handleDrawerAdd}
courses={courses}
/>
) : (
/* Cart */
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', background: '#f8fafc' }}>
{/* Cart header */}
<div style={{ padding: '12px 16px', borderBottom: '1px solid #e2e8f0', flexShrink: 0 }}>
<div style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>Νέα Παραγγελία</div>
<div style={{ fontSize: 12, color: '#94a3b8', marginTop: 1 }}>
{cart.length === 0 ? 'Επιλέξτε προϊόντα από τα αριστερά' : `${cart.length} ${cart.length === 1 ? 'προϊόν' : 'προϊόντα'}`}
</div>
</div>
{/* Item list */}
<div style={{ flex: 1, overflowY: 'auto', padding: '0 16px' }}>
{cart.length === 0 ? (
<div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', height: '100%', gap: 12, padding: '40px 0' }}>
<svg width="40" height="40" viewBox="0 0 24 24" fill="none" style={{ color: '#e2e8f0' }}>
<path d="M6 2L3 6v14a2 2 0 002 2h14a2 2 0 002-2V6l-3-4zM3 6h18M16 10a4 4 0 01-8 0" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
</svg>
<p style={{ color: '#cbd5e1', fontSize: 13, textAlign: 'center' }}>Το καλάθι είναι άδειο</p>
</div>
) : (
<div>
{cart.map(item => {
const product = products.find(p => p.id === item.product_id)
return (
<CartItemRow
key={item._key}
item={item}
product={product}
onRemove={() => removeFromCart(item._key)}
onChangeQty={qty => changeCartQty(item._key, qty)}
onEdit={() => openEditDrawer(item)}
/>
)
})}
</div>
)}
</div>
{/* Order note */}
{cart.length > 0 && (
<div style={{ padding: '8px 16px', flexShrink: 0 }}>
<textarea
value={orderNote}
onChange={e => setOrderNote(e.target.value)}
placeholder="Σημείωση παραγγελίας (προαιρετικό)…"
rows={2}
style={{
width: '100%', resize: 'none', padding: '8px 10px',
background: 'white', border: '1px solid #e2e8f0',
borderRadius: 8, fontSize: 12, color: '#1e293b', lineHeight: 1.5,
outline: 'none', boxSizing: 'border-box', fontFamily: 'inherit',
}}
/>
</div>
)}
{/* Cart footer */}
<div style={{ padding: '10px 16px 16px', borderTop: '1px solid #e2e8f0', flexShrink: 0, background: 'white' }}>
{cart.length > 0 && (
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
<span style={{ fontSize: 13, color: '#64748b', fontWeight: 600 }}>Σύνολο</span>
<span style={{ fontSize: 18, fontWeight: 800, color: '#1e293b' }}>€{cartTotal.toFixed(2)}</span>
</div>
)}
<button
onClick={() => 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})` : ''}`}
</button>
{cart.length > 0 && (
<button onClick={() => setCart([])}
style={{ width: '100%', marginTop: 6, padding: '6px 0', background: 'none', border: 'none', color: '#94a3b8', fontSize: 12, cursor: 'pointer' }}>
Εκκαθάριση καλαθιού
</button>
)}
</div>
</div>
)}
</div>
{/* View all categories modal */}
{viewAllOpen && (
<>
<div onClick={() => setViewAllOpen(false)} style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 200 }} />
<div style={{
position: 'fixed', top: '15%', left: '50%', transform: 'translateX(-50%)',
zIndex: 201, width: 'min(500px, 90vw)',
background: 'white', borderRadius: 16,
boxShadow: '0 20px 60px rgba(0,0,0,0.18)',
overflow: 'hidden',
}}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '14px 18px', borderBottom: '1px solid #e2e8f0' }}>
<span style={{ fontSize: 15, fontWeight: 700, color: '#1e293b' }}>Κατηγορίες</span>
<button onClick={() => setViewAllOpen(false)} style={{ background: 'none', border: 'none', color: '#94a3b8', cursor: 'pointer', fontSize: 18 }}>✕</button>
</div>
<div style={{ padding: '14px 16px', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8, maxHeight: '60vh', overflowY: 'auto' }}>
{serviceProducts.length > 0 && (
<button onClick={() => { 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
</button>
)}
{topLevel.map(cat => {
const isActive = activeCat === cat.id
return (
<button key={cat.id} onClick={() => { 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}
</button>
)
})}
</div>
</div>
</>
)}
{/* Search modal */}
{searchOpen && (
<SearchOverlay
products={products}
onClose={() => setSearchOpen(false)}
onOpen={p => { setDrawerProduct(p); setSearchOpen(false) }}
/>
)}
</div>
)
}
@@ -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 (
<div style={{
width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
background: selected ? '#f59e0b' : 'transparent',
display: 'flex', alignItems: 'center', justifyContent: 'center',
transition: 'all 120ms ease',
}}>
{selected && <svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M5 12.5L10 17.5L19 7.5" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
</div>
)
}
function RadioDot({ selected }) {
return (
<div style={{
width: 20, height: 20, borderRadius: '50%', flexShrink: 0,
border: `2px solid ${selected ? '#f59e0b' : '#d1d5db'}`,
background: 'transparent',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{selected && <div style={{ width: 9, height: 9, borderRadius: '50%', background: '#f59e0b' }} />}
</div>
)
}
function Row({ selected, onClick, children, right, left }) {
return (
<div onClick={onClick} style={{
padding: '10px 12px',
background: selected ? 'rgba(245,158,11,0.08)' : '#f8fafc',
border: `1px solid ${selected ? 'rgba(245,158,11,0.4)' : '#e2e8f0'}`,
borderRadius: 10,
display: 'flex', alignItems: 'center', gap: 10,
cursor: onClick ? 'pointer' : 'default',
transition: 'background 120ms ease, border-color 120ms ease',
minHeight: 50,
}}>
{left && <div style={{ flexShrink: 0 }}>{left}</div>}
<div style={{ flex: 1, minWidth: 0 }}>{children}</div>
{right && <div style={{ flexShrink: 0 }}>{right}</div>}
</div>
)
}
function Stepper({ value, onChange, min = 0, max = 99 }) {
return (
<div style={{ display: 'inline-flex', alignItems: 'center', height: 36, borderRadius: 18, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}
onClick={e => e.stopPropagation()}>
<button onClick={() => 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' }}>−</button>
<div style={{ minWidth: 26, textAlign: 'center', fontSize: 14, fontWeight: 700, color: '#1e293b' }}>{value}</div>
<button onClick={() => 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' }}>+</button>
</div>
)
}
// ── Option rows ───────────────────────────────────────────────────────────────
function QuickOptionRow({ opt, quickState, setQuickState }) {
const qty = quickState[opt.id] || 0
const selected = qty > 0
return (
<Row selected={selected} onClick={() => setQuickState(s => ({ ...s, [opt.id]: selected ? 0 : 1 }))}
left={<CheckCircle selected={selected} />}
right={opt.allow_multiple ? (
<div onClick={e => e.stopPropagation()}>
{selected
? <Stepper value={qty} onChange={v => setQuickState(s => ({ ...s, [opt.id]: v }))} />
: <button onClick={e => { 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' }}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none"><path d="M12 5v14M5 12h14" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"/></svg>
</button>
}
</div>
) : null}
>
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
{opt.price > 0 && <div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>+{opt.price.toFixed(2)} €</div>}
</Row>
)
}
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 (
<div>
<Row selected={selected} onClick={toggle}
left={<CheckCircle selected={selected} />}
right={
<div style={{ display: 'flex', alignItems: 'center', gap: 4 }} onClick={e => e.stopPropagation()}>
{selected && opt.allow_multiple && (
<Stepper value={sel.qty} onChange={v => {
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 && (
<button onClick={e => { 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' }}>
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" style={{ transform: `rotate(${open ? 180 : 0}deg)`, transition: 'transform 180ms' }}>
<path d="M6 9L12 15L18 9" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/>
</svg>
</button>
)}
</div>
}
>
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{opt.name}</div>
<div style={{ fontSize: 12, color: '#64748b', marginTop: 1 }}>
{(opt.extra_cost ?? 0) !== 0 ? `+${opt.extra_cost.toFixed(2)} €` : 'Included'}
{subLabel && <span style={{ color: '#f59e0b', fontWeight: 600 }}> · {subLabel}</span>}
</div>
</Row>
{selected && open && hasSubs && (
<div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>Επιλογή</div>
{opt.sub_choices.map((sub, si) => {
const isSel = sel.subName === sub.name
return (
<Row key={si} selected={isSel} onClick={() => setExtrasState(s => ({ ...s, [opt.id]: { ...sel, subName: sub.name } }))} left={<RadioDot selected={isSel} />}>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
{(sub.extra_cost ?? 0) !== 0 && <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div>}
</div>
</Row>
)
})}
</div>
)}
</div>
)
}
function IngredientRow({ ing, removedState, setRemovedState }) {
const removed = !!removedState[ing.id]
return (
<Row selected={false} onClick={() => setRemovedState(s => ({ ...s, [ing.id]: !s[ing.id] }))}
right={
<div style={{
height: 30, padding: '0 12px', borderRadius: 15,
background: removed ? '#ef4444' : '#f1f5f9',
border: `1px solid ${removed ? '#ef4444' : '#e2e8f0'}`,
color: removed ? '#fff' : '#475569',
fontSize: 12, fontWeight: 600,
display: 'inline-flex', alignItems: 'center',
}}>
{removed ? 'Αφαιρέθηκε' : 'Αφαίρεση'}
</div>
}
>
<div style={{ fontSize: 14, fontWeight: 500, color: removed ? '#94a3b8' : '#1e293b', textDecoration: removed ? 'line-through' : 'none' }}>{ing.name}</div>
</Row>
)
}
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 (
<div>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8, padding: '0 2px 8px' }}>
<div style={{ fontSize: 13, fontWeight: 700, color: complete ? '#1e293b' : '#ef4444' }}>{ps.name}</div>
{!complete && <div style={{ fontSize: 11, fontWeight: 700, color: '#ef4444', textTransform: 'uppercase', letterSpacing: 0.6 }}>Απαιτείται</div>}
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{ps.choices.map(ch => {
const isSel = selChoice?.id === ch.id
const hasSubs = ch.sub_choices?.length > 0
return (
<div key={ch.id}>
<Row selected={isSel} onClick={() => selectPref(ch)} left={<RadioDot selected={isSel} />}
right={(ch.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 13, color: '#64748b' }}>{ch.extra_cost > 0 ? '+' : ''}{ch.extra_cost.toFixed(2)} €</div> : null}>
<div style={{ fontSize: 14, fontWeight: 500, color: '#1e293b' }}>{ch.name}</div>
</Row>
{isSel && hasSubs && (
<div style={{ margin: '5px 0 2px 14px', paddingLeft: 12, borderLeft: `2px solid ${subChoices[ch.id] == null ? '#ef4444' : 'rgba(245,158,11,0.35)'}`, display: 'flex', flexDirection: 'column', gap: 5 }}>
{ch.sub_choices.map((sub, si) => {
const subSel = subChoices[ch.id]?.name === sub.name
return (
<Row key={si} selected={subSel} onClick={() => setSubChoices(s => ({ ...s, [ch.id]: sub }))} left={<RadioDot selected={subSel} />}
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
</Row>
)
})}
</div>
)}
</div>
)
})}
{showShared && (
<div style={{ marginTop: 4, marginLeft: 8, paddingLeft: 12, borderLeft: '2px solid rgba(245,158,11,0.35)', display: 'flex', flexDirection: 'column', gap: 5 }}>
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, padding: '4px 2px 2px' }}>{ps.shared_subset.name}</div>
{ps.shared_subset.choices.map((sub, si) => {
const subSel = sharedSubs[ps.id]?.name === sub.name
return (
<Row key={si} selected={subSel} onClick={() => setSharedSubs(s => ({ ...s, [ps.id]: sub }))} left={<RadioDot selected={subSel} />}
right={(sub.extra_cost ?? 0) !== 0 ? <div style={{ fontSize: 12, color: '#64748b' }}>+{sub.extra_cost.toFixed(2)} €</div> : null}>
<div style={{ fontSize: 13, color: '#1e293b' }}>{sub.name}</div>
</Row>
)
})}
</div>
)}
</div>
</div>
)
}
// ── Tab content ───────────────────────────────────────────────────────────────
function QuickTab({ product, quickState, setQuickState }) {
const quickOptions = product.quick_options || []
if (quickOptions.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν γρήγορες επιλογές.</p>
return (
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
{quickOptions.map(opt => (
<div key={opt.id} style={{ width: opt.is_compact ? 'calc(50% - 4px)' : '100%', minWidth: 0 }}>
<QuickOptionRow opt={opt} quickState={quickState} setQuickState={setQuickState} />
</div>
))}
</div>
)
}
function ExtrasTab({ product, extrasState, setExtrasState, expandedExtra, setExpandedExtra }) {
const options = product.options || []
if (options.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν extras.</p>
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
{options.map(opt => (
<ExtraOptionRow key={opt.id} opt={opt} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />
))}
</div>
)
}
function IngredientsTab({ product, removedState, setRemovedState }) {
const ingredients = product.ingredients || []
if (ingredients.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν υλικά.</p>
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
<div style={{ padding: '8px 12px', background: '#f1f5f9', borderRadius: 8, fontSize: 12, color: '#64748b', marginBottom: 2 }}>
Κάντε κλικ για να αφαιρέσετε υλικό.
</div>
{ingredients.map(ing => (
<IngredientRow key={ing.id} ing={ing} removedState={removedState} setRemovedState={setRemovedState} />
))}
</div>
)
}
function PrefsTab({ product, prefs, setPrefs, subChoices, setSubChoices, sharedSubs, setSharedSubs }) {
const preferenceSets = product.preference_sets || []
if (preferenceSets.length === 0) return <p style={{ color: '#94a3b8', textAlign: 'center', padding: '24px 0', fontSize: 14 }}>Δεν υπάρχουν προτιμήσεις.</p>
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
{preferenceSets.map(ps => (
<PrefSetBlock key={ps.id} ps={ps}
prefs={prefs} setPrefs={setPrefs}
subChoices={subChoices} setSubChoices={setSubChoices}
sharedSubs={sharedSubs} setSharedSubs={setSharedSubs}
/>
))}
</div>
)
}
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 0 }}>
<div style={{ display: 'inline-flex', alignItems: 'center', height: 48, borderRadius: 24, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden' }}>
<button onClick={() => setQty(q => clamp(q - unitCfg.step))}
style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>−</button>
{editing ? (
<input ref={inputRef} type="number" inputMode="decimal" value={qtyInput}
onChange={e => 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' }}
/>
) : (
<div onClick={() => { 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)}
<span style={{ fontSize: 12, fontWeight: 500, opacity: 0.65 }}>{unitCfg.label}</span>
</div>
)}
<button onClick={() => setQty(q => clamp(q + unitCfg.step))}
style={{ width: 48, height: 48, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
</div>
</div>
<div>
<p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΕΠΙΛΟΓΗ</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
{unitCfg.presets.map(v => (
<button key={v} onClick={() => 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}
</button>
))}
</div>
</div>
<div>
<p style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', letterSpacing: 0.8, marginBottom: 6, textAlign: 'center' }}>ΓΡΗΓΟΡΗ ΠΡΟΣΘΗΚΗ</p>
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
{unitCfg.offsets.map(off => (
<button key={`+${off}`} onClick={() => 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}</button>
))}
{unitCfg.offsets.map(off => (
<button key={`-${off}`} onClick={() => 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}</button>
))}
</div>
</div>
</div>
)
}
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 (
<div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
<div style={{ padding: '8px 12px', background: 'rgba(245,158,11,0.08)', border: '1px solid rgba(245,158,11,0.2)', borderRadius: 8, fontSize: 12, color: '#d97706' }}>
Αλλαγή τιμής μόνο για αυτό το αντικείμενο.
</div>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10 }}>
<button onClick={() => applyDelta(-0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>−</button>
{editing ? (
<input ref={inputRef} type="number" inputMode="decimal" value={rawInput}
onChange={e => 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' }}
/>
) : (
<button onClick={() => { 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)} €
</button>
)}
<button onClick={() => applyDelta(+0.1)} style={{ width: 40, height: 40, borderRadius: '50%', border: '1px solid #e2e8f0', background: '#f1f5f9', fontSize: 18, fontWeight: 700, color: '#1e293b', cursor: 'pointer' }}>+</button>
</div>
{priceAdj !== 0 && (
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>
<span style={{ fontSize: 12, color: '#64748b' }}>Βάση: {basePrice.toFixed(2)} €</span>
<span style={{ fontSize: 12, fontWeight: 700, color: priceAdj > 0 ? '#16a34a' : '#dc2626' }}>{priceAdj > 0 ? '+' : ''}{priceAdj.toFixed(2)} €</span>
<button onClick={() => setPriceAdj(0)} style={{ padding: '2px 8px', borderRadius: 6, border: '1px solid #e2e8f0', background: '#f1f5f9', color: '#64748b', fontSize: 11, cursor: 'pointer' }}>Επαναφορά</button>
</div>
)}
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
{PRICE_DELTAS.map(d => (
<button key={d} onClick={() => 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))} €
</button>
))}
</div>
</div>
)
}
function NotesTab({ note, setNote }) {
return (
<div>
<textarea
value={note}
onChange={e => setNote(e.target.value)}
placeholder="π.χ. Χωρίς αλάτι, κόψτε στη μέση..."
rows={4}
style={{ width: '100%', padding: 12, fontSize: 14, fontFamily: 'inherit', color: '#1e293b', background: 'white', border: '1px solid #e2e8f0', borderRadius: 10, resize: 'none', outline: 'none', boxSizing: 'border-box' }}
/>
<div style={{ fontSize: 11, fontWeight: 700, color: '#94a3b8', textTransform: 'uppercase', letterSpacing: 0.6, marginTop: 14, marginBottom: 6 }}>Γρήγορες σημειώσεις</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
{QUICK_NOTES.map(q => (
<button key={q} onClick={() => setNote(n => n ? `${n}\n${q}` : q)}
style={{ height: 32, padding: '0 12px', borderRadius: 16, background: '#f1f5f9', border: '1px solid #e2e8f0', color: '#475569', fontSize: 12, fontWeight: 500, cursor: 'pointer' }}>
+ {q}
</button>
))}
</div>
</div>
)
}
// ── Courses tab ───────────────────────────────────────────────────────────────
function CoursesTab({ courses, courseId, setCourseId }) {
return (
<div style={{ padding: '12px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
<button
onClick={() => 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)
</button>
{courses.map(c => (
<button
key={c.id}
onClick={() => 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,
}}
>
<span style={{
width: 12, height: 12, borderRadius: '50%',
background: courseId === c.id ? 'rgba(255,255,255,0.5)' : c.color,
flexShrink: 0,
}} />
{c.name}
</button>
))}
</div>
)
}
// ── 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 (
<div style={{
display: 'flex', flexDirection: 'column', height: '100%',
background: 'white', borderLeft: '1px solid #e2e8f0',
}}>
{/* Header */}
<div style={{
padding: '16px 16px 12px',
borderBottom: '1px solid #e2e8f0',
flexShrink: 0,
}}>
<div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
<div style={{
width: 52, height: 52, borderRadius: 12, flexShrink: 0,
background: '#f1f5f9', overflow: 'hidden',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
{product.image_url
? <img src={product.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
: <span style={{ fontSize: 18, fontWeight: 700, color: '#94a3b8' }}>{initials}</span>
}
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 16, fontWeight: 700, color: '#1e293b', lineHeight: 1.2, marginBottom: 3 }}>{product.name}</div>
<div style={{ fontSize: 13, color: priceAdj !== 0 ? '#f59e0b' : '#64748b' }}>
{priceAdj !== 0
? <><span style={{ textDecoration: 'line-through', opacity: 0.5, marginRight: 4 }}>{product.base_price.toFixed(2)}</span>→ {(product.base_price + priceAdj).toFixed(2)} €</>
: <>{product.base_price.toFixed(2)} €</>
}
</div>
</div>
<button onClick={onClose} style={{
width: 32, height: 32, borderRadius: '50%', border: '1px solid #e2e8f0',
background: '#f8fafc', display: 'flex', alignItems: 'center', justifyContent: 'center',
cursor: 'pointer', flexShrink: 0, color: '#64748b',
}}>
<svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M6 6L18 18M6 18L18 6" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"/></svg>
</button>
</div>
{/* Tabs bar */}
{tabs.length > 0 && (
<div style={{ display: 'flex', gap: 2, overflowX: 'auto', scrollbarWidth: 'none' }}>
{tabs.map(t => {
const active = activeTab === t.id
const isAlert = t.id === 'prefs' && !allPrefsOk && addAttempted
return (
<button key={t.id} onClick={() => 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}
</button>
)
})}
</div>
)}
</div>
{/* Scrollable content */}
<div style={{ flex: 1, overflowY: 'auto', padding: '14px 14px 10px' }}>
{activeTab === 'quick' && <QuickTab product={product} quickState={quickState} setQuickState={setQuickState} />}
{activeTab === 'extras' && <ExtrasTab product={product} extrasState={extrasState} setExtrasState={setExtrasState} expandedExtra={expandedExtra} setExpandedExtra={setExpandedExtra} />}
{activeTab === 'ingredients' && <IngredientsTab product={product} removedState={removedState} setRemovedState={setRemovedState} />}
{activeTab === 'prefs' && <PrefsTab product={product} prefs={prefs} setPrefs={setPrefs} subChoices={subChoices} setSubChoices={setSubChoices} sharedSubs={sharedSubs} setSharedSubs={setSharedSubs} />}
{activeTab === 'quantity' && isDecimal && <QuantityTab unitCfg={unitCfg} qty={qty} setQty={setQty} />}
{activeTab === 'courses' && courses?.length > 0 && <CoursesTab courses={courses} courseId={courseId} setCourseId={setCourseId} />}
{activeTab === 'notes' && <NotesTab note={note} setNote={setNote} />}
{activeTab === 'price_adjust' && <PriceAdjustTab basePrice={product.base_price} priceAdj={priceAdj} setPriceAdj={setPriceAdj} />}
</div>
{/* Footer: qty stepper + ADD button */}
<div style={{
padding: '12px 14px',
borderTop: '1px solid #e2e8f0',
background: '#f8fafc',
display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
}}>
{isDecimal ? (
<div onClick={() => 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 }}>
<span style={{ fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{fmtDecimalQty(qty, unitCfg)}</span>
<span style={{ fontSize: 12, color: '#64748b' }}>{unitCfg.label}</span>
</div>
) : (
<div style={{ display: 'inline-flex', alignItems: 'center', height: 44, borderRadius: 22, background: '#f1f5f9', border: '1px solid #e2e8f0', overflow: 'hidden', flexShrink: 0 }}>
<button onClick={() => 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' }}>−</button>
<div style={{ minWidth: 28, textAlign: 'center', fontSize: 16, fontWeight: 700, color: '#1e293b' }}>{qty}</div>
<button onClick={() => setQty(q => q + 1)} style={{ width: 44, height: 44, border: 'none', background: 'transparent', fontSize: 20, fontWeight: 500, cursor: 'pointer', color: '#1e293b' }}>+</button>
</div>
)}
<button onClick={handleAdd} style={{
flex: 1, height: 44, borderRadius: 22,
background: canAdd ? '#f59e0b' : '#e2e8f0',
border: 'none', color: canAdd ? '#fff' : '#94a3b8',
fontSize: 14, fontWeight: 700, fontFamily: 'inherit',
cursor: canAdd ? 'pointer' : 'not-allowed',
display: 'flex', alignItems: 'center', justifyContent: 'space-between',
padding: '0 18px',
transition: 'background 150ms ease',
}}>
<span>ΠΡΟΣΘΗΚΗ</span>
<span>{totalPrice.toFixed(2)} €</span>
</button>
</div>
</div>
)
}
@@ -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 (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50 p-4">
<div className="bg-white rounded-2xl shadow-xl w-full max-w-sm p-6 space-y-5">
<div className="flex items-center justify-between">
<h2 className="text-lg font-bold text-gray-800">Εκτύπωση παραγγελίας</h2>
<button onClick={onClose} className="text-gray-400 hover:text-gray-600 text-xl leading-none">✕</button>
</div>
<div>
<label className="label">Εκτυπωτής</label>
<select className="input w-full" value={printerId} onChange={e => setPrinterId(e.target.value)}>
<option value="">— Επιλέξτε —</option>
{printers.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
</select>
</div>
<div className="flex gap-3">
<button onClick={onClose} className="btn btn-secondary flex-1">Ακύρωση</button>
<button onClick={submit} className="btn btn-primary flex-1">Εκτύπωση</button>
</div>
</div>
</div>
)
}
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 (
<span style={{ fontSize: 10, fontWeight: 700, padding: '1px 6px', borderRadius: 4, background: s.bg, color: s.color, border: `1px solid ${s.border}`, letterSpacing: 0.3 }}>
{s.label}
</span>
)
}
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 <p className="py-8 text-center text-gray-400 text-sm">Δεν υπάρχουν εγγραφές.</p>
}
const itemsById = Object.fromEntries((order.items || []).map(i => [i.id, i]))
return (
<div className="divide-y divide-gray-100">
{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 (
<div key={log.id} className={`flex items-start gap-3 px-4 py-3 ${isDuplicate ? 'bg-red-50' : ''}`}>
<div className="shrink-0 mt-0.5">
<span className={`text-xs font-semibold px-2 py-0.5 rounded-full ${badgeClass}`}>
{EVENT_LABELS[log.event_type] ?? log.event_type}
</span>
{isDuplicate && (
<span className="block text-xs text-red-500 font-semibold mt-0.5">ΔΙΠΛΗ</span>
)}
</div>
<div className="flex-1 min-w-0 text-sm text-gray-700">
<span>{log.waiter_name ?? waiterMap[log.waiter_id] ?? `#${log.waiter_id}`}</span>
{log.amount != null && (
<span className={`ml-2 font-semibold ${isDuplicate ? 'text-red-600' : 'text-green-700'}`}>
€{log.amount.toFixed(2)}
</span>
)}
{log.payment_method && (
<span className="ml-1"><PayMethodChip method={log.payment_method} /></span>
)}
{itemNames.length > 0 && (
<div className="mt-1 flex flex-wrap gap-1">
{itemNames.map((name, i) => (
<span key={i} className="rounded bg-gray-100 px-1.5 py-0.5 text-xs text-gray-600">{name}</span>
))}
</div>
)}
</div>
<div className="text-right shrink-0">
<span className="text-xs text-gray-400">{displayTime}</span>
{log.offline_at && (
<span className="block text-xs text-orange-400">offline</span>
)}
</div>
</div>
)
})}
</div>
)
}
// ─── 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 (
<div className="flex justify-center py-16">
<div className="w-5 h-5 rounded-full border-2 border-sky-500 border-t-transparent animate-spin" />
</div>
)
if (events.length === 0) return (
<div className="py-16 text-center text-gray-400">
<Percent className="w-8 h-8 mx-auto mb-2 opacity-30" />
<p className="text-sm">Δεν υπάρχουν συμβάντα τιμολόγησης για αυτή την παραγγελία.</p>
</div>
)
return (
<div className="divide-y divide-gray-100">
{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 (
<div key={ev.id} className="flex items-start gap-3 px-4 py-3">
<div className="shrink-0 mt-0.5">
<span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: style.bg, color: style.color, border: `1px solid ${style.border}` }}>
{label}
</span>
</div>
<div className="flex-1 min-w-0 text-sm">
<div className="flex flex-wrap gap-x-3 gap-y-0.5 items-baseline">
{ev.modifier_name && <span className="font-medium text-gray-800">{ev.modifier_name}</span>}
{ev.deal_name && <span className="font-medium text-gray-800">{ev.deal_name}</span>}
{ev.applied_by_username && (
<span className="text-gray-500 text-xs">από {ev.applied_by_username}</span>
)}
{hasDelta && (
<span className={`text-xs font-semibold ${ev.delta_amount < 0 ? 'text-green-700' : 'text-red-600'}`}>
{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount?.toFixed(2)}€
<span className="font-normal text-gray-400 ml-1">
({ev.price_before?.toFixed(2)} → {ev.price_after?.toFixed(2)})
</span>
</span>
)}
</div>
{ev.waiter_note && (
<p className="text-xs text-gray-400 mt-0.5 italic">"{ev.waiter_note}"</p>
)}
{ev.conditions_snapshot && Object.keys(ev.conditions_snapshot).length > 0 && (
<details className="mt-1">
<summary className="text-xs text-gray-400 cursor-pointer hover:text-gray-600">Συνθήκες</summary>
<pre className="text-[10px] text-gray-500 bg-gray-50 rounded p-2 mt-1 overflow-x-auto">
{JSON.stringify(ev.conditions_snapshot, null, 2)}
</pre>
</details>
)}
</div>
<div className="shrink-0 text-right">
<span className="text-xs text-gray-400">{formatDate(ev.applied_at)}</span>
</div>
</div>
)
})}
</div>
)
}
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 <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
if (!order) return <div className="text-center py-16 text-gray-400">Παραγγελία δεν βρέθηκε.</div>
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 (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
{/* Compact header strip */}
<div style={{ padding: '10px 20px', borderBottom: '1px solid #e2e8f0', display: 'flex', alignItems: 'center', gap: 16, flexShrink: 0 }}>
{!propOrderId && (
<button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
)}
<div style={{ fontSize: 14, color: '#64748b' }}>
Τραπέζι {order.table_name || order.table_id}
</div>
<Badge status={order.status} />
<span style={{ fontSize: 14, fontWeight: 700, color: '#1e293b' }}>€{total.toFixed(2)}</span>
<div style={{ flex: 1 }} />
{/* Tab strip inline */}
<div style={{ display: 'flex', gap: 1, borderBottom: 'none' }}>
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό']].map(([key, label]) => (
<button key={key} onClick={() => 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}
</button>
))}
</div>
</div>
{/* Full-height ordering terminal */}
<div style={{ flex: 1, minHeight: 0, overflow: 'hidden' }}>
<DesktopOrderingTab
orderId={orderId}
tableId={order.table_id}
orderStatus={order.status}
/>
</div>
</div>
)
}
return (
<div className="overflow-y-auto h-full p-6">
<div className="max-w-3xl mx-auto space-y-6">
{!propOrderId && (
<button onClick={() => navigate(-1)} className="btn btn-ghost text-sm">← Πίσω</button>
)}
{/* Header */}
<div className="card p-5 flex flex-wrap gap-4 items-start justify-between">
<div>
<p className="text-sm text-gray-500">
Τραπέζι {order.table_name || order.table_id} · Ανοίχτηκε {formatDate(order.opened_at)}
{order.closed_at && ` · Έκλεισε ${formatDate(order.closed_at)}`}
</p>
</div>
<div className="flex items-center gap-3">
<Badge status={order.status} />
<span className="text-lg font-bold text-gray-800">€{total.toFixed(2)}</span>
</div>
</div>
{/* Customer assignment */}
<div className="card p-4">
<div className="flex items-center justify-between mb-2">
<h2 className="text-sm font-semibold text-gray-700">Πελάτης</h2>
{order.customer_id && isOpen && !readOnly && (
<button
onClick={() => assignCustomer.mutate(null)}
className="text-xs text-gray-400 hover:text-red-500"
>
Αφαίρεση
</button>
)}
</div>
{order.customer_id ? (
<div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: '#eff6ff', borderRadius: 8, border: '1px solid #bfdbfe' }}>
<span style={{ fontSize: 16 }}>👤</span>
<div>
<div style={{ fontSize: 13.5, fontWeight: 700, color: '#1d4ed8' }}>{order.customer_name || `Πελάτης #${order.customer_id}`}</div>
{order.customer_phone && <div style={{ fontSize: 11.5, color: '#3b82f6' }}>{order.customer_phone}</div>}
</div>
</div>
) : isOpen && !readOnly ? (
<div style={{ position: 'relative' }}>
{!showCustomerDropdown ? (
<button
onClick={() => setShowCustomerDropdown(true)}
style={{ fontSize: 13, color: '#6b7280', border: '1px dashed #d1d5db', borderRadius: 8, padding: '7px 14px', cursor: 'pointer', background: 'white', width: '100%', textAlign: 'left' }}
>
+ Ανάθεση πελάτη
</button>
) : (
<div>
<input
autoFocus
value={customerSearch}
onChange={e => 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' }}
/>
<div style={{ position: 'absolute', top: '100%', left: 0, right: 0, background: 'white', border: '1px solid #e5e7eb', borderRadius: 8, boxShadow: '0 4px 16px rgba(0,0,0,0.10)', zIndex: 20, maxHeight: 220, overflowY: 'auto', marginTop: 4 }}>
{customersData.length === 0 && (
<div style={{ padding: '10px 14px', fontSize: 13, color: '#9ca3af' }}>Δεν βρέθηκαν πελάτες</div>
)}
{customersData.map(c => (
<button key={c.id} onClick={() => 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"
>
<span style={{ fontWeight: 600, color: '#111315' }}>{c.name}</span>
{c.nickname && <span style={{ color: '#9ca3af', marginLeft: 5 }}>«{c.nickname}»</span>}
{c.phone && <span style={{ color: '#6b7280', marginLeft: 8, fontSize: 12 }}>{c.phone}</span>}
</button>
))}
<button onClick={() => { 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' }}>
Ακύρωση
</button>
</div>
</div>
)}
</div>
) : (
<div style={{ fontSize: 13, color: '#d1d5db' }}>Χωρίς πελάτη</div>
)}
</div>
{/* Tabs */}
<div className="flex gap-1 border-b border-gray-200">
{[['overview', 'Επισκόπηση'], ['order', 'Παραγγελία'], ['pricing', 'Τιμολόγηση'], ['audit', 'Ιστορικό Συναλλαγών']].map(([key, label]) => (
<button
key={key}
onClick={() => 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}
</button>
))}
</div>
{tab === 'overview' && <>
{/* Waiters */}
<div className="card p-4">
<h2 className="text-sm font-semibold text-gray-700 mb-3">Προσωπικό</h2>
<div className="flex flex-wrap gap-2">
{order.waiters.map(w => (
<div key={w.waiter_id} className="flex items-center gap-2 bg-gray-100 rounded-full px-3 py-1">
<span className="text-sm">{waiterMap[w.waiter_id] || `#${w.waiter_id}`}</span>
{isOpen && !readOnly && (
<button
onClick={() => removeWaiter.mutate(w.waiter_id)}
className="text-gray-400 hover:text-red-500 text-xs leading-none"
>
✕
</button>
)}
</div>
))}
{isOpen && !readOnly && (
<select
className="text-sm border border-gray-300 rounded-full pl-3 pr-8 py-1 focus:outline-none focus:ring-1 focus:ring-primary-600"
defaultValue=""
onChange={e => { if (e.target.value) assignWaiter.mutate(Number(e.target.value)) }}
>
<option value="">+ Πρόσθεσε</option>
{waiters.filter(w => !assignedIds.has(w.id)).map(w => (
<option key={w.id} value={w.id}>{w.nickname || w.full_name || w.username}</option>
))}
</select>
)}
</div>
</div>
{/* Items */}
<div className="card divide-y divide-gray-100">
<div className="px-4 py-3">
<h2 className="text-sm font-semibold text-gray-700">Αντικείμενα</h2>
</div>
{order.items.length === 0 && (
<p className="px-4 py-6 text-center text-gray-400 text-sm">Κανένα αντικείμενο.</p>
)}
{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 (
<div key={item.id} className={`flex items-center gap-3 px-4 py-3 ${isCancelled ? 'opacity-40 line-through' : ''} ${isClosedItem ? 'bg-amber-50/50' : ''}`}>
<div className="flex-1 min-w-0">
<p className="font-medium text-gray-800 text-sm" style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap' }}>
{item.product?.name ?? `#${item.product_id}`}
{item.course_id != null && (
<span style={{
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
width: 18, height: 18, borderRadius: '50%',
background: '#6366f1', color: '#fff',
fontSize: 10, fontWeight: 700,
}} title="Course">
{item.course_id}
</span>
)}
{isDealItem && <span style={{ fontSize: 10, fontWeight: 700, padding: '1px 5px', borderRadius: 4, background: 'rgba(167,139,250,0.12)', color: '#7c3aed', border: '1px solid rgba(167,139,250,0.3)' }}>ΔΩΡΕΑΝ</span>}
</p>
{item.notes && <p className="text-xs text-gray-400">{item.notes}</p>}
<p className="text-xs" style={{ color: hasPriceAdj ? '#3b82f6' : '#6b7280' }}>
x{item.quantity} · €{effPrice(item).toFixed(2)}/τμχ
{hasPriceAdj && (
<span className="ml-1 line-through text-gray-400">€{(item.unit_price ?? 0).toFixed(2)}</span>
)}
</p>
{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 (
<p key={ei} className="text-xs" style={{ color: evColor, display: 'flex', alignItems: 'center', gap: 3 }}>
<span style={{ opacity: 0.6 }}>↳</span>
<span>{evLabel}</span>
{ev.delta_amount != null && <span style={{ fontWeight: 600 }}>{ev.delta_amount > 0 ? '+' : ''}{ev.delta_amount.toFixed(2)} €</span>}
</p>
)
})}
{item.paid_by && (
<p className="text-xs text-green-600 mt-0.5">
Πληρώθηκε: {item.paid_by_name ?? waiterMap[item.paid_by] ?? `#${item.paid_by}`}
{item.paid_at ? ` · ${formatDate(item.paid_at)}` : ''}
{item.payment_method && (
<span style={{ color: (PAYMENT_METHOD_STYLES[item.payment_method] || {}).color ?? '#374151', fontWeight: 600 }}>
{' · '}{(PAYMENT_METHOD_STYLES[item.payment_method] || { label: item.payment_method.toUpperCase() }).label}
</span>
)}
</p>
)}
{isClosedItem && (
<p className="text-xs text-amber-700 mt-0.5 font-medium">Απλήρωτο — κλείστηκε από manager</p>
)}
</div>
<div className="flex items-center gap-2 shrink-0">
<span className="text-sm font-semibold w-14 text-right" style={{ color: hasPriceAdj ? '#3b82f6' : '#374151' }}>€{itemTotal(item)}</span>
{isOpen && !readOnly && item.status === 'active' && (
<>
<button
onClick={() => requestPay([item.id])}
className="btn btn-secondary text-xs px-2 py-1 min-h-0 h-8"
>
Πληρωμή
</button>
{order.customer_id && (
<button
onClick={() => 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' }}
>
📋 Καρτέλα
</button>
)}
<button
onClick={() => setConfirmAction({ type: 'cancelItem', payload: item.id })}
className="btn btn-danger text-xs px-2 py-1 min-h-0 h-8"
>
Ακύρωση
</button>
</>
)}
{item.status === 'tabbed' && (
<span style={{ fontSize: 11, fontWeight: 700, padding: '2px 8px', borderRadius: 99, background: '#eff6ff', color: '#1d4ed8', border: '1px solid #bfdbfe' }}>
📋 Καρτέλα
</span>
)}
</div>
</div>
)
})}
</div>
{/* Actions */}
<div className="flex flex-wrap gap-3">
{isOpen && !readOnly && activeItems.length > 0 && (
<button
onClick={() => requestPay(activeItems.map(i => i.id))}
className="btn btn-primary"
>
Πληρωμή όλων
</button>
)}
{isOpen && !readOnly && (
<>
<button
onClick={() => setConfirmAction({ type: 'closeOrder' })}
className="btn btn-secondary"
>
Κλείσιμο παραγγελίας
</button>
<button
onClick={() => setConfirmAction({ type: 'cancelOrder' })}
className="btn btn-danger"
>
Ακύρωση παραγγελίας
</button>
</>
)}
<button
onClick={() => setShowPrintModal(true)}
className="btn btn-secondary"
>
🖨 Εκτύπωση
</button>
</div>
</>}
{tab === 'pricing' && (
<div className="card divide-y divide-gray-100">
<PriceEventsTab orderId={orderId} />
</div>
)}
{tab === 'audit' && (
<div className="card divide-y divide-gray-100">
<AuditTab order={order} waiterMap={waiterMap} />
</div>
)}
{payPending && (
<PaymentMethodModal
onSelect={confirmPay}
onCancel={() => setPayPending(null)}
title={payPending.length === 1 ? 'Τρόπος Πληρωμής;' : `Πληρωμή ${payPending.length} αντικειμένων;`}
/>
)}
{confirmAction && (
<ConfirmModal
title={
confirmAction.type === 'cancelItem' ? 'Ακύρωση αντικειμένου;' :
confirmAction.type === 'cancelOrder' ? 'Ακύρωση παραγγελίας;' :
'Κλείσιμο παραγγελίας;'
}
message={
confirmAction.type === 'cancelOrder'
? 'Η παραγγελία θα ακυρωθεί οριστικά.'
: undefined
}
confirmLabel={confirmAction.type === 'closeOrder' ? 'Κλείσιμο' : 'Ακύρωση'}
confirmVariant={confirmAction.type === 'closeOrder' ? 'primary' : 'danger'}
onConfirm={handleConfirm}
onCancel={() => setConfirmAction(null)}
/>
)}
{showPrintModal && printers.length > 0 && (
<PrintOrderModal
printers={printers}
onClose={() => setShowPrintModal(false)}
onPrint={(printerId) => printOrder.mutate(printerId)}
/>
)}
{showPrintModal && printers.length === 0 && (
<div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50">
<div className="bg-white rounded-2xl p-6 max-w-sm w-full mx-4 space-y-4">
<p className="text-gray-700">Δεν βρέθηκαν ενεργοί εκτυπωτές.</p>
<button onClick={() => setShowPrintModal(false)} className="btn btn-secondary w-full">Κλείσιμο</button>
</div>
</div>
)}
</div>
</div>
)
}
-836
View File
@@ -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 (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.4)', zIndex: 9999,
display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
}} onClick={onClose}>
<div style={{
background: 'white', borderRadius: 16, width: '100%', maxWidth: 360,
padding: 20, boxShadow: '0 16px 48px rgba(0,0,0,0.18)',
}} onClick={e => e.stopPropagation()}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
<div style={{ fontSize: 15, fontWeight: 700, color: '#111315' }}>Σημαίες — {tableName}</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 18, cursor: 'pointer', color: '#8a9099' }}>✕</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
{flags.map(f => (
<div key={f.id} style={{
display: 'flex', alignItems: 'center', gap: 12,
padding: '10px 12px', borderRadius: 10,
background: (f.color || '#6b7280') + '11',
border: `1px solid ${(f.color || '#6b7280')}33`,
}}>
{f.emoji && <span style={{ fontSize: 20 }}>{f.emoji}</span>}
<div style={{ flex: 1 }}>
<div style={{ fontSize: 14, fontWeight: 600, color: f.color || '#374151' }}>{f.name}</div>
{f.assigned_at && (
<div style={{ fontSize: 11, color: '#8a9099', marginTop: 1 }}>{relativeTime(f.assigned_at)}</div>
)}
</div>
</div>
))}
</div>
</div>
</div>
)
}
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 (
<img src={waiter.avatarUrl} alt={waiter.name}
style={{ width: size, height: size, borderRadius: '50%', objectFit: 'cover', flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)' }}
/>
)
}
const parts = waiter.name.trim().split(' ')
const initials = (parts[0][0] + (parts[1]?.[0] || '')).toUpperCase()
return (
<div style={{
width: size, height: size, borderRadius: '50%',
background: avatarColor(waiter.name), color: 'white',
fontSize: size * 0.42, fontWeight: 600,
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0, boxShadow: '0 0 0 2px var(--cardBg, white)',
}}>{initials}</div>
)
}
// ─── 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 (
<div style={{
position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.45)', zIndex: 9999,
display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
}} onClick={onClose}>
<div style={{
background: 'white', borderRadius: 20, width: '100%', maxWidth: 460,
padding: 24, boxShadow: '0 24px 64px rgba(0,0,0,0.22)',
}} onClick={e => e.stopPropagation()}>
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
<div style={{ fontSize: 15, fontWeight: 700 }}>⚡ {table.label || `T${table.number}`}</div>
<button onClick={onClose} style={{ background: 'none', border: 'none', fontSize: 20, cursor: 'pointer', color: '#8a9099' }}>✕</button>
</div>
<div style={{ fontSize: 12, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.5, marginBottom: 10 }}>Σημαίες</div>
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 20 }}>
{flagDefs.map(f => {
const sel = selectedFlagIds.includes(f.id)
return (
<button key={f.id} onClick={() => 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 && <span>{f.emoji}</span>}
{f.name}
</button>
)
})}
</div>
{order && (
<>
<label style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, cursor: 'pointer' }}>
<input type="checkbox" checked={notifyWaiters} onChange={e => setNotifyWaiters(e.target.checked)} />
<span style={{ fontSize: 13, color: '#374151', fontWeight: 500 }}>Ειδοποίησε τους σερβιτόρους</span>
</label>
{notifyWaiters && (
<div style={{ marginBottom: 16 }}>
<div style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
{templates.slice(0, 4).map(t => (
<button key={t.id} onClick={() => 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}</button>
))}
</div>
<input
value={notifyMsg}
onChange={e => 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' }}
/>
</div>
)}
</>
)}
<div style={{ display: 'flex', gap: 10, justifyContent: 'flex-end' }}>
<button onClick={onClose} style={{ height: 36, padding: '0 16px', borderRadius: 8, border: '1px solid #dfe2e6', background: 'white', fontSize: 13, cursor: 'pointer' }}>Άκυρο</button>
<button onClick={save} disabled={sending} style={{ height: 36, padding: '0 18px', borderRadius: 8, background: '#3758c9', color: 'white', border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer' }}>
{sending ? 'Αποθήκευση…' : 'Αποθήκευση'}
</button>
</div>
</div>
</div>
)
}
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 (
<div style={{ display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden', flexWrap: 'nowrap', minWidth: 0 }}>
{visible.map(f => (
<span key={f.id} style={{
fontSize: 11, fontWeight: 600, borderRadius: 999, padding: '2px 7px',
background: (f.color || '#6b7280') + '22',
color: f.color || '#6b7280',
border: `1px solid ${f.color || '#6b7280'}55`,
display: 'inline-flex', alignItems: 'center', gap: 3,
whiteSpace: 'nowrap', flexShrink: 0,
}}>
{(displayMode === 'icon' || displayMode === 'both') && f.emoji && <span style={{ fontSize: 12 }}>{f.emoji}</span>}
{(displayMode === 'text' || displayMode === 'both') && <span>{f.name}</span>}
</span>
))}
{overflow > 0 && (
<button
onClick={e => { 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}</button>
)}
</div>
)
}
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 (
<button
type="button"
onClick={onClick}
onMouseEnter={() => 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,
}}
>
<div style={{
position: 'absolute', left: 0, top: 0, bottom: 0, width: 6,
background: s.accent, borderRadius: '14px 0 0 14px',
}} />
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 10 }}>
<div style={{
fontSize: 34, fontWeight: 700, lineHeight: 1, letterSpacing: -0.5,
color: '#111315', fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
}}>{name}</div>
<div style={{
display: 'inline-flex', alignItems: 'center', gap: 6,
height: 26, padding: '0 10px', borderRadius: 999,
background: s.accent, color: 'white',
fontSize: 12, fontWeight: 600, letterSpacing: 0.2,
whiteSpace: 'nowrap', flexShrink: 0,
}}>
<span style={{ width: 6, height: 6, borderRadius: '50%', background: 'rgba(255,255,255,0.9)' }} />
{s.label}
</div>
</div>
<div style={{ marginTop: 6, minHeight: 22, display: 'flex', alignItems: 'center', gap: 4, overflow: 'hidden' }}>
{hasPendingPrint && (
<span style={{
fontSize: 11, fontWeight: 700, background: '#92400e', color: '#fcd34d',
borderRadius: 999, padding: '2px 8px', flexShrink: 0,
display: 'inline-flex', alignItems: 'center', gap: 4,
}}>⏳</span>
)}
{upcomingReservation && (
<span title={`${upcomingReservation.guest_name} · ${upcomingReservation.party_size} άτομα · ${new Date(upcomingReservation.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}`} style={{
fontSize: 11, fontWeight: 700, background: '#4f46e5', color: '#e0e7ff',
borderRadius: 999, padding: '2px 8px', flexShrink: 0,
display: 'inline-flex', alignItems: 'center', gap: 4,
}}>
🔒 RESERVED · {new Date(upcomingReservation.reserved_for).toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })}
</span>
)}
<FlagPills
flags={flags}
displayMode={flagDisplayMode}
onOverflowClick={onFlagsClick}
/>
</div>
<div style={{ marginTop: 'auto', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8, alignItems: 'end' }}>
<div>
<div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Total</div>
<div style={{ fontSize: 22, fontWeight: 600, color: '#111315', marginTop: 2, fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace" }}>
{amount != null ? formatEuro(amount) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
</div>
</div>
<div>
<div style={{ fontSize: 11, fontWeight: 600, color: '#5a6169', textTransform: 'uppercase', letterSpacing: 0.6 }}>Time</div>
<div style={{
fontSize: 22, marginTop: 2,
fontFamily: "'ui-monospace','SFMono-Regular','Menlo',monospace",
fontWeight: occupiedMins != null && occupiedMins >= 90 ? 700 : 500,
color: '#111315',
}}>
{openedAt ? formatDuration(openedAt) : <span style={{ color: '#b8bdc4', letterSpacing: 2 }}>— —</span>}
</div>
</div>
</div>
<div style={{
marginTop: 12, paddingTop: 10,
borderTop: '1px solid ' + s.tintStrong,
height: 36, display: 'flex', alignItems: 'center', gap: 8,
}}>
{waiters.length === 0 ? (
<span style={{ color: '#8a9099', fontSize: 13 }}>Unassigned</span>
) : waiters.length >= 3 ? (
<>
<div style={{ display: 'flex' }}>
{waiters.slice(0, 3).map((w, i) => (
<div key={i} style={{ marginLeft: i === 0 ? 0 : -8 }}>
<WaiterBubble waiter={w} size={24} />
</div>
))}
</div>
<span style={{
fontSize: 13, fontWeight: 600, color: '#2b2f33',
background: 'white', border: '1px solid #dfe2e6',
borderRadius: 999, padding: '2px 8px',
}}>Multiple ({waiters.length})</span>
</>
) : (
waiters.map((w, i) => (
<div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
<WaiterBubble waiter={w} size={24} />
<span style={{ fontSize: 14, color: '#2b2f33', fontWeight: 500 }}>{w.shortName}</span>
</div>
))
)}
{onQuickAction && (
<button
onClick={e => { 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',
}}
>⚡</button>
)}
</div>
</button>
)
}
// ─── 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 (
<div ref={ref} style={{ position: 'relative' }}>
<button
onClick={() => 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',
}}
>
<span style={{ fontSize: 11, color: '#8a9099', fontWeight: 600, textTransform: 'uppercase', letterSpacing: 0.5, marginRight: 2 }}>{label}</span>
{displayLabel}
<span style={{ fontSize: 10, color: '#8a9099', marginLeft: 2 }}>{open ? '▲' : '▼'}</span>
</button>
{open && (
<div style={{
position: 'absolute', top: '100%', left: 0, marginTop: 6, zIndex: 100,
background: 'white', border: '1px solid #dfe2e6', borderRadius: 12,
boxShadow: '0 8px 24px rgba(16,20,24,0.12)',
minWidth: 180, overflow: 'hidden',
}}>
{/* All option */}
<button
onClick={() => { 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',
}}
>
<span style={{
width: 16, height: 16, borderRadius: 4,
border: '1.5px solid ' + (allSelected ? '#3758c9' : '#dfe2e6'),
background: allSelected ? '#3758c9' : 'white',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
{allSelected && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
</span>
{allLabel}
</button>
{options.map(opt => {
const checked = selected.includes(opt.value)
return (
<button
key={opt.value}
onClick={() => 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',
}}
>
<span style={{
width: 16, height: 16, borderRadius: 4,
border: '1.5px solid ' + (checked ? '#7a44c9' : '#dfe2e6'),
background: checked ? '#7a44c9' : 'white',
display: 'flex', alignItems: 'center', justifyContent: 'center',
flexShrink: 0,
}}>
{checked && <span style={{ color: 'white', fontSize: 10, fontWeight: 700 }}>✓</span>}
</span>
{opt.label}
</button>
)
})}
</div>
)}
</div>
)
}
// ─── 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 <div className="flex items-center justify-center h-64 text-gray-400">Φόρτωση…</div>
}
return (
<div className="overflow-y-auto h-full p-6 space-y-6">
{flagsDetail && (
<FlagsDetailModal
flags={flagsDetail.flags}
tableName={flagsDetail.tableName}
onClose={() => setFlagsDetail(null)}
/>
)}
{quickActionTarget && (
<QuickActionModal
table={quickActionTarget.table}
order={quickActionTarget.order}
flagDefs={flagDefs}
currentFlags={quickActionTarget.currentFlags}
waiters={waiters}
templates={quickTemplates}
onClose={() => setQuickActionTarget(null)}
onDone={() => queryClient.invalidateQueries({ queryKey: ['flag-assignments'] })}
/>
)}
<div className="flex items-center justify-end flex-wrap gap-3">
<div className="flex rounded-control border border-line overflow-hidden mr-auto" role="group">
{['list', 'map'].map(v => (
<button key={v} type="button" aria-pressed={view === v} onClick={() => 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}`)}
</button>
))}
</div>
<div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', alignItems: 'center' }}>
<MultiSelectDropdown
label="Κατάσταση"
options={STATUS_OPTIONS}
selected={statusFilter}
onChange={setStatusFilter}
allLabel="Όλες οι καταστάσεις"
/>
<MultiSelectDropdown
label="Ζώνη"
options={zoneOptions}
selected={zoneFilter}
onChange={setZoneFilter}
allLabel="Όλες οι ζώνες"
/>
</div>
</div>
{view === 'map' && <LiveFloor zone={zoneFilter.length === 1 && zoneFilter[0] !== '__none__' ? Number(zoneFilter[0]) : null} onOpen={id => navigate(`/orders/${id}`)} />}
{view === 'list' && filtered.length === 0 && (
<p className="text-center text-gray-400 py-16">Δεν βρέθηκαν τραπέζια.</p>
)}
{view === 'list' && <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(330px, 1fr))', gap: 16 }}>
{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 (
<TableCardV1
key={table.id}
name={table.label || `T${table.number}`}
status={tableStatus}
amount={amount}
openedAt={order?.opened_at ?? null}
waiters={waiterNames}
hasPendingPrint={hasPendingPrint}
flags={tableFlags}
flagDisplayMode={flagDisplayMode}
upcomingReservation={table.upcoming_reservation ?? null}
onClick={order ? () => 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}
/>
)
})}
</div>}
{pendingPrintOrders.length > 0 && (
<div className="bg-white rounded-2xl border border-orange-200 shadow-sm overflow-hidden">
<div className="flex items-center justify-between px-5 py-4 border-b border-orange-100" style={{ background: '#fff7ed' }}>
<div className="flex items-center gap-3">
<span style={{ fontSize: 20 }}>⏳</span>
<div>
<h2 className="text-base font-bold text-orange-900">Εκκρεμείς Εκτυπώσεις</h2>
<p className="text-xs text-orange-700 mt-0.5">
{pendingPrintOrders.length} παραγγελί{pendingPrintOrders.length !== 1 ? 'ες' : 'α'} δεν έχ{pendingPrintOrders.length !== 1 ? 'ουν' : 'ει'} σταλεί στην κουζίνα/μπαρ
</p>
</div>
</div>
<button
className="btn btn-primary text-sm"
style={{ background: '#c2410c', borderColor: '#c2410c' }}
onClick={retryAllOrders}
disabled={retryingId !== null}
>
{retryingId !== null ? 'Αποστολή…' : 'Αποστολή Όλων'}
</button>
</div>
<div className="divide-y divide-orange-50">
{pendingPrintOrders.map(({ table, order }) => {
const unprinted = order.items.filter(i => i.status === 'active' && !i.printed)
const tableName = table.label || `T${table.number}`
return (
<div key={order.id} className="flex items-center gap-4 px-5 py-3">
<div className="shrink-0 w-10 h-10 rounded-xl flex items-center justify-center font-bold text-sm"
style={{ background: '#fff7ed', color: '#c2410c', border: '1px solid #fed7aa' }}>
{tableName}
</div>
<div className="flex-1 min-w-0">
<p className="text-sm font-semibold text-gray-800">
{unprinted.length} αντικείμενο{unprinted.length !== 1 ? 'α' : ''} εκκρεμούν
</p>
<p className="text-xs text-gray-500 truncate">
{unprinted.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
<button className="btn btn-secondary text-xs" onClick={() => navigate(`/orders/${order.id}`)}>
Λεπτομέρειες
</button>
<button
className="btn btn-primary text-xs"
style={{ background: '#c2410c', borderColor: '#c2410c' }}
onClick={() => retrySingleOrder(order.id)}
disabled={retryingId === order.id}
>
{retryingId === order.id ? '…' : 'Εκτύπωση'}
</button>
</div>
</div>
)
})}
</div>
</div>
)}
</div>
)
}
@@ -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 <div className="flex justify-center p-6"><Spinner /></div>
return (
<section className="grid gap-3 content-start min-w-0" data-testid="order-add">
<div className="flex items-center gap-2">
<div className="relative flex-1">
<Search size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-ink-3" aria-hidden="true" />
<Input value={query} onChange={e => setQuery(e.target.value)} placeholder={t('orders.add.search')} aria-label={t('orders.add.search')} className="pl-9" data-testid="order-search" />
</div>
</div>
{!query.trim() && (
<div className="flex flex-wrap gap-1.5" role="tablist">
{[{ id: null, name: t('orders.add.all') }, ...cats, ...(products.some(p => p.service) ? [{ id: SERVICE, name: t('orders.add.service') }] : [])].map(c => (
<button key={c.id ?? 'all'} type="button" role="tab" aria-selected={category === c.id} onClick={() => 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}
</button>
))}
</div>
)}
{shown.length === 0 ? <EmptyState compact title={t('orders.add.nothing')} /> : (
<div className="grid gap-2 max-h-[45vh] overflow-y-auto pr-1" style={{ gridTemplateColumns: 'repeat(auto-fill, minmax(9.5rem, 1fr))' }}>
{shown.map(p => (
<button key={p.id} type="button" onClick={() => 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')}>
<span className="text-label font-semibold text-ink line-clamp-2">{p.name}</span>
<span className="text-caption text-ink-2 tabular-nums">{p.available ? formatMoney(p.price) : t('orders.add.soldOut')}{needsChoices(p) ? ' · …' : ''}</span>
</button>
))}
</div>
)}
<div className="grid gap-2 p-3 rounded-card border border-line bg-surface shadow-raised" data-testid="order-cart">
<h3 className="text-label font-semibold text-ink">{t('orders.add.toSend')}</h3>
{cart.length === 0 ? <p className="text-caption text-ink-3">{t('orders.add.empty')}</p> : (
<ul className="grid divide-y divide-line">
{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 (
<li key={i} className="py-1.5 flex items-center gap-2" data-testid="cart-line">
<span className="flex-1 min-w-0">
<span className="block text-label font-medium text-ink truncate">{p?.name ?? priced?.name}</span>
{priced?.entries?.length > 0 && <span className="block text-caption text-ink-2 truncate">{priced.entries.map(e => e.name).join(', ')}</span>}
</span>
<IconButton size="sm" variant="secondary" label={t('orders.add.less')} onClick={() => setCart(c => setLineQty(c, i, line.quantity - step))}>
{line.quantity - step <= 0 ? <Trash2 size={14} /> : <Minus size={14} />}
</IconButton>
<span className="w-12 text-center text-label font-semibold tabular-nums" data-testid="cart-qty">{unit ? `${line.quantity} ${unit.label}` : line.quantity}</span>
<IconButton size="sm" variant="secondary" label={t('orders.add.more')} onClick={() => setCart(c => setLineQty(c, i, line.quantity + step))}><Plus size={14} /></IconButton>
<span className="w-20 text-right text-label tabular-nums">{priced ? formatMoney(priced.total) : '…'}</span>
</li>
)
})}
</ul>
)}
{error && <p role="alert" className="text-label text-danger-ink">{errorMessage(error, t)}</p>}
<Textarea rows={2} maxLength={300} value={note} onChange={e => setNote(e.target.value)} placeholder={t('orders.add.note')} aria-label={t('orders.add.note')} />
<div className="flex items-center gap-3">
<span className="flex-1 text-body font-semibold text-ink tabular-nums" data-testid="cart-total">
{cart.length ? (quote && !pending ? formatMoney(quote.total) : '…') : ''}
</span>
{cart.length > 0 && <Button variant="ghost" onClick={() => setCart([])}>{t('orders.add.clear')}</Button>}
<Button icon={<Send size={16} />} disabled={!cart.length || !!error} loading={busy} onClick={send} data-testid="order-send">{t('orders.add.send')}</Button>
</div>
</div>
{choosing && <ProductDialog product={choosing} fetchQuote={fetchQuote} onClose={() => setChoosing(null)} onAdd={line => setCart(c => addLine(c, line))} />}
</section>
)
}
@@ -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 <EmptyState compact title={t('orders.history.none')} />
const byId = new Map(order.items.map(i => [i.id, i]))
return (
<ul className="divide-y divide-line" data-testid="order-audit">
{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 (
<li key={log.id} className={cx('px-4 py-2.5 flex items-start gap-3', dup && 'bg-danger-soft')}>
<span className="grid gap-0.5 shrink-0">
<Pill tone={dup ? 'danger' : EVENT_TONE[log.event_type] ?? 'info'}>{t(`orders.history.event.${log.event_type}`, { defaultValue: log.event_type })}</Pill>
{dup && <span className="text-caption font-semibold text-danger-ink">{t('orders.history.duplicate')}</span>}
</span>
<span className="flex-1 min-w-0 grid gap-1 text-label text-ink">
<span>
{log.waiter_name ?? (log.waiter_id ? `#${log.waiter_id}` : '')}
{log.amount != null && <span className="ml-2 font-semibold text-success-ink tabular-nums">{formatMoney(log.amount)}</span>}
{log.payment_method && <span className="ml-2 text-ink-2">{t(`orders.pay.method.${log.payment_method}`, { defaultValue: log.payment_method })}</span>}
</span>
{names.length > 0 && <span className="flex flex-wrap gap-1">{names.map((n, i) => <Pill key={i}>{n}</Pill>)}</span>}
{log.note && <span className="text-caption text-ink-3">{log.note}</span>}
</span>
<span className="text-caption text-ink-3 text-right shrink-0">
{formatDateTime(log.offline_at || log.created_at, 'datetimeShort')}
{log.offline_at && <span className="block text-warning-ink">{t('orders.history.offline')}</span>}
</span>
</li>
)
})}
</ul>
)
}
export function PriceEventList({ events }) {
const { t } = useTranslation('manager')
const { formatDateTime, formatMoney } = useFormat()
if (!events.length) return <EmptyState compact title={t('orders.history.noPrices')} />
return (
<ul className="divide-y divide-line" data-testid="order-price-events">
{events.map(ev => (
<li key={ev.id} className="px-4 py-2.5 flex items-start gap-3">
<Pill tone="info">{t(`orders.history.price.${ev.event_type}`, { defaultValue: ev.event_type })}</Pill>
<span className="flex-1 min-w-0 grid gap-0.5 text-label text-ink">
<span className="flex flex-wrap gap-x-3">
{(ev.modifier_name || ev.deal_name) && <span className="font-semibold">{ev.modifier_name || ev.deal_name}</span>}
{ev.applied_by_username && <span className="text-ink-3">{t('orders.history.by', { name: ev.applied_by_username })}</span>}
{ev.delta_amount != null && (
<span className={cx('font-semibold tabular-nums', ev.delta_amount < 0 ? 'text-success-ink' : 'text-danger-ink')}>
{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}
{ev.price_before != null && ev.price_after != null && <span className="font-normal text-ink-3"> ({formatMoney(ev.price_before)} → {formatMoney(ev.price_after)})</span>}
</span>
)}
</span>
{ev.waiter_note && <span className="text-caption text-ink-3 italic">{ev.waiter_note}</span>}
</span>
<span className="text-caption text-ink-3 shrink-0">{formatDateTime(ev.applied_at, 'datetimeShort')}</span>
</li>
))}
</ul>
)
}
@@ -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 (
<section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden" data-testid="order-lines">
{lines.length === 0 ? <EmptyState compact title={t('orders.lines.none')} /> : (
<ul className="divide-y divide-line">
{lines.map(item => {
const can = open && selectable(item)
const on = picked.includes(item.id)
const d = lineDetails(item)
const evs = priceEvents.filter(ev => ev.order_item_id === item.id && EVENT_TONE[ev.event_type])
const gone = item.status === 'cancelled'
return (
<li key={item.id} className={cx('px-4 py-2.5 flex gap-3 items-start', on && 'bg-accent-soft', gone && 'opacity-50')}
data-testid="order-line" data-status={item.status} data-name={nameOf(item)}>
<input type="checkbox" className="mt-1 size-4 accent-[var(--x-accent)]" disabled={!can} checked={on}
aria-label={t('orders.lines.pick', { name: nameOf(item) })} onChange={() => setSelected(s => toggleSelected(s, item.id))} data-testid="line-pick" />
<div className={cx('flex-1 min-w-0 grid gap-0.5', gone && 'line-through')}>
<div className="flex flex-wrap items-center gap-1.5 text-body font-semibold text-ink">
<span>{item.quantity !== 1 || item.unit_type !== 'piece' ? `${item.quantity}× ` : ''}{nameOf(item)}</span>
{item.deal_id && <Pill tone="accent">{t('orders.lines.free')}</Pill>}
{STATUS_TONE[item.status] && (
<Pill tone={STATUS_TONE[item.status]}>
{t(`orders.lines.status.${item.status}`)}{item.status === 'paid' && item.payment_method ? ` · ${t(`orders.pay.method.${item.payment_method}`, { defaultValue: item.payment_method })}` : ''}
</Pill>
)}
{item.status === 'active' && !item.printed && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.lines.notPrinted')}</Pill>}
</div>
{d.choices.length > 0 && <div className="text-caption text-ink-2">{d.choices.join(', ')}</div>}
{d.removed.length > 0 && <div className="text-caption text-ink-2">{t('orders.lines.without', { list: d.removed.join(', ') })}</div>}
{d.note && <div className="text-caption text-warning-ink">{d.note}</div>}
<div className="text-caption text-ink-3">
{t('orders.lines.added', { time: formatTime(item.added_at), name: item.added_by_name ?? '' })}
{item.paid_by_name && ` · ${t('orders.lines.paidBy', { name: item.paid_by_name })}`}
</div>
{evs.map((ev, i) => (
<div key={i} className={cx('flex items-center gap-2 text-caption', EVENT_TONE[ev.event_type])}>
<span aria-hidden="true">↳</span>
<span>{ev.modifier_name || ev.deal_name || t(`overview.order.event.${ev.event_type}`)}</span>
{ev.delta_amount != null && <span className="font-semibold">{formatMoney(ev.delta_amount, { signDisplay: 'exceptZero' })}</span>}
</div>
))}
</div>
<div className="text-right grid">
<span className={cx('text-body font-semibold tabular-nums', item.price_adjustment ? 'text-info-ink' : 'text-ink')}>{formatMoney(lineAmount(item))}</span>
{item.quantity !== 1 && <span className="text-caption text-ink-3 tabular-nums">{t('orders.lines.each', { price: formatMoney(unitOf(item)) })}</span>}
</div>
</li>
)
})}
</ul>
)}
{open && picked.length > 0 && (
<div className="sticky bottom-0 flex flex-wrap items-center gap-2 px-4 py-3 border-t border-line bg-surface-2" data-testid="line-actions">
<span className="flex-1 text-label text-ink-2">{t('orders.lines.picked', { count: picked.length, amount: formatMoney(amount) })}</span>
<Button size="sm" variant="ghost" onClick={() => setSelected([])}>{t('orders.lines.clear')}</Button>
{order.customer_id && <Button size="sm" variant="secondary" icon={<Receipt size={14} />} loading={toTab.isPending} onClick={() => toTab.mutate()}>{t('orders.lines.toTab')}</Button>}
{canDiscount && <Button size="sm" variant="secondary" icon={<Percent size={14} />} onClick={() => setDiscounting(true)} data-testid="lines-discount">{t('orders.lines.discount')}</Button>}
<Button size="sm" variant="danger" icon={<Ban size={14} />} onClick={() => setCancelling(true)} data-testid="lines-cancel">{t('orders.lines.cancel')}</Button>
<Button size="sm" icon={<CreditCard size={14} />} onClick={() => onPay(picked, amount, () => setSelected([]))} data-testid="lines-pay">{t('orders.lines.pay')}</Button>
</div>
)}
{cancelling && (
<Dialog open size="sm" onClose={() => setCancelling(false)} title={t('orders.lines.cancelTitle', { count: picked.length })}
description={t('orders.lines.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setCancelling(false)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="cancel-no-print">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
{discounting && <DiscountDialog orderId={order.id} itemIds={picked} amount={amount} onClose={() => setDiscounting(false)}
onDone={() => { setDiscounting(false); done(t('orders.discount.done')) }} />}
</section>
)
}
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 (
<Dialog open size="sm" onClose={onClose} title={t('orders.discount.title', { count: itemIds.length })} description={t('orders.discount.body')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
<Button disabled={!ok} loading={apply.isPending} onClick={() => apply.mutate()} data-testid="discount-apply">{t('orders.discount.apply')}</Button>
</>}>
<div className="grid gap-3">
<div className="flex flex-wrap gap-1.5">
{[5, 10, 15, 20, 50, 100].map(p => (
<Button key={p} size="sm" variant={value === p ? 'primary' : 'secondary'} onClick={() => setPct(String(p))}>{p}%</Button>
))}
</div>
<Field label={t('orders.discount.pct')} hint={ok ? t('orders.discount.about', { amount: formatMoney(-(amount * value) / 100) }) : undefined}>
<Input inputMode="decimal" value={pct} onChange={e => setPct(e.target.value)} data-testid="discount-pct" />
</Field>
<Field label={t('orders.discount.note')}>
<Input value={note} maxLength={200} onChange={e => setNote(e.target.value)} />
</Field>
</div>
</Dialog>
)
}
@@ -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 <NewOrder tableId={Number(params.get('table')) || null} />
return <OrderView orderId={Number(orderId)} />
}
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 <Button size="sm" variant="ghost" icon={<ArrowLeft size={16} />} onClick={() => navigate('/tables')}>{t('orders.toTables')}</Button>
}
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 (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-new">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{t('orders.newTitle', { table: table ? tableName(table) : tableId ?? '' })}</h1>
<Pill tone="neutral">{t('overview.tableState.free')}</Pill>
</header>
<p className="text-label text-ink-2">{t('orders.newHint')}</p>
<AddItems orderId={null} openOrder={open} onSent={id => {
qc.invalidateQueries({ queryKey: ['orders-active'] })
navigate(`/orders/${id}`, { replace: true })
}} />
</div>
</div>
)
}
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 <div className="h-full grid place-items-center"><Spinner /></div>
if (error || !order) {
return <div className="p-6 grid gap-3 justify-items-center"><EmptyState title={t('orders.notFound')} description={error ? errorMessage(error, t) : undefined} /><Back /></div>
}
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 (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="order-page" data-status={order.status}>
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<Back />
<h1 className="text-title font-semibold text-ink">{order.table_name ? t('orders.title', { table: order.table_name }) : t('orders.titleNoTable', { id: order.id })}</h1>
<Pill tone={STATUS_TONE[order.status] ?? 'neutral'} data-testid="order-status">{t(`overview.orderStatus.${order.status}`, { defaultValue: order.status })}</Pill>
<span className="text-label text-ink-2">{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) })}</span>
<span className="flex-1" />
<span className="flex items-baseline gap-4 text-label text-ink-2">
{sums.paid > 0 && <span>{t('orders.paid')} <Money value={sums.paid} className="font-semibold text-success-ink" /></span>}
{sums.paid > 0 && sums.due > 0 && <span>{t('orders.due')} <Money value={sums.due} className="font-semibold text-ink" data-testid="order-due" /></span>}
<span>{t('orders.total')} <Money value={sums.total} className="text-title font-semibold text-ink" data-testid="order-total" /></span>
</span>
</header>
<div className="flex flex-wrap items-center gap-2">
<span className="flex gap-1" role="tablist">
{TABS.map(k => <Button key={k} size="sm" variant={tab === k ? 'primary' : 'ghost'} role="tab" aria-selected={tab === k} onClick={() => setTab(k)} data-testid={`order-tab-${k}`}>{t(`orders.tabs.${k}`)}</Button>)}
</span>
<span className="flex-1" />
{editable && due.length > 0 && <Button icon={<CreditCard size={16} />} onClick={() => setPaying({ ids: due, amount: sums.due })} data-testid="order-pay-all">{t('orders.payAll')}</Button>}
{editable && <Button variant="secondary" icon={<CheckCheck size={16} />} onClick={startClose} data-testid="order-close">{t('orders.close')}</Button>}
{editable && <Button variant="danger" icon={<Ban size={16} />} onClick={() => setConfirm('cancel')} data-testid="order-cancel">{t('orders.cancel')}</Button>}
{printers.length > 0 && (
<span className="flex items-center gap-2">
<Select size="sm" value={printerId} onChange={e => setPrinterId(e.target.value)} aria-label={t('orders.printer')}
placeholder={t('orders.printer')} options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
<Button size="sm" variant="secondary" icon={<Printer size={16} />} disabled={!printerId} loading={print.isPending} onClick={() => print.mutate(Number(printerId))}>{t('orders.print')}</Button>
</span>
)}
</div>
{tab === 'order' && (
<div className={cx('grid gap-4 items-start', editable && 'lg:grid-cols-[minmax(0,1fr)_minmax(0,1.1fr)]')}>
<div className="grid gap-4 min-w-0">
<OrderLines order={order} open={editable} priceEvents={priceEvents} onChanged={refresh}
onPay={(ids, amount, after) => setPaying({ ids, amount, after })} />
<OrderPeople order={order} open={editable} staff={staff} onChanged={refresh} />
</div>
{editable && <AddItems orderId={order.id} onSent={refresh} />}
</div>
)}
{tab === 'prices' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><PriceEventList events={priceEvents} /></section>}
{tab === 'history' && <section className="rounded-card border border-line bg-surface shadow-raised overflow-hidden"><AuditList order={order} /></section>}
</div>
{paying && <PayDialog orderId={order.id} itemIds={paying.ids} amount={paying.amount} card={venue.card} thenClose={!!paying.thenClose}
onClose={() => setPaying(null)}
onDone={() => { toast.success(paying.thenClose ? t('orders.closed') : t('orders.pay.done')); paying.after?.(); setPaying(null); refresh() }} />}
{(confirm === 'close' || confirm === 'writeOff') && (
<Dialog open size="sm" onClose={() => 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={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
{confirm === 'writeOff' && <Button variant="secondary" onClick={() => { setConfirm(null); setPaying({ ids: due, amount: sums.due, thenClose: true }) }}>{t('orders.payAndClose')}</Button>}
<Button variant={confirm === 'writeOff' ? 'danger' : 'primary'} loading={close.isPending} onClick={() => close.mutate()} data-testid="order-close-confirm">
{confirm === 'writeOff' ? t('orders.writeOff') : t('orders.close')}
</Button>
</>} />
)}
{confirm === 'cancel' && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t('orders.cancelTitle')} description={t('orders.cancelBody')}
footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('orders.back')}</Button>
<Button variant="secondary" loading={cancel.isPending && cancel.variables === false} onClick={() => cancel.mutate(false)} data-testid="order-cancel-confirm">{t('orders.lines.cancelNoPrint')}</Button>
<Button variant="danger" icon={<Printer size={16} />} loading={cancel.isPending && cancel.variables === true} onClick={() => cancel.mutate(true)}>{t('orders.lines.cancelPrint')}</Button>
</>} />
)}
</div>
)
}
@@ -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 (
<section className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3" data-testid="order-people">
<div className="grid gap-2">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.staff')}</h3>
<div className="flex flex-wrap items-center gap-2">
{order.waiters.length === 0 && <span className="text-label text-ink-3">{t('orders.people.noStaff')}</span>}
{order.waiters.map(w => (
<Pill key={w.waiter_id} tone="accent" data-testid="order-waiter">
{name(w.waiter_id)}
{open && (
<button type="button" className="ml-0.5 rounded-full hover:bg-surface-3" aria-label={t('orders.people.remove', { name: name(w.waiter_id) })}
onClick={() => remove.mutate(w.waiter_id)}><X size={12} /></button>
)}
</Pill>
))}
{open && addable.length > 0 && (
<Select size="sm" value="" placeholder={t('orders.people.add')} aria-label={t('orders.people.add')} data-testid="order-waiter-add"
onChange={e => e.target.value && add.mutate(Number(e.target.value))}
options={addable.map(s => ({ value: String(s.id), label: personName(s) }))} />
)}
</div>
</div>
{crm && <Customer order={order} open={open} onChanged={onChanged} />}
</section>
)
}
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 (
<div className="grid gap-2 border-t border-line pt-3">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.people.customer')}</h3>
{order.customer_id ? (
<div className="flex items-center gap-2 p-2 rounded-control bg-info-soft text-info-ink">
<UserRound size={16} aria-hidden="true" />
<span className="flex-1 min-w-0 grid">
<span className="text-label font-semibold truncate">{order.customer_name || `#${order.customer_id}`}</span>
{order.customer_phone && <span className="text-caption">{order.customer_phone}</span>}
</span>
{open && <IconButton size="sm" variant="ghost" label={t('orders.people.customerRemove')} onClick={() => set.mutate(null)}><X size={14} /></IconButton>}
</div>
) : !open ? <span className="text-label text-ink-3">{t('orders.people.noCustomer')}</span>
: !searching ? <Button size="sm" variant="secondary" onClick={() => setSearching(true)}>{t('orders.people.customerAdd')}</Button>
: (
<div className="grid gap-1">
<Input autoFocus value={q} onChange={e => setQ(e.target.value)} placeholder={t('orders.people.customerSearch')} aria-label={t('orders.people.customerSearch')} />
<ul className="max-h-52 overflow-y-auto rounded-control border border-line divide-y divide-line">
{found.length === 0 && <li className="px-3 py-2 text-label text-ink-3">{t('orders.people.customerNone')}</li>}
{found.map(c => (
<li key={c.id}>
<button type="button" className="w-full text-left px-3 py-2 hover:bg-surface-2 text-label" onClick={() => set.mutate(c.id)}>
<span className="font-semibold text-ink">{c.name}</span>
{c.phone && <span className="ml-2 text-ink-3">{c.phone}</span>}
</button>
</li>
))}
</ul>
<Button size="sm" variant="ghost" onClick={() => { setSearching(false); setQ('') }}>{t('orders.back')}</Button>
</div>
)}
</div>
)
}
@@ -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 (
<Dialog open size="sm" onClose={busy ? undefined : onClose}
title={thenClose ? t('orders.pay.closeTitle') : t('orders.pay.title', { count: itemIds.length })}
description={thenClose ? t('orders.pay.closeBody') : undefined}
footer={<Button variant="secondary" onClick={onClose} disabled={!!busy}>{t('orders.back')}</Button>}>
<div className="grid gap-3" data-testid="pay-dialog">
<div className="text-center text-display font-semibold tabular-nums text-ink" data-testid="pay-amount">{formatMoney(amount)}</div>
<div className="grid grid-cols-2 gap-2">
<Button size="lg" icon={<Banknote size={20} />} loading={busy === 'cash'} disabled={!!busy} onClick={() => pay('cash')} data-testid="pay-cash">
{t('orders.pay.cash')}
</Button>
<Button size="lg" variant="secondary" icon={<CreditCard size={20} />} loading={busy === 'card'} disabled={!!busy || !card}
onClick={() => pay('card')} data-testid="pay-card" title={card ? undefined : t('orders.pay.noCard')}>
{t('orders.pay.card')}
</Button>
</div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</div>
</Dialog>
)
}
@@ -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 (
<Dialog open size="sm" onClose={onClose} title={t('orders.quick.title', { table: tableName(table) })}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('orders.back')}</Button>
<Button loading={busy} disabled={notify && !message.trim()} onClick={save} data-testid="quick-save">{t('orders.quick.save')}</Button>
</>}>
<div className="grid gap-4" data-testid="quick-actions">
<Field label={t('orders.quick.flags')}>
{flagDefs.length === 0 ? <span className="text-label text-ink-3">{t('orders.quick.noFlags')}</span> : (
<span className="flex flex-wrap gap-1.5">
{flagDefs.map(f => (
<button key={f.id} type="button" aria-pressed={ids.includes(f.id)} onClick={() => 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 && <span aria-hidden="true">{f.emoji}</span>}{f.name}
</button>
))}
</span>
)}
</Field>
<label className="flex items-center gap-3 text-body text-ink">
<Switch checked={notify} onChange={setNotify} aria-label={t('orders.quick.notify')} />
{t('orders.quick.notify')}
</label>
{notify && (
<div className="grid gap-2">
{templates.length > 0 && (
<span className="flex flex-wrap gap-1.5">
{templates.slice(0, 6).map(tp => (
<Button key={tp.id} size="sm" variant={message === tp.body ? 'primary' : 'secondary'} onClick={() => setMessage(tp.body)}>{tp.body}</Button>
))}
</span>
)}
<Input value={message} maxLength={300} onChange={e => setMessage(e.target.value)} placeholder={t('orders.quick.message')} aria-label={t('orders.quick.message')} />
{order?.waiters?.length > 0 && (
<label className="flex items-center gap-3 text-label text-ink-2">
<Switch checked={toAll} onChange={setToAll} aria-label={t('orders.quick.toAll')} />
{toAll ? t('orders.quick.toAll') : t('orders.quick.toTable')}
</label>
)}
</div>
)}
</div>
</Dialog>
)
}
@@ -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 <div className="h-full grid place-items-center"><Spinner /></div>
return (
<div className="h-full overflow-y-auto p-4 lg:p-6 grid gap-4 content-start" data-testid="tables-page">
<div className="flex flex-wrap items-center gap-2">
<div className="flex rounded-control border border-line overflow-hidden" role="group">
{['list', 'map'].map(v => (
<button key={v} type="button" aria-pressed={view === v} onClick={() => 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}`)}
</button>
))}
</div>
<span className="flex-1" />
{view === 'list' && TABLE_STATES.map(s => (
<button key={s} type="button" aria-pressed={states.includes(s)} onClick={() => 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')}>
<span className={cx('w-2 h-2 rounded-full', SOLID[STATE_TONE[s]])} aria-hidden="true" />
{t(`overview.tableState.${s}`)}
<span className="tabular-nums text-ink">{cards.filter(c => c.state === s).length}</span>
</button>
))}
<Select size="sm" value={zone} onChange={e => setZone(e.target.value)} aria-label={t('orders.tables.zone')} data-testid="tables-zone">
<option value="">{t('orders.tables.allZones')}</option>
{groups.map(g => <option key={g.id} value={String(g.id)}>{g.name}</option>)}
<option value={NO_ZONE}>{t('orders.tables.noZone')}</option>
</Select>
</div>
{view === 'map' && (
<LiveFloor zone={zone && zone !== NO_ZONE ? Number(zone) : null} onOpen={id => navigate(`/orders/${id}`)} />
)}
{view === 'list' && (shown.length === 0
? <EmptyState title={t('orders.tables.none')} />
: (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(17rem,1fr))]">
{shown.map(card => (
<TableCard key={card.table.id} card={card} zone={groups.length > 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)} />
))}
</div>
))}
<PendingPrints cards={cards.filter(c => c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
</div>
)
}
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 (
<div className={cx('relative rounded-card border bg-surface shadow-raised overflow-hidden grid', BORDER[tone])} data-testid="table-card" data-state={state} data-table={table.id}>
<span className={cx('absolute inset-y-0 left-0 w-1.5', SOLID[tone])} aria-hidden="true" />
<button type="button" onClick={onOpen} className="text-left pl-5 pr-4 pt-3 pb-2 grid gap-2 hover:bg-surface-2 transition-colors duration-fast"
aria-label={t('orders.tables.open', { table: tableName(table), state: t(`overview.tableState.${state}`) })}>
<span className="flex items-start gap-2">
<span className="flex-1 grid gap-1">
<span className="text-display font-bold leading-none text-ink tabular-nums">{tableName(table)}</span>
{zone && <span className="text-caption text-ink-3">{zone}</span>}
</span>
<span className={cx('px-2 py-0.5 rounded-full text-caption font-semibold', SOFT[tone])}>{t(`overview.tableState.${state}`)}</span>
</span>
<span className="flex flex-wrap gap-1 min-h-6">
{pendingPrint && <Pill tone="warning"><Printer size={12} aria-hidden="true" />{t('orders.tables.notPrinted')}</Pill>}
{booking && (
<Pill tone="accent" data-testid="table-reserved" title={`${booking.guest_name} · ${booking.party_size}`}>
<Lock size={12} aria-hidden="true" />{t('orders.tables.reserved', { time: formatTime(booking.reserved_for), name: booking.guest_name })}
</Pill>
)}
{flags.slice(0, 3).map(f => (
<Pill key={f.id} tone="neutral">{f.emoji && <span aria-hidden="true">{f.emoji}</span>}{f.name}</Pill>
))}
{flags.length > 3 && <Pill tone="neutral" title={flags.slice(3).map(f => f.name).join(', ')}>+{flags.length - 3}</Pill>}
</span>
<span className="grid grid-cols-2 gap-2">
<span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.total')}</span>
{order ? <Money value={orderTotal(order.items)} className="text-title font-semibold text-ink" /> : <span className="text-title text-ink-3">—</span>}
</span>
<span className="grid">
<span className="text-caption font-semibold uppercase tracking-wide text-ink-3">{t('orders.tables.time')}</span>
<span className={cx('text-title tabular-nums inline-flex items-center gap-1', long ? 'font-bold text-warning-ink' : 'text-ink')}>
{order ? <><Clock size={14} aria-hidden="true" />{since(order.opened_at)}</> : <span className="text-ink-3">—</span>}
</span>
</span>
</span>
</button>
<div className="flex items-center gap-2 pl-5 pr-2 py-2 border-t border-line">
<span className="flex-1 min-w-0 truncate text-label text-ink-2">
{!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')}
</span>
<IconButton size="sm" variant="ghost" label={t('orders.quick.title', { table: tableName(table) })} onClick={onQuick} data-testid="table-quick"><Zap size={16} /></IconButton>
<Button size="sm" variant={order ? 'secondary' : 'primary'} onClick={onOpen} data-testid="table-open">{order ? t('orders.tables.view') : t('orders.tables.take')}</Button>
</div>
</div>
)
}
@@ -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}`)
@@ -14,6 +14,8 @@ import { useLiveQuery } from '../../live/useLiveQuery'
import { lineTotal, orderTotal } from './overviewLogic' import { lineTotal, orderTotal } from './overviewLogic'
import { Money, Pill } from './parts' import { Money, Pill } from './parts'
import { useDuration } from './hooks' 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 ORDER_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'order_refunded']
const STATUS_TONE = { open: 'success', partially_paid: 'info', paid: 'accent', closed: 'neutral', cancelled: 'danger' } 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 [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 [printCancel, setPrintCancel] = useState(null) // the same, after "yes": ask about the ticket
const [printerId, setPrinterId] = useState('') 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({ const { data: order, isPending } = useLiveQuery({
queryKey: ['order', orderId], queryKey: ['order', orderId],
@@ -52,7 +57,12 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
onSuccess: () => { toast.success(done); refresh(); after?.() }, onSuccess: () => { toast.success(done); refresh(); after?.() },
onError: err => toast.error(errorMessage(err, t)), 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 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 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)) 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 confirmed = () => {
const c = confirm const c = confirm
setConfirm(null) setConfirm(null)
if (c.kind === 'close') close.mutate() if (c.kind === 'close' || c.kind === 'writeOff') close.mutate()
else setPrintCancel(c) else setPrintCancel(c)
} }
const cancelWith = printIt => { const cancelWith = printIt => {
@@ -83,8 +93,8 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
</span>} </span>}
description={order ? t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at) }) : undefined} description={order ? t('overview.order.sub', { id: order.id, time: formatTime(order.opened_at), since: since(order.opened_at) }) : undefined}
footer={order && <div className="flex flex-wrap items-center gap-2 w-full"> footer={order && <div className="flex flex-wrap items-center gap-2 w-full">
{isOpen && active.length > 0 && <Button onClick={() => pay.mutate(active.map(i => i.id))} loading={pay.isPending} data-testid="order-pay-all">{t('overview.order.payAll')}</Button>} {isOpen && active.length > 0 && <Button onClick={() => pay(active.map(i => i.id))} data-testid="order-pay-all">{t('overview.order.payAll')}</Button>}
{isOpen && <Button variant="secondary" onClick={() => setConfirm({ kind: 'close' })}>{t('overview.order.close')}</Button>} {isOpen && <Button variant="secondary" onClick={startClose} data-testid="order-close">{t('overview.order.close')}</Button>}
{isOpen && <Button variant="danger" onClick={() => setConfirm({ kind: 'cancelOrder' })}>{t('overview.order.cancel')}</Button>} {isOpen && <Button variant="danger" onClick={() => setConfirm({ kind: 'cancelOrder' })}>{t('overview.order.cancel')}</Button>}
<span className="flex-1" /> <span className="flex-1" />
{printers.length > 0 && ( {printers.length > 0 && (
@@ -125,7 +135,7 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
</div> </div>
<Money value={lineTotal(item)} className={cx('text-body font-semibold min-w-16 text-right', item.price_adjustment ? 'text-info-ink' : 'text-ink')} /> <Money value={lineTotal(item)} className={cx('text-body font-semibold min-w-16 text-right', item.price_adjustment ? 'text-info-ink' : 'text-ink')} />
{isOpen && item.status === 'active' && (<> {isOpen && item.status === 'active' && (<>
<Button size="sm" variant="secondary" onClick={() => pay.mutate([item.id])}>{t('overview.order.pay')}</Button> <Button size="sm" variant="secondary" onClick={() => pay([item.id])}>{t('overview.order.pay')}</Button>
<IconButton size="sm" variant="ghost" label={t('overview.order.cancelLine')} onClick={() => setConfirm({ kind: 'cancelItem', itemId: item.id })}><X size={16} /></IconButton> <IconButton size="sm" variant="ghost" label={t('overview.order.cancelLine')} onClick={() => setConfirm({ kind: 'cancelItem', itemId: item.id })}><X size={16} /></IconButton>
</>)} </>)}
</div> </div>
@@ -146,16 +156,28 @@ export default function OrderDialog({ orderId, tableName, onClose, onOpenFull })
)} )}
{confirm && ( {confirm && (
<Dialog open size="sm" onClose={() => setConfirm(null)} title={t(`overview.order.confirm.${confirm.kind}`)} <Dialog open size="sm" onClose={() => setConfirm(null)} title={confirm.kind === 'writeOff' ? t('orders.writeOffTitle') : t(`overview.order.confirm.${confirm.kind}`)}
footer={<> footer={<>
<Button variant="secondary" onClick={() => setConfirm(null)}>{t('overview.back')}</Button> <Button variant="secondary" onClick={() => setConfirm(null)}>{t('overview.back')}</Button>
<Button variant={confirm.kind === 'close' ? 'primary' : 'danger'} onClick={confirmed} data-testid="order-confirm"> <Button variant={confirm.kind === 'close' ? 'primary' : 'danger'} onClick={confirmed} data-testid="order-confirm">
{confirm.kind === 'close' ? t('overview.order.close') : t('overview.order.cancel')} {confirm.kind === 'close' ? t('overview.order.close') : confirm.kind === 'writeOff' ? t('orders.writeOff') : t('overview.order.cancel')}
</Button> </Button>
</>}> </>}>
{confirm.kind === 'cancelOrder' && <p>{t('overview.order.confirm.cancelOrderBody')}</p>} {confirm.kind === 'cancelOrder' && <p>{t('overview.order.confirm.cancelOrderBody')}</p>}
{confirm.kind === 'writeOff' && <p>{t('orders.writeOffBody', { count: unpaidIds(order).length, amount: formatMoney(selectedAmount(order, unpaidIds(order))) })}</p>}
</Dialog> </Dialog>
)} )}
{paying && order && (
<PayDialog orderId={orderId} itemIds={paying.ids} amount={selectedAmount(order, paying.ids)} card={venue.card} thenClose={!!paying.thenClose}
onClose={() => setPaying(null)}
onDone={() => {
toast.success(paying.thenClose ? t('overview.order.closed') : t('overview.order.paidDone'))
const closed = paying.thenClose
setPaying(null)
refresh()
if (closed) onClose()
}} />
)}
{printCancel && ( {printCancel && (
<Dialog open size="sm" onClose={() => setPrintCancel(null)} title={t('overview.order.printCancel')} <Dialog open size="sm" onClose={() => setPrintCancel(null)} title={t('overview.order.printCancel')}
footer={<> footer={<>
@@ -1,54 +0,0 @@
import { X } from 'lucide-react'
const METHODS = [
{ key: 'cash', label: 'ΜΕΤΡΗΤΑ', icon: '💵', color: '#15803d', bg: '#f0fdf4', border: '#86efac' },
{ key: 'card', label: 'ΚΑΡΤΑ', icon: '💳', color: '#1d4ed8', bg: '#eff6ff', border: '#93c5fd' },
{ key: 'transfer', label: 'ΤΡΑΠΕΖΙΚΗ ΜΕΤΑΦΟΡΑ', icon: '🏦', color: '#6d28d9', bg: '#f5f3ff', border: '#c4b5fd' },
{ key: 'treat', label: 'ΚΕΡΑΣΤΗΚΕ', icon: '🎁', color: '#b45309', bg: '#fffbeb', border: '#fcd34d' },
]
export default function PaymentMethodModal({ onSelect, onCancel, title = 'Τρόπος Πληρωμής;' }) {
return (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4"
onClick={onCancel}
>
<div
className="w-full max-w-sm rounded-2xl bg-white shadow-2xl"
onClick={e => e.stopPropagation()}
>
{/* Header */}
<div className="flex items-center justify-between px-5 py-4 border-b border-gray-100">
<span className="text-base font-bold text-gray-800">{title}</span>
<button onClick={onCancel} className="text-gray-400 hover:text-gray-600 p-1">
<X size={16} />
</button>
</div>
{/* Method buttons */}
<div className="p-4 grid grid-cols-2 gap-3">
{METHODS.map(m => (
<button
key={m.key}
onClick={() => onSelect(m.key)}
style={{ background: m.bg, borderColor: m.border, color: m.color }}
className="flex flex-col items-center justify-center gap-2 rounded-xl border-2 py-5 font-bold text-sm transition-transform active:scale-95 hover:opacity-90"
>
<span className="text-2xl">{m.icon}</span>
{m.label}
</button>
))}
</div>
<div className="px-4 pb-4">
<button
onClick={onCancel}
className="w-full rounded-lg border border-gray-200 py-2 text-sm text-gray-500 hover:bg-gray-50"
>
Ακύρωση
</button>
</div>
</div>
</div>
)
}
+1 -1
View File
@@ -4,7 +4,7 @@ import xenia from '@xenia/ui/tailwind-preset'
export default { export default {
// Shared design tokens (bg-surface, text-ink-2, rounded-control…); adds names only // Shared design tokens (bg-surface, text-ink-2, rounded-control…); adds names only
presets: [xenia], presets: [xenia],
content: ['./index.html', './src/**/*.{js,jsx}', '../packages/signage/src/**/*.{js,jsx}'], // signage slides use a few utilities (5.6a) content: ['./index.html', './src/**/*.{js,jsx}', '../packages/signage/src/**/*.{js,jsx}', '../packages/ordering/src/**/*.{js,jsx}'], // signage slides use a few utilities (5.6a)
theme: { theme: {
extend: { extend: {
fontFamily: { fontFamily: {
+56
View File
@@ -0,0 +1,56 @@
// The manager's tables and orders (plan step 6.9): the phones' rules as plain data.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
NO_ZONE, addableWaiters, cardTarget, closeStep, filterCards, flagsByTable, lineDetails, selectable, selectedAmount, sendBody,
shownLines, toggleSelected, totals, unpaidIds, venueRules,
} from '../src/pages/orders/orderLogic.js'
const item = (id, status, price, qty = 1, extra = {}) => ({ id, status, unit_price: price, price_adjustment: 0, quantity: qty, added_at: `2026-11-18T10:0${id}:00Z`, ...extra })
const order = { status: 'partially_paid', items: [item(1, 'paid', 5), item(2, 'active', 3, 2), item(3, 'cancelled', 9), item(4, 'active', 2, 1, { price_adjustment: -0.5 })] }
test('sums: total without cancelled lines, paid, due', () => {
assert.deepEqual(totals(order), { total: 12.5, paid: 5, due: 7.5 })
assert.deepEqual(unpaidIds(order), [2, 4])
assert.equal(selectedAmount(order, [2]), 6)
})
test('lines in the order they came, cancelled last; only unpaid ones can be picked', () => {
assert.deepEqual(shownLines(order).map(i => i.id), [1, 2, 4, 3])
assert.deepEqual(shownLines(order, { showCancelled: false }).map(i => i.id), [1, 2, 4])
assert.equal(selectable(order.items[0]), false)
assert.equal(selectable(order.items[1]), true)
assert.deepEqual(toggleSelected(toggleSelected([], 2), 4), [2, 4])
assert.deepEqual(toggleSelected([2, 4], 2), [4])
})
test('close: nothing unpaid closes; unpaid lines are paid first unless the venue writes them off', () => {
assert.equal(closeStep(order, false), 'payFirst')
assert.equal(closeStep(order, true), 'writeOff')
assert.equal(closeStep({ items: [item(1, 'paid', 5)] }, false), 'close')
assert.deepEqual(venueRules({ 'orders.close_with_unpaid': { value: 'true' } }), { closeWithUnpaid: true, card: true })
assert.deepEqual(venueRules({ 'payments.card_enabled': { value: 'false' } }), { closeWithUnpaid: false, card: false })
})
test('what a line has, the body sent (ids only), waiters to add', () => {
const d = lineDetails({ selected_options: JSON.stringify([{ name: 'Well done' }, 'Fries']), removed_ingredients: '["Onion"]', notes: 'no salt' })
assert.deepEqual(d, { choices: ['Well done', 'Fries'], removed: ['Onion'], note: 'no salt' })
assert.deepEqual(lineDetails({ selected_options: 'not json' }).choices, [])
assert.deepEqual(sendBody([{ line: { product_id: 1, quantity: 2 } }], ' '), { lines: [{ product_id: 1, quantity: 2 }], order_note: null })
const staff = [{ id: 1 }, { id: 2 }, { id: 3, is_active: false }]
assert.deepEqual(addableWaiters(staff, { waiters: [{ waiter_id: 1 }] }).map(s => s.id), [2])
})
test('tables: filters by state and zone, flags per table, where a card goes', () => {
const cards = [
{ table: { id: 1, group_id: 10 }, state: 'open', order: { id: 7 } },
{ table: { id: 2, group_id: null }, state: 'free', order: null },
{ table: { id: 3, group_id: 11 }, state: 'free', order: null },
]
assert.deepEqual(filterCards(cards, { states: ['free'] }).map(c => c.table.id), [2, 3])
assert.deepEqual(filterCards(cards, { zone: NO_ZONE }).map(c => c.table.id), [2])
assert.deepEqual(filterCards(cards, { zone: '11', states: ['free'] }).map(c => c.table.id), [3])
assert.deepEqual(flagsByTable([{ id: 1, name: 'VIP' }], [{ flag_id: 1, table_id: 2, assigned_at: 'x' }, { flag_id: 9, table_id: 2 }]), { 2: [{ id: 1, name: 'VIP', assigned_at: 'x' }] })
assert.equal(cardTarget(cards[0]), '/orders/7')
assert.equal(cardTarget(cards[1]), '/orders/new?table=2')
})
+2 -2
View File
@@ -1,9 +1,9 @@
{ {
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.", "_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [ "paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx" "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders"
], ],
"strict": [ "strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor" "src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders"
] ]
} }
+19
View File
@@ -21,6 +21,7 @@
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0", "@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/signage": "^0.0.0", "@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
@@ -3225,6 +3226,10 @@
"resolved": "packages/i18n", "resolved": "packages/i18n",
"link": true "link": true
}, },
"node_modules/@xenia/ordering": {
"resolved": "packages/ordering",
"link": true
},
"node_modules/@xenia/signage": { "node_modules/@xenia/signage": {
"resolved": "packages/signage", "resolved": "packages/signage",
"link": true "link": true
@@ -9592,6 +9597,19 @@
"react": "^19.0.0" "react": "^19.0.0"
} }
}, },
"packages/ordering": {
"name": "@xenia/ordering",
"version": "0.0.0",
"dependencies": {
"@xenia/access": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"lucide-react": "^1.73.0"
},
"peerDependencies": {
"react": "^19.0.0"
}
},
"packages/signage": { "packages/signage": {
"name": "@xenia/signage", "name": "@xenia/signage",
"version": "0.0.0", "version": "0.0.0",
@@ -9619,6 +9637,7 @@
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0", "@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/signage": "^0.0.0", "@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
+13
View File
@@ -117,5 +117,18 @@
"paid": "Πληρωμένο", "paid": "Πληρωμένο",
"reserved": "Κράτηση σύντομα" "reserved": "Κράτηση σύντομα"
} }
},
"ordering": {
"dialog": {
"close": "Κλείσιμο",
"add": "Στο καλάθι",
"pickOne": "επιλέξτε ένα",
"quick": "Προσθήκες",
"extras": "Έξτρα",
"without": "Χωρίς",
"note": "Σημείωση για την κουζίνα",
"quantity": "Ποσότητα",
"missing": "Μένει να επιλέξετε: {{list}}"
}
} }
} }
+2 -1
View File
@@ -157,7 +157,8 @@
"not_found": "Η κράτηση {{reservation_id}} δεν βρέθηκε.", "not_found": "Η κράτηση {{reservation_id}} δεν βρέθηκε.",
"status_changed": "Η κράτηση άλλαξε από άλλη οθόνη στο μεταξύ (τώρα είναι {{current}}).", "status_changed": "Η κράτηση άλλαξε από άλλη οθόνη στο μεταξύ (τώρα είναι {{current}}).",
"table_unknown": "Το τραπέζι {{table_id}} δεν βρέθηκε.", "table_unknown": "Το τραπέζι {{table_id}} δεν βρέθηκε.",
"table_busy": "Αυτό το τραπέζι έχει ήδη ανοιχτή παραγγελία. Διαλέξτε άλλο τραπέζι ή κλείστε πρώτα εκείνη την παραγγελία." "table_busy": "Αυτό το τραπέζι έχει ήδη ανοιχτή παραγγελία. Διαλέξτε άλλο τραπέζι ή κλείστε πρώτα εκείνη την παραγγελία.",
"table_kept": "Αυτό το τραπέζι είναι ήδη κρατημένο για {{name}} στις {{time}}."
}, },
"display": { "display": {
"qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός.", "qr_url_missing": "Γράψτε τον σύνδεσμο που ανοίγει ο QR κωδικός.",
+172
View File
@@ -2182,5 +2182,177 @@
"rotateRight": "Στροφή δεξιά 15°", "rotateRight": "Στροφή δεξιά 15°",
"takeOff": "Βγάλτε το από την κάτοψη", "takeOff": "Βγάλτε το από την κάτοψη",
"removeThing": "Αφαίρεση" "removeThing": "Αφαίρεση"
},
"orders": {
"back": "Πίσω",
"toTables": "Τραπέζια",
"title": "Τραπέζι {{table}}",
"titleNoTable": "Παραγγελία #{{id}}",
"newTitle": "Τραπέζι {{table}}: νέα παραγγελία",
"newHint": "Επιλέξτε τι παραγγέλνουν και στείλτε το: η παραγγελία ανοίγει με την πρώτη αποστολή.",
"notFound": "Η παραγγελία δεν βρέθηκε.",
"total": "Σύνολο",
"paid": "Πληρώθηκαν",
"due": "Μένουν",
"tabs": {
"order": "Παραγγελία",
"prices": "Αλλαγές τιμών",
"history": "Ιστορικό"
},
"payAll": "Πληρωμή όλων",
"close": "Κλείσιμο",
"cancel": "Ακύρωση παραγγελίας",
"closed": "Η παραγγελία έκλεισε",
"cancelled": "Η παραγγελία ακυρώθηκε",
"confirmClose": "Κλείσιμο παραγγελίας;",
"writeOffTitle": "Κλείσιμο με απλήρωτα;",
"writeOffBody_one": "{{count}} γραμμή ({{amount}}) δεν έχει πληρωθεί. Με το κλείσιμο διαγράφεται: μετράει ως απλήρωτη στις αναφορές.",
"writeOffBody_other": "{{count}} γραμμές ({{amount}}) δεν έχουν πληρωθεί. Με το κλείσιμο διαγράφονται: μετράνε ως απλήρωτες στις αναφορές.",
"writeOff": "Κλείσιμο χωρίς πληρωμή",
"payAndClose": "Πληρωμή και κλείσιμο",
"cancelTitle": "Ακύρωση όλης της παραγγελίας;",
"cancelBody": "Ακυρώνεται κάθε απλήρωτη γραμμή. Να τυπωθεί δελτίο ακύρωσης για την κουζίνα;",
"printer": "Εκτυπωτής…",
"print": "Εκτύπωση",
"printing": "Στάλθηκε στον εκτυπωτή…",
"pay": {
"title_one": "Πληρωμή {{count}} γραμμής",
"title_other": "Πληρωμή {{count}} γραμμών",
"closeTitle": "Πληρωμή υπολοίπου και κλείσιμο",
"closeBody": "Σε αυτό το κατάστημα η πληρωμή γίνεται πριν κλείσει η παραγγελία (Ρυθμίσεις: κλείσιμο με απλήρωτα).",
"cash": "Μετρητά",
"card": "Κάρτα",
"noCard": "Το κατάστημα δεν δέχεται κάρτες (Ρυθμίσεις).",
"done": "Πληρώθηκε",
"method": {
"cash": "Μετρητά",
"card": "Κάρτα",
"transfer": "Τραπεζική",
"treat": "Κεράστηκε",
"comp": "Κεράστηκε",
"other": "Άλλο"
}
},
"lines": {
"none": "Δεν έχει παραγγελθεί τίποτα ακόμη.",
"pick": "Επιλογή {{name}}",
"free": "ΔΩΡΕΑΝ",
"notPrinted": "Δεν τυπώθηκε",
"status": {
"paid": "Πληρώθηκε",
"cancelled": "Ακυρώθηκε",
"tabbed": "Στην καρτέλα",
"closed": "Απλήρωτο"
},
"without": "Χωρίς {{list}}",
"added": "{{time}} · {{name}}",
"paidBy": "πλήρωσε: {{name}}",
"each": "{{price}} το ένα",
"picked_one": "{{count}} γραμμή · {{amount}}",
"picked_other": "{{count}} γραμμές · {{amount}}",
"clear": "Καθαρισμός",
"toTab": "Στην καρτέλα",
"tabbed": "Πέρασε στην καρτέλα του πελάτη",
"discount": "Έκπτωση",
"cancel": "Ακύρωση",
"pay": "Πληρωμή",
"cancelTitle_one": "Ακύρωση {{count}} γραμμής;",
"cancelTitle_other": "Ακύρωση {{count}} γραμμών;",
"cancelBody": "Να τυπωθεί δελτίο ακύρωσης για την κουζίνα;",
"cancelNoPrint": "Ακύρωση χωρίς δελτίο",
"cancelPrint": "Ακύρωση και εκτύπωση",
"cancelled_one": "Ακυρώθηκε {{count}} γραμμή",
"cancelled_other": "Ακυρώθηκαν {{count}} γραμμές"
},
"discount": {
"title_one": "Έκπτωση σε {{count}} γραμμή",
"title_other": "Έκπτωση σε {{count}} γραμμές",
"body": "Ποσοστό έκπτωσης· η νέα τιμή στρογγυλεύει στα 0,10. Ισχύουν τα όριά σας.",
"pct": "Έκπτωση (%)",
"about": "Περίπου {{amount}}",
"note": "Αιτία (προαιρετικά)",
"apply": "Εφαρμογή",
"done": "Η έκπτωση εφαρμόστηκε"
},
"people": {
"staff": "Προσωπικό",
"noStaff": "Κανείς ακόμη.",
"add": "Προσθήκη…",
"remove": "Αφαίρεση {{name}}",
"customer": "Πελάτης",
"noCustomer": "Χωρίς πελάτη.",
"customerAdd": "Ανάθεση πελάτη",
"customerSearch": "Αναζήτηση με όνομα ή τηλέφωνο…",
"customerNone": "Δεν βρέθηκαν πελάτες.",
"customerRemove": "Αφαίρεση πελάτη"
},
"history": {
"none": "Δεν υπάρχουν εγγραφές.",
"noPrices": "Καμία αλλαγή τιμής σε αυτή την παραγγελία.",
"duplicate": "ΔΙΠΛΗ",
"offline": "offline",
"by": "από {{name}}",
"event": {
"ORDER_OPENED": "Άνοιγμα",
"ITEMS_ADDED": "Προσθήκη",
"PAYMENT": "Πληρωμή",
"PAYMENT_OFFLINE": "Πληρωμή (offline)",
"ORDER_CLOSED": "Κλείσιμο",
"ORDER_CANCELLED": "Ακύρωση",
"ITEM_CANCELLED": "Ακύρωση γραμμής"
},
"price": {
"modifier_applied": "Κανόνας τιμής",
"deal_triggered": "Προσφορά",
"deal_offer_shown": "Προσφορά (εμφανίστηκε)",
"deal_offer_accepted": "Προσφορά (αποδεκτή)",
"deal_offer_dismissed": "Προσφορά (απορρίφθηκε)",
"waiter_discount": "Έκπτωση",
"free_item_added": "Δωρεάν προϊόν"
}
},
"add": {
"search": "Αναζήτηση στο μενού…",
"all": "Όλα",
"service": "Σέρβις",
"nothing": "Τίποτα εδώ.",
"soldOut": "Εξαντλήθηκε",
"toSend": "Για αποστολή",
"empty": "Πατήστε ένα προϊόν για να το προσθέσετε.",
"less": "Ένα λιγότερο",
"more": "Ένα ακόμη",
"note": "Σημείωση για όλη την παραγγελία (προαιρετικά)",
"clear": "Καθαρισμός",
"send": "Αποστολή",
"sent": "Στάλθηκε στην κουζίνα",
"notPrinted": "Στάλθηκε, αλλά δεν τυπώθηκε σε: {{printers}}"
},
"tables": {
"zone": "Ζώνη",
"allZones": "Όλες οι ζώνες",
"noZone": "Χωρίς ζώνη",
"none": "Δεν βρέθηκαν τραπέζια.",
"open": "Τραπέζι {{table}}, {{state}}",
"notPrinted": "Δεν τυπώθηκε",
"reserved": "Κράτηση {{time}} · {{name}}",
"time": "Χρόνος",
"seats_one": "{{count}} θέση",
"seats_other": "{{count}} θέσεις",
"noWaiter": "Χωρίς σερβιτόρο",
"view": "Άνοιγμα",
"take": "Νέα παραγγελία"
},
"quick": {
"title": "Τραπέζι {{table}}: γρήγορες ενέργειες",
"flags": "Σημαίες",
"noFlags": "Δεν υπάρχουν σημαίες ακόμη (Ρυθμίσεις).",
"notify": "Ειδοποίηση σερβιτόρων",
"message": "Ή γράψτε μήνυμα…",
"toAll": "Σε όλους",
"toTable": "Στους σερβιτόρους του τραπεζιού",
"save": "Αποθήκευση",
"saved": "Οι σημαίες αποθηκεύτηκαν",
"sent": "Σημαίες αποθηκεύτηκαν και το μήνυμα στάλθηκε"
}
} }
} }
+7 -12
View File
@@ -183,17 +183,6 @@
"less": "Ένα λιγότερο", "less": "Ένα λιγότερο",
"more": "Ένα ακόμη", "more": "Ένα ακόμη",
"each": "{{price}} το ένα", "each": "{{price}} το ένα",
"dialog": {
"close": "Κλείσιμο",
"add": "Στο καλάθι",
"pickOne": "επιλέξτε ένα",
"quick": "Προσθήκες",
"extras": "Έξτρα",
"without": "Χωρίς",
"note": "Σημείωση για την κουζίνα",
"quantity": "Ποσότητα",
"missing": "Μένει να επιλέξετε: {{list}}"
},
"gate": { "gate": {
"dayClosed": "Η ημέρα εργασίας δεν έχει ανοίξει", "dayClosed": "Η ημέρα εργασίας δεν έχει ανοίξει",
"dayOpeners": "Ζητήστε από κάποιον που μπορεί να την ανοίξει: {{names}}.", "dayOpeners": "Ζητήστε από κάποιον που μπορεί να την ανοίξει: {{names}}.",
@@ -463,7 +452,10 @@
"noTable": "Χωρίς τραπέζι ακόμα", "noTable": "Χωρίς τραπέζι ακόμα",
"arrive": "Ήρθαν: καθίστε τους", "arrive": "Ήρθαν: καθίστε τους",
"cancel": "Ακύρωση", "cancel": "Ακύρωση",
"noShow": "Δεν ήρθαν" "noShow": "Δεν ήρθαν",
"keep": "Κράτηση αυτού του τραπεζιού",
"release": "Χωρίς κρατημένο τραπέζι",
"busyNow": "πιασμένο τώρα"
}, },
"call": { "call": {
"title": "Εισερχόμενη κλήση", "title": "Εισερχόμενη κλήση",
@@ -471,6 +463,9 @@
"takeaway": "Νέα πώληση για παραλαβή", "takeaway": "Νέα πώληση για παραλαβή",
"visits_one": "{{count}} επίσκεψη · {{spent}}", "visits_one": "{{count}} επίσκεψη · {{spent}}",
"visits_other": "{{count}} επισκέψεις · {{spent}}" "visits_other": "{{count}} επισκέψεις · {{spent}}"
},
"dialog": {
"close": "Κλείσιμο"
} }
}, },
"display": { "display": {
+4 -1
View File
@@ -841,7 +841,10 @@
"closed": "Είμαστε κλειστά τότε", "closed": "Είμαστε κλειστά τότε",
"party": "Ιδιωτική εκδήλωση", "party": "Ιδιωτική εκδήλωση",
"other": "Άλλος λόγος" "other": "Άλλος λόγος"
} },
"keep": "Κράτηση αυτού του τραπεζιού",
"release": "Χωρίς κρατημένο τραπέζι",
"busyNow": "πιασμένο τώρα"
}, },
"tabletOrder": { "tabletOrder": {
"title": "Παραγγελία από το tablet", "title": "Παραγγελία από το tablet",
+13
View File
@@ -117,5 +117,18 @@
"paid": "Paid", "paid": "Paid",
"reserved": "Booked soon" "reserved": "Booked soon"
} }
},
"ordering": {
"dialog": {
"close": "Close",
"add": "Add to cart",
"pickOne": "choose one",
"quick": "Add-ons",
"extras": "Extras",
"without": "Without",
"note": "Note for the kitchen",
"quantity": "Quantity",
"missing": "Still to choose: {{list}}"
}
} }
} }
+2 -1
View File
@@ -157,7 +157,8 @@
"not_found": "Booking {{reservation_id}} not found.", "not_found": "Booking {{reservation_id}} not found.",
"status_changed": "This booking was changed on another screen in the meantime (it is now {{current}}).", "status_changed": "This booking was changed on another screen in the meantime (it is now {{current}}).",
"table_unknown": "Table {{table_id}} not found.", "table_unknown": "Table {{table_id}} not found.",
"table_busy": "That table already has an open order. Pick another table, or close that order first." "table_busy": "That table already has an open order. Pick another table, or close that order first.",
"table_kept": "That table is already kept for {{name}} at {{time}}."
}, },
"display": { "display": {
"qr_url_missing": "Enter the link the QR code opens.", "qr_url_missing": "Enter the link the QR code opens.",
+172
View File
@@ -2182,5 +2182,177 @@
"rotateRight": "Turn right 15°", "rotateRight": "Turn right 15°",
"takeOff": "Take it off the plan", "takeOff": "Take it off the plan",
"removeThing": "Remove" "removeThing": "Remove"
},
"orders": {
"back": "Back",
"toTables": "Tables",
"title": "Table {{table}}",
"titleNoTable": "Order #{{id}}",
"newTitle": "Table {{table}}: new order",
"newHint": "Pick what they order and send it: the order opens with the first send.",
"notFound": "This order can't be found.",
"total": "Total",
"paid": "Paid",
"due": "Still to pay",
"tabs": {
"order": "Order",
"prices": "Price changes",
"history": "History"
},
"payAll": "Pay everything",
"close": "Close",
"cancel": "Cancel order",
"closed": "Order closed",
"cancelled": "Order cancelled",
"confirmClose": "Close the order?",
"writeOffTitle": "Close with unpaid items?",
"writeOffBody_one": "{{count}} line ({{amount}}) is not paid. Closing writes it off: it counts as not paid in the reports.",
"writeOffBody_other": "{{count}} lines ({{amount}}) are not paid. Closing writes them off: they count as not paid in the reports.",
"writeOff": "Close without paying",
"payAndClose": "Take the payment and close",
"cancelTitle": "Cancel the whole order?",
"cancelBody": "Every line not paid is cancelled. Should the kitchen get a cancellation ticket?",
"printer": "Printer…",
"print": "Print",
"printing": "Sent to the printer…",
"pay": {
"title_one": "Pay {{count}} line",
"title_other": "Pay {{count}} lines",
"closeTitle": "Pay the rest and close",
"closeBody": "This venue takes the payment before an order closes (Settings: close with unpaid items).",
"cash": "Cash",
"card": "Card",
"noCard": "The venue doesn't take cards (Settings).",
"done": "Paid",
"method": {
"cash": "Cash",
"card": "Card",
"transfer": "Transfer",
"treat": "On the house",
"comp": "On the house",
"other": "Other"
}
},
"lines": {
"none": "Nothing ordered yet.",
"pick": "Pick {{name}}",
"free": "FREE",
"notPrinted": "Not printed",
"status": {
"paid": "Paid",
"cancelled": "Cancelled",
"tabbed": "On the tab",
"closed": "Written off"
},
"without": "Without {{list}}",
"added": "{{time}} · {{name}}",
"paidBy": "paid by {{name}}",
"each": "{{price}} each",
"picked_one": "{{count}} line picked · {{amount}}",
"picked_other": "{{count}} lines picked · {{amount}}",
"clear": "Clear",
"toTab": "On the tab",
"tabbed": "Put on the customer's tab",
"discount": "Discount",
"cancel": "Cancel",
"pay": "Pay",
"cancelTitle_one": "Cancel {{count}} line?",
"cancelTitle_other": "Cancel {{count}} lines?",
"cancelBody": "Should the kitchen get a cancellation ticket?",
"cancelNoPrint": "Cancel, no ticket",
"cancelPrint": "Cancel and print",
"cancelled_one": "{{count}} line cancelled",
"cancelled_other": "{{count}} lines cancelled"
},
"discount": {
"title_one": "Discount on {{count}} line",
"title_other": "Discount on {{count}} lines",
"body": "A percentage off; the new price rounds to the nearest 0.10. Your discount limits apply.",
"pct": "Discount (%)",
"about": "About {{amount}}",
"note": "Why (optional)",
"apply": "Apply",
"done": "Discount applied"
},
"people": {
"staff": "Staff",
"noStaff": "No one yet.",
"add": "Add someone…",
"remove": "Take {{name}} off",
"customer": "Customer",
"noCustomer": "No customer.",
"customerAdd": "Add a customer",
"customerSearch": "Search by name or phone…",
"customerNone": "No customers found.",
"customerRemove": "Take the customer off"
},
"history": {
"none": "Nothing recorded.",
"noPrices": "No price changes on this order.",
"duplicate": "COUNTED TWICE",
"offline": "offline",
"by": "by {{name}}",
"event": {
"ORDER_OPENED": "Opened",
"ITEMS_ADDED": "Added",
"PAYMENT": "Payment",
"PAYMENT_OFFLINE": "Payment (offline)",
"ORDER_CLOSED": "Closed",
"ORDER_CANCELLED": "Cancelled",
"ITEM_CANCELLED": "Line cancelled"
},
"price": {
"modifier_applied": "Price rule",
"deal_triggered": "Deal",
"deal_offer_shown": "Deal offered",
"deal_offer_accepted": "Deal accepted",
"deal_offer_dismissed": "Deal declined",
"waiter_discount": "Discount",
"free_item_added": "Free item"
}
},
"add": {
"search": "Search the menu…",
"all": "All",
"service": "Service",
"nothing": "Nothing here.",
"soldOut": "Sold out",
"toSend": "To send",
"empty": "Tap a product to add it.",
"less": "One less",
"more": "One more",
"note": "Note for the whole order (optional)",
"clear": "Clear",
"send": "Send",
"sent": "Sent to the kitchen",
"notPrinted": "Sent, but not printed on: {{printers}}"
},
"tables": {
"zone": "Zone",
"allZones": "All zones",
"noZone": "No zone",
"none": "No tables match.",
"open": "Table {{table}}, {{state}}",
"notPrinted": "Not printed",
"reserved": "Booked {{time}} · {{name}}",
"time": "Time",
"seats_one": "{{count}} seat",
"seats_other": "{{count}} seats",
"noWaiter": "No waiter",
"view": "Open",
"take": "Take an order"
},
"quick": {
"title": "Table {{table}}: quick actions",
"flags": "Flags",
"noFlags": "No flags yet (Settings).",
"notify": "Tell the waiters",
"message": "Or type a message…",
"toAll": "To everyone",
"toTable": "To this table's waiters",
"save": "Save",
"saved": "Flags saved",
"sent": "Flags saved and message sent"
}
} }
} }
+7 -12
View File
@@ -183,17 +183,6 @@
"less": "One less", "less": "One less",
"more": "One more", "more": "One more",
"each": "{{price}} each", "each": "{{price}} each",
"dialog": {
"close": "Close",
"add": "Add to cart",
"pickOne": "choose one",
"quick": "Add-ons",
"extras": "Extras",
"without": "Without",
"note": "Note for the kitchen",
"quantity": "Quantity",
"missing": "Still to choose: {{list}}"
},
"gate": { "gate": {
"dayClosed": "The business day isn't open", "dayClosed": "The business day isn't open",
"dayOpeners": "Ask someone who can open it: {{names}}.", "dayOpeners": "Ask someone who can open it: {{names}}.",
@@ -463,7 +452,10 @@
"noTable": "No table yet", "noTable": "No table yet",
"arrive": "They're here: seat them", "arrive": "They're here: seat them",
"cancel": "Cancel", "cancel": "Cancel",
"noShow": "No-show" "noShow": "No-show",
"keep": "Keep this table for them",
"release": "Don't keep a table",
"busyNow": "busy now"
}, },
"call": { "call": {
"title": "Incoming call", "title": "Incoming call",
@@ -471,6 +463,9 @@
"takeaway": "New takeaway sale", "takeaway": "New takeaway sale",
"visits_one": "{{count}} visit · {{spent}}", "visits_one": "{{count}} visit · {{spent}}",
"visits_other": "{{count}} visits · {{spent}}" "visits_other": "{{count}} visits · {{spent}}"
},
"dialog": {
"close": "Close"
} }
}, },
"display": { "display": {
+4 -1
View File
@@ -841,7 +841,10 @@
"closed": "We're closed then", "closed": "We're closed then",
"party": "Private event", "party": "Private event",
"other": "Other reason" "other": "Other reason"
} },
"keep": "Keep this table for them",
"release": "Don't keep a table",
"busyNow": "busy now"
}, },
"tabletOrder": { "tabletOrder": {
"title": "Ordered from the tablet", "title": "Ordered from the tablet",
+24
View File
@@ -0,0 +1,24 @@
{
"name": "@xenia/ordering",
"version": "0.0.0",
"private": true,
"type": "module",
"description": "A product's choices and the cart's rules as lines the server prices (plan steps 3.3a, 6.9): the product dialog, the quote hook and the pure cart rules, shared by the counter POS, the menu tablet and the manager.",
"main": "src/index.js",
"exports": {
".": "./src/index.js",
"./cart": "./src/cart.js"
},
"dependencies": {
"@xenia/access": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"lucide-react": "^1.73.0"
},
"scripts": {
"test": "node --test \"tests/*.test.mjs\""
},
"peerDependencies": {
"react": "^19.0.0"
}
}
+197
View File
@@ -0,0 +1,197 @@
// A product's choices and price in one dialog (plan step 3.3a; shared since 6.9): the counter POS,
// the menu tablet and the manager's ordering. "Check price" opens it without adding anything; a
// product with preferences to pick opens it on tap. The price shown is the backend's (the menu
// price, then the app's quote endpoint through `fetchQuote(lines)`), never added up here.
// `product` is the counter's product shape (routers/pos._product_out).
import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Stepper } from '@xenia/ui'
import { Allergens } from '@xenia/access'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
} from './cart.js'
import { useQuote } from './useQuote.js'
const chip = on => `min-h-[var(--x-control-md)] px-3 rounded-control border-2 text-body text-left flex items-center gap-2 transition-colors duration-fast
${on ? 'border-accent bg-accent-soft text-accent-ink font-medium' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`
function Section({ title, hint, children }) {
return (
<section className="grid gap-2">
<h3 className="text-label font-semibold text-ink-2 uppercase tracking-wide">{title}{hint && <span className="ml-2 normal-case font-normal text-warning-ink">{hint}</span>}</h3>
<div className="flex flex-wrap gap-2">{children}</div>
</section>
)
}
function Price({ value }) {
const { formatMoney } = useFormat()
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
}
// fetchQuote(lines) → the server's quote ({lines, total}); each app its endpoint (the menu tablet's
// has in-store prices and no discounts, 6.6)
export function ProductDialog({ product, onAdd, onClose, fetchQuote, addLabel }) {
const { t } = useTranslation('common')
const { formatMoney } = useFormat()
const unit = unitOf(product)
const [sel, setSel] = useState(() => defaultSelection(product))
const [qty, setQty] = useState(unit ? unit.start : 1)
const missing = missingChoices(product, sel)
const line = useMemo(() => toLine(product, sel, qty), [product, sel, qty])
const { quote, pending } = useQuote(fetchQuote, missing.length ? [] : [line])
const priced = quote?.lines?.[0]
const add = () => { onAdd(line); onClose() }
return (
<Dialog open onClose={onClose} size="lg" title={product.name} description={product.description || undefined}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('ordering.dialog.close')}</Button>
<Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add">
{(addLabel ?? t('ordering.dialog.add'))}{priced && !pending ? ` · ${formatMoney(priced.total)}` : ''}
</Button>
</>}>
<div className="grid gap-5" data-testid="product-dialog" data-product={product.id}>
<div className="flex gap-4 items-start">
{product.image_url && <img src={product.image_url} alt="" className="size-28 rounded-card object-cover shrink-0 bg-surface-2" />}
<div className="grid gap-1">
<div className="text-display font-semibold text-ink" data-testid="dialog-price">
{formatMoney(priced ? priced.unit_price : product.price)}
{unit && <span className="text-body text-ink-2"> / {unit.label}</span>}
</div>
{product.price !== product.base_price && !priced && (
<div className="text-label text-ink-3 line-through">{formatMoney(product.base_price)}</div>
)}
{priced?.adjustments?.map(a => (
<div key={a.label} className="text-label text-success-ink">{a.label} {a.delta > 0 ? '+' : ''}{formatMoney(a.delta)}</div>
))}
{product.tags?.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{product.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-full bg-surface-2 text-caption text-ink-2">{tag}</span>)}
</div>
)}
<Allergens allergens={product.allergens} style={{ marginTop: 4 }} />
</div>
</div>
{product.prefs.map(ps => {
const picked = sel.prefs[ps.id]?.choices ?? []
const one = !ps.multi && picked[0] ? ps.choices.find(c => c.id === picked[0].id) : null
const need = missing.find(m => m.kind === 'pref' && m.name === ps.name)
return (
<div key={ps.id} className="grid gap-3" data-pref={ps.id}>
<Section title={ps.name} hint={need ? t('ordering.dialog.pickOne') : null}>
{ps.choices.map(c => {
const p = picked.find(x => x.id === c.id)
return (
<span key={c.id} className="flex items-center gap-1">
<button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}>
{c.name} <Price value={c.price} />
</button>
{ps.multi && p && (
<Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} />
)}
</span>
)
})}
</Section>
{one?.subs?.length > 0 && (
<Section title={one.name}>
{one.subs.map(s => (
<button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
{ps.shared && one && !one.disables_shared && (
<Section title={ps.shared.name}>
{ps.shared.subs.map(s => (
<button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
</div>
)
})}
{product.quick.length > 0 && (
<Section title={t('ordering.dialog.quick')}>
{product.quick.map(q => {
const n = sel.quick[q.id] ?? 0
return (
<span key={q.id} className="flex items-center gap-1">
<button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}>
{q.name} <Price value={q.price} />
</button>
{q.allow_multiple && n > 0 && (
<Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={q.name} />
)}
</span>
)
})}
</Section>
)}
{product.options.length > 0 && (
<Section title={t('ordering.dialog.extras')}>
{product.options.map(o => {
const s = sel.options[o.id]
return (
<span key={o.id} className="grid gap-2">
<span className="flex items-center gap-1">
<button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}>
{o.name} <Price value={o.price} />
</button>
{o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={o.name} />}
</span>
{s && o.subs.length > 0 && (
<span className="flex flex-wrap gap-1 pl-3">
{o.subs.map(sub => (
<button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}>
{sub.name} <Price value={sub.price} />
</button>
))}
</span>
)}
</span>
)
})}
</Section>
)}
{product.ingredients.length > 0 && (
<Section title={t('ordering.dialog.without')}>
{product.ingredients.map(i => (
<button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}>
{sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{i.name}
</button>
))}
</Section>
)}
<div className="grid sm:grid-cols-[1fr_auto] gap-3 items-end">
<label className="grid gap-1 text-label text-ink-2">
{t('ordering.dialog.note')}
<Input value={sel.notes} onChange={e => setSel(s => ({ ...s, notes: e.target.value }))} maxLength={200} />
</label>
<div className="grid gap-1 text-label text-ink-2">
{t('ordering.dialog.quantity')}
<Stepper value={qty} min={unit ? unit.step : 1} max={unit ? 999 : 99} step={unit ? unit.step : 1}
format={v => (unit ? `${Number(v).toFixed(unit.step < 1 ? 1 : 0)} ${unit.label}` : String(v))}
onChange={v => setQty(Math.round(v * 1000) / 1000)} label={t('ordering.dialog.quantity')} data-testid="dialog-qty" />
</div>
</div>
{missing.length > 0 && (
<p className="text-label text-warning-ink" data-testid="dialog-missing">{t('ordering.dialog.missing', { list: missing.map(m => m.name).join(', ') })}</p>
)}
</div>
</Dialog>
)
}
+236
View File
@@ -0,0 +1,236 @@
// The counter POS's menu and cart, without prices (plan step 3.3a). Prices always come from
// the backend: the menu's `price` and POST /api/pos/quote (services/pos_cart.py). This file
// only knows what was chosen; the rules for a complete choice mirror the backend's, so the
// screen can say what's missing before asking. Pure: unit-tested in Node (tests/pos.test.mjs).
// ── menu ────────────────────────────────────────────────────────────────────
/** Lower case, accents and Greek tonos removed: "Φρέντο" matches "φρεντο". */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
/** Products in a category (a product listed in several shows in each), in that category's
* order; categoryId null = all products (each once). */
export function productsIn(products, categoryId) {
if (categoryId == null) return products
const pos = p => p.categories.find(c => c.category_id === categoryId)
return products.filter(pos).sort((a, b) => pos(a).sort_order - pos(b).sort_order || a.name.localeCompare(b.name))
}
/** Search by name (any word order, accents ignored), each product once whatever its
* categories. */
export function searchProducts(products, query) {
const words = fold(query).split(/\s+/).filter(Boolean)
if (!words.length) return []
return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) })
}
/** Categories that have products, in their order (top level first, then by sort order). */
export function categoriesWithProducts(categories, products) {
const used = new Set(products.flatMap(p => p.categories.map(c => c.category_id)))
return categories.filter(c => used.has(c.id))
}
// ── one product's choices ───────────────────────────────────────────────────
const defaultSub = subs => (subs?.length ? (subs.find(s => s.is_default) ?? subs[0]).name : null)
/** The choices a product starts with: default preference choices (+ their default subs and
* the set's default shared sub), nothing else. */
export function defaultSelection(product) {
const prefs = {}
for (const ps of product.prefs ?? []) {
const def = ps.choices.find(c => c.id === ps.default_choice_id)
prefs[ps.id] = def
? { choices: [{ id: def.id, qty: 1, sub: ps.multi ? null : defaultSub(def.subs) }], shared: ps.shared && !def.disables_shared ? defaultSub(ps.shared.subs) : null }
: { choices: [], shared: null }
}
return { quick: {}, options: {}, prefs, removed: [], notes: '' }
}
/** Does the product need the options dialog (a preference to pick)? Otherwise a tap adds it. */
export function needsChoices(product) {
return (product.prefs ?? []).length > 0
}
/** What's still missing: [{ kind: 'pref' | 'sub' | 'option_sub', name }] (empty = complete). */
export function missingChoices(product, sel) {
const out = []
for (const ps of product.prefs ?? []) {
const picked = sel.prefs[ps.id]?.choices ?? []
if (!picked.length) { out.push({ kind: 'pref', name: ps.name }); continue }
if (ps.multi) continue
const c = ps.choices.find(x => x.id === picked[0].id)
if (c?.subs?.length && !picked[0].sub) out.push({ kind: 'sub', name: c.name })
if (ps.shared && c && !c.disables_shared && !sel.prefs[ps.id]?.shared) out.push({ kind: 'sub', name: ps.shared.name })
}
for (const o of product.options ?? []) {
const s = sel.options[o.id]
if (s && o.subs?.length && !(s.subs?.length)) out.push({ kind: 'option_sub', name: o.name })
}
return out
}
/** Pick a single-choice preference (its default sub and the set's shared sub come with it). */
export function pickChoice(product, sel, setId, choiceId) {
const ps = product.prefs.find(p => p.id === setId)
const c = ps.choices.find(x => x.id === choiceId)
const prev = sel.prefs[setId] ?? { choices: [], shared: null }
if (ps.multi) {
const has = prev.choices.some(x => x.id === choiceId)
const choices = has ? prev.choices.filter(x => x.id !== choiceId) : [...prev.choices, { id: choiceId, qty: 1, sub: null }]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices } } }
}
const shared = ps.shared && !c.disables_shared ? (prev.shared ?? defaultSub(ps.shared.subs)) : null
return { ...sel, prefs: { ...sel.prefs, [setId]: { choices: [{ id: choiceId, qty: 1, sub: defaultSub(c.subs) }], shared } } }
}
export function setChoiceQty(sel, setId, choiceId, qty) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map(x => (x.id === choiceId ? { ...x, qty: Math.max(1, qty) } : x)) } } }
}
export function pickChoiceSub(sel, setId, sub) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map((x, i) => (i === 0 ? { ...x, sub } : x)) } } }
}
export function pickShared(sel, setId, shared) {
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...sel.prefs[setId], shared } } }
}
/** Toggle an extra (with its default sub). */
export function toggleOption(product, sel, optionId) {
const options = { ...sel.options }
if (options[optionId]) delete options[optionId]
else {
const o = product.options.find(x => x.id === optionId)
const sub = defaultSub(o.subs)
options[optionId] = { qty: 1, subs: sub ? [sub] : [] }
}
return { ...sel, options }
}
export function pickOptionSub(product, sel, optionId, name) {
const o = product.options.find(x => x.id === optionId)
const cur = sel.options[optionId]?.subs ?? []
const subs = o.multi_select ? (cur.includes(name) ? cur.filter(n => n !== name) : [...cur, name]) : [name]
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], subs } } }
}
export function setOptionQty(sel, optionId, qty) {
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], qty: Math.max(1, qty) } } }
}
/** Quick add-ons: qty 0 removes it. */
export function setQuick(sel, quickId, qty) {
const quick = { ...sel.quick }
if (qty > 0) quick[quickId] = qty
else delete quick[quickId]
return { ...sel, quick }
}
export function toggleRemoved(sel, ingredientId) {
const removed = sel.removed.includes(ingredientId) ? sel.removed.filter(i => i !== ingredientId) : [...sel.removed, ingredientId]
return { ...sel, removed }
}
/** The cart line POST /api/pos/quote (and 3.3b's sale) takes. */
export function toLine(product, sel, quantity) {
const line = { product_id: product.id, quantity }
const quick = Object.entries(sel.quick).map(([id, qty]) => ({ id: Number(id), qty }))
const options = Object.entries(sel.options).map(([id, o]) => ({ id: Number(id), qty: o.qty, subs: o.subs }))
const prefs = Object.entries(sel.prefs).filter(([, p]) => p.choices.length)
.map(([id, p]) => ({ set_id: Number(id), choices: p.choices.map(c => ({ id: c.id, qty: c.qty, sub: c.sub })), shared: p.shared }))
if (quick.length) line.quick = quick
if (options.length) line.options = options
if (prefs.length) line.prefs = prefs
if (sel.removed.length) line.removed = [...sel.removed]
if (sel.notes?.trim()) line.notes = sel.notes.trim()
return line
}
// ── the cart ────────────────────────────────────────────────────────────────
/** Two lines are the same sale when everything but the quantity is the same. */
export function lineKey(line) {
const { quantity, ...rest } = line // eslint-disable-line no-unused-vars
return stable(rest)
}
const stable = v => (Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object' ? `{${Object.keys(v).sort().map(k => `${k}:${stable(v[k])}`).join(',')}}`
: JSON.stringify(v))
/** Add a line; the same product with the same choices adds to its quantity. */
export function addLine(cart, line) {
const key = lineKey(line)
const i = cart.findIndex(l => lineKey(l) === key)
if (i < 0) return [...cart, line]
return cart.map((l, j) => (j === i ? { ...l, quantity: round(l.quantity + line.quantity) } : l))
}
export function setLineQty(cart, index, quantity) {
if (quantity <= 0) return cart.filter((_, i) => i !== index)
return cart.map((l, i) => (i === index ? { ...l, quantity: round(quantity) } : l))
}
const round = n => Math.round(n * 1000) / 1000
// Weighed products (kg, L, g, mL): step and starting amount (the waiter app's)
export const UNITS = {
kg: { step: 0.1, start: 0.5, label: 'kg' },
liter: { step: 0.1, start: 0.5, label: 'L' },
gram: { step: 10, start: 100, label: 'g' },
ml: { step: 5, start: 100, label: 'mL' },
}
export const unitOf = product => UNITS[product.unit_type] ?? null
// ── paying (3.3b) ───────────────────────────────────────────────────────────
/** Amounts a customer typically hands over for `total`: the exact amount, then the next
* round amounts above it (notes of 5, 10, 20, 50, 100), at most five. */
export function quickAmounts(total) {
const out = [round2(total)]
for (const step of [5, 10, 20, 50, 100]) {
const v = Math.ceil((total + 0.0001) / step) * step
if (v > total + 0.004 && !out.includes(v)) out.push(v)
}
return out.slice(0, 5)
}
/** Change to give back (null when not enough was given). */
export function changeFor(given, due) {
if (given == null || Number.isNaN(given)) return null
const c = round2(given - due)
return c < 0 ? null : c
}
/** Cash and card parts of a split: methods[i] is 'cash' | 'card' for line i, totals from the
* quote. → { cash, card, payments } (payments as POST /api/pos/sales takes them). */
export function splitPayments(methods, totals) {
const lines = { cash: [], card: [] }
methods.forEach((m, i) => lines[m].push(i))
const sum = idx => round2(idx.reduce((s, i) => s + (totals[i] ?? 0), 0))
const payments = ['card', 'cash'].filter(m => lines[m].length).map(m => ({ method: m, lines: lines[m] }))
return { cash: sum(lines.cash), card: sum(lines.card), payments }
}
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
const round2 = n => Math.round(n * 100) / 100
/** The counter's sales point for an order type (phase 3S; backend pos_cart.point_for). */
export function salesPointFor(orderType) {
return orderType === 'takeaway' ? 'in_store_takeaway' : 'in_store'
}
/** The menu's products sold at a sales point, each with that sales point's price (GET
* /api/pos/menu sends `sold_at` and `prices`; older answers: everything, `price`). */
export function forSalesPoint(products, point) {
return products
.filter(p => !p.sold_at || p.sold_at.includes(point))
.map(p => (p.prices?.[point] != null ? { ...p, price: p.prices[point] } : p))
}
+6
View File
@@ -0,0 +1,6 @@
// @xenia/ordering (plan step 6.9): what a person chooses for a product and how it becomes a line
// the server prices (line ids, 4.4), one implementation for the counter POS, the menu tablet and
// the manager's ordering. Pure rules in ./cart (Node-testable); the dialog and the quote hook.
export * from './cart.js'
export { ProductDialog } from './ProductDialog.jsx'
export { useQuote } from './useQuote.js'
+29
View File
@@ -0,0 +1,29 @@
// The server's price for a cart, asked again shortly after it changes (plan steps 3.3a, 6.9).
// `fetchQuote(lines)` is the app's call (the counter: /api/pos/quote; the manager and the phones:
// /api/orders/quote; the menu tablet: its own). Only the latest answer counts.
import { useEffect, useRef, useState } from 'react'
const QUOTE_DELAY_MS = 120
export function useQuote(fetchQuote, lines, extraKey = '') {
const [state, setState] = useState({ quote: null, pending: false, error: null })
const seq = useRef(0)
const fn = useRef(fetchQuote)
useEffect(() => { fn.current = fetchQuote })
const key = JSON.stringify([lines, extraKey])
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined } // eslint-disable-line react-hooks/set-state-in-effect
setState(s => ({ ...s, pending: true }))
const id = setTimeout(async () => {
try {
const data = await fn.current(lines)
if (mine === seq.current) setState({ quote: data, pending: false, error: null })
} catch (err) {
if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err }))
}
}, QUOTE_DELAY_MS)
return () => clearTimeout(id)
}, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is the lines + the caller's extra key
return state
}
+23
View File
@@ -0,0 +1,23 @@
// The shared cart rules (plan step 6.9); the counter's own cases are in terminal/tests/pos.test.mjs.
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { defaultSelection, missingChoices, needsChoices, toLine } from '../src/cart.js'
const burger = {
id: 1, unit_type: 'piece', quick: [{ id: 5, name: 'Cheese', price: 1 }], options: [], ingredients: [{ id: 9, name: 'Onion' }],
prefs: [{ id: 3, name: 'Cooking', default_choice_id: null, multi: false, shared: null, choices: [{ id: 7, name: 'Rare', subs: [] }] }],
}
test('a product with a preference to pick needs the dialog; the line holds ids only', () => {
assert.equal(needsChoices(burger), true)
const sel = defaultSelection(burger)
assert.deepEqual(missingChoices(burger, sel).map(m => m.name), ['Cooking'])
sel.prefs[3] = { choices: [{ id: 7, qty: 1 }] }
sel.quick[5] = 2
sel.removed = [9]
assert.deepEqual(missingChoices(burger, sel), [])
const line = toLine(burger, sel, 1)
assert.equal(line.product_id, 1)
assert.equal('unit_price' in line, false)
assert.deepEqual(line.removed, [9])
})
+1
View File
@@ -13,6 +13,7 @@ COPY packages/api/package.json packages/api/
COPY packages/access/package.json packages/access/ COPY packages/access/package.json packages/access/
COPY packages/signage/package.json packages/signage/ COPY packages/signage/package.json packages/signage/
COPY packages/floorplan/package.json packages/floorplan/ COPY packages/floorplan/package.json packages/floorplan/
COPY packages/ordering/package.json packages/ordering/
COPY waiter_pwa/package.json waiter_pwa/ COPY waiter_pwa/package.json waiter_pwa/
COPY manager_dashboard/package.json manager_dashboard/ COPY manager_dashboard/package.json manager_dashboard/
COPY terminal/package.json terminal/ COPY terminal/package.json terminal/
+1
View File
@@ -16,6 +16,7 @@
"@xenia/api": "^0.0.0", "@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0", "@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0", "@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/signage": "^0.0.0", "@xenia/signage": "^0.0.0",
"@xenia/ui": "^0.0.0", "@xenia/ui": "^0.0.0",
"axios": "^1.21.1", "axios": "^1.21.1",
+11 -3
View File
@@ -2,7 +2,8 @@
// and the food they ordered ahead (with a warning when the venue's prices differ). A request is // and the food they ordered ahead (with a warning when the venue's prices differ). A request is
// confirmed or declined (the customer sees the answer and the reason); a confirmed booking says // confirmed or declined (the customer sees the answer and the reason); a confirmed booking says
// when its food goes to the kitchen, seats the guests at a free table (their food's order moves // when its food goes to the kitchen, seats the guests at a free table (their food's order moves
// there, and is sent now if it hadn't been), or is cancelled / marked as a no-show. // there, and is sent now if it hadn't been), or is cancelled / marked as a no-show. Since 6.9 a
// confirmed booking can keep its table ahead (the table shows RESERVED; seating offers it first).
import { useState } from 'react' import { useState } from 'react'
import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react' import { AlertTriangle, Ban, Check, ChefHat, MessageSquare, Phone, UserX, Users } from 'lucide-react'
import { errorMessage } from '@xenia/api' import { errorMessage } from '@xenia/api'
@@ -18,7 +19,7 @@ export default function BookingPanel({ booking, tables, onChanged }) {
const fmt = useFormat() const fmt = useFormat()
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const [error, setError] = useState('') const [error, setError] = useState('')
const [table, setTable] = useState('') const [table, setTable] = useState(booking?.table_id ? String(booking.table_id) : '')
const [declining, setDeclining] = useState(false) const [declining, setDeclining] = useState(false)
if (!booking) { if (!booking) {
@@ -32,6 +33,8 @@ export default function BookingPanel({ booking, tables, onChanged }) {
const steps = bookingSteps(booking) const steps = bookingSteps(booking)
const food = foodState(booking) const food = foodState(booking)
const free = freeTables(tables) const free = freeTables(tables)
const all = (tables ?? []).map(x => ({ ...x, busy: !free.includes(x) })) // 6.9: a table can be kept while busy now
const kept = booking.table_id ? String(booking.table_id) : ''
const run = async (path, body) => { const run = async (path, body) => {
setBusy(true) setBusy(true)
setError('') setError('')
@@ -102,8 +105,13 @@ export default function BookingPanel({ booking, tables, onChanged }) {
<div className="flex gap-2"> <div className="flex gap-2">
<Select value={table} onChange={e => setTable(e.target.value)} aria-label={t('pos.bookings.table')} data-testid="booking-table" className="flex-1"> <Select value={table} onChange={e => setTable(e.target.value)} aria-label={t('pos.bookings.table')} data-testid="booking-table" className="flex-1">
<option value="">{t('pos.bookings.noTable')}</option> <option value="">{t('pos.bookings.noTable')}</option>
{free.map(x => <option key={x.id} value={x.id}>{x.name}</option>)} {all.map(x => <option key={x.id} value={x.id}>{x.name}{x.busy ? ` · ${t('pos.bookings.busyNow')}` : ''}</option>)}
</Select> </Select>
{table !== kept && (
<Button variant="secondary" disabled={busy} onClick={() => run('table', { table_id: table ? Number(table) : null })} data-testid="booking-keep">
{table ? t('pos.bookings.keep') : t('pos.bookings.release')}
</Button>
)}
</div> </div>
<Button size="lg" icon={<Check size={20} />} loading={busy} onClick={() => run('arrive', { table_id: table ? Number(table) : null })} data-testid="booking-arrive"> <Button size="lg" icon={<Check size={20} />} loading={busy} onClick={() => run('arrive', { table_id: table ? Number(table) : null })} data-testid="booking-arrive">
{t('pos.bookings.arrive')} {t('pos.bookings.arrive')}
+8 -192
View File
@@ -1,195 +1,11 @@
// A product on the counter POS (plan step 3.3a): price check and choices in one dialog. // The counter's product dialog: the shared one (@xenia/ordering, 6.9) priced by the counter's quote
// "Check price" opens it from the product's info button without adding anything; a product // (POST /api/pos/quote, the order type chosen at the till), or by `quoteUrl` (the menu tablet, 6.6).
// with preferences to pick opens it on tap. The price shown is the backend's (the menu price, import { ProductDialog as Shared } from '@xenia/ordering'
// then POST /api/pos/quote for what's chosen), never added up here. import client from '../../api/client'
import { useMemo, useState } from 'react'
import { Minus, Plus } from 'lucide-react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Input, Stepper } from '@xenia/ui'
import { Allergens } from '@xenia/access'
import {
defaultSelection, missingChoices, pickChoice, pickChoiceSub, pickOptionSub, pickShared, setChoiceQty, setOptionQty,
setQuick, toLine, toggleOption, toggleRemoved, unitOf,
} from './logic/cart'
import { useQuote } from './usePos'
const chip = on => `min-h-[var(--x-control-md)] px-3 rounded-control border-2 text-body text-left flex items-center gap-2 transition-colors duration-fast const quiet = { xenia: { noOverride: true } }
${on ? 'border-accent bg-accent-soft text-accent-ink font-medium' : 'border-line bg-surface-2 text-ink hover:bg-surface-3'}`
function Section({ title, hint, children }) { export default function ProductDialog({ orderType, quoteUrl = '/api/pos/quote', ...rest }) {
return ( const fetchQuote = lines => client.post(quoteUrl, { order_type: orderType, lines }, quiet).then(r => r.data)
<section className="grid gap-2"> return <Shared {...rest} fetchQuote={fetchQuote} />
<h3 className="text-label font-semibold text-ink-2 uppercase tracking-wide">{title}{hint && <span className="ml-2 normal-case font-normal text-warning-ink">{hint}</span>}</h3>
<div className="flex flex-wrap gap-2">{children}</div>
</section>
)
}
function Price({ value }) {
const { formatMoney } = useFormat()
return value ? <span className="text-ink-2 text-label">{value > 0 ? '+' : ''}{formatMoney(value)}</span> : null
}
// quoteUrl: the menu tablet (6.6) prices a guest's choices with its own endpoint (in-store prices, no discounts)
export default function ProductDialog({ product, orderType, onAdd, onClose, quoteUrl }) {
const { t } = useTranslation('terminal')
const { formatMoney } = useFormat()
const unit = unitOf(product)
const [sel, setSel] = useState(() => defaultSelection(product))
const [qty, setQty] = useState(unit ? unit.start : 1)
const missing = missingChoices(product, sel)
const line = useMemo(() => toLine(product, sel, qty), [product, sel, qty])
const { quote, pending } = useQuote(missing.length ? [] : [line], orderType, null, quoteUrl)
const priced = quote?.lines?.[0]
const add = () => { onAdd(line); onClose() }
return (
<Dialog open onClose={onClose} size="lg" title={product.name} description={product.description || undefined}
footer={<>
<Button variant="secondary" size="lg" onClick={onClose}>{t('pos.dialog.close')}</Button>
<Button size="lg" disabled={missing.length > 0} onClick={add} data-testid="dialog-add">
{t('pos.dialog.add')}{priced && !pending ? ` · ${formatMoney(priced.total)}` : ''}
</Button>
</>}>
<div className="grid gap-5" data-testid="product-dialog" data-product={product.id}>
<div className="flex gap-4 items-start">
{product.image_url && <img src={product.image_url} alt="" className="size-28 rounded-card object-cover shrink-0 bg-surface-2" />}
<div className="grid gap-1">
<div className="text-display font-semibold text-ink" data-testid="dialog-price">
{formatMoney(priced ? priced.unit_price : product.price)}
{unit && <span className="text-body text-ink-2"> / {unit.label}</span>}
</div>
{product.price !== product.base_price && !priced && (
<div className="text-label text-ink-3 line-through">{formatMoney(product.base_price)}</div>
)}
{priced?.adjustments?.map(a => (
<div key={a.label} className="text-label text-success-ink">{a.label} {a.delta > 0 ? '+' : ''}{formatMoney(a.delta)}</div>
))}
{product.tags?.length > 0 && (
<div className="flex flex-wrap gap-1 mt-1">
{product.tags.map(tag => <span key={tag} className="px-2 py-0.5 rounded-full bg-surface-2 text-caption text-ink-2">{tag}</span>)}
</div>
)}
<Allergens allergens={product.allergens} style={{ marginTop: 4 }} />
</div>
</div>
{product.prefs.map(ps => {
const picked = sel.prefs[ps.id]?.choices ?? []
const one = !ps.multi && picked[0] ? ps.choices.find(c => c.id === picked[0].id) : null
const need = missing.find(m => m.kind === 'pref' && m.name === ps.name)
return (
<div key={ps.id} className="grid gap-3" data-pref={ps.id}>
<Section title={ps.name} hint={need ? t('pos.dialog.pickOne') : null}>
{ps.choices.map(c => {
const p = picked.find(x => x.id === c.id)
return (
<span key={c.id} className="flex items-center gap-1">
<button type="button" className={chip(!!p)} onClick={() => setSel(s => pickChoice(product, s, ps.id, c.id))} data-choice={c.id}>
{c.name} <Price value={c.price} />
</button>
{ps.multi && p && (
<Stepper value={p.qty} min={1} max={99} onChange={v => setSel(s => setChoiceQty(s, ps.id, c.id, v))} label={c.name} />
)}
</span>
)
})}
</Section>
{one?.subs?.length > 0 && (
<Section title={one.name}>
{one.subs.map(s => (
<button key={s.name} type="button" className={chip(picked[0].sub === s.name)} onClick={() => setSel(x => pickChoiceSub(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
{ps.shared && one && !one.disables_shared && (
<Section title={ps.shared.name}>
{ps.shared.subs.map(s => (
<button key={s.name} type="button" className={chip(sel.prefs[ps.id]?.shared === s.name)} onClick={() => setSel(x => pickShared(x, ps.id, s.name))}>
{s.name} <Price value={s.price} />
</button>
))}
</Section>
)}
</div>
)
})}
{product.quick.length > 0 && (
<Section title={t('pos.dialog.quick')}>
{product.quick.map(q => {
const n = sel.quick[q.id] ?? 0
return (
<span key={q.id} className="flex items-center gap-1">
<button type="button" className={chip(n > 0)} onClick={() => setSel(s => setQuick(s, q.id, n > 0 ? 0 : 1))} data-quick={q.id}>
{q.name} <Price value={q.price} />
</button>
{q.allow_multiple && n > 0 && (
<Stepper value={n} min={1} max={99} onChange={v => setSel(s => setQuick(s, q.id, v))} label={q.name} />
)}
</span>
)
})}
</Section>
)}
{product.options.length > 0 && (
<Section title={t('pos.dialog.extras')}>
{product.options.map(o => {
const s = sel.options[o.id]
return (
<span key={o.id} className="grid gap-2">
<span className="flex items-center gap-1">
<button type="button" className={chip(!!s)} onClick={() => setSel(x => toggleOption(product, x, o.id))} data-option={o.id}>
{o.name} <Price value={o.price} />
</button>
{o.allow_multiple && s && <Stepper value={s.qty} min={1} max={99} onChange={v => setSel(x => setOptionQty(x, o.id, v))} label={o.name} />}
</span>
{s && o.subs.length > 0 && (
<span className="flex flex-wrap gap-1 pl-3">
{o.subs.map(sub => (
<button key={sub.name} type="button" className={chip(s.subs.includes(sub.name))} onClick={() => setSel(x => pickOptionSub(product, x, o.id, sub.name))}>
{sub.name} <Price value={sub.price} />
</button>
))}
</span>
)}
</span>
)
})}
</Section>
)}
{product.ingredients.length > 0 && (
<Section title={t('pos.dialog.without')}>
{product.ingredients.map(i => (
<button key={i.id} type="button" className={chip(sel.removed.includes(i.id))} onClick={() => setSel(s => toggleRemoved(s, i.id))} data-ingredient={i.id}>
{sel.removed.includes(i.id) ? <Minus size={14} /> : <Plus size={14} className="opacity-40" />}{i.name}
</button>
))}
</Section>
)}
<div className="grid sm:grid-cols-[1fr_auto] gap-3 items-end">
<label className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.note')}
<Input value={sel.notes} onChange={e => setSel(s => ({ ...s, notes: e.target.value }))} maxLength={200} />
</label>
<div className="grid gap-1 text-label text-ink-2">
{t('pos.dialog.quantity')}
<Stepper value={qty} min={unit ? unit.step : 1} max={unit ? 999 : 99} step={unit ? unit.step : 1}
format={v => (unit ? `${Number(v).toFixed(unit.step < 1 ? 1 : 0)} ${unit.label}` : String(v))}
onChange={v => setQty(Math.round(v * 1000) / 1000)} label={t('pos.dialog.quantity')} data-testid="dialog-qty" />
</div>
</div>
{missing.length > 0 && (
<p className="text-label text-warning-ink" data-testid="dialog-missing">{t('pos.dialog.missing', { list: missing.map(m => m.name).join(', ') })}</p>
)}
</div>
</Dialog>
)
} }
+2 -236
View File
@@ -1,236 +1,2 @@
// The counter POS's menu and cart, without prices (plan step 3.3a). Prices always come from // The cart's rules live in @xenia/ordering since plan step 6.9 (the manager orders by them too).
// the backend: the menu's `price` and POST /api/pos/quote (services/pos_cart.py). This file export * from '@xenia/ordering/cart'
// only knows what was chosen; the rules for a complete choice mirror the backend's, so the
// screen can say what's missing before asking. Pure: unit-tested in Node (tests/pos.test.mjs).
// ── menu ────────────────────────────────────────────────────────────────────
/** Lower case, accents and Greek tonos removed: "Φρέντο" matches "φρεντο". */
export function fold(text) {
return String(text ?? '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().trim()
}
/** Products in a category (a product listed in several shows in each), in that category's
* order; categoryId null = all products (each once). */
export function productsIn(products, categoryId) {
if (categoryId == null) return products
const pos = p => p.categories.find(c => c.category_id === categoryId)
return products.filter(pos).sort((a, b) => pos(a).sort_order - pos(b).sort_order || a.name.localeCompare(b.name))
}
/** Search by name (any word order, accents ignored), each product once whatever its
* categories. */
export function searchProducts(products, query) {
const words = fold(query).split(/\s+/).filter(Boolean)
if (!words.length) return []
return products.filter(p => { const name = fold(p.name); return words.every(w => name.includes(w)) })
}
/** Categories that have products, in their order (top level first, then by sort order). */
export function categoriesWithProducts(categories, products) {
const used = new Set(products.flatMap(p => p.categories.map(c => c.category_id)))
return categories.filter(c => used.has(c.id))
}
// ── one product's choices ───────────────────────────────────────────────────
const defaultSub = subs => (subs?.length ? (subs.find(s => s.is_default) ?? subs[0]).name : null)
/** The choices a product starts with: default preference choices (+ their default subs and
* the set's default shared sub), nothing else. */
export function defaultSelection(product) {
const prefs = {}
for (const ps of product.prefs ?? []) {
const def = ps.choices.find(c => c.id === ps.default_choice_id)
prefs[ps.id] = def
? { choices: [{ id: def.id, qty: 1, sub: ps.multi ? null : defaultSub(def.subs) }], shared: ps.shared && !def.disables_shared ? defaultSub(ps.shared.subs) : null }
: { choices: [], shared: null }
}
return { quick: {}, options: {}, prefs, removed: [], notes: '' }
}
/** Does the product need the options dialog (a preference to pick)? Otherwise a tap adds it. */
export function needsChoices(product) {
return (product.prefs ?? []).length > 0
}
/** What's still missing: [{ kind: 'pref' | 'sub' | 'option_sub', name }] (empty = complete). */
export function missingChoices(product, sel) {
const out = []
for (const ps of product.prefs ?? []) {
const picked = sel.prefs[ps.id]?.choices ?? []
if (!picked.length) { out.push({ kind: 'pref', name: ps.name }); continue }
if (ps.multi) continue
const c = ps.choices.find(x => x.id === picked[0].id)
if (c?.subs?.length && !picked[0].sub) out.push({ kind: 'sub', name: c.name })
if (ps.shared && c && !c.disables_shared && !sel.prefs[ps.id]?.shared) out.push({ kind: 'sub', name: ps.shared.name })
}
for (const o of product.options ?? []) {
const s = sel.options[o.id]
if (s && o.subs?.length && !(s.subs?.length)) out.push({ kind: 'option_sub', name: o.name })
}
return out
}
/** Pick a single-choice preference (its default sub and the set's shared sub come with it). */
export function pickChoice(product, sel, setId, choiceId) {
const ps = product.prefs.find(p => p.id === setId)
const c = ps.choices.find(x => x.id === choiceId)
const prev = sel.prefs[setId] ?? { choices: [], shared: null }
if (ps.multi) {
const has = prev.choices.some(x => x.id === choiceId)
const choices = has ? prev.choices.filter(x => x.id !== choiceId) : [...prev.choices, { id: choiceId, qty: 1, sub: null }]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices } } }
}
const shared = ps.shared && !c.disables_shared ? (prev.shared ?? defaultSub(ps.shared.subs)) : null
return { ...sel, prefs: { ...sel.prefs, [setId]: { choices: [{ id: choiceId, qty: 1, sub: defaultSub(c.subs) }], shared } } }
}
export function setChoiceQty(sel, setId, choiceId, qty) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map(x => (x.id === choiceId ? { ...x, qty: Math.max(1, qty) } : x)) } } }
}
export function pickChoiceSub(sel, setId, sub) {
const prev = sel.prefs[setId]
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...prev, choices: prev.choices.map((x, i) => (i === 0 ? { ...x, sub } : x)) } } }
}
export function pickShared(sel, setId, shared) {
return { ...sel, prefs: { ...sel.prefs, [setId]: { ...sel.prefs[setId], shared } } }
}
/** Toggle an extra (with its default sub). */
export function toggleOption(product, sel, optionId) {
const options = { ...sel.options }
if (options[optionId]) delete options[optionId]
else {
const o = product.options.find(x => x.id === optionId)
const sub = defaultSub(o.subs)
options[optionId] = { qty: 1, subs: sub ? [sub] : [] }
}
return { ...sel, options }
}
export function pickOptionSub(product, sel, optionId, name) {
const o = product.options.find(x => x.id === optionId)
const cur = sel.options[optionId]?.subs ?? []
const subs = o.multi_select ? (cur.includes(name) ? cur.filter(n => n !== name) : [...cur, name]) : [name]
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], subs } } }
}
export function setOptionQty(sel, optionId, qty) {
return { ...sel, options: { ...sel.options, [optionId]: { ...sel.options[optionId], qty: Math.max(1, qty) } } }
}
/** Quick add-ons: qty 0 removes it. */
export function setQuick(sel, quickId, qty) {
const quick = { ...sel.quick }
if (qty > 0) quick[quickId] = qty
else delete quick[quickId]
return { ...sel, quick }
}
export function toggleRemoved(sel, ingredientId) {
const removed = sel.removed.includes(ingredientId) ? sel.removed.filter(i => i !== ingredientId) : [...sel.removed, ingredientId]
return { ...sel, removed }
}
/** The cart line POST /api/pos/quote (and 3.3b's sale) takes. */
export function toLine(product, sel, quantity) {
const line = { product_id: product.id, quantity }
const quick = Object.entries(sel.quick).map(([id, qty]) => ({ id: Number(id), qty }))
const options = Object.entries(sel.options).map(([id, o]) => ({ id: Number(id), qty: o.qty, subs: o.subs }))
const prefs = Object.entries(sel.prefs).filter(([, p]) => p.choices.length)
.map(([id, p]) => ({ set_id: Number(id), choices: p.choices.map(c => ({ id: c.id, qty: c.qty, sub: c.sub })), shared: p.shared }))
if (quick.length) line.quick = quick
if (options.length) line.options = options
if (prefs.length) line.prefs = prefs
if (sel.removed.length) line.removed = [...sel.removed]
if (sel.notes?.trim()) line.notes = sel.notes.trim()
return line
}
// ── the cart ────────────────────────────────────────────────────────────────
/** Two lines are the same sale when everything but the quantity is the same. */
export function lineKey(line) {
const { quantity, ...rest } = line // eslint-disable-line no-unused-vars
return stable(rest)
}
const stable = v => (Array.isArray(v) ? `[${v.map(stable).join(',')}]`
: v && typeof v === 'object' ? `{${Object.keys(v).sort().map(k => `${k}:${stable(v[k])}`).join(',')}}`
: JSON.stringify(v))
/** Add a line; the same product with the same choices adds to its quantity. */
export function addLine(cart, line) {
const key = lineKey(line)
const i = cart.findIndex(l => lineKey(l) === key)
if (i < 0) return [...cart, line]
return cart.map((l, j) => (j === i ? { ...l, quantity: round(l.quantity + line.quantity) } : l))
}
export function setLineQty(cart, index, quantity) {
if (quantity <= 0) return cart.filter((_, i) => i !== index)
return cart.map((l, i) => (i === index ? { ...l, quantity: round(quantity) } : l))
}
const round = n => Math.round(n * 1000) / 1000
// Weighed products (kg, L, g, mL): step and starting amount (the waiter app's)
export const UNITS = {
kg: { step: 0.1, start: 0.5, label: 'kg' },
liter: { step: 0.1, start: 0.5, label: 'L' },
gram: { step: 10, start: 100, label: 'g' },
ml: { step: 5, start: 100, label: 'mL' },
}
export const unitOf = product => UNITS[product.unit_type] ?? null
// ── paying (3.3b) ───────────────────────────────────────────────────────────
/** Amounts a customer typically hands over for `total`: the exact amount, then the next
* round amounts above it (notes of 5, 10, 20, 50, 100), at most five. */
export function quickAmounts(total) {
const out = [round2(total)]
for (const step of [5, 10, 20, 50, 100]) {
const v = Math.ceil((total + 0.0001) / step) * step
if (v > total + 0.004 && !out.includes(v)) out.push(v)
}
return out.slice(0, 5)
}
/** Change to give back (null when not enough was given). */
export function changeFor(given, due) {
if (given == null || Number.isNaN(given)) return null
const c = round2(given - due)
return c < 0 ? null : c
}
/** Cash and card parts of a split: methods[i] is 'cash' | 'card' for line i, totals from the
* quote. → { cash, card, payments } (payments as POST /api/pos/sales takes them). */
export function splitPayments(methods, totals) {
const lines = { cash: [], card: [] }
methods.forEach((m, i) => lines[m].push(i))
const sum = idx => round2(idx.reduce((s, i) => s + (totals[i] ?? 0), 0))
const payments = ['card', 'cash'].filter(m => lines[m].length).map(m => ({ method: m, lines: lines[m] }))
return { cash: sum(lines.cash), card: sum(lines.card), payments }
}
export const DISCOUNTS = [0, 5, 10, 15, 20, 25, 50, 100]
const round2 = n => Math.round(n * 100) / 100
/** The counter's sales point for an order type (phase 3S; backend pos_cart.point_for). */
export function salesPointFor(orderType) {
return orderType === 'takeaway' ? 'in_store_takeaway' : 'in_store'
}
/** The menu's products sold at a sales point, each with that sales point's price (GET
* /api/pos/menu sends `sold_at` and `prices`; older answers: everything, `price`). */
export function forSalesPoint(products, point) {
return products
.filter(p => !p.sold_at || p.sold_at.includes(point))
.map(p => (p.prices?.[point] != null ? { ...p, price: p.prices[point] } : p))
}
+4 -19
View File
@@ -5,10 +5,10 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useModule } from '@xenia/access' import { useModule } from '@xenia/access'
import client from '../../api/client' import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context' import { useLiveEvent, useLiveEvents } from '../../device/context'
import { useQuote as useSharedQuote } from '@xenia/ordering'
const quiet = { xenia: { noOverride: true } } const quiet = { xenia: { noOverride: true } }
const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours) const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours)
const QUOTE_DELAY_MS = 120
/** GET /api/pos/session: { business_day, shift, self_start, day_openers } (null while loading). */ /** GET /api/pos/session: { business_day, shift, self_start, day_openers } (null while loading). */
export function usePosSession() { export function usePosSession() {
@@ -46,24 +46,9 @@ export function useMenu() {
* `orderId` (a table's order) the order's items count for deals, as when it's sent. * `orderId` (a table's order) the order's items count for deals, as when it's sent.
* → { quote, pending, error } */ * → { quote, pending, error } */
export function useQuote(lines, orderType, orderId = null, url = '/api/pos/quote') { export function useQuote(lines, orderType, orderId = null, url = '/api/pos/quote') {
const [state, setState] = useState({ quote: null, pending: false, error: null }) // the shared hook (@xenia/ordering, 6.9) with the counter's endpoint
const seq = useRef(0) return useSharedQuote(ls => client.post(url, { order_type: orderType, lines: ls, order_id: orderId ?? undefined }, quiet).then(r => r.data),
const key = JSON.stringify([lines, orderType, orderId, url]) lines, JSON.stringify([orderType, orderId, url]))
useEffect(() => {
const mine = ++seq.current
if (!lines.length) { setState({ quote: { lines: [], total: 0 }, pending: false, error: null }); return undefined }
setState(s => ({ ...s, pending: true }))
const id = setTimeout(async () => {
try {
const { data } = await client.post(url, { order_type: orderType, lines, order_id: orderId ?? undefined }, quiet)
if (mine === seq.current) setState({ quote: data, pending: false, error: null })
} catch (err) {
if (mine === seq.current) setState(s => ({ ...s, pending: false, error: err }))
}
}, QUOTE_DELAY_MS)
return () => clearTimeout(id)
}, [key]) // eslint-disable-line react-hooks/exhaustive-deps -- `key` is lines + orderType + orderId
return state
} }
const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated'] const TABLE_EVENTS = ['order_updated', 'order_paid', 'order_closed', 'table_flags_changed', 'table_list_changed', 'kds_order_updated', 'kds_item_updated']
+1 -1
View File
@@ -4,7 +4,7 @@ import xenia from '@xenia/ui/tailwind-preset'
export default { export default {
// Shared design tokens only (bg-surface, text-ink-2, rounded-control…), CS-16 // Shared design tokens only (bg-surface, text-ink-2, rounded-control…), CS-16
presets: [xenia], presets: [xenia],
content: ['./index.html', './src/**/*.{js,jsx}', '../packages/signage/src/**/*.{js,jsx}'], // signage slides use a few utilities (5.6a) content: ['./index.html', './src/**/*.{js,jsx}', '../packages/signage/src/**/*.{js,jsx}', '../packages/ordering/src/**/*.{js,jsx}'], // signage slides use a few utilities (5.6a)
theme: { extend: {} }, theme: { extend: {} },
plugins: [], plugins: [],
} }
+49
View File
@@ -1007,6 +1007,55 @@ try {
&& await page.locator('[data-testid="manager-floor"] [data-testid="floor-table"]').count() >= 2) && await page.locator('[data-testid="manager-floor"] [data-testid="floor-table"]').count() >= 2)
await page.screenshot({ path: path.join(OUT, 'manager-floor-live.png') }) await page.screenshot({ path: path.join(OUT, 'manager-floor-live.png') })
// ── 6.9: an order taken, changed, paid and closed from the manager by the phones' rules ──
const od = 'orders:'
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
await api('PUT', '/api/settings/orders.close_with_unpaid', { token: boss, body: { value: 'false' } })
const omenu = await api('GET', '/api/orders/menu', { token: boss })
const [pA, pB] = omenu.products.filter(p => p.available && !p.service && !p.prefs.length && p.price > 0)
const busyIds = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
const otable = (await api('GET', '/api/tables/', { token: boss })).find(x => x.is_active !== false && !busyIds.has(x.id))
await page.goto(`${APP}/tables`)
await page.locator(`[data-testid="table-card"][data-table="${otable.id}"] [data-testid="table-open"]`).click()
await page.getByTestId('order-new').waitFor({ timeout: 10_000 }).catch(() => {})
const product = id => page.locator(`[data-testid="order-product"][data-id="${id}"]`).first()
await product(pA.id).click()
await product(pA.id).click()
r.check(`${od} a free table opens a new order; two taps make one line of 2`, (await page.getByTestId('cart-qty').first().textContent().catch(() => '')) === '2')
await page.getByTestId('order-send').click()
await page.waitForURL(/\/orders\/\d+$/, { timeout: 10_000 }).catch(() => {})
const oid = Number(page.url().split('/').pop())
let mo = oid ? await api('GET', `/api/orders/${oid}`, { token: boss }) : null
r.check(`${od} "Send" opened the table's order, priced by the server`, mo?.table_id === otable.id && mo.items.length === 1
&& mo.items[0].quantity === 2 && Math.abs(mo.items[0].unit_price - pA.price) < 0.001, JSON.stringify(mo?.items?.map(i => [i.product_id, i.quantity, i.unit_price])))
await page.getByTestId('order-page').waitFor({ timeout: 8000 }).catch(() => {})
await product(pB.id).click()
await page.getByTestId('order-send').click()
const lineB = page.locator(`[data-testid="order-line"][data-status="active"][data-name="${pB.name}"]`).first()
await lineB.waitFor({ timeout: 8000 }).catch(() => {})
await lineB.getByTestId('line-pick').check()
await page.getByTestId('lines-cancel').click()
await page.getByTestId('cancel-no-print').click()
for (let i = 0; i < 20 && !mo?.items?.some(x => x.product_id === pB.id && x.status === 'cancelled'); i++) { await sleep(250); mo = await api('GET', `/api/orders/${oid}`, { token: boss }) }
r.check(`${od} a line added, then cancelled (no ticket)`, mo.items.some(x => x.product_id === pB.id && x.status === 'cancelled'))
await page.screenshot({ path: path.join(OUT, 'manager-order.png'), fullPage: true })
await page.getByTestId('order-close').click()
const payFirst = await page.getByTestId('pay-dialog').waitFor({ timeout: 5000 }).then(() => true).catch(() => false)
r.check(`${od} "Close" with unpaid lines takes the payment first (close_with_unpaid off)`, payFirst
&& (await page.getByTestId('pay-amount').textContent()).includes((pA.price * 2).toFixed(2)))
await page.getByTestId('pay-cash').click()
for (let i = 0; i < 20 && mo?.status !== 'closed'; i++) { await sleep(250); mo = await api('GET', `/api/orders/${oid}`, { token: boss }) }
r.check(`${od} …paid in cash and closed`, mo.status === 'closed' && mo.items.filter(x => x.status === 'paid').every(x => x.payment_method === 'cash')
&& await page.locator('[data-testid="order-page"][data-status="closed"]').waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
// a booking given a table ahead shows RESERVED on it
const soon = await page.evaluate(() => new Date(Date.now() + 3600_000).toISOString())
const kept = await api('POST', '/api/reservations/', { token: boss, body: { guest_name: 'Kept E2E', party_size: 3, reserved_for: soon, table_id: otable.id } })
await page.goto(`${APP}/tables`)
r.check(`${od} a booking given the table shows RESERVED on its card`, !!kept?.id
&& await page.locator(`[data-testid="table-card"][data-table="${otable.id}"] [data-testid="table-reserved"]`).waitFor({ timeout: 8000 }).then(() => true).catch(() => false))
await page.screenshot({ path: path.join(OUT, 'manager-tables.png'), fullPage: true })
await api('PATCH', `/api/reservations/${kept.id}/status`, { token: boss, body: { status: 'cancelled' } }).catch(() => {})
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } }) await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`) await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {}) await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})
+1
View File
@@ -16,6 +16,7 @@ const suites = [
['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS], ['unit: packages/access (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/access'], CS],
['unit: packages/signage (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/signage'], CS], ['unit: packages/signage (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/signage'], CS],
['unit: packages/floorplan (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/floorplan'], CS], ['unit: packages/floorplan (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/floorplan'], CS],
['unit: packages/ordering (node --test)', 'npm', ['test', '--silent', '-w', '@xenia/ordering'], CS],
['unit: manager_dashboard (node --test)', 'npm', ['test', '--silent', '-w', 'manager-dashboard'], CS], ['unit: manager_dashboard (node --test)', 'npm', ['test', '--silent', '-w', 'manager-dashboard'], CS],
['lint: manager_dashboard (v2 code)', 'npm', ['run', 'lint', '--silent', '-w', 'manager-dashboard'], CS], ['lint: manager_dashboard (v2 code)', 'npm', ['run', 'lint', '--silent', '-w', 'manager-dashboard'], CS],
['unit: terminal (node --test)', 'npm', ['test', '--silent', '-w', 'terminal'], CS], ['unit: terminal (node --test)', 'npm', ['test', '--silent', '-w', 'terminal'], CS],
+1
View File
@@ -16,6 +16,7 @@ COPY packages/api/package.json packages/api/
COPY packages/access/package.json packages/access/ COPY packages/access/package.json packages/access/
COPY packages/signage/package.json packages/signage/ COPY packages/signage/package.json packages/signage/
COPY packages/floorplan/package.json packages/floorplan/ COPY packages/floorplan/package.json packages/floorplan/
COPY packages/ordering/package.json packages/ordering/
COPY waiter_pwa/package.json waiter_pwa/ COPY waiter_pwa/package.json waiter_pwa/
COPY manager_dashboard/package.json manager_dashboard/ COPY manager_dashboard/package.json manager_dashboard/
COPY terminal/package.json terminal/ COPY terminal/package.json terminal/
+15 -5
View File
@@ -30,7 +30,8 @@ export default function BookingsPage() {
try { try {
const [tables, orders] = await Promise.all([db.pos_tables.toArray(), db.pos_orders.toArray()]) const [tables, orders] = await Promise.all([db.pos_tables.toArray(), db.pos_orders.toArray()])
const busyTables = new Set(orders.filter(o => OPEN.includes(o.status)).map(o => o.table_id)) const busyTables = new Set(orders.filter(o => OPEN.includes(o.status)).map(o => o.table_id))
setFree(tables.filter(tb => tb.is_active !== false && !busyTables.has(tb.id))) // 6.9: every table (a booking can keep one that is busy now); busy ones say so
setFree(tables.filter(tb => tb.is_active !== false).map(tb => ({ ...tb, busy: busyTables.has(tb.id) })))
} catch { setFree([]) } } catch { setFree([]) }
}, [t]) }, [t])
@@ -82,7 +83,8 @@ export default function BookingsPage() {
{upcoming.length === 0 && <p style={empty}>{t('bookings.noUpcoming')}</p>} {upcoming.length === 0 && <p style={empty}>{t('bookings.noUpcoming')}</p>}
{upcoming.map(b => ( {upcoming.map(b => (
<BookingCard key={b.id} booking={b}> <BookingCard key={b.id} booking={b}>
<SeatControls booking={b} free={free} busy={busy === b.id} onSeat={tableId => run(b, 'arrive', { table_id: tableId })} <SeatControls key={`${b.id}-${b.table_id ?? ''}`} booking={b} free={free} busy={busy === b.id} onSeat={tableId => run(b, 'arrive', { table_id: tableId })}
onKeep={tableId => run(b, 'table', { table_id: tableId })}
onCancel={status => run(b, 'cancel', { status })} /> onCancel={status => run(b, 'cancel', { status })} />
</BookingCard> </BookingCard>
))} ))}
@@ -130,10 +132,11 @@ function BookingCard({ booking: b, children }) {
) )
} }
function SeatControls({ booking, free, busy, onSeat, onCancel }) { function SeatControls({ booking, free, busy, onSeat, onKeep, onCancel }) {
const { t } = useTranslation('waiter') const { t } = useTranslation('waiter')
const [table, setTable] = useState('') const [table, setTable] = useState(booking.table_id ? String(booking.table_id) : '')
const options = free.map(tb => ({ id: tb.id, name: tb.label || `T${tb.number}`, seats: tb.seat_count })) const options = free.map(tb => ({ id: tb.id, name: tb.label || `T${tb.number}`, seats: tb.seat_count, busy: tb.busy }))
const kept = booking.table_id ? String(booking.table_id) : ''
return ( return (
<div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}> <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
<select value={table} onChange={e => setTable(e.target.value)} aria-label={t('bookings.table')} data-testid="booking-table" <select value={table} onChange={e => setTable(e.target.value)} aria-label={t('bookings.table')} data-testid="booking-table"
@@ -143,9 +146,16 @@ function SeatControls({ booking, free, busy, onSeat, onCancel }) {
<option key={o.id} value={o.id}> <option key={o.id} value={o.id}>
{o.name}{o.seats ? ` · ${t('seats.table', { count: o.seats })}` : ''} {o.name}{o.seats ? ` · ${t('seats.table', { count: o.seats })}` : ''}
{o.seats && booking.party_size > o.seats ? ' ⚠' : ''} {o.seats && booking.party_size > o.seats ? ' ⚠' : ''}
{o.busy ? ` · ${t('bookings.busyNow')}` : ''}
</option> </option>
))} ))}
</select> </select>
{/* 6.9: keep the table ahead, so it shows RESERVED and others see it's taken */}
{table !== kept && (
<button className="btn btn--secondary" disabled={busy} onClick={() => onKeep(table ? Number(table) : null)} data-testid="booking-keep">
{table ? t('bookings.keep') : t('bookings.release')}
</button>
)}
<button className="btn btn--accent" disabled={busy} onClick={() => onSeat(table ? Number(table) : null)} data-testid="booking-arrive"> <button className="btn btn--accent" disabled={busy} onClick={() => onSeat(table ? Number(table) : null)} data-testid="booking-arrive">
{t('bookings.arrive')} {t('bookings.arrive')}
</button> </button>