diff --git a/local_backend/core/errors.py b/local_backend/core/errors.py
index 79f5864..c8557f6 100644
--- a/local_backend/core/errors.py
+++ b/local_backend/core/errors.py
@@ -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."),
diff --git a/local_backend/migrations/versions/0036_print_job_resolution.py b/local_backend/migrations/versions/0036_print_job_resolution.py
new file mode 100644
index 0000000..17b45bc
--- /dev/null
+++ b/local_backend/migrations/versions/0036_print_job_resolution.py
@@ -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')
diff --git a/local_backend/models/order.py b/local_backend/models/order.py
index 19932e0..57ae70b 100644
--- a/local_backend/models/order.py
+++ b/local_backend/models/order.py
@@ -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")
diff --git a/local_backend/modules/ordering/manifest.py b/local_backend/modules/ordering/manifest.py
index 6a940bc..ceedf34 100644
--- a/local_backend/modules/ordering/manifest.py
+++ b/local_backend/modules/ordering/manifest.py
@@ -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
),
)
diff --git a/local_backend/routers/orders.py b/local_backend/routers/orders.py
index 951b5b3..b49d53a 100644
--- a/local_backend/routers/orders.py
+++ b/local_backend/routers/orders.py
@@ -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}
diff --git a/local_backend/routers/prep_zones.py b/local_backend/routers/prep_zones.py
index be057c3..d8c5857 100644
--- a/local_backend/routers/prep_zones.py
+++ b/local_backend/routers/prep_zones.py
@@ -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:
diff --git a/local_backend/routers/print_problems.py b/local_backend/routers/print_problems.py
new file mode 100644
index 0000000..d6ef61e
--- /dev/null
+++ b/local_backend/routers/print_problems.py
@@ -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)
diff --git a/local_backend/routers/system.py b/local_backend/routers/system.py
index 5dc4651..80c64c5 100644
--- a/local_backend/routers/system.py
+++ b/local_backend/routers/system.py
@@ -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()}
diff --git a/local_backend/services/print_problems.py b/local_backend/services/print_problems.py
new file mode 100644
index 0000000..75e44c3
--- /dev/null
+++ b/local_backend/services/print_problems.py
@@ -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}
diff --git a/local_backend/services/printer_service.py b/local_backend/services/printer_service.py
index 268b723..277b6c2 100644
--- a/local_backend/services/printer_service.py
+++ b/local_backend/services/printer_service.py
@@ -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()
diff --git a/local_backend/tests/test_print_problems.py b/local_backend/tests/test_print_problems.py
new file mode 100644
index 0000000..6590c95
--- /dev/null
+++ b/local_backend/tests/test_print_problems.py
@@ -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"] == []
diff --git a/manager_dashboard/src/App.jsx b/manager_dashboard/src/App.jsx
index 83c7f27..24a77df 100644
--- a/manager_dashboard/src/App.jsx
+++ b/manager_dashboard/src/App.jsx
@@ -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
diff --git a/manager_dashboard/src/pages/Management/PrepZonesConfigPage.jsx b/manager_dashboard/src/pages/Management/PrepZonesConfigPage.jsx
deleted file mode 100644
index 7d57de0..0000000
--- a/manager_dashboard/src/pages/Management/PrepZonesConfigPage.jsx
+++ /dev/null
@@ -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 (
- !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'}`}
- >
-
-
- )
-}
-
-function CopySpinner({ value, onChange, min = 1, max = 9 }) {
- return (
-
- 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"
- >−
- {value}×
- 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"
- >+
-
- )
-}
-
-// ── 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 (
-
-
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"
- >
-
- {selected ? (
- <>
-
- {selected.name}
- {selected.ip_address}:{selected.port}
- >
- ) : (
- — Χωρίς κύριο —
- )}
-
-
-
-
- {open && (
-
-
{ 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' : ''}`}
- >
-
- {!value && }
-
- Χωρίς κύριο εκτυπωτή
-
- {printers.map(p => (
-
{ 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' : ''}`}
- >
-
- {value === p.id && }
-
-
- {p.name}
- {p.ip_address}:{p.port}
-
- ))}
-
- )}
-
- )
-}
-
-// ── 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 (
-
-
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]"
- >
-
- {selectedPrinters.length === 0 ? (
- — Χωρίς δευτερεύοντες —
- ) : (
- selectedPrinters.map(p => (
-
- {p.name}
-
- ))
- )}
-
-
-
-
- {open && (
-
- {eligible.length === 0 ? (
-
- {printers.length <= 1 ? 'Δεν υπάρχουν άλλοι εκτυπωτές' : 'Ο μόνος εκτυπωτής είναι ο κύριος'}
-
- ) : eligible.map(p => {
- const on = selectedSet.has(p.id)
- return (
-
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' : ''}`}
- >
-
- {on && }
-
-
- {p.name}
- {p.ip_address}:{p.port}
-
- )
- })}
-
- Κλικ έξω για κλείσιμο
-
-
- )}
-
- )
-}
-
-// ── 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 (
-
-
-
-
-
Σειρά Κατηγοριών Εκτύπωσης
-
Σύρετε για αλλαγή σειράς
-
-
-
-
-
-
-
- {list.map((cat, i) => (
-
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"
- >
-
-
-
{cat.name}
-
- move(i, -1)} disabled={i === 0}
- className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
-
-
- move(i, 1)} disabled={i === list.length - 1}
- className="p-1 rounded text-gray-400 hover:text-gray-600 disabled:opacity-20">
-
-
-
-
{i + 1}
-
- ))}
- {list.length === 0 && (
-
Δεν υπάρχουν κατηγορίες
- )}
-
-
-
- Ακύρωση
- { onSave(list.map(c => c.id)); onClose() }}
- className="btn btn-primary flex items-center gap-2"
- >
- Αποθήκευση σειράς
-
-
-
-
- )
-}
-
-// ── Section header ────────────────────────────────────────────────────────────
-
-function Section({ icon: Icon_, label, children }) {
- return (
-
-
-
- {label}
-
- {children}
-
- )
-}
-
-// ── Toggle row ────────────────────────────────────────────────────────────────
-
-function ToggleRow({ label, desc, value, onChange, disabled, children, warning }) {
- return (
-
-
-
-
-
{label}
- {warning &&
}
-
- {desc &&
{desc}
}
-
-
-
- {value && children && (
-
{children}
- )}
-
- )
-}
-
-// ── 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 (
- <>
-
-
- {catModal && (
- 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 (
-
- {children}
-
- )
-}
-
-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 (
-
-
-
-
-
{zone.name}
- {zone.bypass_kds && Bypass KDS }
- {!zone.bypass_kds && zone.bypass_pending && Bypass Pending }
- {zone.auto_ready_to_served && Auto Served }
-
- {zone.notification_name && (
-
{zone.notification_name}
- )}
- {zone.description &&
{zone.description}
}
-
-
-
onEdit(zone)}
- className="p-1.5 rounded-lg text-gray-400 hover:text-primary-600 hover:bg-primary-50 transition-colors">
-
-
- {!confirmDelete ? (
-
setConfirmDelete(true)}
- className="p-1.5 rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50 transition-colors">
-
-
- ) : (
-
- setConfirmDelete(false)}
- className="p-1.5 rounded-lg text-gray-400 hover:bg-gray-100 transition-colors">
-
-
- 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">
- Διαγραφή
-
-
- )}
-
-
-
-
-
-
Κύριος
- {masterPrinter ? (
- <>
-
- {masterPrinter.name}
-
- {zone.auto_print !== 'none' && (
-
{zone.master_copies}×
- )}
- >
- ) : (
-
Χωρίς
- )}
-
- {secondaryPrinters.length > 0 && (
-
-
Δευτ.
- {secondaryPrinters.map(p => (
-
- {p.name}
-
- ))}
- {zone.auto_print === 'all' && (
-
{zone.secondary_copies}×
- )}
-
- )}
-
-
-
- {printLabel.text}
- {sortLabel}
- {zone.group_by_category && Κατά κατηγορία }
- {zone.print_checkboxes && Checkboxes }
-
-
- )
-}
-
-// ── 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 (
-
- )
- }
-
- 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
-
-
- {/* Page header */}
-
-
-
-
-
-
-
Ζώνες Προετοιμασίας
-
Ζώνες, εκτυπωτές και συμπεριφορά KDS
-
-
- {!formOpen && (
-
setShowForm(true)} className="btn btn-primary flex items-center gap-2 shrink-0">
-
- Νέα Ζώνη
-
- )}
-
-
- {/* Two-column layout when form is open */}
- {formOpen ? (
-
- {/* Form panel */}
-
-
-
-
- {showForm ? 'Νέα Ζώνη Προετοιμασίας' : `Επεξεργασία: ${editing?.name}`}
-
-
-
create.mutate(body)
- : (body) => update.mutate({ id: editing.id, ...body })}
- onCancel={() => { setShowForm(false); setEditing(null) }}
- saving={create.isPending || update.isPending}
- />
-
-
- {/* Zone list sidebar */}
-
- {zones.length === 0 ? (
-
-
-
Δεν υπάρχουν ζώνες ακόμα
-
- ) : zones.map(zone => (
-
{ setShowForm(false); setEditing(z) }}
- onDelete={id => remove.mutate(id)}
- />
- ))}
-
-
- ) : (
- /* Full-width zone grid when no form open */
- zones.length === 0 ? (
-
-
-
-
-
Δεν υπάρχουν ζώνες ακόμα
-
Δημιουργήστε την πρώτη ζώνη για να αρχίσετε.
-
- ) : (
-
- {zones.map(zone => (
- { setShowForm(false); setEditing(z) }}
- onDelete={id => remove.mutate(id)}
- />
- ))}
-
- )
- )}
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/Settings/SettingsPage.jsx b/manager_dashboard/src/pages/Settings/SettingsPage.jsx
index 334b2f7..297e183 100644
--- a/manager_dashboard/src/pages/Settings/SettingsPage.jsx
+++ b/manager_dashboard/src/pages/Settings/SettingsPage.jsx
@@ -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' && }
{activeTab === 'operation' && }
{activeTab === 'colours' && }
- {activeTab === 'print-fonts' && }
+ {activeTab === 'print-fonts' && }
{activeTab === 'fiscal' && }
{activeTab === 'development' && }
diff --git a/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx b/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx
deleted file mode 100644
index 10576e6..0000000
--- a/manager_dashboard/src/pages/Settings/tabs/PrintFontsTab.jsx
+++ /dev/null
@@ -1,1196 +0,0 @@
-import React, { useState, useEffect, useRef, useCallback } from 'react'
-import PrintAlertSetting from '../sections/PrintAlertSetting'
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
-import toast from 'react-hot-toast'
-import client from '../../../api/client'
-
-// ── Font option definitions ────────────────────────────────────────────────
-// Value encodes: "SIZE:BOLD:CAPS"
-// SIZE: ESC ! base byte — 0=normal, 16=tall, 32=wide, 48=tall+wide
-// BOLD: 0|1 CAPS: 0|1
-const FONT_SIZE_OPTIONS = [
- { size: '0', label: 'Μικρά' },
- { size: '16', label: 'Ψηλά' },
- { size: '32', label: 'Πλατιά' },
- { size: '48', label: 'Ψηλά και Πλατιά' },
-]
-
-function encodeFont(size, bold, caps) {
- return `${size}:${bold ? '1' : '0'}:${caps ? '1' : '0'}`
-}
-function decodeFont(val) {
- if (!val) return { size: '0', bold: false, caps: false }
- const [size, bold, caps] = val.split(':')
- return { size: size ?? '0', bold: bold === '1', caps: caps === '1' }
-}
-
-const DIVIDER_OPTIONS = [
- { value: 'dash', label: 'Παύλες ( - )', chars: '-------------------' },
- { value: 'equals', label: 'Ίσον ( = )', chars: '===================' },
- { value: 'star', label: 'Αστερίσκοι ( * )', chars: '*******************' },
- { value: 'empty', label: 'Κενή γραμμή', chars: '' },
-]
-
-const DOT_STYLE_OPTIONS = [
- { value: 'dot_space', label: 'Τελεία + κενό ( . )', preview: '. . . . .' },
- { value: 'dot', label: 'Τελείες ( . )', preview: '.........' },
- { value: 'dash_space', label: 'Παύλα + κενό ( - )', preview: '- - - - -' },
- { value: 'underscore', label: 'Κάτω παύλα ( _ )', preview: '_________' },
-]
-
-const FONT_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',
-}
-
-// ── Preview ────────────────────────────────────────────────────────────────
-const PREVIEW_W = 200
-const PREVIEW_H = 50
-
-const sizeStyle = {
- '0': { fontSize: 13, scaleY: 1, scaleX: 1 },
- '16': { fontSize: 13, scaleY: 1.9, scaleX: 1 },
- '32': { fontSize: 13, scaleY: 1, scaleX: 1.9 },
- '48': { fontSize: 13, scaleY: 1.9, scaleX: 1.9 },
-}
-
-function FontPreview({ size, bold, caps }) {
- const s = sizeStyle[size] ?? sizeStyle['0']
- return (
-
-
- {caps ? 'SAMPLE' : 'Sample'}
-
-
- )
-}
-
-// ── Toggle button (shared) ─────────────────────────────────────────────────
-function ToggleBtn({ active, onClick, disabled, label }) {
- return (
-
-
- {active && ✓ }
-
- {label}
-
- )
-}
-
-// ── Single font row ────────────────────────────────────────────────────────
-function FontRow({ field, value, onChange, isPending, nested = false }) {
- const { size, bold, caps } = decodeFont(value)
-
- function handleSize(e) { onChange(field.key, encodeFont(e.target.value, bold, caps)) }
- function handleBold() { onChange(field.key, encodeFont(size, !bold, caps)) }
- function handleCaps() { onChange(field.key, encodeFont(size, bold, !caps)) }
-
- return (
-
- {nested && (
-
└
- )}
- {/* Label */}
-
-
- {field.label}
-
- {field.sub && (
- {field.sub}
- )}
-
-
- {/* Size dropdown */}
-
- {FONT_SIZE_OPTIONS.map(o => (
- {o.label}
- ))}
-
-
- {/* Bold toggle */}
-
-
- {/* Caps toggle */}
-
-
- {/* Preview */}
-
-
- )
-}
-
-// ── Subgroup header row ────────────────────────────────────────────────────
-function SubgroupHeader({ label }) {
- return (
-
-
- {label}
-
-
- )
-}
-
-// ── Divider row ────────────────────────────────────────────────────────────
-function DividerRow({ value, onChange, isPending }) {
- return (
-
-
-
- Στυλ Διαχωριστικού
-
- Ανάμεσα στις ενότητες κάθε ticket
-
-
-
onChange('print.divider_style', e.target.value)}
- disabled={isPending}
- style={{
- height: 36, borderRadius: 8, border: '1px solid #dfe2e6',
- background: 'white', padding: '0 10px', fontSize: 13,
- color: '#111315', cursor: 'pointer', width: 160, flexShrink: 0,
- }}
- >
- {DIVIDER_OPTIONS.map(o => (
- {o.label}
- ))}
-
-
- {/* spacer to align with bold+caps column */}
-
-
- {/* Preview */}
-
- {value === 'empty'
- ? (κενή γραμμή)
- :
- {DIVIDER_OPTIONS.find(o => o.value === value)?.chars}
-
- }
-
-
- )
-}
-
-// ── Dot style row ─────────────────────────────────────────────────────────
-function decodeDotStyle(val) {
- if (!val) return { style: 'dot_space', size: '0', bold: false }
- const [style, size, bold] = val.split(':')
- return { style: style ?? 'dot_space', size: size ?? '0', bold: bold === '1' }
-}
-function encodeDotStyle(style, size, bold) {
- return `${style}:${size}:${bold ? '1' : '0'}`
-}
-
-function DotStyleRow({ value, onChange, isPending }) {
- const { style, size, bold } = decodeDotStyle(value)
- const selected = DOT_STYLE_OPTIONS.find(o => o.value === style) ?? DOT_STYLE_OPTIONS[0]
- const s = sizeStyle[size] ?? sizeStyle['0']
-
- function handleStyle(e) { onChange('print.dot_style', encodeDotStyle(e.target.value, size, bold)) }
- function handleSize(e) { onChange('print.dot_style', encodeDotStyle(style, e.target.value, bold)) }
- function handleBold() { onChange('print.dot_style', encodeDotStyle(style, size, !bold)) }
-
- return (
-
-
└
-
-
-
- Στυλ Dots
-
- Χαρακτήρας · μέγεθος · έντονο για τη γραμμή dot-leader
-
-
- {/* Style dropdown */}
-
- {DOT_STYLE_OPTIONS.map(o => (
- {o.label}
- ))}
-
-
- {/* Size dropdown */}
-
- {FONT_SIZE_OPTIONS.map(o => (
- {o.label}
- ))}
-
-
- {/* Bold toggle */}
-
-
- {/* Preview */}
-
-
- Esp {selected.preview} x2
-
-
-
- )
-}
-
-// ── Ticket mode section ────────────────────────────────────────────────────
-function TicketModeSection({ value, onChange, isPending, printers }) {
- const [selectedPrinter, setSelectedPrinter] = useState(null)
- const [printing, setPrinting] = useState(false)
-
- // Auto-select first active printer
- useEffect(() => {
- if (printers.length > 0 && !selectedPrinter) {
- const first = printers.find(p => p.is_active) ?? printers[0]
- setSelectedPrinter(first.id)
- }
- }, [printers])
-
- async function handleTestOrder() {
- if (!selectedPrinter) return
- setPrinting(true)
- try {
- const res = await client.post(`/api/system/printers/test-order?printer_id=${selectedPrinter}`)
- if (res.data.success) toast.success('Test order στάλθηκε!')
- else toast.error(`Σφάλμα: ${res.data.error}`)
- } catch {
- toast.error('Σφάλμα επικοινωνίας')
- } finally {
- setPrinting(false)
- }
- }
-
- return (
-
-
-
Τύπος Εκτύπωσης
-
- Επιλέξτε πόσο λεπτομερές θα είναι κάθε ticket κουζίνας.
-
-
-
- {[
- {
- key: 'detailed',
- title: 'Αναλυτικό',
- desc: 'Κάθε επιλογή σε ξεχωριστή γραμμή. Περισσότερος χώρος, μέγιστη ευκρίνεια.',
- },
- {
- key: 'compact',
- title: 'Συμπαγές',
- desc: 'Ίδιου τύπου επιλογές στην ίδια γραμμή, διαχωρισμένες με |. Λιγότερο χαρτί.',
- },
- ].map(opt => {
- const active = value === opt.key
- return (
-
onChange('print.ticket_mode', opt.key)}
- disabled={isPending}
- style={{
- flex: '1 1 200px', textAlign: 'left', padding: '14px 16px',
- borderRadius: 10, cursor: 'pointer',
- border: `2px solid ${active ? '#3758c9' : '#e5e7eb'}`,
- background: active ? '#eff3ff' : 'white',
- }}
- >
-
- {opt.title}
-
- {opt.desc}
-
- )
- })}
-
- {/* Test order button */}
-
-
-
- {printing ? 'Εκτύπωση…' : 'Δοκιμαστική Εκτύπωση'}
-
-
- Εκτυπώνει fake παραγγελία με όλους τους τύπους επιλογών για προεπισκόπηση ρυθμίσεων.
-
-
- {printers.length > 0 && (
- e.stopPropagation()}>
- setSelectedPrinter(Number(e.target.value))}
- disabled={printing}
- style={{
- width: '100%', height: 32, borderRadius: 6,
- border: '1px solid #dfe2e6', background: 'white',
- padding: '0 8px', fontSize: 12, color: '#374151', cursor: 'pointer',
- }}
- >
- {printers.map(p => (
- {p.name} ({p.ip_address})
- ))}
-
-
- )}
- {printers.length === 0 && (
-
- Δεν υπάρχουν εκτυπωτές
-
- )}
-
-
-
- )
-}
-
-// ── Beep section ───────────────────────────────────────────────────────────
-
-const BEEP_PRESETS = [
- { id: 'off', label: 'Χωρίς Ήχο', desc: 'Χωρίς beep κατά την εκτύπωση' },
- { id: 'single', label: 'Μονό', desc: '1× παλμός 200ms' },
- { id: 'double', label: 'Διπλό', desc: '2× σύντομοι παλμοί (προτεινόμενο)' },
- { id: 'triple', label: 'Τριπλό', desc: '3× σύντομοι παλμοί — πιο εντονο' },
- { id: 'long', label: 'Μακρύ', desc: '1× παλμός 500ms' },
- { id: 'custom', label: 'Προσαρμοσμένο', desc: 'Ορίστε τη διάρκεια χειροκίνητα' },
-]
-
-// Parse beep settings → { preset, n1, n2, n3 }
-function decodeBeep(patternVal, enabledVal) {
- if (enabledVal === 'false') return { preset: 'off', n1: 2, n2: 2, n3: 1 }
- if (!patternVal || patternVal === 'double') return { preset: 'double', n1: 1, n2: 1, n3: 2 }
- if (patternVal.startsWith('custom:')) {
- const [, n1, n2, n3] = patternVal.split(':')
- return { preset: 'custom', n1: parseInt(n1) || 2, n2: parseInt(n2) || 2, n3: parseInt(n3) || 1 }
- }
- const presetMap = { single: [2,2,1], double: [1,1,2], triple: [1,1,3], long: [5,2,1] }
- const [n1, n2, n3] = presetMap[patternVal] ?? [1,1,2]
- return { preset: patternVal, n1, n2, n3 }
-}
-
-function BeepSection({ beepEnabled, beepPattern, onChange, isPending, printers }) {
- const { preset: initPreset, n1: iN1, n2: iN2, n3: iN3 } = decodeBeep(beepPattern, beepEnabled)
- const [preset, setPreset] = useState(initPreset)
- const [n1, setN1] = useState(iN1)
- const [n2, setN2] = useState(iN2)
- const [n3, setN3] = useState(iN3)
- const [testPrinter, setTestPrinter] = useState(null)
- const [testing, setTesting] = useState(false)
-
- useEffect(() => {
- if (printers.length > 0 && !testPrinter) {
- setTestPrinter((printers.find(p => p.is_active) ?? printers[0]).id)
- }
- }, [printers])
-
- // Sync local state if parent settings change (e.g. after save)
- useEffect(() => {
- const decoded = decodeBeep(beepPattern, beepEnabled)
- setPreset(decoded.preset)
- setN1(decoded.n1); setN2(decoded.n2); setN3(decoded.n3)
- }, [beepPattern, beepEnabled])
-
- function handlePresetChange(id) {
- setPreset(id)
- if (id === 'off') {
- onChange('print.beep_on_ticket', 'false')
- } else if (id === 'custom') {
- onChange('print.beep_on_ticket', 'true')
- onChange('print.beep_pattern', `custom:${n1}:${n2}:${n3}`)
- } else {
- onChange('print.beep_on_ticket', 'true')
- onChange('print.beep_pattern', id)
- }
- }
-
- function handleCustomChange(field, raw) {
- const v = Math.max(1, Math.min(30, parseInt(raw) || 1))
- const next = { n1, n2, n3, [field]: v }
- if (field === 'n1') setN1(v)
- if (field === 'n2') setN2(v)
- if (field === 'n3') setN3(v)
- onChange('print.beep_pattern', `custom:${next.n1}:${next.n2}:${next.n3}`)
- }
-
- // Compute beep bytes from current state for test
- function getBeepBytes() {
- if (preset === 'custom') return { n1, n2, n3 }
- const presetMap = { single: [2,2,1], double: [1,1,2], triple: [1,1,3], long: [5,2,1] }
- const [bn1, bn2, bn3] = presetMap[preset] ?? [1,1,2]
- return { n1: bn1, n2: bn2, n3: bn3 }
- }
-
- async function handleTestBeep() {
- if (!testPrinter || preset === 'off') return
- const { n1: b1, n2: b2, n3: b3 } = getBeepBytes()
- setTesting(true)
- try {
- const res = await client.post(`/api/system/printers/test-beep?printer_id=${testPrinter}&n1=${b1}&n2=${b2}&n3=${b3}`)
- if (res.data.success) toast.success('Beep στάλθηκε!')
- else toast.error(`Σφάλμα: ${res.data.error}`)
- } catch {
- toast.error('Σφάλμα επικοινωνίας')
- } finally {
- setTesting(false)
- }
- }
-
- return (
-
-
-
Ήχος Εκτυπωτή (Beep)
-
- Ο εκτυπωτής χτυπά για να ειδοποιεί την κουζίνα σε κάθε νέα παραγγελία.
-
-
-
- {/* Preset grid */}
-
- {BEEP_PRESETS.map(opt => {
- const active = preset === opt.id
- return (
-
handlePresetChange(opt.id)}
- disabled={isPending}
- style={{
- flex: '1 1 140px', textAlign: 'left', padding: '12px 14px',
- borderRadius: 10, cursor: isPending ? 'default' : 'pointer',
- border: `2px solid ${active ? '#3758c9' : '#e5e7eb'}`,
- background: active ? '#eff3ff' : 'white',
- }}
- >
-
- {opt.label}
-
- {opt.desc}
-
- )
- })}
-
-
- {/* Custom fields */}
- {preset === 'custom' && (
-
- {[
- { field: 'n1', label: 'Διάρκεια ON (×100ms)', val: n1, hint: 'π.χ. 3 = 300ms' },
- { field: 'n2', label: 'Διάρκεια OFF (×100ms)', val: n2, hint: 'Διάλλειμα μεταξύ παλμών' },
- { field: 'n3', label: 'Επαναλήψεις', val: n3, hint: 'Πόσες φορές' },
- ].map(({ field, label, val, hint }) => (
-
- {label}
- handleCustomChange(field, e.target.value)}
- disabled={isPending}
- style={{ ...inputStyle, width: '100%' }}
- />
- {hint}
-
- ))}
-
- )}
-
- {/* Test beep */}
-
- Δοκιμαστικό Beep:
- {printers.length > 0 ? (
- <>
- setTestPrinter(Number(e.target.value))}
- disabled={testing}
- style={{ ...inputStyle, width: 200 }}
- >
- {printers.map(p => {p.name} ({p.ip_address}) )}
-
-
- {testing ? 'Αποστολή…' : '🔔 Τεστ Beep'}
-
- {preset === 'off' && (
- Ο ήχος είναι απενεργοποιημένος
- )}
- >
- ) : (
- Δεν υπάρχουν εκτυπωτές
- )}
-
-
- )
-}
-
-// ── Printers section ───────────────────────────────────────────────────────
-
-const PROTOCOLS = [{ value: 'escpos_tcp', label: 'ESC/POS TCP (standard)' }]
-
-const PRINTER_PROFILES = [
- { label: 'Jolimark TP850UE', codepage_n: 29 },
- { label: 'S4MAS Giant 100', codepage_n: 29 },
- { label: 'NETUM NT8330L', codepage_n: 24 },
-]
-const codepageToProfile = (n) => PRINTER_PROFILES.find(p => p.codepage_n === n) ?? PRINTER_PROFILES[0]
-
-const EMPTY_FORM = { name: '', ip_address: '', port: 9100, protocol: 'escpos_tcp', line_width: 48, codepage_n: 29, is_active: true }
-
-function PrinterForm({ initial, onSave, onCancel, isPending }) {
- const [form, setForm] = useState(initial ?? EMPTY_FORM)
- function set(k, v) { setForm(f => ({ ...f, [k]: v })) }
-
- return (
-
-
- ΟΝΟΜΑ
- set('name', e.target.value)}
- placeholder="π.χ. Κουζίνα" style={inputStyle} />
-
-
- IP ADDRESS
- set('ip_address', e.target.value)}
- placeholder="10.98.20.25" style={inputStyle} />
-
-
- PORT
- set('port', parseInt(e.target.value) || 9100)}
- type="number" style={inputStyle} />
-
-
- ΜΟΝΤΕΛΟ ΕΚΤΥΠΩΤΗ
- set('codepage_n', parseInt(e.target.value))}
- style={inputStyle}
- >
- {PRINTER_PROFILES.map(p => (
- {p.label}
- ))}
-
-
-
- ΧΑΡΑΚΤ./ΓΡΑΜΜΗ
- set('line_width', parseInt(e.target.value) || 48)}
- type="number" min={20} max={80} style={inputStyle} />
-
-
- onSave(form)} disabled={isPending || !form.name.trim() || !form.ip_address.trim()}
- style={btnPrimary}>Αποθήκευση
- Άκυρο
-
-
- )
-}
-
-const inputStyle = {
- height: 36, borderRadius: 8, border: '1px solid #dfe2e6', background: 'white',
- padding: '0 10px', fontSize: 13, color: '#111315', fontFamily: 'inherit', width: '100%',
-}
-const btnPrimary = {
- height: 36, padding: '0 16px', borderRadius: 8, background: '#3758c9', color: 'white',
- border: 'none', fontSize: 13, fontWeight: 600, cursor: 'pointer',
-}
-const btnSecondary = {
- height: 36, padding: '0 14px', borderRadius: 8, border: '1px solid #dfe2e6',
- background: 'white', fontSize: 13, cursor: 'pointer', color: '#374151',
-}
-const btnDanger = {
- height: 28, padding: '0 10px', borderRadius: 6, border: '1px solid #fee2e2',
- background: '#fff5f5', fontSize: 12, cursor: 'pointer', color: '#dc2626',
-}
-
-function PrinterRow({ printer, onEdit, onDelete, onTest, onToggle, testPending }) {
- const [reachable, setReachable] = useState(null)
-
- useEffect(() => {
- let cancelled = false
- client.get('/api/system/status').then(r => {
- if (cancelled) return
- const match = r.data.printers?.find(p => p.id === printer.id)
- if (match) setReachable(match.reachable)
- }).catch(() => {})
- return () => { cancelled = true }
- }, [printer.id])
-
- return (
-
-
onToggle(printer)} title={printer.is_active ? 'Απενεργοποίηση' : 'Ενεργοποίηση'}
- style={{
- width: 40, height: 22, borderRadius: 999, border: 'none', cursor: 'pointer', flexShrink: 0,
- background: printer.is_active ? '#16a34a' : '#d1d5db', position: 'relative', transition: 'background 150ms',
- }}>
-
-
-
-
- {printer.name}
-
- {printer.ip_address}:{printer.port}
-
- — {codepageToProfile(printer.codepage_n ?? 29).label}
- — {printer.line_width ?? 48} χαρ.
-
-
-
- {reachable === null ? 'Έλεγχος…' : reachable ? 'Προσβάσιμος' : 'Μη προσβάσιμος'}
-
-
-
onTest(printer.id)} disabled={testPending}
- style={{ ...btnSecondary, height: 28, padding: '0 10px', fontSize: 12, flexShrink: 0 }}>
- Test Print
-
-
onEdit(printer)}
- style={{ ...btnSecondary, height: 28, padding: '0 10px', fontSize: 12, flexShrink: 0 }}>
- Επεξεργασία
-
-
onDelete(printer.id)} style={{ ...btnDanger, flexShrink: 0 }}>
- Διαγραφή
-
-
- )
-}
-
-function FindPrintersModal({ onClose, onSelect }) {
- const [subnet, setSubnet] = useState('')
- const [port, setPort] = useState(9100)
- const [scanning, setScanning] = useState(false)
- const [found, setFound] = useState([])
- const [progress, setProgress] = useState(null) // { done, total }
- const [error, setError] = useState(null)
- const esRef = useRef(null)
-
- // Fetch auto-detected subnets on mount
- useEffect(() => {
- client.get('/api/system/printers/scan-hints')
- .then(r => { if (r.data.subnets?.length) setSubnet(r.data.subnets[0]) })
- .catch(() => {})
- }, [])
-
- const stopScan = useCallback(() => {
- if (esRef.current) { esRef.current.close(); esRef.current = null }
- setScanning(false)
- }, [])
-
- useEffect(() => () => stopScan(), [stopScan])
-
- function startScan() {
- stopScan()
- setFound([])
- setProgress(null)
- setError(null)
- setScanning(true)
-
- const token = localStorage.getItem('manager_token') || ''
- const params = new URLSearchParams({ subnet, port })
- // Use fetch with ReadableStream to consume SSE (EventSource doesn't support auth headers)
- fetch(`/api/system/printers/scan?${params}`, {
- headers: { Authorization: `Bearer ${token}` },
- }).then(async res => {
- if (!res.ok) { setError('Σφάλμα σύνδεσης'); setScanning(false); return }
- const reader = res.body.getReader()
- const decoder = new TextDecoder()
- let buf = ''
- while (true) {
- 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
- try {
- const msg = JSON.parse(line.slice(6))
- if (msg.type === 'found') setFound(prev => [...prev, { ip: msg.ip, port: msg.port }])
- else if (msg.type === 'progress') setProgress({ done: msg.done, total: msg.total })
- else if (msg.type === 'done') setScanning(false)
- else if (msg.error) { setError(msg.error); setScanning(false) }
- } catch {}
- }
- }
- setScanning(false)
- }).catch(e => { setError(String(e)); setScanning(false) })
- }
-
- const pct = progress ? Math.round((progress.done / progress.total) * 100) : 0
-
- return (
- { if (e.target === e.currentTarget) onClose() }}>
-
-
-
Εύρεση εκτυπωτών
-
- Σκανάρει το δίκτυο για συσκευές που ακούνε στη θύρα εκτύπωσης.
-
-
-
-
-
-
- ΥΠΟΔΙΚΤΥΟ (π.χ. 192.168.1.0/24)
-
- setSubnet(e.target.value)}
- placeholder="192.168.1.0/24"
- style={inputStyle}
- disabled={scanning}
- />
-
-
- PORT
- setPort(parseInt(e.target.value) || 9100)}
- type="number"
- style={inputStyle}
- disabled={scanning}
- />
-
-
- {scanning ? 'Διακοπή' : 'Σκανάρισμα'}
-
-
-
- {scanning && (
-
-
-
- {progress ? `${progress.done} / ${progress.total} IPs ελέγχθηκαν` : 'Εκκίνηση…'}
-
-
- )}
-
- {error && (
-
{error}
- )}
-
-
- {found.length === 0 && !scanning && (
-
- {progress ? 'Κανένας εκτυπωτής δεν βρέθηκε.' : 'Πατήστε «Σκανάρισμα» για να ξεκινήσει η αναζήτηση.'}
-
- )}
- {found.map(item => (
-
-
- {item.ip}
- :{item.port}
-
-
{ onSelect({ ip_address: item.ip, port: item.port }); onClose() }}
- style={{ ...btnPrimary, height: 30, padding: '0 14px', fontSize: 12 }}
- >
- Χρήση
-
-
- ))}
-
-
-
- Κλείσιμο
-
-
-
- )
-}
-
-function PrintersSection() {
- const qc = useQueryClient()
- const [showNew, setShowNew] = useState(false)
- const [editingId, setEditingId] = useState(null)
- const [showFinder, setShowFinder] = useState(false)
- const [newFormInitial, setNewFormInitial] = useState(null)
-
- const { data: printers = [], isLoading } = useQuery({
- queryKey: ['printers-all'],
- queryFn: () => client.get('/api/system/printers').then(r => r.data),
- staleTime: 15_000,
- })
-
- const createMut = useMutation({
- mutationFn: body => client.post('/api/system/printers', body),
- onSuccess: () => { toast.success('Εκτυπωτής προστέθηκε'); qc.invalidateQueries({ queryKey: ['printers-all'] }); setShowNew(false) },
- onError: () => toast.error('Σφάλμα δημιουργίας'),
- })
- const updateMut = useMutation({
- mutationFn: ({ id, ...body }) => client.put(`/api/system/printers/${id}`, body),
- onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['printers-all'] }); setEditingId(null) },
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
- const deleteMut = useMutation({
- mutationFn: id => client.delete(`/api/system/printers/${id}`),
- onSuccess: () => { toast.success('Διαγράφηκε'); qc.invalidateQueries({ queryKey: ['printers-all'] }) },
- onError: () => toast.error('Σφάλμα διαγραφής'),
- })
- const testMut = useMutation({
- mutationFn: id => client.post(`/api/system/printers/test?printer_id=${id}`),
- onSuccess: res => res.data.success ? toast.success('Test print στάλθηκε!') : toast.error(`Σφάλμα: ${res.data.error}`),
- onError: () => toast.error('Σφάλμα επικοινωνίας'),
- })
-
- function handleToggle(printer) {
- updateMut.mutate({ id: printer.id, is_active: !printer.is_active })
- }
-
- function handleFinderSelect(prefill) {
- setNewFormInitial({ ...EMPTY_FORM, ...prefill })
- setShowNew(true)
- setEditingId(null)
- }
-
- return (
-
- {showFinder && (
-
setShowFinder(false)}
- onSelect={handleFinderSelect}
- />
- )}
-
-
-
Εκτυπωτές
-
Διαχείριση εκτυπωτών του συστήματος
-
-
- setShowFinder(true)} style={{ ...btnSecondary, fontSize: 13 }}>
- Εύρεση εκτυπωτών
-
- { setNewFormInitial(null); setShowNew(v => !v); setEditingId(null) }} style={btnSecondary}>
- + Νέος εκτυπωτής
-
-
-
-
- {showNew && (
-
-
createMut.mutate(form)}
- onCancel={() => { setShowNew(false); setNewFormInitial(null) }}
- isPending={createMut.isPending}
- />
-
- )}
-
- {isLoading && Φόρτωση…
}
- {!isLoading && printers.length === 0 && !showNew && (
-
- Δεν υπάρχουν εκτυπωτές ακόμα.
-
- )}
-
- {printers.map(printer => (
- editingId === printer.id ? (
-
-
updateMut.mutate({ id: printer.id, ...form })}
- onCancel={() => setEditingId(null)}
- isPending={updateMut.isPending}
- />
-
- ) : (
- { setEditingId(p.id); setShowNew(false) }}
- onDelete={id => deleteMut.mutate(id)}
- onTest={id => testMut.mutate(id)}
- onToggle={handleToggle}
- testPending={testMut.isPending}
- />
- )
- ))}
-
- )
-}
-
-// ── Font groups definition ─────────────────────────────────────────────────
-const FONT_GROUPS = [
- {
- group: 'Αριθμός Παραγγελίας',
- fields: [
- { key: 'print.font_order_number', label: 'Αριθμός Παραγγελίας', sub: '"Παραγγελια #42" — η επικεφαλίδα του ticket' },
- ],
- },
- {
- group: 'Επικεφαλίδα Ticket',
- fields: [
- { key: 'print.font_meta', label: 'Τραπέζι · Σερβιτόρος · Ώρα', sub: 'Γραμμές ταυτότητας κάτω από τον αριθμό' },
- ],
- },
- {
- group: 'Αντικείμενα',
- fields: [
- { key: 'print.font_item_name', label: 'Όνομα Αντικειμένου', sub: 'Το κυρίως πιάτο/ποτό — γραμμή dot-leader' },
- { key: 'print.font_quick', label: '* Quick Options', sub: 'Γρήγορες επιλογές ( * )' },
- { key: 'print.font_pref', label: '> Προτιμήσεις', sub: 'Επιλογές preference sets ( > )' },
- { key: 'print.font_extra', label: '+ Extras', sub: 'Πρόσθετα / τροποποιητές ( + )' },
- { key: 'print.font_ingredient', label: '- Αφαιρέσεις', sub: 'ΧΩΡΙΣ: συστατικά ( - )' },
- ],
- },
- {
- group: 'Σημειώσεις',
- fields: [
- { key: 'print.font_item_note', label: '(!) Σημείωση Αντικειμένου', sub: 'Free-text σημείωση ανά πιάτο' },
- { key: 'print.font_order_note', label: 'Σημειώσεις Παραγγελίας', sub: 'Η γενική σημείωση της παραγγελίας' },
- ],
- },
-]
-
-// ── Main tab ───────────────────────────────────────────────────────────────
-export default function PrintFontsTab() {
- const qc = useQueryClient()
-
- const { data: settings, isLoading } = useQuery({
- queryKey: ['pos-settings'],
- queryFn: () => client.get('/api/settings/').then(r => r.data),
- staleTime: 30_000,
- })
-
- const { data: printers = [] } = useQuery({
- queryKey: ['printers-all'],
- queryFn: () => client.get('/api/system/printers').then(r => r.data),
- staleTime: 15_000,
- })
-
- const updateMut = useMutation({
- mutationFn: ({ key, value }) => client.put(`/api/settings/${key}`, { value }),
- onSuccess: () => { toast.success('Αποθηκεύτηκε'); qc.invalidateQueries({ queryKey: ['pos-settings'] }) },
- onError: () => toast.error('Σφάλμα αποθήκευσης'),
- })
-
- function val(key) { return settings?.[key]?.value ?? FONT_DEFAULTS[key] }
- function handleChange(key, value) { updateMut.mutate({ key, value }) }
-
- if (isLoading) {
- return Φόρτωση…
- }
-
- return (
-
-
-
- {/* 1. Printers */}
-
-
- {/* 2. Ticket mode */}
-
-
- {/* 3. Beep settings */}
-
-
- {/* 4. Font sizes */}
-
-
-
Μεγέθη Γραμματοσειράς
-
- Οι αλλαγές εφαρμόζονται στην επόμενη εκτύπωση.
-
-
-
- {FONT_GROUPS.map(group => (
-
-
- {group.fields.map((field) => (
-
- 1}
- />
- {field.key === 'print.font_ingredient' && (
-
- )}
-
- ))}
-
- ))}
-
-
- {/* 5. Divider style */}
-
-
-
Διαχωριστικές Γραμμές
-
-
-
-
-
- Σημείωση: Το "Πλατιά" και "Ψηλά και Πλατιά" χωράνε ~24 χαρακτήρες ανά γραμμή αντί για 48.
- Χρησιμοποιήστε τα μόνο για σύντομα κείμενα (αριθμοί παραγγελίας, επικεφαλίδες).
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/orders/OrderPage.jsx b/manager_dashboard/src/pages/orders/OrderPage.jsx
index b4e97b3..14ca7c3 100644
--- a/manager_dashboard/src/pages/orders/OrderPage.jsx
+++ b/manager_dashboard/src/pages/orders/OrderPage.jsx
@@ -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 }) {
)}
+
+
{tab === 'order' && (
diff --git a/manager_dashboard/src/pages/orders/PrintProblemsCard.jsx b/manager_dashboard/src/pages/orders/PrintProblemsCard.jsx
new file mode 100644
index 0000000..ec8ed50
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/PrintProblemsCard.jsx
@@ -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 (
+
+ {tc('printProblems.title')}
+ {tc('printProblems.count', { count: shown.length })}
+ }>
+ onOpen(p.order_id, p.table_name) : undefined} />
+ {t('orders.printHelp')}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/orders/TablesPage.jsx b/manager_dashboard/src/pages/orders/TablesPage.jsx
index 21129a2..b5af021 100644
--- a/manager_dashboard/src/pages/orders/TablesPage.jsx
+++ b/manager_dashboard/src/pages/orders/TablesPage.jsx
@@ -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() {
))}
-
c.pendingPrint)} onOpen={id => navigate(`/orders/${id}`)} />
+ navigate(`/orders/${id}`)} />
{quick && setQuick(null)} />}
diff --git a/manager_dashboard/src/pages/orders/usePrintProblems.js b/manager_dashboard/src/pages/orders/usePrintProblems.js
new file mode 100644
index 0000000..30b3ac5
--- /dev/null
+++ b/manager_dashboard/src/pages/orders/usePrintProblems.js
@@ -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,
+ })
+}
diff --git a/manager_dashboard/src/pages/overview/OverviewPage.jsx b/manager_dashboard/src/pages/overview/OverviewPage.jsx
index ec9fe0f..280ef45 100644
--- a/manager_dashboard/src/pages/overview/OverviewPage.jsx
+++ b/manager_dashboard/src/pages/overview/OverviewPage.jsx
@@ -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() {
+ {/* 6.10: tickets that didn't print come first: they need someone now */}
+
setOrder({ id, table: table ?? `#${id}` })} />
setShift({ shift: s, mode: 'close' })}
@@ -169,7 +172,6 @@ export default function OverviewPage() {
- setOrder({ id, table })} />
{notesOn &&
}
diff --git a/manager_dashboard/src/pages/overview/PendingPrints.jsx b/manager_dashboard/src/pages/overview/PendingPrints.jsx
deleted file mode 100644
index cad9285..0000000
--- a/manager_dashboard/src/pages/overview/PendingPrints.jsx
+++ /dev/null
@@ -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 (
-
- {t('overview.prints.title')}
- {t('overview.prints.count', { count: cards.length })}
- }
- action={ } loading={busy === 'all'} disabled={busy != null}
- onClick={() => run('all', async () => { for (const c of cards) await retry(c.order.id) })}>{t('overview.prints.all')}}>
-
- {cards.map(({ table, order }) => {
- const waiting = order.items.filter(i => i.status === 'active' && !i.printed)
- const retries = printRetries(order)
- return (
-
- {tableName(table)}
-
-
-
#{order.id}
- {order.opened_at &&
{formatTime(order.opened_at)} }
- {retries > 0 &&
{t('overview.prints.retries', { count: retries })} }
-
-
- {t('overview.prints.lines', { count: waiting.length })} · {waiting.map(i => i.product?.name || `#${i.product_id}`).join(', ')}
-
-
- onOpen(order.id, tableName(table))}>{t('overview.prints.open')}
- run(order.id, () => retry(order.id))}>{t('overview.prints.print')}
-
- )
- })}
-
-
- )
-}
diff --git a/manager_dashboard/src/pages/overview/overviewLogic.js b/manager_dashboard/src/pages/overview/overviewLogic.js
index 0f33774..dc91cc6 100644
--- a/manager_dashboard/src/pages/overview/overviewLogic.js
+++ b/manager_dashboard/src/pages/overview/overviewLogic.js
@@ -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).
diff --git a/manager_dashboard/src/pages/printing/PrepZonesPage.jsx b/manager_dashboard/src/pages/printing/PrepZonesPage.jsx
new file mode 100644
index 0000000..77423f6
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/PrepZonesPage.jsx
@@ -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 (
+
+
+
+
+ {isPending ?
+ : !zones?.length ?
} title={t('printing.zones.none')} description={t('printing.zones.noneHint')} />
+ : (
+
+ {zones.map(z => (
+
+
+
+
+ {t('printing.zones.main')}
+ {z.master_printer_id ? {nameOf(z.master_printer_id)}{z.auto_print !== 'none' && z.master_copies > 1 ? ` ×${z.master_copies}` : ''}
+ : {t('printing.zones.noPrinter')} }
+
+ {z.secondary_printer_ids?.length > 0 && (
+
+ {t('printing.zones.also')}
+ {z.secondary_printer_ids.map(id => {nameOf(id)} )}
+ {z.auto_print === 'all' && z.secondary_copies > 1 && ×{z.secondary_copies} }
+
+ )}
+
+
+ {t(`printing.zones.autoShort.${z.auto_print}`)}
+ {t(`printing.zones.sortShort.${z.sort_items_by}`)}
+ {z.group_by_category && {t('printing.zones.byCategory')} }
+ {z.print_checkboxes && {t('printing.zones.checkboxes')} }
+ {z.language && {z.language.toUpperCase()} }
+ {z.bypass_kds ? {t('printing.zones.skipKds')} : z.bypass_pending && {t('printing.zones.startReady')} }
+ {z.auto_ready_to_served && {t('printing.zones.readyServed')} }
+
+
+ ))}
+
+ )}
+
+
+ {editing &&
setEditing(null)} onSaved={() => { setEditing(null); qc.invalidateQueries({ queryKey: ['prep-zones'] }) }} />}
+ {deleting && (
+ setDeleting(null)} title={t('printing.zones.deleteTitle', { name: deleting.name })}
+ description={t('printing.zones.deleteBody')}
+ footer={<>
+ setDeleting(null)}>{t('printing.back')}
+ remove.mutate(deleting.id)} data-testid="zone-delete-confirm">{t('printing.zones.deleteYes')}
+ >} />
+ )}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/printing/PrintersCard.jsx b/manager_dashboard/src/pages/printing/PrintersCard.jsx
new file mode 100644
index 0000000..b0ad924
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/PrintersCard.jsx
@@ -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 (
+
+
+ } onClick={() => setEditing({ ...EMPTY_PRINTER })} data-testid="printer-new">{t('printing.printers.add')}
+ } onClick={() => setFinding(true)}>{t('printing.printers.find')}
+
+ {!isPending && printers.length === 0 && } title={t('printing.printers.none')} />}
+ {printers.map(p => {
+ const r = p.is_active ? reachable(p.id) : null
+ return (
+
+
toggle.mutate(p)} aria-label={t('printing.printers.on', { name: p.name })} />
+
+
{p.name}
+
+ {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 })}
+
+
+ {p.is_active && (r == null ? {t('printing.printers.checking')}
+ : r ? {t('printing.printers.answers')} : {t('printing.printers.noAnswer')} )}
+ test.mutate(p.id)}>{t('printing.printers.test')}
+ setEditing(p)}>
+ setRemoving(p)}>
+
+ )
+ })}
+ {editing && setEditing(null)} onSaved={() => { setEditing(null); changed() }} />}
+ {finding && setFinding(false)} onPick={found => { setFinding(false); setEditing({ ...EMPTY_PRINTER, ...found }) }} />}
+ {removing && (
+ setRemoving(null)} title={t('printing.printers.removeTitle', { name: removing.name })}
+ description={t('printing.printers.removeBody')}
+ footer={<>
+ setRemoving(null)}>{t('printing.back')}
+ remove.mutate(removing.id)}>{t('printing.printers.removeYes')}
+ >} />
+ )}
+
+ )
+}
+
+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 (
+
+ {t('printing.back')}
+ {t('printing.save')}
+ >}>
+
+
+ )
+}
+
+/** 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 (
+
{t('printing.close')}}>
+
+
+
+ setSubnet(e.target.value)} disabled={scan.running} />
+
+
+ setPort(e.target.value)} disabled={scan.running} />
+
+ {scan.running
+ ? stop.current?.abort()}>{t('printing.printers.stop')}
+ : {t('printing.printers.scan')} }
+
+ {scan.running && (
+
+
+
{t('printing.printers.scanned', { done: scan.done, total: scan.total })}
+
+ )}
+ {scan.error &&
{scan.error}
}
+
+ {scan.found.length === 0 && {scan.ran && !scan.running ? t('printing.printers.foundNone') : t('printing.printers.scanStart')} }
+ {scan.found.map(f => (
+
+ {f.ip_address}:{f.port}
+ onPick(f)}>{t('printing.printers.use')}
+
+ ))}
+
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/printing/PrintingSettings.jsx b/manager_dashboard/src/pages/printing/PrintingSettings.jsx
new file mode 100644
index 0000000..f027d72
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/PrintingSettings.jsx
@@ -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 (
+
+ )
+}
diff --git a/manager_dashboard/src/pages/printing/TicketSettings.jsx b/manager_dashboard/src/pages/printing/TicketSettings.jsx
new file mode 100644
index 0000000..e9b6768
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/TicketSettings.jsx
@@ -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
{children}
+}
+
+function Pick({ options, value, onChange, label }) {
+ return (
+
+ {options.map(o => (
+ 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}
+
+ ))}
+
+ )
+}
+
+function Check({ on, onChange, label }) {
+ return (
+
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}
+
+ )
+}
+
+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 (
+
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 (
+
+
+
+ s.save('print.ticket_mode', v)}
+ options={TICKET_MODES.map(m => ({ value: m, label: t(`printing.ticket.modes.${m}`) }))} />
+
+ {active.length > 0 && (
+
+
{t('printing.ticket.testHint')}
+
+
} 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')}
+
+ )}
+
+
+
+
+
+ {FONT_GROUPS.map(g => (
+
+
{t(`printing.ticket.groups.${g.key}`)}
+ {g.fields.map(key =>
s.save(key, v)} />)}
+ {g.key === 'items' && s.save('print.dot_style', v)} />}
+
+ ))}
+
+
+ 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}`) }))} />
+
+
+
+
{DIVIDER_CHARS[val('print.divider_style')] ? DIVIDER_CHARS[val('print.divider_style')].repeat(32) : {t('printing.ticket.emptyLine')} }
+
+
+
+ )
+}
+
+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 (
+
+
+ {t(`printing.ticket.parts.${name}`)}
+ {t(`printing.ticket.partsHint.${name}`)}
+
+
set({ size: e.target.value })} className="w-40"
+ options={FONT_SIZES.map(z => ({ value: z, label: t(`printing.ticket.sizes.${z}`) }))} />
+ set({ bold: v })} label={t('printing.ticket.bold')} />
+ set({ caps: v })} label={t('printing.ticket.caps')} />
+ {f.caps ? 'SAMPLE' : 'Sample'}
+ {isWide(f.size) && {t('printing.ticket.wideNote')} }
+
+ )
+}
+
+function DotsRow({ value, onSave }) {
+ const { t } = useTranslation('manager')
+ const d = decodeDots(value)
+ const set = patch => onSave(encodeDots({ ...d, ...patch }))
+ return (
+
+
+ {t('printing.ticket.dots')}
+ {t('printing.ticket.dotsHint')}
+
+
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}`) }))} />
+ 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}`) }))} />
+ set({ bold: v })} label={t('printing.ticket.bold')} />
+ {t('printing.ticket.dotsSample', { dots: DOT_PREVIEW[d.style] })}
+
+ )
+}
+
+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 (
+
+
+
({ value: b, label: t(`printing.beep.presets.${b}`) }))} />
+
+ {saved.preset === 'custom' && (
+
+ {['n1', 'n2', 'n3'].map(k => (
+
+ {t(`printing.beep.${k}`)}
+ setPart(k, e.target.value)} onBlur={savePart} />
+ {t(`printing.beep.${k}Hint`)}
+
+ ))}
+
+ )}
+ {printers.length > 0 && saved.preset !== 'off' && (
+
+
{t('printing.beep.testHint')}
+
+
} 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')}
+
+ )}
+
+ )
+}
diff --git a/manager_dashboard/src/pages/printing/ZoneDialog.jsx b/manager_dashboard/src/pages/printing/ZoneDialog.jsx
new file mode 100644
index 0000000..b1562d1
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/ZoneDialog.jsx
@@ -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 (
+
+ )
+}
+
+function Choice({ options, value, onChange, label, testId }) {
+ return (
+
+ {options.map(o => (
+ 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')}>
+ {o.label}
+ {o.hint}
+
+ ))}
+
+ )
+}
+
+function Toggle({ label, tip, checked, onChange, testId }) {
+ return (
+
+
+ {label}{tip && {tip} }
+
+ )
+}
+
+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 (
+
+ {t('printing.back')}
+ {t('printing.save')}
+ >}>
+
+
+
+
+ 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 ? {t('printing.zones.noPrinters')}
: (
+
+
+ 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 }))]} />
+
+
+
{t('printing.zones.secondPrinters')}{t('printing.zones.secondTip')}
+
+ {printers.filter(p => p.id !== form.master_printer_id).map(p => {
+ const on = form.printer_ids.includes(p.id)
+ return (
+ 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}
+
+ )
+ })}
+
+
+
+ )}
+ {form.auto_print !== 'none' && (
+
+ {t('printing.zones.mainCopies')}
+ set('master_copies', v)} label={t('printing.zones.mainCopies')} />
+
+ {form.auto_print === 'all' && (
+ {t('printing.zones.secondCopies')}
+ set('secondary_copies', v)} label={t('printing.zones.secondCopies')} />
+
+ )}
+
+ )}
+
+
+
+ set('sort_items_by', v)}
+ options={SORT_BY.map(v => ({ value: v, label: t(`printing.zones.sortShort.${v}`), hint: t(`printing.zones.sortHint.${v}`) }))} />
+ set('group_by_category', v)} />
+ {form.group_by_category && (
+
+ setOrdering(true)}>
+ {t('printing.zones.categoryOrder')}{form.category_order.length ? ` (${form.category_order.length})` : ''}
+
+
+ )}
+ set('print_checkboxes', v)} />
+
+
+
+ setForm(f => setBypass(f, 'bypass_pending', v))} />
+ setForm(f => setBypass(f, 'bypass_kds', v))} />
+ set('auto_ready_to_served', v)} />
+
+
+
+ {ordering && setOrdering(false)}
+ onSave={ids => { set('category_order', ids); setOrdering(false) }} />}
+
+ )
+}
+
+function CategoryOrder({ categories, order, onClose, onSave }) {
+ const { t } = useTranslation('manager')
+ const [list, setList] = useState(() => orderedCategories(categories, order))
+ return (
+
+ onSave([])}>{t('printing.zones.categoryOrderReset')}
+ {t('printing.back')}
+ onSave(list.map(c => c.id))}>{t('printing.save')}
+ >}>
+
+ {list.map((c, i) => (
+
+ {i + 1}
+ {c.name}
+ setList(l => move(l, i, -1))}>
+ setList(l => move(l, i, 1))}>
+
+ ))}
+
+
+ )
+}
diff --git a/manager_dashboard/src/pages/printing/printingLogic.js b/manager_dashboard/src/pages/printing/printingLogic.js
new file mode 100644
index 0000000..63bb4c8
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/printingLogic.js
@@ -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
+}
diff --git a/manager_dashboard/src/pages/printing/usePrinters.js b/manager_dashboard/src/pages/printing/usePrinters.js
new file mode 100644
index 0000000..aa8ce7f
--- /dev/null
+++ b/manager_dashboard/src/pages/printing/usePrinters.js
@@ -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 })
+}
diff --git a/manager_dashboard/tests/overview.test.mjs b/manager_dashboard/tests/overview.test.mjs
index 8d52b8c..846417f 100644
--- a/manager_dashboard/tests/overview.test.mjs
+++ b/manager_dashboard/tests/overview.test.mjs
@@ -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', () => {
diff --git a/manager_dashboard/tests/printing.test.mjs b/manager_dashboard/tests/printing.test.mjs
new file mode 100644
index 0000000..e42dda4
--- /dev/null
+++ b/manager_dashboard/tests/printing.test.mjs
@@ -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])
+})
diff --git a/manager_dashboard/v2.json b/manager_dashboard/v2.json
index 936b930..8b6600b 100644
--- a/manager_dashboard/v2.json
+++ b/manager_dashboard/v2.json
@@ -1,9 +1,9 @@
{
"_comment": "Plan step 6.1: what is on the v2 rules. `paths` (files or folders): `npm run lint` checks them, and tests/v2-guards.test.mjs refuses Greek and colour literals in them. `strict`: also no setState in effects (data loads with useLiveQuery / react-query). Each phase 6 step adds what it converted; 6.14 ends with `src`.",
"paths": [
- "src/shell", "src/live", "src/pages/platform", "src/pages/online", "src/pages/media", "src/pages/signage", "src/pages/staff", "src/pages/Settings/sections", "src/pages/LoginPage.jsx", "src/components/NotificationBell.jsx", "src/components/PhoneListener.jsx", "src/pages/PhonePage.jsx", "src/store/phoneStore.js", "src/components/UserMenuButton.jsx", "src/pages/reports/operations/LogsPanel.jsx", "src/api/client.js", "src/store/authStore.js", "src/main.jsx", "src/pages/overview", "src/hooks", "src/pages/products", "src/pages/pricing", "src/pages/floor", "src/pages/Management/TablesConfigPage.jsx", "src/pages/orders"
+ "src/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"
]
}
diff --git a/package-lock.json b/package-lock.json
index 3552d48..f7cb751 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -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",
diff --git a/packages/i18n/locales/el/common.json b/packages/i18n/locales/el/common.json
index 2d80dba..dbbc53c 100644
--- a/packages/i18n/locales/el/common.json
+++ b/packages/i18n/locales/el/common.json
@@ -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": "Σημειώθηκε ότι το χειριστήκατε"
+ }
}
}
diff --git a/packages/i18n/locales/el/errors.json b/packages/i18n/locales/el/errors.json
index 6596376..4edb254 100644
--- a/packages/i18n/locales/el/errors.json
+++ b/packages/i18n/locales/el/errors.json
@@ -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}}). Το δελτίο περιμένει ακόμα."
}
}
diff --git a/packages/i18n/locales/el/manager.json b/packages/i18n/locales/el/manager.json
index cdaad87..3997529 100644
--- a/packages/i18n/locales/el/manager.json
+++ b/packages/i18n/locales/el/manager.json
@@ -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": "Δοκιμή ήχου"
}
}
}
diff --git a/packages/i18n/locales/en/common.json b/packages/i18n/locales/en/common.json
index 254bf54..8703863 100644
--- a/packages/i18n/locales/en/common.json
+++ b/packages/i18n/locales/en/common.json
@@ -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"
+ }
}
}
diff --git a/packages/i18n/locales/en/errors.json b/packages/i18n/locales/en/errors.json
index 50058e3..f71f606 100644
--- a/packages/i18n/locales/en/errors.json
+++ b/packages/i18n/locales/en/errors.json
@@ -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."
}
}
diff --git a/packages/i18n/locales/en/manager.json b/packages/i18n/locales/en/manager.json
index 84263ab..5e0f4fe 100644
--- a/packages/i18n/locales/en/manager.json
+++ b/packages/i18n/locales/en/manager.json
@@ -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"
}
}
}
diff --git a/packages/ordering/package.json b/packages/ordering/package.json
index f440c34..abd23e0 100644
--- a/packages/ordering/package.json
+++ b/packages/ordering/package.json
@@ -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\""
diff --git a/packages/ordering/src/PrintProblemsPanel.jsx b/packages/ordering/src/PrintProblemsPanel.jsx
new file mode 100644
index 0000000..32b282d
--- /dev/null
+++ b/packages/ordering/src/PrintProblemsPanel.jsx
@@ -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 (
+
+ {problems.map(p => (
+
+ ))}
+
+ )
+}
+
+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 (
+
+
+ {showPlace && (
+
onOpen?.(p)}>
+ {placeOf(p)}
+
+ )}
+
+ {t('printProblems.notOn', { printer: p.printer.name })}
+
+
+ {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(', ') })}`}
+
+
+ {itemsText(p)}
+ {p.error && {p.error}
}
+
+ } loading={busy === 'retry'} disabled={!!busy} onClick={() => act('retry')} data-testid="problem-retry">
+ {t('printProblems.retry')}
+
+ {others.length > 0 && (
+
+ setTo(e.target.value)} aria-label={t('printProblems.sendTo')} data-testid="problem-printer"
+ options={others.map(o => ({ value: String(o.id), label: o.name }))} />
+ } loading={busy === 'redirect'} disabled={!!busy || !to} onClick={() => act('redirect', Number(to))} data-testid="problem-redirect">
+ {t('printProblems.send')}
+
+
+ )}
+ } loading={busy === 'handled'} disabled={!!busy} onClick={() => act('handled')} data-testid="problem-handled"
+ title={t('printProblems.handledHint')}>
+ {t('printProblems.handled')}
+
+
+ {error && {error}
}
+
+ )
+}
diff --git a/packages/ordering/src/index.js b/packages/ordering/src/index.js
index 55f28ce..2eeb39d 100644
--- a/packages/ordering/src/index.js
+++ b/packages/ordering/src/index.js
@@ -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'
diff --git a/packages/ordering/src/printProblems.js b/packages/ordering/src/printProblems.js
new file mode 100644
index 0000000..b66e152
--- /dev/null
+++ b/packages/ordering/src/printProblems.js
@@ -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}`, {}]
+}
diff --git a/packages/ordering/tests/printProblems.test.mjs b/packages/ordering/tests/printProblems.test.mjs
new file mode 100644
index 0000000..a8618bb
--- /dev/null
+++ b/packages/ordering/tests/printProblems.test.mjs
@@ -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', {}])
+})
diff --git a/terminal/src/apps/pos/PosScreen.jsx b/terminal/src/apps/pos/PosScreen.jsx
index e78b5a9..bfa26ae 100644
--- a/terminal/src/apps/pos/PosScreen.jsx
+++ b/terminal/src/apps/pos/PosScreen.jsx
@@ -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 }) {
)}
setMode('receipts')} icon={Receipt} testId="mode-receipts">{t('pos.mode.receipts')}
+
{ setMode('tables'); setTableId(id); setTableCart([]) }} />
{mode === 'receipts' ? (
diff --git a/terminal/src/apps/pos/PrintProblems.jsx b/terminal/src/apps/pos/PrintProblems.jsx
new file mode 100644
index 0000000..6daca66
--- /dev/null
+++ b/terminal/src/apps/pos/PrintProblems.jsx
@@ -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 (
+ <>
+
+ } onClick={() => setOpen(true)} data-testid="pos-print-problems">
+ {t('printProblems.count', { count: problems.length })}
+
+
+ {open && (
+
setOpen(false)} title={t('printProblems.title')}
+ footer={ setOpen(false)}>{t('printProblems.close')} }>
+
+
{ if (p.table_id != null) { setOpen(false); onOpenTable(p.table_id) } }} />
+
+
+ )}
+ >
+ )
+}
diff --git a/terminal/src/apps/pos/usePos.js b/terminal/src/apps/pos/usePos.js
index c0eddf6..0505220 100644
--- a/terminal/src/apps/pos/usePos.js
+++ b/terminal/src/apps/pos/usePos.js
@@ -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)
diff --git a/tests/e2e/manager.mjs b/tests/e2e/manager.mjs
index 50b4176..6b0a45b 100644
--- a/tests/e2e/manager.mjs
+++ b/tests/e2e/manager.mjs
@@ -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(() => {})
diff --git a/tests/e2e/print_problems.mjs b/tests/e2e/print_problems.mjs
new file mode 100644
index 0000000..54fc39a
--- /dev/null
+++ b/tests/e2e/print_problems.mjs
@@ -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)
diff --git a/tests/e2e/run-all.mjs b/tests/e2e/run-all.mjs
index 47b7f7c..ff42c24 100644
--- a/tests/e2e/run-all.mjs
+++ b/tests/e2e/run-all.mjs
@@ -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],
diff --git a/waiter_pwa/package.json b/waiter_pwa/package.json
index cc76b2b..32b4628 100644
--- a/waiter_pwa/package.json
+++ b/waiter_pwa/package.json
@@ -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",
diff --git a/waiter_pwa/src/components/AppShell.jsx b/waiter_pwa/src/components/AppShell.jsx
index 89b7bb0..689c74d 100644
--- a/waiter_pwa/src/components/AppShell.jsx
+++ b/waiter_pwa/src/components/AppShell.jsx
@@ -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 (
- {/* Failed print badge — navigates to order log */}
-
navigate('/order-log?filter=failed')} />
+ {/* Tickets that didn't print (6.10): opens them with what can be done */}
+ setShowPrints(true)} />
{/* Bell */}
@@ -700,6 +703,9 @@ export default function AppShell({ children, title, rightActions }) {
+ {showPrints && setShowPrints(false)} />}
+
{/* ── Side drawer ───────────────────────────────────────── */}
setDrawerOpen(false)} />
diff --git a/waiter_pwa/src/components/PrintProblemsSheet.jsx b/waiter_pwa/src/components/PrintProblemsSheet.jsx
new file mode 100644
index 0000000..97c7a62
--- /dev/null
+++ b/waiter_pwa/src/components/PrintProblemsSheet.jsx
@@ -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 (
+
+
e.stopPropagation()} data-testid="print-problems-sheet">
+
+
{t('printProblems.title')}
+ {problems.length === 0 &&
{t('printProblems.none')}
}
+ {problems.map(p =>
)}
+
{t('printProblems.close')}
+
+
+ )
+}
+
+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 (
+
+
+ {showPlace && (
+ { 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)}
+
+ )}
+ 🖨 {t('printProblems.notOn', { printer: p.printer.name })}
+
+
+ {t('printProblems.since', { time: formatTime(p.since) })} · {t('printProblems.tries', { count: p.attempts })}
+
+
{itemsText(p)}
+
act('retry')} data-testid="problem-retry">
+ {busy === 'retry' ? '…' : t('printProblems.retry')}
+
+ {others.length > 0 && (
+
+ 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 => {o.name} )}
+
+ act('redirect', Number(to))} data-testid="problem-redirect">
+ {busy === 'redirect' ? '…' : t('printProblems.send')}
+
+
+ )}
+
act('handled')} data-testid="problem-handled">
+ {busy === 'handled' ? '…' : t('printProblems.handled')}
+
+
{t('printProblems.handledHint')}
+ {note &&
{note.text}
}
+
+ )
+}
diff --git a/waiter_pwa/src/components/TablePrintWarning.jsx b/waiter_pwa/src/components/TablePrintWarning.jsx
new file mode 100644
index 0000000..c84f9f0
--- /dev/null
+++ b/waiter_pwa/src/components/TablePrintWarning.jsx
@@ -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 (
+ <>
+ 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 => (
+
+ 🖨 {t('printProblems.notOn', { printer: p.printer.name })} · {t('printProblems.since', { time: formatTime(p.since) })}
+ {itemsText(p)}
+
+ ))}
+ {t('printProblems.whatNow')} ›
+
+ {open && setOpen(false)} />}
+ >
+ )
+}
diff --git a/waiter_pwa/src/hooks/useFailedPrintCount.js b/waiter_pwa/src/hooks/useFailedPrintCount.js
deleted file mode 100644
index 3665edd..0000000
--- a/waiter_pwa/src/hooks/useFailedPrintCount.js
+++ /dev/null
@@ -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
-}
diff --git a/waiter_pwa/src/hooks/usePrintProblems.js b/waiter_pwa/src/hooks/usePrintProblems.js
new file mode 100644
index 0000000..a40059e
--- /dev/null
+++ b/waiter_pwa/src/hooks/usePrintProblems.js
@@ -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 }
+}
diff --git a/waiter_pwa/src/pages/TableDetailPage.jsx b/waiter_pwa/src/pages/TableDetailPage.jsx
index de3f1da..c828faf 100644
--- a/waiter_pwa/src/pages/TableDetailPage.jsx
+++ b/waiter_pwa/src/pages/TableDetailPage.jsx
@@ -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() {
)}
+ {/* tickets of this order that didn't print (6.10) */}
+
+
{/* orders from the table's menu tablet waiting for a waiter (6.6) */}
{!isStandalone && }