feat: printing problems shown and handled; printing set-up on v2 (platform-v2 step 6.10)

- a ticket that doesn't print is a problem for whoever sent it and the managers:
  GET /api/print-problems (the order, table, dishes, printer, since when, tries,
  last error, who sent it) and three ways out: print again, send to another
  printer, handled (services/print_problems.py; print_jobs.resolved_by /
  redirected_to, Alembic 0036); live event print.problems from the print paths
- phone: the red printer button opens the problems sheet, the table page warns
  (usePrintProblems replaces the 8 s poll); counter POS: a red button under the
  modes with the shared panel (@xenia/ordering PrintProblemsPanel + pure rules);
  manager: a card on the overview (top), the Tables page and the order page
- manager: Settings -> Printing (printers with reachability, test print, network
  scan; ticket layout + test ticket, beep, fonts with previews, dot leader,
  dividers) and Management -> Prep zones (cards + zone dialog with the ticket
  language, printers, copies, sorting, category order, kitchen screen) rebuilt in
  src/pages/printing; v1 PrintFontsTab, PrepZonesConfigPage, PendingPrints and
  /api/orders/pending-prints removed
- access: printer add/edit/delete/scan need core.settings.manage, prep zone
  changes catalog.menu.manage (were any dashboard user)
- tests: test_print_problems.py, @xenia/ordering printProblems, manager
  printing.test.mjs, e2e print_problems.mjs (done-when) + manager.mjs printing

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 01:40:07 +02:00
co-authored by Claude Opus 5.5
parent 070c9cf625
commit f31bdf42aa
57 changed files with 2557 additions and 2221 deletions
+3
View File
@@ -224,6 +224,9 @@ CODES: dict[str, tuple[int, str]] = {
"printer.not_found": (404, "That printer isn't there or is turned off."),
"print_job.not_found": (404, "That print job isn't there any more."),
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
"print_job.done": (409, "That ticket isn't waiting any more: it was printed or dealt with on another screen."),
"print.printer_off": (409, "The printer {printer} is turned off in the settings."),
"print.redirect_failed": (502, "{printer} didn't print it either ({error}). The ticket is still waiting."),
"table.not_found": (404, "Table not found."),
"floor_plan.not_found": (404, "Floor plan not found."),
"floor_plan.bad_outline": (422, "The floor's shape needs 3 to 100 corners, all inside the plan."),
@@ -0,0 +1,28 @@
"""A print job's way out besides printing (plan step 6.10): who resolved it and, when the
ticket was sent to another printer, which one. `status` gains no new value: a ticket sent
elsewhere ends as 'success' (redirected_to set), one marked as handled as 'cancelled' with
cancel_reason 'handled'.
Revision ID: 0036_print_job_resolution
Revises: 0035_floor_plans
Create Date: 2026-11-19 09:00:00
"""
from alembic import op
import sqlalchemy as sa
revision = '0036_print_job_resolution'
down_revision = '0035_floor_plans'
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
batch_op.add_column(sa.Column('resolved_by', sa.Integer(), nullable=True))
batch_op.add_column(sa.Column('redirected_to', sa.Integer(), nullable=True))
def downgrade() -> None:
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
batch_op.drop_column('redirected_to')
batch_op.drop_column('resolved_by')
+3 -1
View File
@@ -181,7 +181,9 @@ class PrintJob(Base):
last_attempted_at = Column(UTCDateTime, nullable=True)
succeeded_at = Column(UTCDateTime, nullable=True)
cancelled_at = Column(UTCDateTime, nullable=True)
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed"
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed" | "handled" (6.10)
resolved_by = Column(Integer, nullable=True) # 6.10: who sent it elsewhere / marked it handled
redirected_to = Column(Integer, nullable=True) # 6.10: the printer it was sent to instead (status success)
order = relationship("Order", back_populates="print_jobs")
printer = relationship("Printer", back_populates="print_jobs")
@@ -51,5 +51,6 @@ MODULE = Module(
Mount('routers.business_day', '/api/business-day'),
Mount('routers.shifts', '/api/shifts'),
Mount('routers.flags', '/api/flags'),
Mount('routers.print_problems', '/api/print-problems'), # 6.10
),
)
+5 -43
View File
@@ -284,49 +284,6 @@ def list_active_orders(db: Session = Depends(get_db), user: User = Depends(get_c
]
# ─── Pending print jobs count (for PWA header badge) ─────────────────────────
@router.get("/pending-prints")
def get_pending_prints(
db: Session = Depends(get_db),
user: User = Depends(get_current_user),
):
"""Returns count of pending print jobs + per-order detail for the current shift."""
pending_jobs = db.query(PrintJob).filter(PrintJob.status == "pending").all()
from collections import defaultdict
by_order: dict = defaultdict(list)
for pj in pending_jobs:
by_order[pj.order_id].append(pj)
orders_data = []
for order_id, jobs in by_order.items():
order = db.query(Order).filter(Order.id == order_id).first()
if not order or order.status in ("closed", "cancelled"):
continue
table_name = None
if order.table:
table_name = order.table.label or f"T{order.table.number}"
orders_data.append({
"order_id": order_id,
"table_name": table_name,
"opened_at": order.opened_at.isoformat() if order.opened_at else None,
"jobs": [
{
"id": pj.id,
"printer_id": pj.printer_id,
"retry_count": pj.retry_count,
"first_attempted_at": pj.first_attempted_at.isoformat() if pj.first_attempted_at else None,
"last_attempted_at": pj.last_attempted_at.isoformat() if pj.last_attempted_at else None,
"item_ids": json.loads(pj.item_ids or "[]"),
}
for pj in jobs
],
})
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
@@ -900,6 +857,9 @@ def retry_print(
print_results = route_and_print_sync(order_id, unprinted_ids, db)
db.refresh(order)
if print_results and all(r.get("success") for r in print_results):
from services.print_problems import announce
announce(order_id) # 6.10: printed again, the warning clears
return {"order": order, "print_results": print_results}
@@ -1892,6 +1852,8 @@ def cancel_print_job(
logging.getLogger("services.printer_service").warning(
"print.job.abandoned job=%s order=%s attempts=%s reason=staff_cancelled", pj.id, order_id, pj.retry_count)
broadcast_sync("order_updated", {"order_id": order_id, "table_id": order.table_id, "status": order.status, "action": "print_job_cancelled"})
from services.print_problems import announce
announce(order_id)
return {"ok": True, "job_id": job_id}
+7 -3
View File
@@ -8,6 +8,7 @@ DELETE /api/prep-zones/{id} delete a prep zone
"""
import json
from core.i18n import normalize_language
from core.access.deps import require
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from pydantic import BaseModel
@@ -114,11 +115,14 @@ def list_prep_zones(
return [_zone_out(z) for z in zones]
_MENU = require("catalog.menu.manage") # 6.10: like the nav entry
@router.post("")
def create_prep_zone(
body: PrepZoneCreate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(_MENU),
):
zone = PrepZone(
name=body.name,
@@ -152,7 +156,7 @@ def update_prep_zone(
zone_id: int,
body: PrepZoneUpdate,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(_MENU),
):
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
if not zone:
@@ -213,7 +217,7 @@ def update_prep_zone(
def delete_prep_zone(
zone_id: int,
db: Session = Depends(get_db),
user: User = Depends(require_manager),
user: User = Depends(_MENU),
):
zone = db.query(PrepZone).filter(PrepZone.id == zone_id).first()
if not zone:
+40
View File
@@ -0,0 +1,40 @@
"""Printing problems (plan step 6.10, services/print_problems.py): the tickets that didn't
print, for whoever may act on their orders (the managers see all), and the three ways out:
print again, send to another printer, mark as handled. Live event: `print.problems`."""
from __future__ import annotations
from fastapi import APIRouter, Depends
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core.access.deps import require_any
from database import get_db
from services import print_problems as svc
router = APIRouter()
_STAFF = require_any("ordering.orders.open", "core.dashboard.access")
@router.get("")
def list_problems(db: Session = Depends(get_db), user=Depends(_STAFF)):
"""{problems: [...oldest first], printers: [{id, name}]} (the printers a ticket can go to)."""
return {"problems": svc.problems(db, user), "printers": svc.printers(db)}
@router.post("/{job_id}/retry")
def retry(job_id: int, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.retry(db, job_id, user)
class RedirectBody(BaseModel):
printer_id: int
@router.post("/{job_id}/redirect")
def redirect(job_id: int, body: RedirectBody, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.redirect(db, job_id, body.printer_id, user)
@router.post("/{job_id}/handled")
def handled(job_id: int, db: Session = Depends(get_db), user=Depends(_STAFF)):
return svc.handled(db, job_id, user)
+10 -7
View File
@@ -1,6 +1,5 @@
from core.access.deps import public
from core.access.deps import public, require
from core.access.queries import holders_filter
from core.access.deps import require
import asyncio
import ipaddress
import json
@@ -206,8 +205,12 @@ def list_printers(db: Session = Depends(get_db), user: User = Depends(require_ma
return db.query(Printer).all()
# 6.10: adding, changing, removing and finding printers is venue set-up
_SETTINGS = require("core.settings.manage")
@router.post("/printers", response_model=PrinterOut)
def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def create_printer(body: PrinterCreate, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = Printer(**body.model_dump())
db.add(printer)
db.commit()
@@ -243,7 +246,7 @@ def test_beep(printer_id: int, n1: int = 2, n2: int = 2, n3: int = 1, db: Sessio
@router.put("/printers/{printer_id}", response_model=PrinterOut)
def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer:
raise XeniaError("printer.not_found")
@@ -255,7 +258,7 @@ def update_printer(printer_id: int, body: PrinterUpdate, db: Session = Depends(g
@router.delete("/printers/{printer_id}")
def delete_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(require_manager)):
def delete_printer(printer_id: int, db: Session = Depends(get_db), user: User = Depends(_SETTINGS)):
printer = db.query(Printer).filter(Printer.id == printer_id).first()
if not printer:
raise XeniaError("printer.not_found")
@@ -337,7 +340,7 @@ async def _scan_subnet_sse(subnet: str, port: int, token: str):
async def scan_printers(
subnet: str = Query(default=""),
port: int = Query(default=9100),
user: User = Depends(require_manager),
user: User = Depends(_SETTINGS),
):
"""SSE endpoint: scan a subnet for devices responding on the given port."""
# Fall back to auto-detected subnet if none provided
@@ -356,7 +359,7 @@ async def scan_printers(
@router.get("/printers/scan-hints")
def scan_hints(user: User = Depends(require_manager)):
def scan_hints(user: User = Depends(_SETTINGS)):
"""Return auto-detected local subnets to suggest in the scan UI."""
return {"subnets": _detect_local_subnets()}
+200
View File
@@ -0,0 +1,200 @@
"""Printing problems (plan step 6.10): tickets that didn't print, shown to whoever sent them and
to the managers, with three ways out.
A problem is a PrintJob still `pending` on an open order: the first attempt failed (a job
that prints at once is `success` straight away) and services/printer_service.py retries it
every 8 s. From a problem, staff can
* print again now (`retry`): the same printer, at once, without waiting for the sweep;
* send it to another printer (`redirect`): the job's unprinted lines print there with the
same zone's layout; on success the job ends `success` with `redirected_to`;
* mark it handled (`handled`): someone told the kitchen by voice; the job ends `cancelled`
with cancel_reason 'handled' and its lines count as printed, so nobody is warned again.
Every change goes out as the live event `print.problems` ({order_id}); the apps reload the list.
"""
from __future__ import annotations
import json
import logging
from core.errors import XeniaError
from core.timeutil import utcnow
from models.order import Order, OrderItem, PrintJob, PrintLog
from models.printer import Printer
logger = logging.getLogger("services.printer_service")
EVENT = "print.problems"
def announce(order_id: int | None) -> None:
"""Tell every app the list changed (never raises: printing must not fail on it)."""
try:
from services.ws_bus import broadcast_sync
broadcast_sync(EVENT, {"order_id": order_id})
except Exception:
logger.exception("print.problems: broadcast failed")
def _table_name(order) -> str | None:
t = order.table
return (t.label or f"T{t.number}") if t is not None else None
def _waiting_items(db, pj) -> list:
ids = json.loads(pj.item_ids or "[]")
if not ids:
return []
return (db.query(OrderItem)
.filter(OrderItem.id.in_(ids), OrderItem.status == "active", OrderItem.printed == False) # noqa: E712
.order_by(OrderItem.id).all())
def _last_error(db, pj) -> str | None:
log = (db.query(PrintLog)
.filter(PrintLog.order_id == pj.order_id, PrintLog.printer_id == pj.printer_id, PrintLog.success == False) # noqa: E712
.order_by(PrintLog.id.desc()).first())
return log.error_message if log else None
def problems(db, user=None) -> list[dict]:
"""Every ticket waiting to print on an open order, oldest first; with `user`, only the
orders that person may act on (the managers see all of them)."""
from models.prep_zone import PrepZone
from models.user import User
from routers.orders import _can_access_order
jobs = db.query(PrintJob).filter(PrintJob.status == "pending").order_by(PrintJob.first_attempted_at, PrintJob.id).all()
out, names = [], {}
for pj in jobs:
order = db.get(Order, pj.order_id)
if order is None or order.status in ("closed", "cancelled"):
continue
if user is not None and not _can_access_order(order, user, db):
continue
items = _waiting_items(db, pj)
if not items:
continue # printed meanwhile; the sweep will mark the job
printer = db.get(Printer, pj.printer_id)
zone = db.get(PrepZone, pj.zone_id) if pj.zone_id else None
senders = sorted({i.added_by for i in items if i.added_by})
for uid in senders:
if uid not in names:
u = db.get(User, uid)
names[uid] = (u.nickname or u.full_name or u.username) if u else f"#{uid}"
out.append({
"job_id": pj.id,
"order_id": order.id,
"table_id": order.table_id,
"table_name": _table_name(order),
"order_type": order.order_type or "here",
"printer": {"id": pj.printer_id, "name": printer.name if printer else f"#{pj.printer_id}"},
"zone": zone.name if zone is not None else None,
"items": [{"id": i.id, "name": i.product_name or (i.product.name if i.product else f"#{i.product_id}"),
"quantity": i.quantity, "unit_type": i.unit_type or "piece"} for i in items],
"since": pj.first_attempted_at,
"last_attempt": pj.last_attempted_at,
"attempts": pj.retry_count or 0,
"error": _last_error(db, pj),
"sent_by": [names[u] for u in senders],
})
return out
def printers(db) -> list[dict]:
"""The printers a ticket can be sent to instead."""
return [{"id": p.id, "name": p.name} for p in db.query(Printer).filter(Printer.is_active == True).order_by(Printer.name).all()] # noqa: E712
def _job(db, job_id: int, user) -> PrintJob:
from routers.orders import _can_access_order
pj = db.get(PrintJob, job_id)
if pj is None:
raise XeniaError("print_job.not_found")
if pj.status != "pending":
raise XeniaError("print_job.done")
order = db.get(Order, pj.order_id)
if order is None or not _can_access_order(order, user, db):
raise XeniaError("order.not_yours")
return pj
def _print(db, pj, printer, items) -> str | None:
"""One attempt of the job's lines on `printer` (the job's zone layout). → the error, or None."""
from models.prep_zone import PrepZone
from services import printer_service as ps
order = db.get(Order, pj.order_id)
zone = db.get(PrepZone, pj.zone_id) if pj.zone_id else None
error = None
try:
if ps._is_spoof_mode(db):
logger.info("Spoof printing ON — dropping print job %s on %s", pj.id, printer.name)
else:
for _ in range(pj.copies or 1):
p = ps._get_printer(printer.ip_address, printer.port, printer.codepage_n)
ps._print_kitchen_ticket(p, order, items, db, printer.line_width, zone=zone)
p.close()
except Exception as e: # noqa: BLE001 — any printer error is the answer
error = str(e) or e.__class__.__name__
db.add(PrintLog(order_id=pj.order_id, printer_id=printer.id, item_ids=json.dumps([i.id for i in items]),
success=error is None, error_message=error))
return error
def _done(db, pj, items, user) -> None:
for i in items:
i.printed = True
pj.resolved_by = user.id if user is not None else None
def retry(db, job_id: int, user) -> dict:
"""Print again now, on the same printer."""
pj = _job(db, job_id, user)
printer = db.get(Printer, pj.printer_id)
if printer is None or not printer.is_active:
raise XeniaError("print.printer_off", printer=printer.name if printer else f"#{pj.printer_id}")
items = _waiting_items(db, pj)
now = utcnow()
pj.last_attempted_at = now
pj.retry_count = (pj.retry_count or 0) + 1
error = _print(db, pj, printer, items) if items else None
if error is None:
pj.status, pj.succeeded_at = "success", now
_done(db, pj, items, user)
logger.info("print.job.success job=%s attempt=%s printer=%s by=user:%s", pj.id, pj.retry_count, printer.name, user.id)
else:
logger.error("print.job.failed job=%s attempt=%s printer=%s by=user:%s error=%r", pj.id, pj.retry_count, printer.name, user.id, error)
db.commit()
announce(pj.order_id)
return {"ok": error is None, "printer": printer.name, "error": error}
def redirect(db, job_id: int, printer_id: int, user) -> dict:
"""Send the ticket to another printer. Refused (print.redirect_failed) when that one
fails too; the problem then stays as it was."""
pj = _job(db, job_id, user)
printer = db.get(Printer, printer_id)
if printer is None or not printer.is_active:
raise XeniaError("print.printer_off", printer=printer.name if printer else f"#{printer_id}")
items = _waiting_items(db, pj)
error = _print(db, pj, printer, items) if items else None
if error is not None:
db.commit() # keep the attempt in the printer history
logger.error("print.job.redirect_failed job=%s to=%s by=user:%s error=%r", pj.id, printer.name, user.id, error)
raise XeniaError("print.redirect_failed", printer=printer.name, error=error)
pj.status, pj.succeeded_at, pj.redirected_to = "success", utcnow(), printer.id
_done(db, pj, items, user)
db.commit()
logger.warning("print.job.redirected job=%s order=%s from=%s to=%s by=user:%s", pj.id, pj.order_id, pj.printer_id, printer.name, user.id)
announce(pj.order_id)
return {"ok": True, "printer": printer.name}
def handled(db, job_id: int, user) -> dict:
"""Someone told the kitchen another way: stop retrying and stop warning."""
pj = _job(db, job_id, user)
items = _waiting_items(db, pj)
pj.status, pj.cancelled_at, pj.cancel_reason = "cancelled", utcnow(), "handled"
_done(db, pj, items, user)
db.commit()
logger.warning("print.job.abandoned job=%s order=%s attempts=%s reason=handled by=user:%s", pj.id, pj.order_id, pj.retry_count, user.id)
announce(pj.order_id)
return {"ok": True}
+12
View File
@@ -2026,6 +2026,9 @@ def _do_route_and_print(order_id: int, item_ids: List[int], db: Session, ephemer
db.commit()
for pj, printer_name in failing: # after the commit: notify() commits too
_notify_print_failing(db, pj, printer_name)
if failing: # 6.10: the apps show the problem at once
from services.print_problems import announce
announce(order_id)
return results
@@ -2208,6 +2211,7 @@ def _retry_sweep():
logger.warning("print.job.abandoned job=%s order=%s attempts=%s reason=order_closed",
pj.id, pj.order_id, pj.retry_count)
_notify_print_failed(db, pj)
_announce(pj.order_id)
continue
item_ids = json.loads(pj.item_ids or "[]")
@@ -2223,6 +2227,7 @@ def _retry_sweep():
pj.succeeded_at = now
db.commit()
logger.info("print.job.resolved job=%s reason=items_printed_or_removed", pj.id)
_announce(pj.order_id)
continue
printer = db.query(Printer).filter(Printer.id == pj.printer_id, Printer.is_active == True).first() # noqa: E712
@@ -2268,6 +2273,8 @@ def _retry_sweep():
db.commit()
if not success:
_notify_print_failing(db, pj, printer.name)
else:
_announce(pj.order_id) # 6.10: printed on a retry, the warning clears
except Exception as e:
logger.exception("Unexpected error processing PrintJob %s: %s", job_id, e)
@@ -2275,6 +2282,11 @@ def _retry_sweep():
db.close()
def _announce(order_id) -> None:
from services.print_problems import announce
announce(order_id)
def _alert_after_failures(db) -> int:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == "print.alert_after_failures").first()
+147
View File
@@ -0,0 +1,147 @@
"""Printing problems (plan step 6.10): a ticket that doesn't print is listed for whoever sent it
and for the managers, and can be printed again, sent to another printer or marked as handled."""
import socket
import threading
import time
import pytest
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, waiter # noqa: F401 (fixtures)
def _closed_port() -> int:
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close() # nothing listens: connection refused, like a printer off
return port
@pytest.fixture
def bar_printer():
"""A printer that works: a TCP listener that keeps what it gets."""
srv = socket.socket()
srv.bind(("127.0.0.1", 0))
srv.listen(8)
got = []
def serve():
while True:
try:
conn, _ = srv.accept()
except OSError:
return
data = b""
while chunk := conn.recv(4096):
data += chunk
got.append(data)
conn.close()
threading.Thread(target=serve, daemon=True).start()
yield srv.getsockname()[1], got
srv.close()
@pytest.fixture
def on_shift(db, day, waiter):
from models.shift import WaiterShift
db.add(WaiterShift(waiter_id=waiter["user"].id, business_day_id=day.id, starting_cash=0))
db.commit()
@pytest.fixture
def kitchen(db, menu, bar_printer):
"""The burger prints in the kitchen (whose printer is off); the bar printer works."""
from models.prep_zone import PrepZone
from models.printer import Printer
k = Printer(name="Kitchen", ip_address="127.0.0.1", port=_closed_port(), is_active=True)
b = Printer(name="Bar", ip_address="127.0.0.1", port=bar_printer[0], is_active=True)
db.add_all([k, b])
db.flush()
zone = PrepZone(name="Kitchen", auto_print="master", master_printer_id=k.id)
db.add(zone)
db.flush()
menu["burger"].prep_zones.append(zone)
db.commit()
return {"kitchen": k, "bar": b, "zone": zone, "got": bar_printer[1]}
def _order_with_burger(client, h, m):
o = client.post("/api/orders/", headers=h, json={"table_id": None, "order_type": "here"}).json()
line = {"product_id": m["burger"].id, "quantity": 1, "prefs": [{"set_id": m["cook"].id, "choices": [{"id": m["rare"].id}], "shared": "Fries"}]}
r = client.post(f"/api/orders/{o['id']}/items", headers=h, json={"lines": [line]})
assert r.status_code == 200, r.text
return o["id"], r.json()
def test_a_ticket_that_doesnt_print_is_sent_to_the_bar_and_the_warning_clears(client, db, menu, kitchen, day, waiter, on_shift, owner_h, monkeypatch):
import services.print_problems as pp
events = []
monkeypatch.setattr(pp, "announce", lambda order_id: events.append(order_id))
order_id, sent = _order_with_burger(client, waiter["h"], menu)
assert [r["success"] for r in sent["print_results"]] == [False]
assert events == [order_id] # told at once
# the waiter who sent it sees it, and so do the managers
for h in (waiter["h"], owner_h):
data = client.get("/api/print-problems", headers=h).json()
assert len(data["problems"]) == 1
p = data["problems"][0]
assert p["order_id"] == order_id and p["printer"]["name"] == "Kitchen" and p["zone"] == "Kitchen"
assert [i["name"] for i in p["items"]] == ["Burger"] and p["attempts"] == 1 and p["error"]
assert p["sent_by"] and {x["name"] for x in data["printers"]} == {"Kitchen", "Bar"}
# print again: still off
again = client.post(f"/api/print-problems/{p['job_id']}/retry", headers=waiter["h"]).json()
assert again["ok"] is False and client.get("/api/print-problems", headers=owner_h).json()["problems"][0]["attempts"] == 2
# to the bar: it prints there, the job is done, the line counts as printed, the list is empty
moved = client.post(f"/api/print-problems/{p['job_id']}/redirect", headers=waiter["h"], json={"printer_id": kitchen["bar"].id})
assert moved.status_code == 200 and moved.json()["printer"] == "Bar", moved.text
for _ in range(40):
if kitchen["got"]:
break
time.sleep(0.05)
assert kitchen["got"] and b"Burger" in kitchen["got"][0]
assert client.get("/api/print-problems", headers=owner_h).json()["problems"] == []
from models.order import OrderItem, PrintJob
db.expire_all()
job = db.get(PrintJob, p["job_id"])
assert job.status == "success" and job.redirected_to == kitchen["bar"].id and job.resolved_by == waiter["user"].id
assert all(i.printed for i in db.query(OrderItem).filter(OrderItem.order_id == order_id))
# done means done: a second answer from another screen is refused
assert err(client.post(f"/api/print-problems/{p['job_id']}/handled", headers=owner_h)) == "print_job.done"
def test_marked_handled_or_a_dead_second_printer(client, db, menu, kitchen, day, waiter, on_shift, owner_h, make_user, login):
from models.order import PrintJob
from models.user import WaiterZone
order_id, _ = _order_with_burger(client, waiter["h"], menu)
job_id = client.get("/api/print-problems", headers=owner_h).json()["problems"][0]["job_id"]
# another printer that is off too: refused, the problem stays
kitchen["bar"].port = _closed_port()
db.commit()
r = client.post(f"/api/print-problems/{job_id}/redirect", headers=owner_h, json={"printer_id": kitchen["bar"].id})
assert err(r) == "print.redirect_failed" and len(client.get("/api/print-problems", headers=owner_h).json()["problems"]) == 1
# a waiter of another zone doesn't see it (nor can act on it)
from models.table import TableGroup
g = TableGroup(name="Terrace")
db.add(g)
db.flush()
other = make_user(role="waiter")
db.add(WaiterZone(waiter_id=other.id, group_id=g.id))
db.commit()
oh = login(other, client="waiter")
from models.table import Table
t = Table(number=9, group_id=None)
db.add(t)
db.commit()
o = db.get(__import__("models.order", fromlist=["Order"]).Order, order_id)
o.table_id = t.id
db.commit()
assert client.get("/api/print-problems", headers=oh).json()["problems"] == []
assert err(client.post(f"/api/print-problems/{job_id}/handled", headers=oh)) == "order.not_yours"
# handled: told the kitchen by voice
assert client.post(f"/api/print-problems/{job_id}/handled", headers=owner_h).json() == {"ok": True}
db.expire_all()
job = db.get(PrintJob, job_id)
assert job.status == "cancelled" and job.cancel_reason == "handled"
assert client.get("/api/print-problems", headers=owner_h).json()["problems"] == []
+1 -1
View File
@@ -37,7 +37,7 @@ import StaffPage from './pages/Management/StaffPage'
import SessionsPage from './pages/staff/SessionsPage'
import ApprovalsPage from './pages/staff/ApprovalsPage'
import ManagementSchedulePage from './pages/Management/SchedulePage'
import PrepZonesConfigPage from './pages/Management/PrepZonesConfigPage'
import PrepZonesConfigPage from './pages/printing/PrepZonesPage'
import PricingPage from './pages/pricing/PricingPage'
// Inventory
@@ -1,810 +0,0 @@
import { useState, useRef, useEffect } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import {
Plus, Pencil, Trash2, Printer, X, Check, ChevronDown,
Zap, Settings2, ArrowUpDown, Layers, CheckSquare, SkipForward,
GripVertical, ChevronUp, AlertTriangle, FlameKindling,
} from 'lucide-react'
import client from '../../api/client'
// ── API ───────────────────────────────────────────────────────────────────────
const fetchZones = () => client.get('/api/prep-zones').then(r => r.data)
const fetchPrinters = () => client.get('/api/system/printers').then(r => r.data)
const fetchCategories = () => client.get('/api/products/categories').then(r => r.data)
// ── Constants ─────────────────────────────────────────────────────────────────
const AUTO_PRINT_OPTIONS = [
{ value: 'none', label: 'Χωρίς εκτύπωση', desc: 'Μη αυτόματη εκτύπωση' },
{ value: 'master', label: 'Μόνο κύριος', desc: 'Εκτύπωση στον κύριο' },
{ value: 'all', label: 'Όλοι εκτυπωτές', desc: 'Master + δευτερεύοντες' },
]
const SORT_OPTIONS = [
{ value: 'order_time', label: 'Σειρά παραγγελίας', desc: 'Όπως προστέθηκαν στο καλάθι' },
{ value: 'item_count', label: 'Πλήθος (φθίνον)', desc: 'Πρώτα τα αντικείμενα με τη μεγαλύτερη ποσότητα' },
{ value: 'alpha', label: 'Αλφαβητικά', desc: 'Ταξινόμηση κατά όνομα' },
]
const EMPTY_ZONE = {
name: '', description: '', notification_name: '',
printer_ids: [], master_printer_id: null,
auto_print: 'none', master_copies: 1, secondary_copies: 1,
sort_items_by: 'order_time', group_by_category: false, category_order: [], print_checkboxes: false,
bypass_pending: false, bypass_kds: false, auto_ready_to_served: false,
}
// ── Helpers ───────────────────────────────────────────────────────────────────
function Toggle({ value, onChange, disabled }) {
return (
<button
type="button"
onClick={() => !disabled && onChange(!value)}
disabled={disabled}
className={`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors duration-200 focus:outline-none
${value ? 'bg-primary-600' : 'bg-gray-200'} ${disabled ? 'opacity-40 cursor-not-allowed' : 'cursor-pointer'}`}
>
<span className={`inline-block h-3.5 w-3.5 rounded-full bg-white shadow transition-transform duration-200
${value ? 'translate-x-4' : 'translate-x-0.5'}`} />
</button>
)
}
function CopySpinner({ value, onChange, min = 1, max = 9 }) {
return (
<div className="flex items-center gap-1.5">
<button
type="button"
onClick={() => onChange(Math.max(min, value - 1))}
className="w-8 h-8 rounded-lg border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-100 hover:border-gray-400 transition-colors text-base font-medium"
>−</button>
<span className="w-9 text-center text-sm font-bold text-gray-800 tabular-nums">{value}×</span>
<button
type="button"
onClick={() => onChange(Math.min(max, value + 1))}
className="w-8 h-8 rounded-lg border border-gray-300 flex items-center justify-center text-gray-600 hover:bg-gray-100 hover:border-gray-400 transition-colors text-base font-medium"
>+</button>
</div>
)
}
// ── Click-outside hook for dropdowns ─────────────────────────────────────────
function useClickOutside(ref, onClose) {
useEffect(() => {
function handle(e) {
if (ref.current && !ref.current.contains(e.target)) onClose()
}
document.addEventListener('mousedown', handle)
return () => document.removeEventListener('mousedown', handle)
}, [ref, onClose])
}
// ── Master printer single-select ──────────────────────────────────────────────
function MasterPrinterPicker({ printers, value, onChange }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
useClickOutside(ref, () => setOpen(false))
const selected = printers.find(p => p.id === value)
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen(v => !v)}
className="w-full flex items-center justify-between gap-2 px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm text-left hover:border-gray-400 transition-colors"
>
<span className="flex items-center gap-2 flex-1 min-w-0">
{selected ? (
<>
<span className="w-2 h-2 rounded-full bg-green-500 shrink-0" />
<span className="font-medium text-gray-800 truncate">{selected.name}</span>
<span className="text-xs text-gray-400 font-mono ml-auto shrink-0">{selected.ip_address}:{selected.port}</span>
</>
) : (
<span className="text-gray-400">— Χωρίς κύριο —</span>
)}
</span>
<ChevronDown size={13} className={`text-gray-400 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div className="absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-xl overflow-hidden">
<button
type="button"
onClick={() => { onChange(null); setOpen(false) }}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${!value ? 'bg-gray-50' : ''}`}
>
<span className="w-4 h-4 rounded border border-gray-300 flex items-center justify-center shrink-0">
{!value && <Check size={10} className="text-gray-600" />}
</span>
<span className="text-gray-400 italic text-xs">Χωρίς κύριο εκτυπωτή</span>
</button>
{printers.map(p => (
<button
key={p.id}
type="button"
onClick={() => { onChange(p.id); setOpen(false) }}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${value === p.id ? 'bg-primary-50' : ''}`}
>
<span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${value === p.id ? 'bg-primary-600 border-primary-600' : 'border-gray-300'}`}>
{value === p.id && <Check size={10} className="text-white" />}
</span>
<Printer size={13} className="text-gray-400 shrink-0" />
<span className={`flex-1 ${value === p.id ? 'font-semibold text-primary-700' : 'text-gray-700'}`}>{p.name}</span>
<span className="text-xs text-gray-400 font-mono">{p.ip_address}:{p.port}</span>
</button>
))}
</div>
)}
</div>
)
}
// ── Secondary printers multi-select ──────────────────────────────────────────
function SecondaryPrinterPicker({ printers, selected, masterId, onChange }) {
const [open, setOpen] = useState(false)
const ref = useRef(null)
useClickOutside(ref, () => setOpen(false))
const selectedSet = new Set(selected)
const eligible = printers.filter(p => p.id !== masterId)
const selectedPrinters = eligible.filter(p => selectedSet.has(p.id))
const toggle = (id) => {
const next = new Set(selectedSet)
if (next.has(id)) next.delete(id); else next.add(id)
onChange([...next])
}
return (
<div className="relative" ref={ref}>
<button
type="button"
onClick={() => setOpen(v => !v)}
className="w-full flex items-center justify-between gap-2 px-3 py-2 border border-gray-300 rounded-lg bg-white text-sm text-left hover:border-gray-400 transition-colors min-h-[38px]"
>
<span className="flex flex-wrap gap-1 flex-1 min-w-0">
{selectedPrinters.length === 0 ? (
<span className="text-gray-400">— Χωρίς δευτερεύοντες —</span>
) : (
selectedPrinters.map(p => (
<span key={p.id} className="inline-flex items-center gap-1 bg-gray-100 text-gray-600 rounded px-1.5 py-0.5 text-xs font-medium">
<Printer size={10} />{p.name}
</span>
))
)}
</span>
<ChevronDown size={13} className={`text-gray-400 shrink-0 transition-transform ${open ? 'rotate-180' : ''}`} />
</button>
{open && (
<div className="absolute z-50 top-full left-0 right-0 mt-1 bg-white border border-gray-200 rounded-xl shadow-xl overflow-hidden">
{eligible.length === 0 ? (
<div className="px-3 py-4 text-sm text-gray-400 text-center italic">
{printers.length <= 1 ? 'Δεν υπάρχουν άλλοι εκτυπωτές' : 'Ο μόνος εκτυπωτής είναι ο κύριος'}
</div>
) : eligible.map(p => {
const on = selectedSet.has(p.id)
return (
<button
key={p.id}
type="button"
onClick={() => toggle(p.id)}
className={`w-full flex items-center gap-3 px-3 py-2.5 text-sm text-left transition-colors hover:bg-gray-50 ${on ? 'bg-gray-50' : ''}`}
>
<span className={`w-4 h-4 rounded border flex items-center justify-center shrink-0 ${on ? 'bg-gray-700 border-gray-700' : 'border-gray-300'}`}>
{on && <Check size={10} className="text-white" />}
</span>
<Printer size={13} className="text-gray-400 shrink-0" />
<span className={`flex-1 ${on ? 'font-semibold text-gray-800' : 'text-gray-700'}`}>{p.name}</span>
<span className="text-xs text-gray-400 font-mono">{p.ip_address}:{p.port}</span>
</button>
)
})}
<div className="border-t border-gray-100 px-3 py-2 text-xs text-gray-400 italic">
Κλικ έξω για κλείσιμο
</div>
</div>
)}
</div>
)
}
// ── Category order modal ──────────────────────────────────────────────────────
function CategoryOrderModal({ categories, order, onSave, onClose }) {
const ranked = order.map(id => categories.find(c => c.id === id)).filter(Boolean)
const unranked = categories.filter(c => !order.includes(c.id))
const [list, setList] = useState([...ranked, ...unranked])
const dragIdx = useRef(null)
const onDragStart = (i) => { dragIdx.current = i }
const onDragOver = (e, i) => {
e.preventDefault()
if (dragIdx.current === null || dragIdx.current === i) return
const next = [...list]
const [moved] = next.splice(dragIdx.current, 1)
next.splice(i, 0, moved)
dragIdx.current = i
setList(next)
}
const onDragEnd = () => { dragIdx.current = null }
const move = (i, dir) => {
const j = i + dir
if (j < 0 || j >= list.length) return
const next = [...list];
[next[i], next[j]] = [next[j], next[i]]
setList(next)
}
return (
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-sm p-4">
<div className="bg-white rounded-2xl shadow-2xl w-full max-w-md overflow-hidden">
<div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
<div>
<h2 className="text-sm font-bold text-gray-900">Σειρά Κατηγοριών Εκτύπωσης</h2>
<p className="text-xs text-gray-500 mt-0.5">Σύρετε για αλλαγή σειράς</p>
</div>
<button type="button" onClick={onClose} className="p-1.5 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100 transition-colors">
<X size={16} />
</button>
</div>
<div className="px-3 py-3 max-h-80 overflow-y-auto space-y-1">
{list.map((cat, i) => (
<div
key={cat.id}
draggable
onDragStart={() => onDragStart(i)}
onDragOver={e => onDragOver(e, i)}
onDragEnd={onDragEnd}
className="flex items-center gap-2.5 px-3 py-2.5 bg-gray-50 rounded-xl border border-gray-100 cursor-grab active:cursor-grabbing select-none group hover:bg-white hover:border-gray-200 hover:shadow-sm transition-all"
>
<GripVertical size={14} className="text-gray-300 group-hover:text-gray-400 shrink-0" />
<span className="w-2.5 h-2.5 rounded-full shrink-0" style={{ background: cat.color || '#94a3b8' }} />
<span className="text-sm text-gray-700 font-medium flex-1 min-w-0 truncate">{cat.name}</span>
<div className="flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity">
<button type="button" onClick={() => move(i, -1)} disabled={i === 0}
className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
<ChevronUp size={13} />
</button>
<button type="button" onClick={() => move(i, 1)} disabled={i === list.length - 1}
className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
<ChevronDown size={13} />
</button>
</div>
<span className="text-xs text-gray-300 font-mono w-5 text-right shrink-0">{i + 1}</span>
</div>
))}
{list.length === 0 && (
<div className="py-8 text-center text-sm text-gray-400">Δεν υπάρχουν κατηγορίες</div>
)}
</div>
<div className="px-5 py-4 border-t border-gray-100 flex gap-2 justify-end">
<button type="button" onClick={onClose} className="btn btn-secondary">Ακύρωση</button>
<button
type="button"
onClick={() => { onSave(list.map(c => c.id)); onClose() }}
className="btn btn-primary flex items-center gap-2"
>
<Check size={14} /> Αποθήκευση σειράς
</button>
</div>
</div>
</div>
)
}
// ── Section header ────────────────────────────────────────────────────────────
function Section({ icon: Icon_, label, children }) {
return (
<div className="space-y-3">
<div className="flex items-center gap-2 pb-1.5 border-b border-gray-100">
<Icon_ size={13} className="text-gray-400" />
<span className="text-[11px] font-bold text-gray-400 uppercase tracking-widest">{label}</span>
</div>
{children}
</div>
)
}
// ── Toggle row ────────────────────────────────────────────────────────────────
function ToggleRow({ label, desc, value, onChange, disabled, children, warning }) {
return (
<div className={`rounded-xl border transition-colors ${value ? 'border-primary-200 bg-primary-50/40' : 'border-gray-200 bg-gray-50/40'} ${disabled ? 'opacity-60' : ''}`}>
<div className="flex items-center gap-3 px-4 py-3">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1.5">
<span className="text-sm font-semibold text-gray-800">{label}</span>
{warning && <AlertTriangle size={12} className="text-amber-500 shrink-0" />}
</div>
{desc && <p className="text-xs text-gray-500 mt-0.5 leading-relaxed">{desc}</p>}
</div>
<Toggle value={value} onChange={onChange} disabled={disabled} />
</div>
{value && children && (
<div className="px-4 pb-3">{children}</div>
)}
</div>
)
}
// ── Zone Form ─────────────────────────────────────────────────────────────────
function ZoneForm({ initial, printers, categories, onSave, onCancel, saving }) {
const z = initial || EMPTY_ZONE
const [name, setName] = useState(z.name)
const [description, setDesc] = useState(z.description || '')
const [notifName, setNotifName] = useState(z.notification_name || '')
const [allPrinterIds, setAllPrinterIds] = useState(z.printer_ids || [])
const [masterId, setMasterId] = useState(z.master_printer_id ?? null)
const [autoPrint, setAutoPrint] = useState(z.auto_print || 'none')
const [masterCopies, setMasterCopies] = useState(z.master_copies || 1)
const [secondaryCopies, setSecondaryCopies] = useState(z.secondary_copies || 1)
const [sortBy, setSortBy] = useState(z.sort_items_by || 'order_time')
const [groupCat, setGroupCat] = useState(z.group_by_category || false)
const [catOrder, setCatOrder] = useState(z.category_order || [])
const [checkboxes, setCheckboxes] = useState(z.print_checkboxes || false)
const [bypassPending, setBypassPending] = useState(z.bypass_pending || false)
const [bypassKds, setBypassKds] = useState(z.bypass_kds || false)
const [autoReadyServed, setAutoReadyServed] = useState(z.auto_ready_to_served || false)
const [catModal, setCatModal] = useState(false)
const secondaryIds = allPrinterIds.filter(id => id !== masterId)
const handleMasterChange = (id) => {
setMasterId(id)
if (id && !allPrinterIds.includes(id)) setAllPrinterIds(prev => [...prev, id])
}
const handleSecondaryChange = (ids) => {
const next = new Set(ids)
if (masterId) next.add(masterId)
setAllPrinterIds([...next])
}
const handleBypassKds = (v) => { setBypassKds(v); if (v) setBypassPending(true) }
const handleBypassPending = (v) => { setBypassPending(v); if (!v) setBypassKds(false) }
const valid = name.trim().length > 0
const submit = (e) => {
e.preventDefault()
if (!valid) return
onSave({
name: name.trim(),
description: description.trim() || null,
notification_name: notifName.trim() || null,
printer_ids: allPrinterIds,
master_printer_id: masterId || null,
auto_print: autoPrint,
master_copies: masterCopies,
secondary_copies: secondaryCopies,
sort_items_by: sortBy,
group_by_category: groupCat,
category_order: catOrder,
print_checkboxes: checkboxes,
bypass_pending: bypassPending,
bypass_kds: bypassKds,
auto_ready_to_served: autoReadyServed,
})
}
return (
<>
<form onSubmit={submit} className="space-y-5">
{/* Identity */}
<Section icon={Settings2} label="Στοιχεία Ζώνης">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="label">Όνομα ζώνης *</label>
<input className="input" value={name} onChange={e => setName(e.target.value)}
placeholder="π.χ. Kitchen – Grill" autoFocus />
</div>
<div>
<label className="label">Όνομα ειδοποίησης</label>
<input className="input" value={notifName} onChange={e => setNotifName(e.target.value)}
placeholder="π.χ. Κουζίνα" />
</div>
</div>
<div>
<label className="label">Περιγραφή</label>
<input className="input" value={description} onChange={e => setDesc(e.target.value)}
placeholder="Προαιρετική περιγραφή" />
</div>
</Section>
{/* Printers */}
<Section icon={Printer} label="Εκτυπωτές">
<div className="grid grid-cols-2 gap-3">
<div>
<label className="label">Κύριος εκτυπωτής</label>
<MasterPrinterPicker printers={printers} value={masterId} onChange={handleMasterChange} />
<p className="mt-1 text-xs text-gray-400">Ένας μόνο, υψηλή προτεραιότητα.</p>
</div>
<div>
<label className="label">Δευτερεύοντες εκτυπωτές</label>
<SecondaryPrinterPicker
printers={printers} selected={secondaryIds}
masterId={masterId} onChange={handleSecondaryChange}
/>
<p className="mt-1 text-xs text-gray-400">Μόνο στη λειτουργία «Όλοι».</p>
</div>
</div>
<div>
<label className="label">Αυτόματη εκτύπωση</label>
<div className="grid grid-cols-3 gap-2">
{AUTO_PRINT_OPTIONS.map(opt => (
<button key={opt.value} type="button" onClick={() => setAutoPrint(opt.value)}
className={`px-3 py-2.5 rounded-xl border text-left transition-all
${autoPrint === opt.value
? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
: 'border-gray-200 hover:border-gray-300 bg-white'}`}>
<div className={`text-xs font-bold leading-tight ${autoPrint === opt.value ? 'text-primary-700' : 'text-gray-700'}`}>{opt.label}</div>
<div className="text-[11px] text-gray-400 mt-0.5">{opt.desc}</div>
</button>
))}
</div>
</div>
{autoPrint !== 'none' && (
<div className="grid grid-cols-2 gap-4">
<div>
<label className="label">Αντίτυπα κύριου</label>
<CopySpinner value={masterCopies} onChange={setMasterCopies} />
</div>
{autoPrint === 'all' && (
<div>
<label className="label">Αντίτυπα δευτερευόντων</label>
<CopySpinner value={secondaryCopies} onChange={setSecondaryCopies} />
</div>
)}
</div>
)}
</Section>
{/* Ticket formatting */}
<Section icon={ArrowUpDown} label="Μορφοποίηση Δελτίου">
<div>
<label className="label">Ταξινόμηση αντικειμένων</label>
<div className="grid grid-cols-3 gap-2">
{SORT_OPTIONS.map(opt => (
<button key={opt.value} type="button" onClick={() => setSortBy(opt.value)}
className={`px-3 py-2.5 rounded-xl border text-left transition-all
${sortBy === opt.value
? 'border-primary-500 bg-primary-50 ring-1 ring-primary-500'
: 'border-gray-200 hover:border-gray-300 bg-white'}`}>
<div className={`text-xs font-bold leading-tight ${sortBy === opt.value ? 'text-primary-700' : 'text-gray-700'}`}>{opt.label}</div>
<div className="text-[11px] text-gray-400 mt-0.5">{opt.desc}</div>
</button>
))}
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<ToggleRow
label="Ομαδοποίηση κατά κατηγορία"
desc="Αντικείμενα ομαδοποιούνται ανά κατηγορία."
value={groupCat} onChange={setGroupCat}
>
<button type="button" onClick={() => setCatModal(true)}
className="mt-1 inline-flex items-center gap-1.5 text-xs font-semibold text-primary-600 hover:text-primary-700 bg-white border border-primary-200 rounded-lg px-3 py-1.5 hover:bg-primary-50 transition-colors">
<Layers size={12} />
Σειρά κατηγοριών
{catOrder.length > 0 && (
<span className="bg-primary-100 text-primary-700 rounded px-1 text-[10px] font-bold">{catOrder.length}</span>
)}
</button>
</ToggleRow>
<ToggleRow
label="Checkboxes"
desc="Προσθέτει [ ] πριν από κάθε αντικείμενο."
value={checkboxes} onChange={setCheckboxes}
/>
</div>
</Section>
{/* KDS Behavior */}
<Section icon={Zap} label="Συμπεριφορά KDS">
<div className="grid grid-cols-1 gap-3">
<ToggleRow
label="Παράκαμψη Pending & Prep"
desc="Αντικείμενα ξεκινούν απευθείας σε READY. Χρήσιμο για ποτά ή μπύρες."
value={bypassPending} onChange={handleBypassPending}
/>
<ToggleRow
label="Παράκαμψη KDS Status"
desc="Αντικείμενα πηγαίνουν κατευθείαν σε SERVED. Ενεργοποιεί αυτόματα και την Παράκαμψη Pending."
value={bypassKds} onChange={handleBypassKds} warning
/>
<ToggleRow
label="Αυτόματο Ready → Served"
desc="Όταν ο σεφ επισημαίνει READY στο KDS, αυτόματα αναβαθμίζεται και σε SERVED."
value={autoReadyServed} onChange={setAutoReadyServed}
/>
</div>
</Section>
{/* Actions */}
<div className="flex gap-3 justify-end pt-3 border-t border-gray-100">
<button type="button" onClick={onCancel} className="btn btn-secondary">
Ακύρωση
</button>
<button type="submit" disabled={!valid || saving} className="btn btn-primary flex items-center gap-2">
<Check size={15} />
{saving ? 'Αποθήκευση…' : 'Αποθήκευση'}
</button>
</div>
</form>
{catModal && (
<CategoryOrderModal
categories={categories} order={catOrder}
onSave={setCatOrder} onClose={() => setCatModal(false)}
/>
)}
</>
)
}
// ── Zone Card ─────────────────────────────────────────────────────────────────
function Badge({ children, variant = 'default' }) {
const cls = {
default: 'bg-gray-100 text-gray-600',
primary: 'bg-primary-100 text-primary-700',
green: 'bg-green-100 text-green-700',
amber: 'bg-amber-100 text-amber-700',
red: 'bg-red-100 text-red-700',
}[variant] || 'bg-gray-100 text-gray-600'
return (
<span className={`inline-flex items-center gap-1 rounded-md px-2 py-0.5 text-[11px] font-semibold ${cls}`}>
{children}
</span>
)
}
function ZoneCard({ zone, printers, onEdit, onDelete }) {
const [confirmDelete, setConfirmDelete] = useState(false)
const printerMap = Object.fromEntries(printers.map(p => [p.id, p]))
const masterPrinter = printerMap[zone.master_printer_id]
const secondaryPrinters = (zone.secondary_printer_ids || []).map(id => printerMap[id]).filter(Boolean)
const printLabel = {
none: { text: 'Χωρίς εκτύπωση', variant: 'default' },
master: { text: 'Κύριος μόνο', variant: 'primary' },
all: { text: 'Όλοι', variant: 'primary' },
}[zone.auto_print] || { text: '—', variant: 'default' }
const sortLabel = {
order_time: 'Σειρά παρ.',
item_count: 'Κατά πλήθος',
alpha: 'Αλφαβητικά',
}[zone.sort_items_by] || zone.sort_items_by
return (
<div className="bg-white border border-gray-200 rounded-2xl shadow-sm overflow-hidden hover:shadow-md hover:border-gray-300 transition-all group">
<div className="px-4 pt-4 pb-3 flex items-start justify-between gap-3">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-2 flex-wrap">
<h3 className="font-bold text-gray-900 text-sm leading-tight">{zone.name}</h3>
{zone.bypass_kds && <Badge variant="red"><Zap size={10} />Bypass KDS</Badge>}
{!zone.bypass_kds && zone.bypass_pending && <Badge variant="amber"><SkipForward size={10} />Bypass Pending</Badge>}
{zone.auto_ready_to_served && <Badge variant="green"><Check size={10} />Auto Served</Badge>}
</div>
{zone.notification_name && (
<p className="text-xs text-primary-600 font-medium mt-0.5">{zone.notification_name}</p>
)}
{zone.description && <p className="text-xs text-gray-400 mt-0.5">{zone.description}</p>}
</div>
<div className="flex gap-0.5 shrink-0 opacity-0 group-hover:opacity-100 transition-opacity">
<button onClick={() => onEdit(zone)}
className="p-1.5 rounded-lg text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors">
<Pencil size={13} />
</button>
{!confirmDelete ? (
<button onClick={() => setConfirmDelete(true)}
className="p-1.5 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 size={13} />
</button>
) : (
<div className="flex gap-1 items-center">
<button onClick={() => setConfirmDelete(false)}
className="p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 transition-colors">
<X size={13} />
</button>
<button onClick={() => onDelete(zone.id)}
className="px-2 py-1 rounded-lg text-xs font-bold bg-red-600 text-white hover:bg-red-700 transition-colors">
Διαγραφή
</button>
</div>
)}
</div>
</div>
<div className="px-4 pb-3 space-y-1.5">
<div className="flex items-center gap-2">
<span className="text-[10px] font-bold text-gray-400 uppercase tracking-wide w-14 shrink-0">Κύριος</span>
{masterPrinter ? (
<>
<span className="inline-flex items-center gap-1 bg-primary-50 text-primary-700 rounded-md px-2 py-0.5 text-xs font-medium">
<Printer size={10} />{masterPrinter.name}
</span>
{zone.auto_print !== 'none' && (
<span className="text-xs text-gray-400 font-mono">{zone.master_copies}×</span>
)}
</>
) : (
<span className="text-xs text-gray-400 italic">Χωρίς</span>
)}
</div>
{secondaryPrinters.length > 0 && (
<div className="flex items-center gap-2 flex-wrap">
<span className="text-[10px] font-bold text-gray-400 uppercase tracking-wide w-14 shrink-0">Δευτ.</span>
{secondaryPrinters.map(p => (
<span key={p.id} className="inline-flex items-center gap-1 bg-gray-100 text-gray-600 rounded-md px-2 py-0.5 text-xs font-medium">
<Printer size={10} />{p.name}
</span>
))}
{zone.auto_print === 'all' && (
<span className="text-xs text-gray-400 font-mono">{zone.secondary_copies}×</span>
)}
</div>
)}
</div>
<div className="px-4 py-2.5 border-t border-gray-100 bg-gray-50/60 flex flex-wrap gap-1.5 items-center">
<Badge variant={zone.auto_print !== 'none' ? 'primary' : 'default'}>{printLabel.text}</Badge>
<Badge>{sortLabel}</Badge>
{zone.group_by_category && <Badge><Layers size={10} />Κατά κατηγορία</Badge>}
{zone.print_checkboxes && <Badge><CheckSquare size={10} />Checkboxes</Badge>}
</div>
</div>
)
}
// ── Main Page ─────────────────────────────────────────────────────────────────
export default function PrepZonesConfigPage() {
const qc = useQueryClient()
const [showForm, setShowForm] = useState(false)
const [editing, setEditing] = useState(null)
const { data: zones = [], isLoading: lZ } = useQuery({ queryKey: ['prep-zones'], queryFn: fetchZones })
const { data: printers = [], isLoading: lP } = useQuery({ queryKey: ['printers'], queryFn: fetchPrinters })
const { data: categories = [], isLoading: lC } = useQuery({ queryKey: ['categories'], queryFn: fetchCategories })
const invalidate = () => qc.invalidateQueries({ queryKey: ['prep-zones'] })
const create = useMutation({
mutationFn: body => client.post('/api/prep-zones', body).then(r => r.data),
onSuccess: () => { invalidate(); setShowForm(false); toast.success('Ζώνη δημιουργήθηκε') },
onError: () => toast.error('Σφάλμα κατά τη δημιουργία'),
})
const update = useMutation({
mutationFn: ({ id, ...body }) => client.put(`/api/prep-zones/${id}`, body).then(r => r.data),
onSuccess: () => { invalidate(); setEditing(null); toast.success('Ζώνη ενημερώθηκε') },
onError: () => toast.error('Σφάλμα κατά την ενημέρωση'),
})
const remove = useMutation({
mutationFn: id => client.delete(`/api/prep-zones/${id}`),
onSuccess: () => { invalidate(); toast.success('Ζώνη διαγράφηκε') },
onError: () => toast.error('Σφάλμα κατά τη διαγραφή'),
})
if (lZ || lP || lC) {
return (
<div className="p-8 flex items-center gap-3 text-sm text-gray-400">
<div className="w-4 h-4 rounded-full border-2 border-gray-300 border-t-primary-500 animate-spin" />
Φόρτωση…
</div>
)
}
const flatCategories = categories.flatMap(c => [c, ...(c.subcategories || [])])
const formOpen = showForm || !!editing
return (
// h-full + overflow-y-auto makes this page scroll within the fixed AppLayout <main>
<div className="h-full overflow-y-auto">
<div className="p-6">
{/* Page header */}
<div className="flex items-start justify-between mb-6">
<div className="flex items-center gap-2.5">
<div className="w-8 h-8 rounded-xl bg-orange-100 flex items-center justify-center shrink-0">
<FlameKindling size={16} className="text-orange-600" />
</div>
<div>
<h1 className="text-xl font-bold text-gray-900 leading-tight">Ζώνες Προετοιμασίας</h1>
<p className="text-sm text-gray-500">Ζώνες, εκτυπωτές και συμπεριφορά KDS</p>
</div>
</div>
{!formOpen && (
<button onClick={() => setShowForm(true)} className="btn btn-primary flex items-center gap-2 shrink-0">
<Plus size={15} />
Νέα Ζώνη
</button>
)}
</div>
{/* Two-column layout when form is open */}
{formOpen ? (
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,1fr)] gap-6 items-start xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
{/* Form panel */}
<div className={`bg-white rounded-2xl p-6 shadow-sm border ${showForm ? 'border-primary-200' : 'border-amber-200'}`}>
<div className="flex items-center gap-2 mb-5">
<div className={`w-1 h-5 rounded-full ${showForm ? 'bg-primary-500' : 'bg-amber-400'}`} />
<h2 className="text-sm font-bold text-gray-800">
{showForm ? 'Νέα Ζώνη Προετοιμασίας' : `Επεξεργασία: ${editing?.name}`}
</h2>
</div>
<ZoneForm
initial={editing}
printers={printers}
categories={flatCategories}
onSave={showForm
? (body) => create.mutate(body)
: (body) => update.mutate({ id: editing.id, ...body })}
onCancel={() => { setShowForm(false); setEditing(null) }}
saving={create.isPending || update.isPending}
/>
</div>
{/* Zone list sidebar */}
<div className="space-y-3">
{zones.length === 0 ? (
<div className="text-center py-10 text-gray-400 bg-white rounded-2xl border border-gray-200">
<FlameKindling size={24} className="mx-auto mb-2 text-gray-300" />
<p className="text-sm">Δεν υπάρχουν ζώνες ακόμα</p>
</div>
) : zones.map(zone => (
<ZoneCard
key={zone.id}
zone={zone}
printers={printers}
onEdit={z => { setShowForm(false); setEditing(z) }}
onDelete={id => remove.mutate(id)}
/>
))}
</div>
</div>
) : (
/* Full-width zone grid when no form open */
zones.length === 0 ? (
<div className="text-center py-20 text-gray-400">
<div className="w-16 h-16 mx-auto mb-4 rounded-2xl bg-gray-100 flex items-center justify-center">
<FlameKindling size={28} className="text-gray-300" />
</div>
<div className="font-semibold text-gray-600 mb-1">Δεν υπάρχουν ζώνες ακόμα</div>
<p className="text-sm">Δημιουργήστε την πρώτη ζώνη για να αρχίσετε.</p>
</div>
) : (
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">
{zones.map(zone => (
<ZoneCard
key={zone.id}
zone={zone}
printers={printers}
onEdit={z => { setShowForm(false); setEditing(z) }}
onDelete={id => remove.mutate(id)}
/>
))}
</div>
)
)}
</div>
</div>
)
}
@@ -7,7 +7,7 @@ import VenueSettings from './sections/VenueSettings'
import AppInfoTab from './tabs/AppInfoTab'
import ColoursTab from './tabs/ColoursTab'
import OperationTab from './tabs/OperationTab'
import PrintFontsTab from './tabs/PrintFontsTab'
import PrintingSettings from '../printing/PrintingSettings'
import SecurityTab from './tabs/SecurityTab'
import DevelopmentTab from './tabs/DevelopmentTab'
import FiscalTab from './tabs/FiscalTab'
@@ -39,7 +39,7 @@ export default function SettingsPage() {
{activeTab === 'security' && <SecurityTab />}
{activeTab === 'operation' && <OperationTab />}
{activeTab === 'colours' && <ColoursTab />}
{activeTab === 'print-fonts' && <PrintFontsTab />}
{activeTab === 'print-fonts' && <PrintingSettings />}
{activeTab === 'fiscal' && <FiscalTab />}
{activeTab === 'development' && <DevelopmentTab />}
</div>
File diff suppressed because it is too large Load Diff
@@ -20,6 +20,7 @@ import AddItems from './AddItems'
import OrderLines from './OrderLines'
import OrderPeople from './OrderPeople'
import PayDialog from './PayDialog'
import PrintProblemsCard from './PrintProblemsCard'
import { AuditList, PriceEventList } from './OrderHistory'
import { closeStep, totals, unpaidIds, venueRules } from './orderLogic'
@@ -152,6 +153,8 @@ function OrderView({ orderId }) {
)}
</div>
<PrintProblemsCard orderId={order.id} />
{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">
@@ -0,0 +1,43 @@
// Tickets that didn't print (plan step 6.10; replaces the overview's "waiting prints" card):
// on the overview, the Tables page (all of them) and an order's page (its own). Live: the list
// reloads on every `print.problems` event, so a ticket sent elsewhere or printed on a retry
// leaves every screen at once. The bell still tells managers away from these pages (print.failing).
import toast from 'react-hot-toast'
import { useQueryClient } from '@tanstack/react-query'
import { PrintProblemsPanel, actionRequest, problemsOf } from '@xenia/ordering'
import { useTranslation } from '@xenia/i18n'
import client from '../../api/client'
import { Card } from '../overview/parts'
import { usePrintProblems } from './usePrintProblems'
export default function PrintProblemsCard({ orderId = null, onOpen }) {
const { t } = useTranslation('manager')
const tc = useTranslation('common').t
const qc = useQueryClient()
const { data } = usePrintProblems()
const all = data?.problems ?? []
const shown = orderId == null ? all : problemsOf(all, orderId)
if (!shown.length) return null
async function run(kind, problem, printerId) {
const [url, body] = actionRequest(kind, problem, printerId)
const { data: res } = await client.post(url, body)
if (kind === 'retry' && !res.ok) toast.error(tc('printProblems.stillNot', { printer: res.printer }))
else toast.success(tc(`printProblems.done.${kind}`, { printer: res.printer }))
qc.invalidateQueries({ queryKey: ['print-problems'] })
qc.invalidateQueries({ queryKey: ['orders-active'] })
qc.invalidateQueries({ queryKey: ['order', problem.order_id] })
}
return (
<Card tone="danger" testId="print-problems-card"
title={<span className="grid">
<span>{tc('printProblems.title')}</span>
<span className="text-label font-normal">{tc('printProblems.count', { count: shown.length })}</span>
</span>}>
<PrintProblemsPanel problems={shown} printers={data?.printers ?? []} run={run} showPlace={orderId == null}
onOpen={onOpen ? p => onOpen(p.order_id, p.table_name) : undefined} />
<p className="px-4 pb-3 text-caption text-ink-3">{t('orders.printHelp')}</p>
</Card>
)
}
@@ -1,7 +1,8 @@
// 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.
// and can tell its waiters (or everyone) a message. Tickets that didn't print are listed below
// with what can be done about them (6.10).
// Everything stays current through the live events.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
@@ -14,7 +15,7 @@ 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 PrintProblemsCard from './PrintProblemsCard'
import { BORDER, SOFT, SOLID } from '../overview/tones'
import QuickActions from './QuickActions'
import { NO_ZONE, cardTarget, filterCards, flagsByTable, personName } from './orderLogic'
@@ -94,7 +95,7 @@ export default function TablesPage() {
</div>
))}
<PendingPrints cards={cards.filter(c => c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
<PrintProblemsCard onOpen={id => navigate(`/orders/${id}`)} />
{quick && <QuickActions card={quick} flagDefs={flagDefs} current={flags[quick.table.id] ?? []} onClose={() => setQuick(null)} />}
</div>
@@ -0,0 +1,14 @@
// The tickets that didn't print (plan step 6.10): GET /api/print-problems → { problems, printers },
// reloaded on the live event `print.problems` (and a closed order).
import { PRINT_EVENT } from '@xenia/ordering'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
export function usePrintProblems() {
return useLiveQuery({
queryKey: ['print-problems'],
queryFn: () => client.get('/api/print-problems').then(r => r.data),
events: [PRINT_EVENT, 'order_closed'],
refetchInterval: 60_000,
})
}
@@ -22,7 +22,8 @@ import DaySummaryDialog from './DaySummaryDialog'
import MessagesCard, { ComposeDialog } from './MessagesCard'
import NotesCard from './NotesCard'
import OrderDialog from './OrderDialog'
import PendingPrints from './PendingPrints'
import PrintProblemsCard from '../orders/PrintProblemsCard'
import { usePrintProblems } from '../orders/usePrintProblems'
import ShiftDialog from './ShiftDialog'
import ShiftsCard from './ShiftsCard'
import TablesCard from './TablesCard'
@@ -73,7 +74,7 @@ export default function OverviewPage() {
const dayOpen = !!day
const cards = tableCards(tables, orders)
const waiting = cards.filter(c => c.pendingPrint)
const waiting = usePrintProblems().data?.problems ?? [] // 6.10: tickets that didn't print
const today = dayOrders(orders, day?.opened_at)
const k = dayKpis({ cards, orders: today, shifts })
const idle = staff.filter(w => w.role === 'waiter' && !shifts.some(s => s.waiter_id === w.id))
@@ -160,6 +161,8 @@ export default function OverviewPage() {
<div className="grid gap-5 lg:grid-cols-[13fr_7fr] items-start">
<div className="grid gap-5 min-w-0">
{/* 6.10: tickets that didn't print come first: they need someone now */}
<PrintProblemsCard onOpen={(id, table) => setOrder({ id, table: table ?? `#${id}` })} />
<ShiftsCard shifts={shifts} idle={idle} dayOpen={dayOpen} hidden={hidden} canMessage={chatOn}
onStart={startShift}
onEnd={s => setShift({ shift: s, mode: 'close' })}
@@ -169,7 +172,6 @@ export default function OverviewPage() {
<Card title={t('overview.revenueByHour')} testId="revenue-chart">
<div className="p-4"><HourBars buckets={hourBuckets(orderPairs(today), hourOf)} current={nowHour} /></div>
</Card>
<PendingPrints cards={waiting} onOpen={(id, table) => setOrder({ id, table })} />
</div>
<div className="grid gap-5 min-w-0">
{notesOn && <NotesCard />}
@@ -1,74 +0,0 @@
// Orders with lines that haven't printed (plan step 6.2): which table, since when, how many
// retries, the lines waiting; print one again or all of them, or open the order.
import { useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button } from '@xenia/ui'
import client from '../../api/client'
import { printRetries, tableName } from './overviewLogic'
import { Card, Pill } from './parts'
export default function PendingPrints({ cards, onOpen }) {
const { t } = useTranslation('manager')
const { formatTime } = useFormat()
const qc = useQueryClient()
const [busy, setBusy] = useState(null) // an order id, or 'all'
if (cards.length === 0) return null
async function retry(orderId) {
try {
const res = await client.post(`/api/orders/${orderId}/retry-print`)
const failed = (res.data.print_results ?? []).filter(r => !r.success).map(r => r.printer_name)
if (failed.length) toast.error(t('overview.prints.failed', { printers: failed.join(', ') }))
else toast.success(t('overview.prints.done'))
} catch (err) {
toast.error(errorMessage(err, t))
}
}
async function run(id, fn) {
setBusy(id)
try { await fn() } finally {
setBusy(null)
qc.invalidateQueries({ queryKey: ['orders-active'] })
}
}
return (
<Card tone="warning" testId="pending-prints"
title={<span className="grid">
<span>{t('overview.prints.title')}</span>
<span className="text-label font-normal">{t('overview.prints.count', { count: cards.length })}</span>
</span>}
action={<Button size="sm" variant="secondary" icon={<Printer size={16} />} loading={busy === 'all'} disabled={busy != null}
onClick={() => run('all', async () => { for (const c of cards) await retry(c.order.id) })}>{t('overview.prints.all')}</Button>}>
<ul className="divide-y divide-line">
{cards.map(({ table, order }) => {
const waiting = order.items.filter(i => i.status === 'active' && !i.printed)
const retries = printRetries(order)
return (
<li key={order.id} className="flex items-center gap-3 px-4 py-2.5" data-testid="pending-print">
<span className="w-10 h-10 shrink-0 grid place-items-center rounded-control bg-warning-soft text-warning-ink text-label font-bold">{tableName(table)}</span>
<div className="flex-1 min-w-0">
<div className="flex flex-wrap items-center gap-2 text-label">
<span className="font-semibold text-ink">#{order.id}</span>
{order.opened_at && <span className="text-ink-2">{formatTime(order.opened_at)}</span>}
{retries > 0 && <Pill tone="warning">{t('overview.prints.retries', { count: retries })}</Pill>}
</div>
<div className="text-caption text-ink-2 truncate">
{t('overview.prints.lines', { count: waiting.length })} · {waiting.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
</div>
</div>
<Button size="sm" variant="ghost" onClick={() => onOpen(order.id, tableName(table))}>{t('overview.prints.open')}</Button>
<Button size="sm" variant="secondary" loading={busy === order.id} disabled={busy != null}
onClick={() => run(order.id, () => retry(order.id))}>{t('overview.prints.print')}</Button>
</li>
)
})}
</ul>
</Card>
)
}
@@ -203,12 +203,6 @@ export function notesPreview(notes = [], todos = []) {
].slice(0, 6)
}
/** The highest retry count among an order's waiting print jobs. */
export function printRetries(order) {
const waiting = (order.print_jobs ?? []).filter(j => j.status === 'pending').map(j => j.retry_count || 0)
return waiting.length ? Math.max(...waiting) : 0
}
/**
* The venue's wall clock for a moment, as a datetime-local value ("YYYY-MM-DDTHH:mm").
* Bookings are typed in venue time; the backend reads a time without an offset as venue time (D-11).
@@ -0,0 +1,103 @@
// Prep zones (plan step 6.10; replaces the v1 Management → Prep zones page): where each dish's
// ticket prints and how the kitchen screen treats it. A card per zone (its printers, whether it
// prints, the ticket's sorting, the kitchen screen's shortcuts); New / Edit open the zone's
// dialog, Delete asks first. Products are put in zones from the product editor.
import { useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { CookingPot, Pencil, Plus, Printer, Trash2 } from 'lucide-react'
import { useCan } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, IconButton, Spinner } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import ZoneDialog from './ZoneDialog'
export default function PrepZonesPage() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const canEdit = useCan('catalog.menu.manage')
const [editing, setEditing] = useState(null) // a zone, or {} for a new one
const [deleting, setDeleting] = useState(null)
const { data: zones, isPending } = useLiveQuery({ queryKey: ['prep-zones'], queryFn: () => client.get('/api/prep-zones').then(r => r.data) })
const { data: printers = [] } = useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 60_000 })
const { data: categories = [] } = useLiveQuery({ queryKey: ['categories'], queryFn: () => client.get('/api/products/categories').then(r => r.data), staleTime: 60_000 })
const remove = useMutation({
mutationFn: id => client.delete(`/api/prep-zones/${id}`),
onSuccess: () => { toast.success(t('printing.zones.deleted')); setDeleting(null); qc.invalidateQueries({ queryKey: ['prep-zones'] }) },
onError: err => toast.error(errorMessage(err, t)),
})
const nameOf = id => printers.find(p => p.id === id)?.name ?? `#${id}`
return (
<div className="h-full overflow-y-auto p-4 lg:p-6" data-testid="prep-zones-page">
<div className="max-w-6xl mx-auto grid gap-4">
<header className="flex flex-wrap items-center gap-3">
<div className="flex-1 min-w-0">
<h1 className="text-title font-semibold text-ink">{t('printing.zones.title')}</h1>
<p className="text-label text-ink-2">{t('printing.zones.intro')}</p>
</div>
{canEdit && <Button icon={<Plus size={16} />} onClick={() => setEditing({})} data-testid="zone-new">{t('printing.zones.new')}</Button>}
</header>
{isPending ? <div className="py-10 flex justify-center"><Spinner /></div>
: !zones?.length ? <EmptyState icon={<CookingPot size={28} />} title={t('printing.zones.none')} description={t('printing.zones.noneHint')} />
: (
<div className="grid gap-3 grid-cols-[repeat(auto-fill,minmax(18rem,1fr))]">
{zones.map(z => (
<section key={z.id} className="rounded-card border border-line bg-surface shadow-raised p-4 grid gap-3 content-start" data-testid="zone-card" data-name={z.name}>
<header className="flex items-start gap-2">
<div className="flex-1 min-w-0">
<h2 className="text-body-lg font-semibold text-ink truncate">{z.name}</h2>
{z.notification_name && <p className="text-label text-accent-ink">{z.notification_name}</p>}
{z.description && <p className="text-caption text-ink-3">{z.description}</p>}
</div>
{canEdit && (<>
<IconButton size="sm" variant="ghost" label={t('printing.zones.edit', { name: z.name })} onClick={() => setEditing(z)} data-testid="zone-edit"><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.zones.delete', { name: z.name })} onClick={() => setDeleting(z)}><Trash2 size={14} /></IconButton>
</>)}
</header>
<div className="grid gap-1 text-label">
<span className="flex flex-wrap items-center gap-1.5">
<span className="w-16 shrink-0 text-caption font-semibold uppercase tracking-wide text-ink-3">{t('printing.zones.main')}</span>
{z.master_printer_id ? <Pill tone="accent"><Printer size={12} aria-hidden="true" />{nameOf(z.master_printer_id)}{z.auto_print !== 'none' && z.master_copies > 1 ? ` ×${z.master_copies}` : ''}</Pill>
: <span className="text-ink-3">{t('printing.zones.noPrinter')}</span>}
</span>
{z.secondary_printer_ids?.length > 0 && (
<span className="flex flex-wrap items-center gap-1.5">
<span className="w-16 shrink-0 text-caption font-semibold uppercase tracking-wide text-ink-3">{t('printing.zones.also')}</span>
{z.secondary_printer_ids.map(id => <Pill key={id}><Printer size={12} aria-hidden="true" />{nameOf(id)}</Pill>)}
{z.auto_print === 'all' && z.secondary_copies > 1 && <span className="text-ink-3">×{z.secondary_copies}</span>}
</span>
)}
</div>
<footer className="flex flex-wrap gap-1.5 pt-2 border-t border-line">
<Pill tone={z.auto_print === 'none' ? 'warning' : 'success'}>{t(`printing.zones.autoShort.${z.auto_print}`)}</Pill>
<Pill>{t(`printing.zones.sortShort.${z.sort_items_by}`)}</Pill>
{z.group_by_category && <Pill>{t('printing.zones.byCategory')}</Pill>}
{z.print_checkboxes && <Pill>{t('printing.zones.checkboxes')}</Pill>}
{z.language && <Pill>{z.language.toUpperCase()}</Pill>}
{z.bypass_kds ? <Pill tone="danger">{t('printing.zones.skipKds')}</Pill> : z.bypass_pending && <Pill tone="warning">{t('printing.zones.startReady')}</Pill>}
{z.auto_ready_to_served && <Pill tone="info">{t('printing.zones.readyServed')}</Pill>}
</footer>
</section>
))}
</div>
)}
</div>
{editing && <ZoneDialog zone={editing.id ? editing : null} printers={printers} categories={categories}
onClose={() => setEditing(null)} onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['prep-zones'] }) }} />}
{deleting && (
<Dialog open size="sm" onClose={() => setDeleting(null)} title={t('printing.zones.deleteTitle', { name: deleting.name })}
description={t('printing.zones.deleteBody')}
footer={<>
<Button variant="secondary" onClick={() => setDeleting(null)}>{t('printing.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(deleting.id)} data-testid="zone-delete-confirm">{t('printing.zones.deleteYes')}</Button>
</>} />
)}
</div>
)
}
@@ -0,0 +1,206 @@
// The venue's printers (plan step 6.10; was the top of Settings → Print fonts): each with its
// address, model and line width, whether it answers now, on/off, a test print, edit, remove;
// "Add a printer" and "Find printers" (a scan of the network for the printing port).
import { useEffect, useRef, useState } from 'react'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Pencil, Plus, Printer, Radar, Trash2 } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, EmptyState, Field, IconButton, Input, Select, Switch } from '@xenia/ui'
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
import { Pill } from '../overview/parts'
import { SettingsCard } from '../Settings/sections/SettingsCard'
import { usePrinters } from './usePrinters'
import { EMPTY_PRINTER, PRINTER_MODELS, modelOf, printerBody, printerProblems } from './printingLogic'
export default function PrintersCard() {
const { t } = useTranslation('manager')
const qc = useQueryClient()
const { data: printers = [], isPending } = usePrinters()
const { data: status } = useLiveQuery({ queryKey: ['system-status'], queryFn: () => client.get('/api/system/status').then(r => r.data), refetchInterval: 30_000 })
const [editing, setEditing] = useState(null) // a printer, or a new one's starting values
const [finding, setFinding] = useState(false)
const [removing, setRemoving] = useState(null)
const changed = () => { qc.invalidateQueries({ queryKey: ['printers'] }); qc.invalidateQueries({ queryKey: ['system-status'] }) }
const onError = err => toast.error(errorMessage(err, t))
const toggle = useMutation({ mutationFn: p => client.put(`/api/system/printers/${p.id}`, { is_active: !p.is_active }), onSuccess: changed, onError })
const remove = useMutation({ mutationFn: id => client.delete(`/api/system/printers/${id}`), onSuccess: () => { setRemoving(null); toast.success(t('printing.printers.removed')); changed() }, onError })
const test = useMutation({
mutationFn: id => client.post('/api/system/printers/test', null, { params: { printer_id: id } }).then(r => r.data),
onSuccess: res => (res.success ? toast.success(t('printing.printers.testSent')) : toast.error(t('printing.printers.testFailed', { error: res.error }))),
onError,
})
const reachable = id => status?.printers?.find(p => p.id === id)?.reachable
return (
<SettingsCard title={t('printing.printers.title')} description={t('printing.printers.intro')} testId="printers-card">
<div className="px-5 py-3 flex flex-wrap gap-2">
<Button size="sm" icon={<Plus size={14} />} onClick={() => setEditing({ ...EMPTY_PRINTER })} data-testid="printer-new">{t('printing.printers.add')}</Button>
<Button size="sm" variant="secondary" icon={<Radar size={14} />} onClick={() => setFinding(true)}>{t('printing.printers.find')}</Button>
</div>
{!isPending && printers.length === 0 && <EmptyState compact icon={<Printer size={24} />} title={t('printing.printers.none')} />}
{printers.map(p => {
const r = p.is_active ? reachable(p.id) : null
return (
<div key={p.id} className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid="printer-row" data-name={p.name}>
<Switch checked={p.is_active} onChange={() => toggle.mutate(p)} aria-label={t('printing.printers.on', { name: p.name })} />
<div className={`flex-1 min-w-48 ${p.is_active ? '' : 'opacity-60'}`}>
<div className="text-body font-semibold text-ink">{p.name}</div>
<div className="text-caption text-ink-2">
{p.ip_address}:{p.port} · {modelOf(p.codepage_n)?.label ?? t('printing.printers.codepage', { n: p.codepage_n })} · {t('printing.printers.chars', { count: p.line_width })}
</div>
</div>
{p.is_active && (r == null ? <Pill>{t('printing.printers.checking')}</Pill>
: r ? <Pill tone="success">{t('printing.printers.answers')}</Pill> : <Pill tone="danger">{t('printing.printers.noAnswer')}</Pill>)}
<Button size="sm" variant="secondary" loading={test.isPending && test.variables === p.id} onClick={() => test.mutate(p.id)}>{t('printing.printers.test')}</Button>
<IconButton size="sm" variant="ghost" label={t('printing.printers.edit', { name: p.name })} onClick={() => setEditing(p)}><Pencil size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.printers.remove', { name: p.name })} onClick={() => setRemoving(p)}><Trash2 size={14} /></IconButton>
</div>
)
})}
{editing && <PrinterDialog printer={editing} onClose={() => setEditing(null)} onSaved={() => { setEditing(null); changed() }} />}
{finding && <FindPrinters onClose={() => setFinding(false)} onPick={found => { setFinding(false); setEditing({ ...EMPTY_PRINTER, ...found }) }} />}
{removing && (
<Dialog open size="sm" onClose={() => setRemoving(null)} title={t('printing.printers.removeTitle', { name: removing.name })}
description={t('printing.printers.removeBody')}
footer={<>
<Button variant="secondary" onClick={() => setRemoving(null)}>{t('printing.back')}</Button>
<Button variant="danger" loading={remove.isPending} onClick={() => remove.mutate(removing.id)}>{t('printing.printers.removeYes')}</Button>
</>} />
)}
</SettingsCard>
)
}
function PrinterDialog({ printer, onClose, onSaved }) {
const { t } = useTranslation('manager')
const [form, setForm] = useState(printer)
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const wrong = printerProblems(form)
const err = k => (tried && wrong.includes(k) ? t(`printing.printers.wrong.${k}`) : undefined)
const save = useMutation({
mutationFn: body => (printer.id ? client.put(`/api/system/printers/${printer.id}`, body) : client.post('/api/system/printers', body)),
onSuccess: () => { toast.success(t(printer.id ? 'printing.printers.saved' : 'printing.printers.added')); onSaved() },
onError: e => toast.error(errorMessage(e, t)),
})
const submit = () => { setTried(true); if (!wrong.length) save.mutate(printerBody(form)) }
const models = PRINTER_MODELS.some(m => m.codepage_n === Number(form.codepage_n)) ? PRINTER_MODELS
: [...PRINTER_MODELS, { label: t('printing.printers.codepage', { n: form.codepage_n }), codepage_n: Number(form.codepage_n) }]
return (
<Dialog open onClose={onClose} title={printer.id ? t('printing.printers.editTitle', { name: printer.name }) : t('printing.printers.addTitle')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="printer-save">{t('printing.save')}</Button>
</>}>
<div className="grid gap-3" data-testid="printer-dialog">
<Field label={t('printing.printers.name')} required error={err('name')}>
<Input value={form.name} onChange={e => set('name', e.target.value)} placeholder={t('printing.printers.namePh')} data-testid="printer-name" />
</Field>
<div className="grid gap-3 grid-cols-[1fr_7rem]">
<Field label={t('printing.printers.address')} required error={err('ip_address')} hint={t('printing.printers.addressHint')}>
<Input value={form.ip_address} inputMode="decimal" onChange={e => set('ip_address', e.target.value)} placeholder="192.168.1.50" data-testid="printer-ip" />
</Field>
<Field label={t('printing.printers.port')} error={err('port')}>
<Input value={form.port} inputMode="numeric" onChange={e => set('port', e.target.value)} data-testid="printer-port" />
</Field>
</div>
<div className="grid gap-3 grid-cols-[1fr_9rem]">
<Field label={t('printing.printers.model')} hint={t('printing.printers.modelHint')}>
<Select value={String(form.codepage_n)} onChange={e => set('codepage_n', Number(e.target.value))}
options={models.map(m => ({ value: String(m.codepage_n), label: m.label }))} />
</Field>
<Field label={t('printing.printers.width')} error={err('line_width')} hint={t('printing.printers.widthHint')}>
<Input value={form.line_width} inputMode="numeric" onChange={e => set('line_width', e.target.value)} />
</Field>
</div>
</div>
</Dialog>
)
}
/** A scan of the venue's network for devices answering on the printing port (streamed by the server). */
function FindPrinters({ onClose, onPick }) {
const { t } = useTranslation('manager')
const [subnet, setSubnet] = useState('')
const [port, setPort] = useState('9100')
const [scan, setScan] = useState({ running: false, found: [], done: 0, total: 0, error: null, ran: false })
const stop = useRef(null)
const { data: hints } = useLiveQuery({ queryKey: ['printer-scan-hints'], queryFn: () => client.get('/api/system/printers/scan-hints').then(r => r.data), staleTime: 60_000 })
const shownSubnet = subnet || hints?.subnets?.[0] || ''
useEffect(() => () => stop.current?.abort(), [])
async function start() {
stop.current?.abort()
const ctl = new AbortController()
stop.current = ctl
setScan({ running: true, found: [], done: 0, total: 0, error: null, ran: true })
try {
const res = await fetch(`/api/system/printers/scan?${new URLSearchParams({ subnet: shownSubnet, port })}`, {
headers: { Authorization: `Bearer ${localStorage.getItem('manager_token') || ''}` }, signal: ctl.signal,
})
if (!res.ok) throw new Error(String(res.status))
const reader = res.body.getReader()
const decoder = new TextDecoder()
let buf = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
const lines = buf.split('\n')
buf = lines.pop()
for (const line of lines) {
if (!line.startsWith('data: ')) continue
let msg = null
try { msg = JSON.parse(line.slice(6)) } catch { continue }
if (msg.type === 'found') setScan(s => ({ ...s, found: [...s.found, { ip_address: msg.ip, port: msg.port }] }))
else if (msg.type === 'progress') setScan(s => ({ ...s, done: msg.done, total: msg.total }))
else if (msg.error) setScan(s => ({ ...s, error: msg.error }))
}
}
} catch (err) {
if (err.name !== 'AbortError') setScan(s => ({ ...s, error: t('printing.printers.scanFailed') }))
} finally {
setScan(s => ({ ...s, running: false }))
}
}
const pct = scan.total ? Math.round((scan.done / scan.total) * 100) : 0
return (
<Dialog open onClose={onClose} title={t('printing.printers.findTitle')} description={t('printing.printers.findBody')}
footer={<Button variant="secondary" onClick={onClose}>{t('printing.close')}</Button>}>
<div className="grid gap-3">
<div className="grid gap-3 grid-cols-[1fr_6rem_auto] items-end">
<Field label={t('printing.printers.subnet')} hint="192.168.1.0/24">
<Input value={shownSubnet} onChange={e => setSubnet(e.target.value)} disabled={scan.running} />
</Field>
<Field label={t('printing.printers.port')}>
<Input value={port} inputMode="numeric" onChange={e => setPort(e.target.value)} disabled={scan.running} />
</Field>
{scan.running
? <Button variant="danger" onClick={() => stop.current?.abort()}>{t('printing.printers.stop')}</Button>
: <Button onClick={start} disabled={!shownSubnet}>{t('printing.printers.scan')}</Button>}
</div>
{scan.running && (
<div className="grid gap-1">
<div className="h-1.5 rounded-full bg-surface-2 overflow-hidden"><div className="h-full bg-accent transition-[width] duration-base" style={{ width: `${pct}%` }} /></div>
<span className="text-caption text-ink-3">{t('printing.printers.scanned', { done: scan.done, total: scan.total })}</span>
</div>
)}
{scan.error && <p role="alert" className="text-label text-danger-ink">{scan.error}</p>}
<ul className="divide-y divide-line rounded-control border border-line min-h-16">
{scan.found.length === 0 && <li className="px-3 py-4 text-center text-label text-ink-3">{scan.ran && !scan.running ? t('printing.printers.foundNone') : t('printing.printers.scanStart')}</li>}
{scan.found.map(f => (
<li key={f.ip_address} className="px-3 py-2 flex items-center gap-3">
<span className="flex-1 text-body font-semibold tabular-nums">{f.ip_address}<span className="text-ink-3 font-normal">:{f.port}</span></span>
<Button size="sm" onClick={() => onPick(f)}>{t('printing.printers.use')}</Button>
</li>
))}
</ul>
</div>
</Dialog>
)
}
@@ -0,0 +1,15 @@
// Settings → Printing (plan step 6.10; replaces the v1 "Print fonts" tab): when managers are
// told about tickets that keep failing, the printers, and the tickets' look and beep.
import PrintAlertSetting from '../Settings/sections/PrintAlertSetting'
import PrintersCard from './PrintersCard'
import TicketSettings from './TicketSettings'
export default function PrintingSettings() {
return (
<div className="max-w-4xl grid gap-5" data-testid="printing-settings">
<PrintersCard />
<PrintAlertSetting />
<TicketSettings />
</div>
)
}
@@ -0,0 +1,197 @@
// How kitchen and bar tickets look and sound (plan step 6.10; was Settings → Print fonts): the
// layout (detailed / compact) with a test ticket, the printer's beep with a test, each part's
// font (size, bold, capitals) with a preview, the dot leader and the dividers. Every change is
// saved at once and used from the next ticket.
import { useId, useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { Bell, Printer } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useTranslation } from '@xenia/i18n'
import { Button, Input, Select, cx } from '@xenia/ui'
import client from '../../api/client'
import { SettingRow, SettingsCard } from '../Settings/sections/SettingsCard'
import { useSettings } from '../Settings/sections/useSettings'
import { usePrinters } from './usePrinters'
import {
BEEPS, DEFAULTS, DIVIDERS, DIVIDER_CHARS, DOT_PREVIEW, DOT_STYLES, FONT_GROUPS, FONT_SIZES, TICKET_MODES,
beepBytes, beepSettings, decodeBeep, decodeDots, decodeFont, encodeDots, encodeFont, isWide,
} from './printingLogic'
// how a size looks on paper: tall doubles the height, wide the width
const SCALE = { 0: 'scale-100', 16: 'scale-y-[1.8]', 32: 'scale-x-[1.8]', 48: 'scale-[1.8]' }
function Paper({ children, className }) {
return <span className={cx('w-44 h-12 shrink-0 rounded-control border border-line bg-surface grid place-items-center overflow-hidden font-mono text-ink', className)}>{children}</span>
}
function Pick({ options, value, onChange, label }) {
return (
<div className="flex flex-wrap gap-1.5" role="radiogroup" aria-label={label}>
{options.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
className={cx('px-3 py-1.5 rounded-control border text-label', value === o.value ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{o.label}
</button>
))}
</div>
)
}
function Check({ on, onChange, label }) {
return (
<button type="button" aria-pressed={on} onClick={() => onChange(!on)}
className={cx('px-2.5 py-1.5 rounded-control border text-label font-semibold', on ? 'border-accent bg-accent-soft text-accent-ink' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{label}
</button>
)
}
function useTest() {
const { t } = useTranslation('manager')
return useMutation({
mutationFn: ({ url, params }) => client.post(url, null, { params }).then(r => r.data),
onSuccess: res => (res.success ? toast.success(t('printing.ticket.testSent')) : toast.error(t('printing.printers.testFailed', { error: res.error }))),
onError: err => toast.error(errorMessage(err, t)),
})
}
function PrinterPick({ printers, value, onChange }) {
const { t } = useTranslation('manager')
return (
<Select size="sm" value={value} onChange={e => onChange(e.target.value)} aria-label={t('printing.ticket.testOn')}
options={printers.map(p => ({ value: String(p.id), label: p.name }))} />
)
}
export default function TicketSettings() {
const { t } = useTranslation('manager')
const s = useSettings()
const { data: printers = [] } = usePrinters()
const active = printers.filter(p => p.is_active)
const [testPrinter, setTestPrinter] = useState('')
const printerId = testPrinter || (active[0] ? String(active[0].id) : '')
const test = useTest()
const val = key => s.get(key, DEFAULTS[key])
if (s.loading) return null
return (
<div className="grid gap-5">
<SettingsCard title={t('printing.ticket.layout')} testId="ticket-layout">
<SettingRow label={t('printing.ticket.mode')} tip={t('printing.ticket.modeTip')}>
<Pick label={t('printing.ticket.mode')} value={val('print.ticket_mode')} onChange={v => s.save('print.ticket_mode', v)}
options={TICKET_MODES.map(m => ({ value: m, label: t(`printing.ticket.modes.${m}`) }))} />
</SettingRow>
{active.length > 0 && (
<div className="px-5 py-3 flex flex-wrap items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t('printing.ticket.testHint')}</span>
<PrinterPick printers={active} value={printerId} onChange={setTestPrinter} />
<Button size="sm" variant="secondary" icon={<Printer size={14} />} loading={test.isPending && test.variables?.kind === 'order'}
onClick={() => test.mutate({ kind: 'order', url: '/api/system/printers/test-order', params: { printer_id: printerId } })}>{t('printing.ticket.testOrder')}</Button>
</div>
)}
</SettingsCard>
<Beep s={s} printers={active} printerId={printerId} onPrinter={setTestPrinter} test={test} />
<SettingsCard title={t('printing.ticket.fonts')} description={t('printing.ticket.fontsHint')} testId="ticket-fonts">
{FONT_GROUPS.map(g => (
<div key={g.key}>
<div className="px-5 pt-3 pb-1 text-caption font-semibold uppercase tracking-wide text-ink-3">{t(`printing.ticket.groups.${g.key}`)}</div>
{g.fields.map(key => <FontRow key={key} field={key} value={val(key)} onSave={v => s.save(key, v)} />)}
{g.key === 'items' && <DotsRow value={val('print.dot_style')} onSave={v => s.save('print.dot_style', v)} />}
</div>
))}
<SettingRow label={t('printing.ticket.divider')} hint={t('printing.ticket.dividerHint')}>
<div className="flex items-center gap-3">
<Select value={val('print.divider_style')} onChange={e => s.save('print.divider_style', e.target.value)} aria-label={t('printing.ticket.divider')}
options={DIVIDERS.map(d => ({ value: d, label: t(`printing.ticket.dividers.${d}`) }))} />
</div>
</SettingRow>
<div className="px-5 pb-4 -mt-1">
<Paper className="w-full">{DIVIDER_CHARS[val('print.divider_style')] ? DIVIDER_CHARS[val('print.divider_style')].repeat(32) : <span className="text-ink-3 text-caption">{t('printing.ticket.emptyLine')}</span>}</Paper>
</div>
</SettingsCard>
</div>
)
}
function FontRow({ field, value, onSave }) {
const { t } = useTranslation('manager')
const id = useId()
const f = decodeFont(value)
const set = patch => onSave(encodeFont({ ...f, ...patch }))
const name = field.replace('print.font_', '')
return (
<div className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid={`font-${name}`}>
<label htmlFor={id} className="flex-1 min-w-48 grid">
<span className="text-body font-medium text-ink">{t(`printing.ticket.parts.${name}`)}</span>
<span className="text-caption text-ink-2">{t(`printing.ticket.partsHint.${name}`)}</span>
</label>
<Select id={id} value={f.size} onChange={e => set({ size: e.target.value })} className="w-40"
options={FONT_SIZES.map(z => ({ value: z, label: t(`printing.ticket.sizes.${z}`) }))} />
<Check on={f.bold} onChange={v => set({ bold: v })} label={t('printing.ticket.bold')} />
<Check on={f.caps} onChange={v => set({ caps: v })} label={t('printing.ticket.caps')} />
<Paper><span className={cx('inline-block', SCALE[f.size], f.bold ? 'font-extrabold' : 'font-normal')}>{f.caps ? 'SAMPLE' : 'Sample'}</span></Paper>
{isWide(f.size) && <span className="w-full text-caption text-warning-ink">{t('printing.ticket.wideNote')}</span>}
</div>
)
}
function DotsRow({ value, onSave }) {
const { t } = useTranslation('manager')
const d = decodeDots(value)
const set = patch => onSave(encodeDots({ ...d, ...patch }))
return (
<div className="px-5 py-3 flex flex-wrap items-center gap-3" data-testid="font-dots">
<span className="flex-1 min-w-48 grid">
<span className="text-body font-medium text-ink">{t('printing.ticket.dots')}</span>
<span className="text-caption text-ink-2">{t('printing.ticket.dotsHint')}</span>
</span>
<Select value={d.style} onChange={e => set({ style: e.target.value })} className="w-40" aria-label={t('printing.ticket.dots')}
options={DOT_STYLES.map(x => ({ value: x, label: t(`printing.ticket.dotStyles.${x}`) }))} />
<Select value={d.size} onChange={e => set({ size: e.target.value })} className="w-40" aria-label={t('printing.ticket.dotsSize')}
options={FONT_SIZES.map(z => ({ value: z, label: t(`printing.ticket.sizes.${z}`) }))} />
<Check on={d.bold} onChange={v => set({ bold: v })} label={t('printing.ticket.bold')} />
<Paper><span className={cx('inline-block whitespace-nowrap', SCALE[d.size], d.bold && 'font-extrabold')}>{t('printing.ticket.dotsSample', { dots: DOT_PREVIEW[d.style] })}</span></Paper>
</div>
)
}
function Beep({ s, printers, printerId, onPrinter, test }) {
const { t } = useTranslation('manager')
const saved = decodeBeep(s.get('print.beep_pattern', 'double'), s.get('print.beep_on_ticket', 'true'))
const [custom, setCustom] = useState({ n1: saved.n1, n2: saved.n2, n3: saved.n3 })
const save = beep => beepSettings(beep).forEach(([k, v]) => s.save(k, v))
const choose = preset => save(preset === 'custom' ? { preset, ...custom } : { preset })
const setPart = (k, v) => setCustom(c => ({ ...c, [k]: v }))
const savePart = () => save({ preset: 'custom', ...custom }) // on leaving the box, not on every key
const bytes = beepBytes(saved.preset === 'custom' ? { preset: 'custom', ...custom } : saved)
return (
<SettingsCard title={t('printing.beep.title')} description={t('printing.beep.intro')} testId="ticket-beep">
<div className="px-5 py-3">
<Pick label={t('printing.beep.title')} value={saved.preset} onChange={choose} options={BEEPS.map(b => ({ value: b, label: t(`printing.beep.presets.${b}`) }))} />
</div>
{saved.preset === 'custom' && (
<div className="px-5 py-3 grid gap-3 sm:grid-cols-3">
{['n1', 'n2', 'n3'].map(k => (
<label key={k} className="grid gap-1 text-label text-ink-2">
{t(`printing.beep.${k}`)}
<Input type="number" min={1} max={30} value={custom[k]} onChange={e => setPart(k, e.target.value)} onBlur={savePart} />
<span className="text-caption text-ink-3">{t(`printing.beep.${k}Hint`)}</span>
</label>
))}
</div>
)}
{printers.length > 0 && saved.preset !== 'off' && (
<div className="px-5 py-3 flex flex-wrap items-center gap-2">
<span className="flex-1 text-label text-ink-2">{t('printing.beep.testHint')}</span>
<PrinterPick printers={printers} value={printerId} onChange={onPrinter} />
<Button size="sm" variant="secondary" icon={<Bell size={14} />} loading={test.isPending && test.variables?.kind === 'beep'}
onClick={() => test.mutate({ kind: 'beep', url: '/api/system/printers/test-beep', params: { printer_id: printerId, ...bytes } })}>{t('printing.beep.test')}</Button>
</div>
)}
</SettingsCard>
)
}
@@ -0,0 +1,180 @@
// A prep zone's settings (plan step 6.10): its name (and the name staff see in messages), the
// ticket's language, the printers (a main one, more for "all printers") and copies, how the
// ticket lists dishes, and the kitchen screen's shortcuts. Each choice has an (i) tip.
import { useState } from 'react'
import { useMutation } from '@tanstack/react-query'
import toast from 'react-hot-toast'
import { ArrowDown, ArrowUp } from 'lucide-react'
import { useAccess } from '@xenia/access'
import { errorMessage } from '@xenia/api'
import { LANGUAGE_NAMES, useTranslation } from '@xenia/i18n'
import { Button, Dialog, Field, IconButton, InfoTip, Input, Select, Stepper, Switch, cx } from '@xenia/ui'
import client from '../../api/client'
import { AUTO_PRINT, SORT_BY, move, orderedCategories, setBypass, setMain, toggleSecond, zoneBody, zoneForm, zoneProblem } from './printingLogic'
function Section({ title, children }) {
return (
<section className="grid gap-3">
<h3 className="text-caption font-semibold uppercase tracking-wide text-ink-3">{title}</h3>
{children}
</section>
)
}
function Choice({ options, value, onChange, label, testId }) {
return (
<div className="grid gap-2 sm:grid-cols-3" role="radiogroup" aria-label={label} data-testid={testId}>
{options.map(o => (
<button key={o.value} type="button" role="radio" aria-checked={value === o.value} onClick={() => onChange(o.value)} data-value={o.value}
className={cx('text-left px-3 py-2 rounded-control border transition-colors duration-fast',
value === o.value ? 'border-accent bg-accent-soft' : 'border-line bg-surface hover:bg-surface-2')}>
<span className={cx('block text-label font-semibold', value === o.value ? 'text-accent-ink' : 'text-ink')}>{o.label}</span>
<span className="block text-caption text-ink-2">{o.hint}</span>
</button>
))}
</div>
)
}
function Toggle({ label, tip, checked, onChange, testId }) {
return (
<div className="flex items-center gap-3">
<Switch checked={checked} onChange={onChange} aria-label={label} data-testid={testId} />
<span className="flex-1 text-body text-ink flex items-center gap-1">{label}{tip && <InfoTip>{tip}</InfoTip>}</span>
</div>
)
}
export default function ZoneDialog({ zone, printers, categories, onClose, onSaved }) {
const { t } = useTranslation('manager')
const { languages } = useAccess()
const [form, setForm] = useState(() => zoneForm(zone))
const [ordering, setOrdering] = useState(false)
const [tried, setTried] = useState(false)
const set = (k, v) => setForm(f => ({ ...f, [k]: v }))
const problem = zoneProblem(form)
const save = useMutation({
mutationFn: body => (zone ? client.put(`/api/prep-zones/${zone.id}`, body) : client.post('/api/prep-zones', body)),
onSuccess: () => { toast.success(t(zone ? 'printing.zones.saved' : 'printing.zones.created')); onSaved() },
onError: err => toast.error(errorMessage(err, t)),
})
const submit = () => { setTried(true); if (!problem) save.mutate(zoneBody(form)) }
const flat = categories.flatMap(c => [c, ...(c.subcategories ?? [])])
return (
<Dialog open size="lg" onClose={onClose} title={zone ? t('printing.zones.editTitle', { name: zone.name }) : t('printing.zones.newTitle')}
footer={<>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button loading={save.isPending} onClick={submit} data-testid="zone-save">{t('printing.save')}</Button>
</>}>
<div className="grid gap-6" data-testid="zone-dialog">
<Section title={t('printing.zones.about')}>
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('printing.zones.name')} required error={tried && problem === 'name' ? t('printing.zones.nameNeeded') : undefined}>
<Input value={form.name} onChange={e => set('name', e.target.value)} placeholder={t('printing.zones.namePh')} data-testid="zone-name" />
</Field>
<Field label={t('printing.zones.shown')} hint={t('printing.zones.shownHint')}>
<Input value={form.notification_name} onChange={e => set('notification_name', e.target.value)} />
</Field>
</div>
<div className="grid gap-3 sm:grid-cols-[1fr_14rem]">
<Field label={t('printing.zones.description')}>
<Input value={form.description} onChange={e => set('description', e.target.value)} />
</Field>
<Field label={t('printing.zones.language')} hint={t('printing.zones.languageHint')}>
<Select value={form.language} onChange={e => set('language', e.target.value)} data-testid="zone-language"
options={[{ value: '', label: t('printing.zones.venueLanguage') }, ...(languages || ['en', 'el']).map(l => ({ value: l, label: LANGUAGE_NAMES[l] || l }))]} />
</Field>
</div>
</Section>
<Section title={t('printing.zones.printers')}>
<Choice label={t('printing.zones.auto')} value={form.auto_print} onChange={v => set('auto_print', v)} testId="zone-auto"
options={AUTO_PRINT.map(v => ({ value: v, label: t(`printing.zones.autoShort.${v}`), hint: t(`printing.zones.autoHint.${v}`) }))} />
{printers.length === 0 ? <p className="text-label text-warning-ink">{t('printing.zones.noPrinters')}</p> : (
<div className="grid gap-3 sm:grid-cols-2">
<Field label={t('printing.zones.mainPrinter')} hint={t('printing.zones.mainHint')}
error={tried && problem === 'printer' ? t('printing.zones.printerNeeded') : undefined}>
<Select value={form.master_printer_id ?? ''} onChange={e => setForm(f => setMain(f, e.target.value ? Number(e.target.value) : null))} data-testid="zone-main"
options={[{ value: '', label: t('printing.zones.noPrinter') }, ...printers.map(p => ({ value: String(p.id), label: p.name }))]} />
</Field>
<div className="grid gap-1.5">
<span className="text-label font-medium text-ink flex items-center gap-1">{t('printing.zones.secondPrinters')}<InfoTip>{t('printing.zones.secondTip')}</InfoTip></span>
<div className="flex flex-wrap gap-1.5">
{printers.filter(p => p.id !== form.master_printer_id).map(p => {
const on = form.printer_ids.includes(p.id)
return (
<button key={p.id} type="button" aria-pressed={on} onClick={() => setForm(f => toggleSecond(f, p.id))}
className={cx('px-3 py-1 rounded-full border text-label', on ? 'border-accent bg-accent-soft text-accent-ink font-semibold' : 'border-line bg-surface text-ink-2 hover:bg-surface-2')}>
{p.name}
</button>
)
})}
</div>
</div>
</div>
)}
{form.auto_print !== 'none' && (
<div className="flex flex-wrap gap-6">
<label className="grid gap-1 text-label text-ink-2">{t('printing.zones.mainCopies')}
<Stepper value={form.master_copies} min={1} max={9} onChange={v => set('master_copies', v)} label={t('printing.zones.mainCopies')} />
</label>
{form.auto_print === 'all' && (
<label className="grid gap-1 text-label text-ink-2">{t('printing.zones.secondCopies')}
<Stepper value={form.secondary_copies} min={1} max={9} onChange={v => set('secondary_copies', v)} label={t('printing.zones.secondCopies')} />
</label>
)}
</div>
)}
</Section>
<Section title={t('printing.zones.ticket')}>
<Choice label={t('printing.zones.sort')} value={form.sort_items_by} onChange={v => set('sort_items_by', v)}
options={SORT_BY.map(v => ({ value: v, label: t(`printing.zones.sortShort.${v}`), hint: t(`printing.zones.sortHint.${v}`) }))} />
<Toggle label={t('printing.zones.byCategory')} tip={t('printing.zones.byCategoryTip')} checked={form.group_by_category} onChange={v => set('group_by_category', v)} />
{form.group_by_category && (
<div className="pl-12">
<Button size="sm" variant="secondary" onClick={() => setOrdering(true)}>
{t('printing.zones.categoryOrder')}{form.category_order.length ? ` (${form.category_order.length})` : ''}
</Button>
</div>
)}
<Toggle label={t('printing.zones.checkboxes')} tip={t('printing.zones.checkboxesTip')} checked={form.print_checkboxes} onChange={v => set('print_checkboxes', v)} />
</Section>
<Section title={t('printing.zones.kds')}>
<Toggle label={t('printing.zones.startReady')} tip={t('printing.zones.startReadyTip')} checked={form.bypass_pending} onChange={v => setForm(f => setBypass(f, 'bypass_pending', v))} />
<Toggle label={t('printing.zones.skipKds')} tip={t('printing.zones.skipKdsTip')} checked={form.bypass_kds} onChange={v => setForm(f => setBypass(f, 'bypass_kds', v))} />
<Toggle label={t('printing.zones.readyServed')} tip={t('printing.zones.readyServedTip')} checked={form.auto_ready_to_served} onChange={v => set('auto_ready_to_served', v)} />
</Section>
</div>
{ordering && <CategoryOrder categories={flat} order={form.category_order} onClose={() => setOrdering(false)}
onSave={ids => { set('category_order', ids); setOrdering(false) }} />}
</Dialog>
)
}
function CategoryOrder({ categories, order, onClose, onSave }) {
const { t } = useTranslation('manager')
const [list, setList] = useState(() => orderedCategories(categories, order))
return (
<Dialog open size="sm" onClose={onClose} title={t('printing.zones.categoryOrder')} description={t('printing.zones.categoryOrderHint')}
footer={<>
<Button variant="ghost" onClick={() => onSave([])}>{t('printing.zones.categoryOrderReset')}</Button>
<Button variant="secondary" onClick={onClose}>{t('printing.back')}</Button>
<Button onClick={() => onSave(list.map(c => c.id))}>{t('printing.save')}</Button>
</>}>
<ol className="grid gap-1">
{list.map((c, i) => (
<li key={c.id} className="flex items-center gap-2 px-3 py-1.5 rounded-control bg-surface-2">
<span className="w-6 text-caption text-ink-3 tabular-nums">{i + 1}</span>
<span className="flex-1 text-label text-ink">{c.name}</span>
<IconButton size="sm" variant="ghost" label={t('printing.up')} disabled={i === 0} onClick={() => setList(l => move(l, i, -1))}><ArrowUp size={14} /></IconButton>
<IconButton size="sm" variant="ghost" label={t('printing.down')} disabled={i === list.length - 1} onClick={() => setList(l => move(l, i, 1))}><ArrowDown size={14} /></IconButton>
</li>
))}
</ol>
</Dialog>
)
}
@@ -0,0 +1,180 @@
// Printing set-up as plain data (plan step 6.10), tested in tests/printing.test.mjs. The ticket
// settings are strings the backend reads (services/printer_service.py):
// fonts "SIZE:BOLD:CAPS" SIZE = ESC ! base byte 0 | 16 (tall) | 32 (wide) | 48 (both)
// dot leader "STYLE:SIZE:BOLD" STYLE = dot_space | dot | dash_space | underscore
// beep print.beep_on_ticket 'true'|'false' + print.beep_pattern single|double|triple|long|custom:n1:n2:n3
export const FONT_SIZES = ['0', '16', '32', '48']
export const DIVIDERS = ['dash', 'equals', 'star', 'empty']
export const DIVIDER_CHARS = { dash: '-', equals: '=', star: '*', empty: '' }
export const DOT_STYLES = ['dot_space', 'dot', 'dash_space', 'underscore']
export const DOT_PREVIEW = { dot_space: '. . . . .', dot: '.........', dash_space: '- - - - -', underscore: '_________' }
export const TICKET_MODES = ['detailed', 'compact']
export const BEEPS = ['off', 'single', 'double', 'triple', 'long', 'custom']
const BEEP_BYTES = { single: [2, 2, 1], double: [1, 1, 2], triple: [1, 1, 3], long: [5, 2, 1] }
/** The ticket's parts with a font of their own, grouped as on the ticket. */
export const FONT_GROUPS = [
{ key: 'header', fields: ['print.font_order_number', 'print.font_meta'] },
{ key: 'items', fields: ['print.font_item_name', 'print.font_quick', 'print.font_pref', 'print.font_extra', 'print.font_ingredient'] },
{ key: 'notes', fields: ['print.font_item_note', 'print.font_order_note'] },
]
export const DEFAULTS = {
'print.font_order_number': '48:1:0', 'print.font_meta': '0:0:0', 'print.font_item_name': '16:1:0',
'print.font_quick': '0:0:0', 'print.font_pref': '0:0:0', 'print.font_extra': '0:0:0', 'print.font_ingredient': '0:0:0',
'print.font_item_note': '0:0:0', 'print.font_order_note': '0:1:0', 'print.divider_style': 'dash',
'print.dot_style': 'dot_space:0:0', 'print.ticket_mode': 'detailed', 'print.beep_on_ticket': 'true', 'print.beep_pattern': 'double',
}
export function decodeFont(value) {
const [size, bold, caps] = String(value || '0:0:0').split(':')
return { size: FONT_SIZES.includes(size) ? size : '0', bold: bold === '1', caps: caps === '1' }
}
export const encodeFont = ({ size, bold, caps }) => `${size}:${bold ? 1 : 0}:${caps ? 1 : 0}`
export function decodeDots(value) {
const [style, size, bold] = String(value || 'dot_space:0:0').split(':')
return { style: DOT_STYLES.includes(style) ? style : 'dot_space', size: FONT_SIZES.includes(size) ? size : '0', bold: bold === '1' }
}
export const encodeDots = ({ style, size, bold }) => `${style}:${size}:${bold ? 1 : 0}`
/** A wide font fits about half as many characters on a line. */
export const isWide = size => size === '32' || size === '48'
/** The two beep settings → { preset, n1, n2, n3 } (n* the printer's beep bytes). */
export function decodeBeep(pattern, enabled) {
if (enabled === 'false') return { preset: 'off', n1: 1, n2: 1, n3: 2 }
const p = pattern || 'double'
if (p.startsWith('custom:')) {
const [, a, b, c] = p.split(':').map(Number)
return { preset: 'custom', n1: a || 2, n2: b || 2, n3: c || 1 }
}
const [n1, n2, n3] = BEEP_BYTES[p] ?? BEEP_BYTES.double
return { preset: BEEP_BYTES[p] ? p : 'double', n1, n2, n3 }
}
/** A beep choice → the settings to save, as [key, value] pairs. */
export function beepSettings({ preset, n1, n2, n3 }) {
if (preset === 'off') return [['print.beep_on_ticket', 'false']]
const clamp = v => Math.max(1, Math.min(30, Math.round(Number(v) || 1)))
const pattern = preset === 'custom' ? `custom:${clamp(n1)}:${clamp(n2)}:${clamp(n3)}` : preset
return [['print.beep_on_ticket', 'true'], ['print.beep_pattern', pattern]]
}
/** The bytes the "Test beep" button sends for a choice. */
export function beepBytes(beep) {
if (beep.preset === 'custom') return { n1: beep.n1, n2: beep.n2, n3: beep.n3 }
const [n1, n2, n3] = BEEP_BYTES[beep.preset] ?? BEEP_BYTES.double
return { n1, n2, n3 }
}
// ── printers ────────────────────────────────────────────────────────────────
/** Printer models by the Greek code page each needs (ESC t n): one choice per code page. */
export const PRINTER_MODELS = [
{ label: 'Jolimark TP850UE / S4MAS Giant 100', codepage_n: 29 },
{ label: 'NETUM NT8330L', codepage_n: 24 },
]
export const modelOf = codepage => PRINTER_MODELS.find(m => m.codepage_n === codepage) ?? null
export const EMPTY_PRINTER = { name: '', ip_address: '', port: 9100, protocol: 'escpos_tcp', line_width: 48, codepage_n: 29, is_active: true }
const IPV4 = /^(25[0-5]|2[0-4]\d|1?\d?\d)(\.(25[0-5]|2[0-4]\d|1?\d?\d)){3}$/
/** The fields of a printer form that are wrong (empty = fine). */
export function printerProblems(form) {
const out = []
if (!form.name?.trim()) out.push('name')
if (!IPV4.test(String(form.ip_address ?? '').trim())) out.push('ip_address')
const port = Number(form.port)
if (!Number.isInteger(port) || port < 1 || port > 65535) out.push('port')
const width = Number(form.line_width)
if (!Number.isInteger(width) || width < 20 || width > 80) out.push('line_width')
return out
}
export function printerBody(form) {
return {
name: form.name.trim(), ip_address: String(form.ip_address).trim(), port: Number(form.port),
protocol: form.protocol || 'escpos_tcp', line_width: Number(form.line_width), codepage_n: Number(form.codepage_n ?? 29),
is_active: form.is_active !== false,
}
}
// ── prep zones ──────────────────────────────────────────────────────────────
export const AUTO_PRINT = ['none', 'master', 'all']
export const SORT_BY = ['order_time', 'item_count', 'alpha']
export const EMPTY_ZONE = {
name: '', description: '', notification_name: '', language: '',
printer_ids: [], master_printer_id: null, auto_print: 'master', master_copies: 1, secondary_copies: 1,
sort_items_by: 'order_time', group_by_category: false, category_order: [], print_checkboxes: false,
bypass_pending: false, bypass_kds: false, auto_ready_to_served: false,
}
/** A zone from the API as the form edits it. */
export function zoneForm(zone) {
const out = { ...EMPTY_ZONE }
if (!zone) return out
for (const k of Object.keys(EMPTY_ZONE)) if (zone[k] != null) out[k] = zone[k]
out.language = zone.language || ''
for (const k of ['group_by_category', 'print_checkboxes', 'bypass_pending', 'bypass_kds', 'auto_ready_to_served']) out[k] = !!zone[k]
return out
}
/** The main printer changes: it's always one of the zone's printers. */
export function setMain(form, printerId) {
const ids = printerId != null && !form.printer_ids.includes(printerId) ? [...form.printer_ids, printerId] : form.printer_ids
return { ...form, master_printer_id: printerId, printer_ids: ids }
}
/** Tick or untick a second printer (the main one stays). */
export function toggleSecond(form, printerId) {
if (printerId === form.master_printer_id) return form
const ids = form.printer_ids.includes(printerId) ? form.printer_ids.filter(i => i !== printerId) : [...form.printer_ids, printerId]
return { ...form, printer_ids: ids }
}
/** "Skip the kitchen screen" implies "start as ready"; turning that off turns the other off. */
export function setBypass(form, key, value) {
if (key === 'bypass_kds') return { ...form, bypass_kds: value, bypass_pending: value ? true : form.bypass_pending }
if (key === 'bypass_pending') return { ...form, bypass_pending: value, bypass_kds: value ? form.bypass_kds : false }
return { ...form, [key]: value }
}
/** What's missing before saving: 'name' | 'printer' (printing on, no printer) | null. */
export function zoneProblem(form) {
if (!form.name.trim()) return 'name'
if (form.auto_print !== 'none' && !form.master_printer_id && !form.printer_ids.length) return 'printer'
return null
}
export function zoneBody(form) {
const text = v => (v ?? '').trim() || null
return {
...form,
name: form.name.trim(), description: text(form.description), notification_name: text(form.notification_name),
language: form.language || null,
master_copies: Math.max(1, Math.min(9, Number(form.master_copies) || 1)),
secondary_copies: Math.max(1, Math.min(9, Number(form.secondary_copies) || 1)),
}
}
/** The categories in the zone's order: ranked ones first, then the rest by their own order. */
export function orderedCategories(categories, order = []) {
const byId = new Map(categories.map(c => [c.id, c]))
const ranked = order.map(id => byId.get(id)).filter(Boolean)
const rest = categories.filter(c => !order.includes(c.id))
return [...ranked, ...rest]
}
/** Move one entry of a list up (-1) or down (+1). */
export function move(list, index, step) {
const to = index + step
if (to < 0 || to >= list.length) return list
const out = [...list]
;[out[index], out[to]] = [out[to], out[index]]
return out
}
@@ -0,0 +1,7 @@
// The venue's printers (GET /api/system/printers), shared by the printing settings and the zones.
import client from '../../api/client'
import { useLiveQuery } from '../../live/useLiveQuery'
export function usePrinters() {
return useLiveQuery({ queryKey: ['printers'], queryFn: () => client.get('/api/system/printers').then(r => r.data), staleTime: 15_000 })
}
+1 -3
View File
@@ -3,7 +3,7 @@ import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
bookingBody, cashCheck, dayKpis, dayOrders, durationParts, hourBuckets, initials, itemKind, itemShown,
messageAcks, messageTargets, notesPreview, orderPairs, orderTotal, paymentTotals, printRetries, quickAmounts,
messageAcks, messageTargets, notesPreview, orderPairs, orderTotal, paymentTotals, quickAmounts,
shiftCounts, shiftMoney, tableCards, tableName, tablesByZone, toneOf, TONES, venueWallClock,
} from '../src/pages/overview/overviewLogic.js'
import { onlineKind, onlineNextStep } from '../src/pages/online/onlineOrdersLogic.js'
@@ -110,8 +110,6 @@ test('the day\'s payments, messages, notes, print retries', () => {
const notes = [{ id: 1, is_pinned: true }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]
const todos = [{ id: 9, priority: 'high' }, { id: 8, priority: 'high', is_done: true }, { id: 7, priority: 'low' }]
assert.deepEqual(notesPreview(notes, todos).map(x => `${x.kind}${x.id}`), ['note1', 'todo9', 'note2', 'note3', 'note4'])
assert.equal(printRetries({ print_jobs: [{ status: 'pending', retry_count: 2 }, { status: 'done', retry_count: 9 }] }), 2)
assert.equal(printRetries({}), 0)
})
test('bookings are typed in venue time', () => {
+60
View File
@@ -0,0 +1,60 @@
// Printing set-up as plain data (plan step 6.10).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
beepBytes, beepSettings, decodeBeep, decodeDots, decodeFont, encodeDots, encodeFont, move, orderedCategories, printerBody,
printerProblems, setBypass, setMain, toggleSecond, zoneBody, zoneForm, zoneProblem,
} from '../src/pages/printing/printingLogic.js'
test('fonts and the dot leader round-trip; bad values fall back', () => {
assert.deepEqual(decodeFont('48:1:0'), { size: '48', bold: true, caps: false })
assert.equal(encodeFont({ size: '16', bold: false, caps: true }), '16:0:1')
assert.deepEqual(decodeFont('99:x'), { size: '0', bold: false, caps: false })
assert.equal(encodeDots(decodeDots('dash_space:32:1')), 'dash_space:32:1')
assert.deepEqual(decodeDots(''), { style: 'dot_space', size: '0', bold: false })
})
test('beep: presets, custom, off, and what the test sends', () => {
assert.deepEqual(decodeBeep('triple', 'true'), { preset: 'triple', n1: 1, n2: 1, n3: 3 })
assert.deepEqual(decodeBeep('custom:3:2:4', 'true'), { preset: 'custom', n1: 3, n2: 2, n3: 4 })
assert.equal(decodeBeep('double', 'false').preset, 'off')
assert.deepEqual(beepSettings({ preset: 'off' }), [['print.beep_on_ticket', 'false']])
assert.deepEqual(beepSettings({ preset: 'custom', n1: 99, n2: 0, n3: 2.4 }), [['print.beep_on_ticket', 'true'], ['print.beep_pattern', 'custom:30:1:2']])
assert.deepEqual(beepBytes({ preset: 'long' }), { n1: 5, n2: 2, n3: 1 })
})
test('printer form: what is wrong, and the body', () => {
assert.deepEqual(printerProblems({ name: ' ', ip_address: '10.0.0.300', port: 0, line_width: 48 }), ['name', 'ip_address', 'port'])
assert.deepEqual(printerProblems({ name: 'Bar', ip_address: '192.168.1.20', port: '9100', line_width: '42' }), [])
assert.deepEqual(printerBody({ name: ' Bar ', ip_address: '192.168.1.20 ', port: '9100', line_width: '42', codepage_n: '24' }),
{ name: 'Bar', ip_address: '192.168.1.20', port: 9100, protocol: 'escpos_tcp', line_width: 42, codepage_n: 24, is_active: true })
})
test('zones: main and second printers, the kitchen screen switches, what is missing, the body', () => {
let f = zoneForm(null)
assert.equal(zoneProblem(f), 'name')
f = { ...f, name: ' Grill ' }
assert.equal(zoneProblem(f), 'printer')
f = setMain(f, 3)
assert.deepEqual(f.printer_ids, [3])
f = toggleSecond(toggleSecond(f, 5), 3) // the main one can't be unticked
assert.deepEqual(f.printer_ids, [3, 5])
assert.equal(zoneProblem(f), null)
f = setBypass(f, 'bypass_kds', true)
assert.equal(f.bypass_pending, true)
f = setBypass(f, 'bypass_pending', false)
assert.equal(f.bypass_kds, false)
const body = zoneBody({ ...f, description: ' ', master_copies: 20 })
assert.equal(body.name, 'Grill')
assert.equal(body.description, null)
assert.equal(body.language, null)
assert.equal(body.master_copies, 9)
assert.equal(zoneForm({ name: 'Bar', group_by_category: 1, language: null }).group_by_category, true)
})
test('category order: ranked first, then the rest; moving within bounds', () => {
const cats = [{ id: 1 }, { id: 2 }, { id: 3 }]
assert.deepEqual(orderedCategories(cats, [3, 9]).map(c => c.id), [3, 1, 2])
assert.deepEqual(move([1, 2, 3], 0, -1), [1, 2, 3])
assert.deepEqual(move([1, 2, 3], 2, -1), [1, 3, 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`.",
"paths": [
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders"
"src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders", "src/pages/printing"
],
"strict": [
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders"
"src/live", "src/pages/staff/SessionsPage.jsx", "src/pages/overview", "src/pages/online/OnlineOrdersPage.jsx", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/orders", "src/pages/printing"
]
}
+2
View File
@@ -9602,6 +9602,7 @@
"version": "0.0.0",
"dependencies": {
"@xenia/access": "^0.0.0",
"@xenia/api": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"lucide-react": "^1.73.0"
@@ -9702,6 +9703,7 @@
"@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
"dexie": "^4.4.7",
+25
View File
@@ -130,5 +130,30 @@
"quantity": "Ποσότητα",
"missing": "Μένει να επιλέξετε: {{list}}"
}
},
"printProblems": {
"title": "Δελτία που δεν τυπώθηκαν",
"count_one": "{{count}} δελτίο δεν τυπώθηκε",
"count_other": "{{count}} δελτία δεν τυπώθηκαν",
"none": "Όλα τυπώθηκαν.",
"close": "Κλείσιμο",
"notOn": "Δεν τυπώθηκε στον {{printer}}",
"since": "από τις {{time}}",
"tries_one": "{{count}} προσπάθεια",
"tries_other": "{{count}} προσπάθειες",
"sentBy": "το έστειλε: {{names}}",
"retry": "Ξανά εκτύπωση",
"sendTo": "Αποστολή σε άλλον εκτυπωτή",
"send": "Αποστολή εκεί",
"handled": "Το χειρίστηκα",
"handledHint": "Ενημερώθηκε η κουζίνα αλλιώς: σταματούν οι προσπάθειες και οι ειδοποιήσεις.",
"stillNot": "Ακόμα δεν τυπώνει στον {{printer}}.",
"failed": "Δεν έγινε.",
"whatNow": "Τι κάνω",
"done": {
"retry": "Τυπώθηκε στον {{printer}}",
"redirect": "Τυπώθηκε στον {{printer}}",
"handled": "Σημειώθηκε ότι το χειριστήκατε"
}
}
}
+6 -1
View File
@@ -260,7 +260,8 @@
},
"print_job": {
"not_found": "Αυτή η εκτύπωση δεν υπάρχει πια.",
"not_pending": "Ακυρώνονται μόνο εκτυπώσεις που περιμένουν ακόμη."
"not_pending": "Ακυρώνονται μόνο εκτυπώσεις που περιμένουν ακόμη.",
"done": "Αυτό το δελτίο δεν περιμένει πια: τυπώθηκε ή το χειρίστηκε κάποιος σε άλλη οθόνη."
},
"table": {
"not_found": "Το τραπέζι δεν βρέθηκε.",
@@ -337,5 +338,9 @@
"bad_zone": "Αυτή η ζώνη δεν υπάρχει πια.",
"bad_background": "Το φόντο πρέπει να είναι εικόνα από τη βιβλιοθήκη πολυμέσων.",
"bad_layout": "Η διάταξη έχει ένα τραπέζι δύο φορές ή μια θέση που δεν είναι αριθμός."
},
"print": {
"printer_off": "Ο εκτυπωτής {{printer}} είναι απενεργοποιημένος στις ρυθμίσεις.",
"redirect_failed": "Ούτε ο {{printer}} το τύπωσε ({{error}}). Το δελτίο περιμένει ακόμα."
}
}
+226 -14
View File
@@ -1337,20 +1337,6 @@
"closed": "Κλειστή",
"cancelled": "Ακυρωμένη"
},
"prints": {
"title": "Εκκρεμείς εκτυπώσεις",
"count_one": "{{count}} παραγγελία δεν έχει σταλεί",
"count_other": "{{count}} παραγγελίες δεν έχουν σταλεί",
"all": "Αποστολή όλων",
"retries_one": "{{count}} επανάληψη",
"retries_other": "{{count}} επαναλήψεις",
"lines_one": "{{count}} αντ. εκκρεμεί",
"lines_other": "{{count}} αντ. εκκρεμούν",
"open": "Λεπτομέρειες",
"print": "Εκτύπωση",
"done": "Εκτυπώθηκε επιτυχώς",
"failed": "Αποτυχία: {{printers}}"
},
"notes": {
"title": "Σημειώσεις & εργασίες",
"counts": "{{notes}} σημειώσεις · {{todos}} εκκρεμείς εργασίες"
@@ -2353,6 +2339,232 @@
"save": "Αποθήκευση",
"saved": "Οι σημαίες αποθηκεύτηκαν",
"sent": "Σημαίες αποθηκεύτηκαν και το μήνυμα στάλθηκε"
},
"printHelp": "Τα δελτία ξαναδοκιμάζονται κάθε 8 δευτερόλεπτα μέχρι να τυπωθούν. Αν ένας εκτυπωτής είναι κλειστός ή χωρίς χαρτί, στείλτε τα σε άλλον, ή σημειώστε ότι τα χειριστήκατε όταν μάθει η κουζίνα."
},
"printing": {
"back": "Πίσω",
"save": "Αποθήκευση",
"close": "Κλείσιμο",
"up": "Πάνω",
"down": "Κάτω",
"zones": {
"title": "Ζώνες προετοιμασίας",
"intro": "Πού τυπώνεται το δελτίο κάθε πιάτου και πώς το χειρίζεται η οθόνη κουζίνας. Τα πιάτα μπαίνουν σε ζώνες από την επεξεργασία προϊόντος.",
"new": "Νέα ζώνη",
"none": "Δεν υπάρχουν ζώνες ακόμα",
"noneHint": "Φτιάξτε μία για την κουζίνα και μία για το μπαρ και βάλτε τα πιάτα σε αυτές.",
"edit": "Επεξεργασία {{name}}",
"delete": "Διαγραφή {{name}}",
"deleteTitle": "Διαγραφή {{name}};",
"deleteBody": "Τα πιάτα της δεν θα τυπώνονται πουθενά μέχρι να μπουν σε άλλη ζώνη.",
"deleteYes": "Διαγραφή",
"deleted": "Η ζώνη διαγράφηκε",
"main": "Κύριος",
"also": "Και",
"noPrinter": "Χωρίς εκτυπωτή",
"noPrinters": "Δεν υπάρχουν εκτυπωτές ακόμα: προσθέστε τους στις Ρυθμίσεις → Εκτύπωση.",
"newTitle": "Νέα ζώνη προετοιμασίας",
"editTitle": "{{name}}",
"created": "Η ζώνη δημιουργήθηκε",
"saved": "Η ζώνη αποθηκεύτηκε",
"about": "Η ζώνη",
"name": "Όνομα",
"namePh": "π.χ. Κουζίνα, Ψησταριά, Μπαρ",
"nameNeeded": "Δώστε όνομα στη ζώνη.",
"shown": "Όνομα στα μηνύματα",
"shownHint": "Τι βλέπει το προσωπικό όταν η ζώνη έχει κάτι έτοιμο (π.χ. «Κουζίνα»).",
"description": "Περιγραφή",
"language": "Γλώσσα δελτίου",
"languageHint": "Η γλώσσα που τυπώνονται τα δελτία της.",
"venueLanguage": "Η γλώσσα του καταστήματος",
"printers": "Εκτύπωση",
"auto": "Τι τυπώνεται",
"autoShort": {
"none": "Δεν τυπώνει",
"master": "Κύριος εκτυπωτής",
"all": "Όλοι οι εκτυπωτές της"
},
"autoHint": {
"none": "Τα πιάτα φαίνονται μόνο στην οθόνη κουζίνας.",
"master": "Ένα δελτίο στον κύριο εκτυπωτή.",
"all": "Ο κύριος και κάθε άλλος που είναι επιλεγμένος."
},
"mainPrinter": "Κύριος εκτυπωτής",
"mainHint": "Εκεί τυπώνεται το δελτίο.",
"printerNeeded": "Επιλέξτε τον εκτυπωτή των δελτίων.",
"secondPrinters": "Άλλοι εκτυπωτές",
"secondTip": "Χρησιμοποιούνται με το «Όλοι οι εκτυπωτές της», π.χ. ένα αντίγραφο για το πάσο.",
"mainCopies": "Αντίτυπα στον κύριο",
"secondCopies": "Αντίτυπα στους άλλους",
"ticket": "Το δελτίο",
"sort": "Σειρά των πιάτων",
"sortShort": {
"order_time": "Όπως παραγγέλθηκαν",
"item_count": "Τα περισσότερα πρώτα",
"alpha": "Αλφαβητικά"
},
"sortHint": {
"order_time": "Με τη σειρά που προστέθηκαν.",
"item_count": "Οι μεγαλύτερες ποσότητες πρώτα.",
"alpha": "Κατά όνομα."
},
"byCategory": "Ομαδοποίηση κατά κατηγορία",
"byCategoryTip": "Τα πιάτα της ίδιας κατηγορίας τυπώνονται μαζί, κάτω από το όνομά της.",
"categoryOrder": "Σειρά κατηγοριών",
"categoryOrderHint": "Οι κατηγορίες τυπώνονται με αυτή τη σειρά· οι υπόλοιπες ακολουθούν.",
"categoryOrderReset": "Η σειρά του μενού",
"checkboxes": "Κουτάκια",
"checkboxesTip": "Τυπώνει [ ] πριν από κάθε πιάτο, για να τα σημειώνουν οι μάγειρες.",
"kds": "Η οθόνη κουζίνας",
"startReady": "Ξεκινά ως έτοιμο",
"startReadyTip": "Τα πιάτα παραλείπουν το «σε αναμονή» και «σε προετοιμασία» και εμφανίζονται αμέσως έτοιμα (ποτά, μπύρες).",
"skipKds": "Παράκαμψη οθόνης κουζίνας",
"skipKdsTip": "Τα πιάτα περνούν κατευθείαν σε σερβιρισμένα και δεν εμφανίζονται στην οθόνη κουζίνας. Ενεργοποιεί και το «Ξεκινά ως έτοιμο».",
"readyServed": "Έτοιμο σημαίνει σερβιρισμένο",
"readyServedTip": "Όταν ο μάγειρας σημειώνει ένα πιάτο έτοιμο στην οθόνη, μετράει και ως σερβιρισμένο."
},
"printers": {
"title": "Εκτυπωτές",
"intro": "Οι εκτυπωτές κουζίνας και μπαρ στο δίκτυο του καταστήματος.",
"add": "Προσθήκη εκτυπωτή",
"find": "Εύρεση εκτυπωτών",
"none": "Δεν υπάρχουν εκτυπωτές ακόμα.",
"on": "{{name}} ενεργός",
"codepage": "Κωδικοσελίδα {{n}}",
"chars_one": "{{count}} χαρακτήρας ανά γραμμή",
"chars_other": "{{count}} χαρακτήρες ανά γραμμή",
"checking": "Έλεγχος…",
"answers": "Απαντά",
"noAnswer": "Δεν απαντά",
"test": "Δοκιμαστική εκτύπωση",
"testSent": "Η δοκιμαστική εκτύπωση στάλθηκε",
"testFailed": "Δεν τυπώθηκε: {{error}}",
"edit": "Επεξεργασία {{name}}",
"remove": "Αφαίρεση {{name}}",
"removeTitle": "Αφαίρεση {{name}};",
"removeBody": "Οι ζώνες που τυπώνουν εκεί θα χρειαστούν άλλον εκτυπωτή.",
"removeYes": "Αφαίρεση",
"removed": "Ο εκτυπωτής αφαιρέθηκε",
"addTitle": "Προσθήκη εκτυπωτή",
"editTitle": "{{name}}",
"added": "Ο εκτυπωτής προστέθηκε",
"saved": "Ο εκτυπωτής αποθηκεύτηκε",
"name": "Όνομα",
"namePh": "π.χ. Κουζίνα",
"address": "Διεύθυνση (IP)",
"addressHint": "Τυπώνεται στη σελίδα αυτοελέγχου του εκτυπωτή.",
"port": "Θύρα",
"model": "Μοντέλο",
"modelHint": "Ορίζει τα ελληνικά που καταλαβαίνει ο εκτυπωτής.",
"width": "Χαρακτήρες ανά γραμμή",
"widthHint": "48 για χαρτί 80 mm, 32 για 58 mm.",
"wrong": {
"name": "Δώστε όνομα στον εκτυπωτή.",
"ip_address": "Μια διεύθυνση όπως 192.168.1.50.",
"port": "Θύρα από 1 έως 65535 (συνήθως 9100).",
"line_width": "Από 20 έως 80."
},
"findTitle": "Εύρεση εκτυπωτών",
"findBody": "Ψάχνει στο δίκτυο συσκευές που απαντούν στη θύρα εκτύπωσης.",
"subnet": "Δίκτυο",
"scan": "Αναζήτηση",
"stop": "Διακοπή",
"scanned": "Ελέγχθηκαν {{done}} από {{total}} διευθύνσεις",
"scanStart": "Πατήστε Αναζήτηση.",
"foundNone": "Δεν βρέθηκαν εκτυπωτές.",
"scanFailed": "Η αναζήτηση δεν έγινε.",
"use": "Χρήση"
},
"ticket": {
"layout": "Διάταξη δελτίου",
"mode": "Διάταξη",
"modeTip": "Αναλυτικό: κάθε επιλογή σε δική της γραμμή, πιο ευανάγνωστο. Συμπαγές: επιλογές ίδιου τύπου στην ίδια γραμμή, λιγότερο χαρτί.",
"modes": {
"detailed": "Αναλυτικό",
"compact": "Συμπαγές"
},
"testHint": "Τυπώνει μια ψεύτικη παραγγελία με όλους τους τύπους επιλογών, για να δείτε τις ρυθμίσεις στο χαρτί.",
"testOn": "Εκτυπωτής για τη δοκιμή",
"testOrder": "Δοκιμαστικό δελτίο",
"testSent": "Στάλθηκε στον εκτυπωτή",
"fonts": "Γράμματα",
"fontsHint": "Μέγεθος, έντονα και κεφαλαία για κάθε μέρος του δελτίου. Οι αλλαγές ισχύουν από το επόμενο δελτίο.",
"groups": {
"header": "Η κορυφή",
"items": "Τα πιάτα",
"notes": "Σημειώσεις"
},
"parts": {
"order_number": "Αριθμός παραγγελίας",
"meta": "Τραπέζι · σερβιτόρος · ώρα",
"item_name": "Όνομα πιάτου",
"quick": "Γρήγορες προσθήκες (*)",
"pref": "Προτιμήσεις (>)",
"extra": "Έξτρα (+)",
"ingredient": "Αφαιρέσεις (-)",
"item_note": "Σημείωση πιάτου",
"order_note": "Σημείωση παραγγελίας"
},
"partsHint": {
"order_number": "Η επικεφαλίδα του δελτίου: «Παραγγελία #42».",
"meta": "Οι γραμμές κάτω από τον αριθμό.",
"item_name": "Κάθε πιάτο, με τις τελείες ως την ποσότητα.",
"quick": "Προσθήκες με ένα πάτημα.",
"pref": "Ψήσιμο, συνοδευτικά και άλλες επιλογές.",
"extra": "Έξτρα σε ένα πιάτο.",
"ingredient": "Γραμμές «ΧΩΡΙΣ».",
"item_note": "Ελεύθερο κείμενο για ένα πιάτο.",
"order_note": "Η σημείωση όλης της παραγγελίας."
},
"sizes": {
"0": "Κανονικά",
"16": "Ψηλά",
"32": "Πλατιά",
"48": "Ψηλά και πλατιά"
},
"bold": "Έντονα",
"caps": "ΚΕΦΑΛΑΙΑ",
"wideNote": "Τα πλατιά γράμματα χωράνε περίπου τους μισούς χαρακτήρες ανά γραμμή: κρατήστε τα για σύντομα κείμενα.",
"dots": "Τελείες",
"dotsHint": "Οι χαρακτήρες ανάμεσα στο πιάτο και την ποσότητα.",
"dotsSize": "Μέγεθος τελειών",
"dotsSample": "Μπριζόλα {{dots}} x2",
"dotStyles": {
"dot_space": "Τελείες με κενά",
"dot": "Τελείες",
"dash_space": "Παύλες με κενά",
"underscore": "Κάτω παύλες"
},
"divider": "Διαχωριστικά",
"dividerHint": "Η γραμμή ανάμεσα στα μέρη του δελτίου.",
"emptyLine": "(κενή γραμμή)",
"dividers": {
"dash": "Παύλες ( - )",
"equals": "Ίσον ( = )",
"star": "Αστερίσκοι ( * )",
"empty": "Κενή γραμμή"
}
},
"beep": {
"title": "Ήχος",
"intro": "Ο εκτυπωτής χτυπά για να ειδοποιήσει την κουζίνα ότι ήρθε δελτίο.",
"presets": {
"off": "Χωρίς ήχο",
"single": "Μία φορά",
"double": "Δύο φορές",
"triple": "Τρεις φορές",
"long": "Ένας μακρύς",
"custom": "Προσαρμοσμένο"
},
"n1": "Ήχος (× 100 ms)",
"n1Hint": "π.χ. 3 = 300 ms",
"n2": "Παύση (× 100 ms)",
"n2Hint": "Η παύση ανάμεσα στους ήχους",
"n3": "Φορές",
"n3Hint": "Πόσοι ήχοι",
"testHint": "Ακούστε τον σε έναν εκτυπωτή.",
"test": "Δοκιμή ήχου"
}
}
}
+25
View File
@@ -130,5 +130,30 @@
"quantity": "Quantity",
"missing": "Still to choose: {{list}}"
}
},
"printProblems": {
"title": "Tickets that didn't print",
"count_one": "{{count}} ticket didn't print",
"count_other": "{{count}} tickets didn't print",
"none": "Everything printed.",
"close": "Close",
"notOn": "Not printed on {{printer}}",
"since": "since {{time}}",
"tries_one": "{{count}} try",
"tries_other": "{{count}} tries",
"sentBy": "sent by {{names}}",
"retry": "Print again",
"sendTo": "Send to another printer",
"send": "Send there",
"handled": "Handled",
"handledHint": "Told the kitchen another way: stop trying and stop warning.",
"stillNot": "Still not printing on {{printer}}.",
"failed": "That didn't work.",
"whatNow": "What to do",
"done": {
"retry": "Printed on {{printer}}",
"redirect": "Printed on {{printer}}",
"handled": "Marked as handled"
}
}
}
+6 -1
View File
@@ -260,7 +260,8 @@
},
"print_job": {
"not_found": "That print job isn't there any more.",
"not_pending": "Only tickets still waiting to print can be cancelled."
"not_pending": "Only tickets still waiting to print can be cancelled.",
"done": "That ticket isn't waiting any more: it was printed or dealt with on another screen."
},
"table": {
"not_found": "Table not found.",
@@ -337,5 +338,9 @@
"bad_zone": "That zone no longer exists.",
"bad_background": "The background must be a picture from the media library.",
"bad_layout": "The layout has a table twice or a place that is not a number."
},
"print": {
"printer_off": "The printer {{printer}} is turned off in the settings.",
"redirect_failed": "{{printer}} didn't print it either ({{error}}). The ticket is still waiting."
}
}
+226 -14
View File
@@ -1337,20 +1337,6 @@
"closed": "Closed",
"cancelled": "Cancelled"
},
"prints": {
"title": "Waiting to print",
"count_one": "{{count}} order hasn't printed",
"count_other": "{{count}} orders haven't printed",
"all": "Print all",
"retries_one": "{{count}} retry",
"retries_other": "{{count}} retries",
"lines_one": "{{count}} line waiting",
"lines_other": "{{count}} lines waiting",
"open": "Details",
"print": "Print",
"done": "Printed",
"failed": "Didn't print: {{printers}}"
},
"notes": {
"title": "Notes & to-dos",
"counts": "{{notes}} notes · {{todos}} open to-dos"
@@ -2353,6 +2339,232 @@
"save": "Save",
"saved": "Flags saved",
"sent": "Flags saved and message sent"
},
"printHelp": "Tickets are tried again every 8 seconds until they print. If a printer is off or out of paper, send them to another one, or mark them handled once the kitchen knows."
},
"printing": {
"back": "Back",
"save": "Save",
"close": "Close",
"up": "Move up",
"down": "Move down",
"zones": {
"title": "Prep zones",
"intro": "Where each dish's ticket prints, and how the kitchen screen treats it. Dishes are put in zones in the product editor.",
"new": "New zone",
"none": "No prep zones yet",
"noneHint": "Make one for the kitchen and one for the bar, then put the dishes in them.",
"edit": "Edit {{name}}",
"delete": "Delete {{name}}",
"deleteTitle": "Delete {{name}}?",
"deleteBody": "Its dishes stop printing anywhere until they are put in another zone.",
"deleteYes": "Delete",
"deleted": "Zone deleted",
"main": "Main",
"also": "Also",
"noPrinter": "No printer",
"noPrinters": "There are no printers yet: add them in Settings → Printing.",
"newTitle": "New prep zone",
"editTitle": "{{name}}",
"created": "Zone made",
"saved": "Zone saved",
"about": "The zone",
"name": "Name",
"namePh": "e.g. Kitchen, Grill, Bar",
"nameNeeded": "Give the zone a name.",
"shown": "Name in messages",
"shownHint": "What staff see when this zone has something ready (e.g. \"Kitchen\").",
"description": "Description",
"language": "Ticket language",
"languageHint": "The language its tickets print in.",
"venueLanguage": "The venue's language",
"printers": "Printing",
"auto": "What prints",
"autoShort": {
"none": "Doesn't print",
"master": "Main printer",
"all": "All its printers"
},
"autoHint": {
"none": "The dishes only show on the kitchen screen.",
"master": "One ticket on the main printer.",
"all": "The main printer and every other one ticked."
},
"mainPrinter": "Main printer",
"mainHint": "Where the ticket prints.",
"printerNeeded": "Pick the printer the tickets go to.",
"secondPrinters": "Other printers",
"secondTip": "Used when \"All its printers\" is chosen, e.g. a copy for the pass.",
"mainCopies": "Copies on the main printer",
"secondCopies": "Copies on the others",
"ticket": "The ticket",
"sort": "Order of the dishes",
"sortShort": {
"order_time": "As ordered",
"item_count": "Most first",
"alpha": "A to Z"
},
"sortHint": {
"order_time": "In the order they were added.",
"item_count": "The largest quantities first.",
"alpha": "By name."
},
"byCategory": "Grouped by category",
"byCategoryTip": "Dishes of the same category print together, under its name.",
"categoryOrder": "Order of the categories",
"categoryOrderHint": "The categories print in this order; the rest follow.",
"categoryOrderReset": "Back to the menu's order",
"checkboxes": "Boxes to tick",
"checkboxesTip": "Prints [ ] before each dish, for the cooks to tick off.",
"kds": "The kitchen screen",
"startReady": "Start as ready",
"startReadyTip": "Dishes skip \"waiting\" and \"preparing\" and show as ready at once (drinks, beers).",
"skipKds": "Skip the kitchen screen",
"skipKdsTip": "Dishes go straight to served and never show on the kitchen screen. Turns on \"Start as ready\" too.",
"readyServed": "Ready means served",
"readyServedTip": "When the cook marks a dish ready on the kitchen screen, it counts as served too."
},
"printers": {
"title": "Printers",
"intro": "The kitchen and bar printers on the venue's network.",
"add": "Add a printer",
"find": "Find printers",
"none": "No printers yet.",
"on": "{{name}} on",
"codepage": "Code page {{n}}",
"chars_one": "{{count}} character a line",
"chars_other": "{{count}} characters a line",
"checking": "Checking…",
"answers": "Answers",
"noAnswer": "Doesn't answer",
"test": "Test print",
"testSent": "Test print sent",
"testFailed": "It didn't print: {{error}}",
"edit": "Edit {{name}}",
"remove": "Remove {{name}}",
"removeTitle": "Remove {{name}}?",
"removeBody": "Zones that print on it will need another printer.",
"removeYes": "Remove",
"removed": "Printer removed",
"addTitle": "Add a printer",
"editTitle": "{{name}}",
"added": "Printer added",
"saved": "Printer saved",
"name": "Name",
"namePh": "e.g. Kitchen",
"address": "Address (IP)",
"addressHint": "Printed on the printer's self-test page.",
"port": "Port",
"model": "Model",
"modelHint": "Sets the Greek letters the printer understands.",
"width": "Characters a line",
"widthHint": "48 for 80 mm paper, 32 for 58 mm.",
"wrong": {
"name": "Give the printer a name.",
"ip_address": "An address like 192.168.1.50.",
"port": "A port from 1 to 65535 (usually 9100).",
"line_width": "Between 20 and 80."
},
"findTitle": "Find printers",
"findBody": "Looks for devices on the network that answer on the printing port.",
"subnet": "Network",
"scan": "Search",
"stop": "Stop",
"scanned": "{{done}} of {{total}} addresses checked",
"scanStart": "Press Search to look.",
"foundNone": "No printers found.",
"scanFailed": "The search didn't work.",
"use": "Use"
},
"ticket": {
"layout": "Ticket layout",
"mode": "Layout",
"modeTip": "Detailed: each choice on its own line, easiest to read. Compact: choices of one kind on one line, less paper.",
"modes": {
"detailed": "Detailed",
"compact": "Compact"
},
"testHint": "Print a made-up order with every kind of choice, to see the settings on paper.",
"testOn": "Printer for the test",
"testOrder": "Print a test ticket",
"testSent": "Sent to the printer",
"fonts": "Letters",
"fontsHint": "Each part of the ticket's size, bold and capitals. Changes apply from the next ticket.",
"groups": {
"header": "The top",
"items": "The dishes",
"notes": "Notes"
},
"parts": {
"order_number": "Order number",
"meta": "Table · waiter · time",
"item_name": "Dish name",
"quick": "Quick add-ons (*)",
"pref": "Preferences (>)",
"extra": "Extras (+)",
"ingredient": "Left out (-)",
"item_note": "A dish's note",
"order_note": "The order's note"
},
"partsHint": {
"order_number": "The ticket's heading: \"Order #42\".",
"meta": "The lines under the number.",
"item_name": "Each dish, with the dot leader to its quantity.",
"quick": "Add-ons picked with one tap.",
"pref": "Cooking, sides and other choices.",
"extra": "Extras added to a dish.",
"ingredient": "\"WITHOUT\" lines.",
"item_note": "Free text written for one dish.",
"order_note": "The note for the whole order."
},
"sizes": {
"0": "Normal",
"16": "Tall",
"32": "Wide",
"48": "Tall and wide"
},
"bold": "Bold",
"caps": "CAPITALS",
"wideNote": "Wide letters fit about half as many characters on a line: keep it for short texts.",
"dots": "Dot leader",
"dotsHint": "The characters between a dish and its quantity.",
"dotsSize": "Dot leader size",
"dotsSample": "Steak {{dots}} x2",
"dotStyles": {
"dot_space": "Dots with spaces",
"dot": "Dots",
"dash_space": "Dashes with spaces",
"underscore": "Underscores"
},
"divider": "Dividers",
"dividerHint": "The line between the ticket's parts.",
"emptyLine": "(an empty line)",
"dividers": {
"dash": "Dashes ( - )",
"equals": "Equals ( = )",
"star": "Stars ( * )",
"empty": "An empty line"
}
},
"beep": {
"title": "Beep",
"intro": "The printer beeps to tell the kitchen a ticket came in.",
"presets": {
"off": "No beep",
"single": "Once",
"double": "Twice",
"triple": "Three times",
"long": "One long",
"custom": "Custom"
},
"n1": "On (× 100 ms)",
"n1Hint": "e.g. 3 = 300 ms",
"n2": "Off (× 100 ms)",
"n2Hint": "The pause between beeps",
"n3": "Times",
"n3Hint": "How many beeps",
"testHint": "Hear it on a printer.",
"test": "Test the beep"
}
}
}
+4 -2
View File
@@ -7,13 +7,15 @@
"main": "src/index.js",
"exports": {
".": "./src/index.js",
"./cart": "./src/cart.js"
"./cart": "./src/cart.js",
"./printProblems": "./src/printProblems.js"
},
"dependencies": {
"@xenia/access": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ui": "^0.0.0",
"lucide-react": "^1.73.0"
"lucide-react": "^1.73.0",
"@xenia/api": "^0.0.0"
},
"scripts": {
"test": "node --test \"tests/*.test.mjs\""
@@ -0,0 +1,76 @@
// The tickets that didn't print (plan step 6.10), for the manager and the counter POS: per
// ticket where it belongs, which printer, since when, how many tries, what's on it and who sent
// it; then Print again, Send to another printer, or Handled (told the kitchen another way).
// `run(kind, problem, printerId)` does the request and resolves (or throws the API error);
// the list itself comes back through the live event, so this keeps no copy of it.
import { useState } from 'react'
import { CheckCheck, Printer, RotateCw, Send } from 'lucide-react'
import { errorMessage } from '@xenia/api'
import { useFormat, useTranslation } from '@xenia/i18n'
import { Button, Select } from '@xenia/ui'
import { itemsText, otherPrinters, placeOf } from './printProblems.js'
export function PrintProblemsPanel({ problems, printers = [], run, onOpen, showPlace = true }) {
return (
<ul className="divide-y divide-line" data-testid="print-problems">
{problems.map(p => (
<Problem key={p.job_id} problem={p} printers={printers} run={run} onOpen={onOpen} showPlace={showPlace} />
))}
</ul>
)
}
function Problem({ problem: p, printers, run, onOpen, showPlace }) {
const { t } = useTranslation('common')
const { formatTime } = useFormat()
const others = otherPrinters(p, printers)
const [to, setTo] = useState(others[0] ? String(others[0].id) : '')
const [busy, setBusy] = useState(null)
const [error, setError] = useState(null)
async function act(kind, printerId) {
setBusy(kind)
setError(null)
try { await run(kind, p, printerId) } catch (err) { setError(errorMessage(err, t)) } finally { setBusy(null) }
}
return (
<li className="px-4 py-3 grid gap-2" data-testid="print-problem" data-job={p.job_id} data-order={p.order_id}>
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
{showPlace && (
<button type="button" className="text-body-lg font-bold text-ink hover:underline disabled:no-underline" disabled={!onOpen} onClick={() => onOpen?.(p)}>
{placeOf(p)}
</button>
)}
<span className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-danger-soft text-danger-ink text-caption font-semibold">
<Printer size={12} aria-hidden="true" />{t('printProblems.notOn', { printer: p.printer.name })}
</span>
<span className="text-caption text-ink-2">
{t('printProblems.since', { time: formatTime(p.since) })} · {t('printProblems.tries', { count: p.attempts })}
{p.sent_by?.length > 0 && ` · ${t('printProblems.sentBy', { names: p.sent_by.join(', ') })}`}
</span>
</div>
<div className="text-body text-ink">{itemsText(p)}</div>
{p.error && <div className="text-caption text-ink-3 truncate" title={p.error}>{p.error}</div>}
<div className="flex flex-wrap items-center gap-2">
<Button size="sm" variant="secondary" icon={<RotateCw size={14} />} loading={busy === 'retry'} disabled={!!busy} onClick={() => act('retry')} data-testid="problem-retry">
{t('printProblems.retry')}
</Button>
{others.length > 0 && (
<span className="flex items-center gap-1">
<Select size="sm" value={to} onChange={e => setTo(e.target.value)} aria-label={t('printProblems.sendTo')} data-testid="problem-printer"
options={others.map(o => ({ value: String(o.id), label: o.name }))} />
<Button size="sm" icon={<Send size={14} />} loading={busy === 'redirect'} disabled={!!busy || !to} onClick={() => act('redirect', Number(to))} data-testid="problem-redirect">
{t('printProblems.send')}
</Button>
</span>
)}
<Button size="sm" variant="ghost" icon={<CheckCheck size={14} />} loading={busy === 'handled'} disabled={!!busy} onClick={() => act('handled')} data-testid="problem-handled"
title={t('printProblems.handledHint')}>
{t('printProblems.handled')}
</Button>
</div>
{error && <p role="alert" className="text-label text-danger-ink">{error}</p>}
</li>
)
}
+4 -1
View File
@@ -1,6 +1,9 @@
// @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.
// the manager's ordering. Pure rules in ./cart (Node-testable); the dialog and the quote hook;
// printing problems (6.10): their pure rules and the panel the manager and the counter show.
export * from './cart.js'
export { ProductDialog } from './ProductDialog.jsx'
export { useQuote } from './useQuote.js'
export * from './printProblems.js'
export { PrintProblemsPanel } from './PrintProblemsPanel.jsx'
+43
View File
@@ -0,0 +1,43 @@
// Printing problems (plan step 6.10), as plain data for every app: GET /api/print-problems
// gives { problems, printers }; a problem is one ticket (an order's lines for one printer)
// that didn't print. Node-tested (tests/printProblems.test.mjs).
export const PRINT_EVENT = 'print.problems'
/** The problems of one order (the order and table pages show only theirs). */
export const problemsOf = (problems = [], orderId) => problems.filter(p => p.order_id === orderId)
/** The printers this ticket can be sent to instead (any but its own). */
export const otherPrinters = (problem, printers = []) => printers.filter(p => p.id !== problem.printer.id)
/** "2× Burger, Freddo": what the ticket holds. */
export function itemsText(problem) {
return problem.items.map(i => (i.quantity !== 1 || i.unit_type !== 'piece' ? `${i.quantity}× ${i.name}` : i.name)).join(', ')
}
/** Where the ticket belongs: the table's name, else the order number. */
export const placeOf = problem => problem.table_name || `#${problem.order_id}`
/** Minutes since the first try (whole minutes, never negative). */
export function minutesSince(problem, now = Date.now()) {
const t = problem.since ? new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(problem.since) ? problem.since : `${problem.since}Z`).getTime() : now
return Math.max(0, Math.floor((now - t) / 60_000))
}
/** One line per printer with how many tickets wait on it (the counter's and the phones' summary). */
export function byPrinter(problems = []) {
const out = new Map()
for (const p of problems) {
const e = out.get(p.printer.id) ?? { printer: p.printer, count: 0 }
e.count += 1
out.set(p.printer.id, e)
}
return [...out.values()]
}
/** The request for an action: 'retry' | 'redirect' (with a printer) | 'handled'. → [url, body] */
export function actionRequest(kind, problem, printerId) {
const base = `/api/print-problems/${problem.job_id}`
if (kind === 'redirect') return [`${base}/redirect`, { printer_id: printerId }]
return [`${base}/${kind}`, {}]
}
@@ -0,0 +1,29 @@
// Printing problems as plain data (plan step 6.10).
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { actionRequest, byPrinter, itemsText, minutesSince, otherPrinters, placeOf, problemsOf } from '../src/printProblems.js'
const p = (job, order, printer, extra = {}) => ({
job_id: job, order_id: order, table_name: null, printer: { id: printer, name: `P${printer}` },
items: [{ name: 'Burger', quantity: 2, unit_type: 'piece' }, { name: 'Freddo', quantity: 1, unit_type: 'piece' }],
since: '2026-11-19T10:00:00', ...extra,
})
test('what a ticket holds, where it belongs, how long it waits', () => {
const a = p(1, 7, 1, { table_name: 'T5' })
assert.equal(itemsText(a), '2× Burger, Freddo')
assert.equal(placeOf(a), 'T5')
assert.equal(placeOf(p(2, 8, 1)), '#8')
assert.equal(minutesSince(a, Date.parse('2026-11-19T10:07:30Z')), 7) // a time without a zone is UTC
assert.equal(minutesSince({ ...a, since: '2026-11-19T10:00:00+02:00' }, Date.parse('2026-11-19T08:03:00Z')), 3)
})
test('per order, per printer, the printers to send to, the requests', () => {
const list = [p(1, 7, 1), p(2, 7, 2), p(3, 8, 1)]
assert.deepEqual(problemsOf(list, 7).map(x => x.job_id), [1, 2])
assert.deepEqual(byPrinter(list).map(x => [x.printer.id, x.count]), [[1, 2], [2, 1]])
assert.deepEqual(otherPrinters(list[0], [{ id: 1 }, { id: 2 }, { id: 3 }]).map(x => x.id), [2, 3])
assert.deepEqual(actionRequest('redirect', list[0], 3), ['/api/print-problems/1/redirect', { printer_id: 3 }])
assert.deepEqual(actionRequest('handled', list[0]), ['/api/print-problems/1/handled', {}])
assert.deepEqual(actionRequest('retry', list[0]), ['/api/print-problems/1/retry', {}])
})
+2
View File
@@ -22,6 +22,7 @@ import { addLine, categoriesWithProducts, forSalesPoint, salesPointFor, defaultS
import { findOnline, ONLINE_LISTS } from './logic/online'
import { BOOKING_LIST, findBooking } from './logic/bookings'
import BookingPanel from './BookingPanel'
import PrintProblems from './PrintProblems'
import CallPopup from './CallPopup'
import { isFresh } from './logic/calls'
import BookingsView from './BookingsView'
@@ -145,6 +146,7 @@ function Counter({ menu, t }) {
)}
<ModeButton active={mode === 'receipts'} onClick={() => setMode('receipts')} icon={Receipt} testId="mode-receipts">{t('pos.mode.receipts')}</ModeButton>
</div>
<PrintProblems onOpenTable={id => { setMode('tables'); setTableId(id); setTableCart([]) }} />
<div className="flex-1 overflow-y-auto p-2 grid content-start gap-1"
data-testid={mode === 'online' ? 'online-lists' : mode === 'receipts' ? 'receipt-scopes' : picking ? 'pos-zones' : 'pos-categories'}>
{mode === 'receipts' ? (
+58
View File
@@ -0,0 +1,58 @@
// Tickets that didn't print, at the counter (plan step 6.10): a red button under the modes
// while any waits ("2 tickets didn't print"), opening the shared panel: print again, send to
// another printer, or handled. A new problem plays the chime once.
import { useEffect, useRef, useState } from 'react'
import { Printer } from 'lucide-react'
import { PrintProblemsPanel, actionRequest } from '@xenia/ordering'
import { useTranslation } from '@xenia/i18n'
import { Button, Dialog, useToast } from '@xenia/ui'
import client from '../../api/client'
import { playChime } from './chime'
import { usePrintProblems } from './usePos'
export default function PrintProblems({ onOpenTable }) {
const { t } = useTranslation('common')
const toast = useToast()
const { data, reload } = usePrintProblems()
const [open, setOpen] = useState(false)
const known = useRef(null) // job ids already seen (null: first load, no chime)
const problems = data?.problems ?? []
const ids = problems.map(p => p.job_id).join(',')
// a ticket the counter hasn't seen fail yet: one chime
useEffect(() => {
if (!data) return
const now = ids ? ids.split(',') : []
if (known.current && now.some(id => !known.current.has(id))) playChime()
known.current = new Set(now)
}, [ids, data])
if (!problems.length) return null
async function run(kind, problem, printerId) {
const [url, body] = actionRequest(kind, problem, printerId)
const { data: res } = await client.post(url, body, { xenia: { noOverride: true } })
if (kind === 'retry' && !res.ok) toast.error(t('printProblems.stillNot', { printer: res.printer }))
else toast.success(t(`printProblems.done.${kind}`, { printer: res.printer }))
reload()
}
return (
<>
<div className="p-2 border-b border-line">
<Button variant="danger" block icon={<Printer size={16} />} onClick={() => setOpen(true)} data-testid="pos-print-problems">
{t('printProblems.count', { count: problems.length })}
</Button>
</div>
{open && (
<Dialog open size="lg" onClose={() => setOpen(false)} title={t('printProblems.title')}
footer={<Button variant="secondary" onClick={() => setOpen(false)}>{t('printProblems.close')}</Button>}>
<div className="-mx-4">
<PrintProblemsPanel problems={problems} printers={data?.printers ?? []} run={run}
onOpen={p => { if (p.table_id != null) { setOpen(false); onOpenTable(p.table_id) } }} />
</div>
</Dialog>
)}
</>
)
}
+14 -1
View File
@@ -5,7 +5,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'
import { useModule } from '@xenia/access'
import client from '../../api/client'
import { useLiveEvent, useLiveEvents } from '../../device/context'
import { useQuote as useSharedQuote } from '@xenia/ordering'
import { PRINT_EVENT, useQuote as useSharedQuote } from '@xenia/ordering'
const quiet = { xenia: { noOverride: true } }
const MENU_REFRESH_MS = 5 * 60_000 // prices can change with the time (happy hours)
@@ -77,6 +77,19 @@ export function useTables() {
return { data, reload: load }
}
/** Tickets that didn't print (6.10): GET /api/print-problems → { problems, printers }; live. */
export function usePrintProblems() {
const [data, setData] = useState(null)
const load = useCallback(async () => {
try { setData((await client.get('/api/print-problems', quiet)).data) } catch { /* the shell shows offline */ }
}, [])
const soon = useCoalesced(load)
useEffect(() => { load() }, [load])
useLiveEvent('ready', load)
useLiveEvents([PRINT_EVENT, 'order_closed'], soon)
return { data, reload: load }
}
/** The table map (6.8): GET /api/floor-plans/live, reloaded on the tables' events and plan changes. */
export function useFloorLive() {
const [data, setData] = useState(null)
+44
View File
@@ -1056,6 +1056,50 @@ try {
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(() => {})
// ── 6.10: printers, the ticket's look and prep zones on v2 ───────────────────
const pz = 'printing:'
const settingValue2 = async key => (await api('GET', '/api/settings/', { token: boss }))[key]?.value
await page.goto(`${APP}/settings`)
await page.getByText('Printing', { exact: true }).click()
await page.getByTestId('printers-card').waitFor({ timeout: 10_000 }).catch(() => {})
await page.getByTestId('printer-new').click()
await page.getByTestId('printer-save').click()
r.check(`${pz} a printer without a name or address isn't saved (the form says why)`, await page.getByTestId('printer-dialog').count() === 1
&& (await page.getByTestId('printer-dialog').textContent()).includes('192.168.1.50'))
await page.getByTestId('printer-name').fill('E2E Grill')
await page.getByTestId('printer-ip').fill('192.168.77.9')
await page.getByTestId('printer-save').click()
const grillRow = page.locator('[data-testid="printer-row"][data-name="E2E Grill"]')
const listed = await grillRow.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
const grill = (await api('GET', '/api/system/printers', { token: boss })).find(p => p.name === 'E2E Grill')
r.check(`${pz} a printer is added in Settings → Printing`, listed && grill?.ip_address === '192.168.77.9' && grill.port === 9100, JSON.stringify(grill))
await page.getByTestId('font-item_name').getByRole('button', { name: 'CAPITALS' }).click()
await page.getByTestId('ticket-beep').locator('[data-value="triple"]').click()
let fontNow = null
for (let i = 0; i < 20 && fontNow !== '16:1:1'; i++) { await sleep(250); fontNow = await settingValue2('print.font_item_name') }
r.check(`${pz} the dish name in capitals and a triple beep are saved`, fontNow === '16:1:1' && await settingValue2('print.beep_pattern') === 'triple', fontNow)
await page.screenshot({ path: path.join(OUT, 'manager-printing.png'), fullPage: true })
await api('PUT', '/api/settings/print.font_item_name', { token: boss, body: { value: '16:1:0' } })
await api('PUT', '/api/settings/print.beep_pattern', { token: boss, body: { value: 'double' } })
// a prep zone printing on it, ticket in Greek, grouped by category
await page.goto(`${APP}/management/prep-zones`)
await page.getByTestId('zone-new').click()
await page.getByTestId('zone-save').click()
r.check(`${pz} a zone needs a name`, await page.getByTestId('zone-dialog').count() === 1)
await page.getByTestId('zone-name').fill('E2E Grill zone')
await page.getByTestId('zone-main').selectOption(String(grill.id))
await page.getByTestId('zone-language').selectOption('el')
await page.getByTestId('zone-dialog').getByRole('switch', { name: 'Grouped by category' }).click()
await page.getByTestId('zone-save').click()
const zoneCard = page.locator('[data-testid="zone-card"][data-name="E2E Grill zone"]')
await zoneCard.waitFor({ timeout: 8000 }).catch(() => {})
const savedZone = (await api('GET', '/api/prep-zones', { token: boss })).find(z => z.name === 'E2E Grill zone')
r.check(`${pz} the zone is made: main printer, Greek tickets, grouped by category`, await zoneCard.waitFor({ timeout: 8000 }).then(() => true).catch(() => false)
&& savedZone?.master_printer_id === grill.id && savedZone.language === 'el' && savedZone.group_by_category === true && savedZone.auto_print === 'master', JSON.stringify(savedZone))
await page.screenshot({ path: path.join(OUT, 'manager-prep-zones.png'), fullPage: true })
if (savedZone) await api('DELETE', `/api/prep-zones/${savedZone.id}`, { token: boss })
if (grill) await api('DELETE', `/api/system/printers/${grill.id}`, { token: boss })
await api('PUT', '/api/platform/modules/connect_orders', { token: boss, body: { enabled: true } })
await page.goto(`${APP}/online-orders`)
await page.getByTestId('online-orders').waitFor({ timeout: 10_000 }).catch(() => {})
+132
View File
@@ -0,0 +1,132 @@
// Printing problems (plan step 6.10), the step's "done when": with the kitchen printer stopped,
// a waiter's order shows "not printed" on the phone and in the manager, is sent to the bar
// printer from there, and the warning clears everywhere. Then a second one is marked "Handled"
// from the manager. The kitchen printer is a port nobody listens on; the bar printer is a small
// TCP listener that keeps what it gets.
// Starts its own backend (:8063), the waiter app (:5183) and the manager (:5184).
// node print_problems.mjs
import net from 'node:net'
import path from 'node:path'
import { openSync } from 'node:fs'
import { spawn } from 'node:child_process'
import { chromium } from 'playwright'
import { BROWSER_CHANNEL, CS, OUT, reporter, sleep } from './lib/env.mjs'
import { killTree, login, startBackend, startViteNative, waitHttp } from './lib/proc.mjs'
const backend = await startBackend({ port: 8063, siteId: 'test-site-1', env: { LICENSE_MODE: 'off' } })
const waiterVite = await startViteNative({ port: 5183, backendUrl: backend.url })
const MANAGER = 'http://localhost:5184'
const mlog = openSync(path.join(OUT, 'vite-5184.log'), 'w')
const managerVite = spawn('npx', ['vite', '--port', '5184', '--strictPort'], {
cwd: path.join(CS, 'manager_dashboard'), shell: process.platform === 'win32', detached: process.platform !== 'win32',
stdio: ['ignore', mlog, mlog], env: { ...process.env, XENIA_BACKEND: backend.url },
})
const browser = await chromium.launch(BROWSER_CHANNEL ? { channel: BROWSER_CHANNEL } : {})
const r = reporter('printing problems (6.10): shown on the phone and in the manager, sent elsewhere, handled')
// the bar printer: accepts and keeps every ticket
const barTickets = []
const bar = net.createServer(sock => { let buf = Buffer.alloc(0); sock.on('data', d => { buf = Buffer.concat([buf, d]) }); sock.on('error', () => {}); sock.on('close', () => { if (buf.length) barTickets.push(buf) }) })
await new Promise(res => bar.listen(0, '127.0.0.1', res))
// the kitchen printer: a port that was free a moment ago (connection refused, like a printer off)
const deadPort = await new Promise(res => { const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => res(p)) }) })
async function api(method, url, { token, body } = {}) {
const res = await fetch(backend.url + url, {
method, headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
})
const text = await res.text()
let data = null
try { data = JSON.parse(text) } catch { data = text }
if (!res.ok) throw new Error(`${method} ${url} → ${res.status} ${text.slice(0, 200)}`)
return data
}
const shown = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ timeout }).then(() => true).catch(() => false)
const gone = (page, testId, timeout = 10_000) => page.getByTestId(testId).first().waitFor({ state: 'detached', timeout }).then(() => true).catch(() => false)
const errors = []
try {
const boss = await login(backend.url)
await api('POST', '/api/business-day/open', { token: boss, body: {} }).catch(() => {})
// printers and a kitchen zone the dishes print in
const kitchen = await api('POST', '/api/system/printers', { token: boss, body: { name: 'Kitchen E2E', ip_address: '127.0.0.1', port: deadPort, is_active: true } })
const barP = await api('POST', '/api/system/printers', { token: boss, body: { name: 'Bar E2E', ip_address: '127.0.0.1', port: bar.address().port, is_active: true } })
const zone = await api('POST', '/api/prep-zones', { token: boss, body: { name: 'Kitchen E2E', printer_ids: [kitchen.id], master_printer_id: kitchen.id, auto_print: 'master' } })
const [dish, dish2] = (await api('GET', '/api/orders/menu', { token: boss })).products.filter(p => p.available && !p.service && !p.prefs.length)
await api('POST', '/api/products/bulk-prep-zones', { token: boss, body: { product_ids: [dish.id, dish2.id], prep_zone_ids: [zone.id] } })
// ── the phone: Maria signs in and starts her shift ─────────────────────────
const ctxP = await browser.newContext({ viewport: { width: 393, height: 852 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true })
const ph = await ctxP.newPage()
ph.on('pageerror', e => errors.push(`phone: ${e.message}`))
await ph.goto(`http://localhost:5183/login`)
await ph.getByTestId('waiter-card').filter({ hasText: 'Κωνσταντίνου' }).click({ timeout: 30_000 })
for (const d of '3302') await ph.getByRole('button', { name: d, exact: true }).first().click()
await ph.waitForURL(u => u.pathname !== '/login', { timeout: 15_000 }).catch(() => {})
await ph.getByRole('button', { name: /Start shift/ }).click({ timeout: 10_000 }).catch(() => {})
await ph.waitForURL(u => u.pathname.startsWith('/tables'), { timeout: 10_000 }).catch(() => {})
const maria = await ph.evaluate(() => localStorage.getItem('xenia:dev:token'))
// ── the manager: signed in on the overview ─────────────────────────────────
await waitHttp(`${MANAGER}/`)
const ctxM = await browser.newContext({ viewport: { width: 1400, height: 900 } })
const mg = await ctxM.newPage()
mg.on('pageerror', e => errors.push(`manager: ${e.message}`))
await mg.goto(`${MANAGER}/login`)
await mg.getByTestId('login-form').waitFor({ timeout: 60_000 })
if (!(await mg.getByTestId('login-account').count())) await mg.getByLabel('Username').fill('manager')
await mg.getByLabel('Password').fill('password')
await mg.getByRole('button', { name: 'Sign in', exact: true }).click()
await mg.waitForURL(u => u.pathname.startsWith('/dashboard'), { timeout: 20_000 }).catch(() => {})
// ── Maria's order: the kitchen printer is off ──────────────────────────────
const busy = new Set((await api('GET', '/api/orders/', { token: boss })).map(o => o.table_id))
const table = (await api('GET', '/api/tables/', { token: boss })).find(t => t.is_active !== false && !busy.has(t.id))
const order = await api('POST', '/api/orders/', { token: maria, body: { table_id: table.id } })
const sent = await api('POST', `/api/orders/${order.id}/items`, { token: maria, body: { lines: [{ product_id: dish.id, quantity: 2 }] } })
r.check('the kitchen printer is off: the ticket fails', sent.print_results?.length === 1 && sent.print_results[0].success === false, JSON.stringify(sent.print_results))
r.check('the phone shows it at once: the red printer button', await shown(ph, 'print-problems-button', 15_000))
r.check('…and in the manager: the card on the overview names the table, the printer and the dish',
await mg.getByTestId('print-problem').first().waitFor({ timeout: 15_000 }).then(() => true).catch(() => false)
&& (await mg.getByTestId('print-problems-card').textContent()).includes('Kitchen E2E')
&& (await mg.getByTestId('print-problems-card').textContent()).includes(dish.name))
await mg.screenshot({ path: path.join(OUT, 'print-problems-manager.png') })
// the table's page on the phone warns too; from there: send it to the bar
await ph.goto(`http://localhost:5183/tables/${table.id}`)
r.check("the table's page on the phone: \"Not printed on Kitchen E2E\"", await shown(ph, 'table-print-warning')
&& (await ph.getByTestId('table-print-warning').textContent()).includes('Kitchen E2E'))
await ph.getByTestId('table-print-warning').click()
await shown(ph, 'print-problems-sheet')
await ph.screenshot({ path: path.join(OUT, 'print-problems-phone.png') })
await ph.getByTestId('problem-printer').first().selectOption(String(barP.id))
await ph.getByTestId('problem-redirect').first().click()
for (let i = 0; i < 40 && !barTickets.length; i++) await sleep(100)
r.check('sent to the bar printer from the phone: it printed there', barTickets.length === 1 && barTickets[0].length > 50, String(barTickets.map(b => b.length)))
r.check('the warning clears on the phone (button and table)', await gone(ph, 'print-problems-button', 10_000) && await gone(ph, 'table-print-warning', 10_000))
r.check('…and in the manager, by itself (live)', await gone(mg, 'print-problem', 10_000))
const left = await api('GET', '/api/print-problems', { token: boss })
r.check('nothing left waiting', left.problems.length === 0, JSON.stringify(left.problems))
// ── a second one, handled from the manager's order page ────────────────────
await api('POST', `/api/orders/${order.id}/items`, { token: maria, body: { lines: [{ product_id: dish2.id, quantity: 1 }] } })
await mg.goto(`${MANAGER}/orders/${order.id}`)
r.check("the manager's order page lists the order's ticket", await mg.getByTestId('print-problem').first().waitFor({ timeout: 10_000 }).then(() => true).catch(() => false))
await mg.getByTestId('problem-handled').first().click()
r.check('"Handled" clears it in the manager and on the phone',
await gone(mg, 'print-problem', 10_000) && (await api('GET', '/api/print-problems', { token: maria })).problems.length === 0)
r.check('no page errors', errors.length === 0, errors.slice(0, 3).join(' | '))
} catch (e) {
console.error(e)
r.check('ran to the end', false, String(e))
} finally {
await browser.close()
waiterVite.stop()
killTree(managerVite)
bar.close()
await backend.stop()
}
process.exit(r.done() ? 1 : 0)
+1
View File
@@ -33,6 +33,7 @@ const suites = [
['terminal (pairing, sign-in, states)', 'node', ['terminal.mjs'], E2E],
['signage (the player on a TV, the editor)', 'node', ['signage.mjs'], E2E],
['menu tablet (menu, search, views, live prices)', 'node', ['menu_tablet.mjs'], E2E],
['printing problems (phone + manager: not printed, sent elsewhere, handled)', 'node', ['print_problems.mjs'], E2E],
['order app (cloud: takeaway + delivery + bookings)', 'node', ['order_app.mjs'], E2E],
['QR menu at the table (cloud + venue)', 'node', ['qr_table.mjs'], E2E],
['stack (compose: terminal :8082, LAN only)', 'node', ['stack.mjs'], E2E],
+1
View File
@@ -23,6 +23,7 @@
"@xenia/api": "^0.0.0",
"@xenia/floorplan": "^0.0.0",
"@xenia/i18n": "^0.0.0",
"@xenia/ordering": "^0.0.0",
"@xenia/ui": "^0.0.0",
"axios": "^1.21.1",
"dexie": "^4.4.7",
+10 -4
View File
@@ -10,7 +10,8 @@ import useChatStore from '../store/chatStore'
import useKdsReadyStore from '../store/kdsReadyStore'
import useInstallPromptStore, { apkAvailable } from '../store/installPromptStore'
import useOfflineQueueCount from '../hooks/useOfflineQueueCount'
import useFailedPrintCount from '../hooks/useFailedPrintCount'
import usePrintProblems from '../hooks/usePrintProblems'
import PrintProblemsSheet from './PrintProblemsSheet'
import { fade } from '../logic/colour'
// ─── Nav item registry ────────────────────────────────────────────────────────
@@ -148,6 +149,7 @@ function FailedPrintButton({ count, onClick }) {
return (
<button
onClick={onClick}
data-testid="print-problems-button"
style={{
position: 'relative',
display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
@@ -650,7 +652,8 @@ export default function AppShell({ children, title, rightActions }) {
const { totalUnread: chatUnread } = useChatStore()
const { readyCount } = useKdsReadyStore()
const offlineCacheCount = useOfflineQueueCount()
const failedPrintCount = useFailedPrintCount()
const prints = usePrintProblems() // 6.10: tickets that didn't print, live
const [showPrints, setShowPrints] = useState(false)
function openNotifs() {
setShowNotifs(true)
@@ -690,8 +693,8 @@ export default function AppShell({ children, title, rightActions }) {
{/* Offline cache badge — visible only when ops are pending */}
<CacheButton count={offlineCacheCount} />
{/* Failed print badge — navigates to order log */}
<FailedPrintButton count={failedPrintCount} onClick={() => navigate('/order-log?filter=failed')} />
{/* Tickets that didn't print (6.10): opens them with what can be done */}
<FailedPrintButton count={prints.problems.length} onClick={() => setShowPrints(true)} />
{/* Bell */}
<BellButton onClick={openNotifs} count={unreadCount || 0} />
@@ -700,6 +703,9 @@ export default function AppShell({ children, title, rightActions }) {
<UserMenu />
</header>
{showPrints && <PrintProblemsSheet problems={prints.problems} printers={prints.printers}
onChanged={prints.reload} onClose={() => setShowPrints(false)} />}
{/* ── Side drawer ───────────────────────────────────────── */}
<SideDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
@@ -0,0 +1,84 @@
// Tickets that didn't print, on the phone (plan step 6.10): opened from the red printer button
// in the header (all of them) or from a table's warning (that order's). Each says where it
// belongs, which printer, since when and what's on it; then Print again, Send to another
// printer, or Handled (told the kitchen by voice). The list comes back over the live event.
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useFormat, useTranslation } from '@xenia/i18n'
import { actionRequest, itemsText, otherPrinters, placeOf } from '@xenia/ordering/printProblems'
import client from '../api/client'
import { apiError } from '../api/errors'
export default function PrintProblemsSheet({ problems, printers, onClose, onChanged, showPlace = true }) {
const { t } = useTranslation('common')
return (
<div className="modal-overlay" onClick={onClose}>
<div className="modal-sheet" onClick={e => e.stopPropagation()} data-testid="print-problems-sheet">
<div className="modal-handle" />
<h2 className="modal-title">{t('printProblems.title')}</h2>
{problems.length === 0 && <p style={{ textAlign: 'center', color: 'var(--muted)' }}>{t('printProblems.none')}</p>}
{problems.map(p => <Problem key={p.job_id} problem={p} printers={printers} onChanged={onChanged} showPlace={showPlace} onClose={onClose} />)}
<button className="btn btn--secondary" onClick={onClose}>{t('printProblems.close')}</button>
</div>
</div>
)
}
function Problem({ problem: p, printers, onChanged, showPlace, onClose }) {
const { t } = useTranslation('common')
const { formatTime } = useFormat()
const navigate = useNavigate()
const others = otherPrinters(p, printers)
const [to, setTo] = useState(others[0] ? String(others[0].id) : '')
const [busy, setBusy] = useState(null)
const [note, setNote] = useState(null) // { ok, text }
async function act(kind, printerId) {
setBusy(kind)
setNote(null)
try {
const [url, body] = actionRequest(kind, p, printerId)
const { data } = await client.post(url, body)
if (kind === 'retry' && !data.ok) setNote({ ok: false, text: t('printProblems.stillNot', { printer: data.printer }) })
onChanged()
} catch (err) { setNote({ ok: false, text: apiError(err, t('printProblems.failed')) }) } finally { setBusy(null) }
}
return (
<div data-testid="print-problem" data-job={p.job_id} data-order={p.order_id}
style={{ border: '2px solid var(--x-danger)', background: 'var(--x-danger-soft)', borderRadius: 14, padding: 12, display: 'grid', gap: 8 }}>
<div style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
{showPlace && (
<button onClick={() => { onClose(); navigate(p.table_id != null ? `/tables/${p.table_id}` : `/orders/${p.order_id}`) }}
style={{ background: 'none', border: 'none', padding: 0, fontSize: 18, fontWeight: 800, color: 'var(--x-ink)', textDecoration: 'underline', cursor: 'pointer' }}>
{placeOf(p)}
</button>
)}
<span style={{ fontWeight: 700, color: 'var(--x-danger-ink)' }}>🖨 {t('printProblems.notOn', { printer: p.printer.name })}</span>
</div>
<div style={{ fontSize: 13, color: 'var(--x-ink-2)' }}>
{t('printProblems.since', { time: formatTime(p.since) })} · {t('printProblems.tries', { count: p.attempts })}
</div>
<div style={{ fontSize: 15, color: 'var(--x-ink)' }}>{itemsText(p)}</div>
<button className="btn btn--secondary" disabled={!!busy} onClick={() => act('retry')} data-testid="problem-retry">
{busy === 'retry' ? '…' : t('printProblems.retry')}
</button>
{others.length > 0 && (
<div style={{ display: 'flex', gap: 8 }}>
<select value={to} onChange={e => setTo(e.target.value)} aria-label={t('printProblems.sendTo')} data-testid="problem-printer"
style={{ flex: 1, height: 44, borderRadius: 10, border: '1px solid var(--border)', background: 'var(--bg3)', color: 'var(--text)', padding: '0 10px', fontSize: 15 }}>
{others.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
</select>
<button className="btn btn--accent" disabled={!!busy || !to} onClick={() => act('redirect', Number(to))} data-testid="problem-redirect">
{busy === 'redirect' ? '…' : t('printProblems.send')}
</button>
</div>
)}
<button className="btn btn--secondary" disabled={!!busy} onClick={() => act('handled')} data-testid="problem-handled">
{busy === 'handled' ? '…' : t('printProblems.handled')}
</button>
<div style={{ fontSize: 12, color: 'var(--x-ink-3)' }}>{t('printProblems.handledHint')}</div>
{note && <p role="alert" className="error-msg">{note.text}</p>}
</div>
)
}
@@ -0,0 +1,31 @@
// A table's tickets that didn't print (plan step 6.10), on the table's page: "Didn't print on
// Kitchen · since 21:03 · Burger, Freddo", tapping opens what can be done (the sheet).
import { useState } from 'react'
import { useFormat, useTranslation } from '@xenia/i18n'
import { itemsText, problemsOf } from '@xenia/ordering/printProblems'
import usePrintProblems from '../hooks/usePrintProblems'
import PrintProblemsSheet from './PrintProblemsSheet'
export default function TablePrintWarning({ orderId }) {
const { t } = useTranslation('common')
const { formatTime } = useFormat()
const { problems, printers, reload } = usePrintProblems()
const [open, setOpen] = useState(false)
const mine = orderId ? problemsOf(problems, orderId) : []
if (!mine.length) return null
return (
<>
<button onClick={() => setOpen(true)} data-testid="table-print-warning"
style={{ margin: '10px 12px 0', textAlign: 'left', border: '2px solid var(--x-danger)', background: 'var(--x-danger-soft)', borderRadius: 14, padding: 12, display: 'grid', gap: 4, cursor: 'pointer', fontFamily: 'inherit' }}>
{mine.map(p => (
<span key={p.job_id} style={{ display: 'grid', gap: 2 }}>
<span style={{ fontWeight: 800, color: 'var(--x-danger-ink)' }}>🖨 {t('printProblems.notOn', { printer: p.printer.name })} · {t('printProblems.since', { time: formatTime(p.since) })}</span>
<span style={{ fontSize: 13, color: 'var(--x-ink)' }}>{itemsText(p)}</span>
</span>
))}
<span style={{ fontSize: 13, fontWeight: 700, color: 'var(--x-danger-ink)' }}>{t('printProblems.whatNow')} ›</span>
</button>
{open && <PrintProblemsSheet problems={mine} printers={printers} showPlace={false} onChanged={reload} onClose={() => setOpen(false)} />}
</>
)
}
@@ -1,29 +0,0 @@
import { useState, useEffect } from 'react'
import client from '../api/client'
// Polls /api/orders/pending-prints every 8s and returns the count of pending print jobs.
export default function useFailedPrintCount() {
const [count, setCount] = useState(0)
useEffect(() => {
let cancelled = false
async function refresh() {
try {
const res = await client.get('/api/orders/pending-prints')
if (!cancelled) setCount(res.data?.count ?? 0)
} catch {
// Network error — leave count as-is
}
}
refresh()
const id = setInterval(refresh, 8000)
return () => {
cancelled = true
clearInterval(id)
}
}, [])
return count
}
+25
View File
@@ -0,0 +1,25 @@
// Tickets that didn't print (plan step 6.10; replaces the 8-second poll of the failed-print
// count): GET /api/print-problems → { problems, printers }, reloaded by the live event
// `print.problems` (and a closed order, a reconnect, every minute as a safety net). The server
// only lists the orders this waiter may act on.
import { useCallback, useEffect, useState } from 'react'
import { PRINT_EVENT } from '@xenia/ordering/printProblems'
import client from '../api/client'
const SAFETY_MS = 60_000
export default function usePrintProblems() {
const [data, setData] = useState(null)
const load = useCallback(async () => {
try { setData((await client.get('/api/print-problems')).data) } catch { /* offline: keep what we had */ }
}, [])
useEffect(() => {
const first = setTimeout(load, 0)
const onEvent = e => { if ([PRINT_EVENT, 'order_closed', 'ready'].includes(e.detail?.type)) load() }
window.addEventListener('live-event', onEvent)
window.addEventListener('live-reconnected', load)
const id = setInterval(load, SAFETY_MS)
return () => { clearTimeout(first); clearInterval(id); window.removeEventListener('live-event', onEvent); window.removeEventListener('live-reconnected', load) }
}, [load])
return { data, problems: data?.problems ?? [], printers: data?.printers ?? [], reload: load }
}
+4
View File
@@ -3,6 +3,7 @@ import { useNavigate, useParams, useSearchParams } from 'react-router-dom'
import { useAllowed, useCan, useModule } from '@xenia/access'
import OrderSummary from '../components/OrderSummary'
import TabletRequests from '../components/TabletRequests'
import TablePrintWarning from '../components/TablePrintWarning'
import TableHistory from '../components/TableHistory'
import useConnectionStore from '../store/connectionStore'
import client from '../api/client'
@@ -1728,6 +1729,9 @@ export default function TableDetailPage() {
</div>
)}
{/* tickets of this order that didn't print (6.10) */}
<TablePrintWarning orderId={order?.id} />
{/* orders from the table's menu tablet waiting for a waiter (6.6) */}
{!isStandalone && <TabletRequests tableId={Number(tableId)} />}