feat: printing problems shown and handled; printing set-up on v2 (platform-v2 step 6.10)
- a ticket that doesn't print is a problem for whoever sent it and the managers: GET /api/print-problems (the order, table, dishes, printer, since when, tries, last error, who sent it) and three ways out: print again, send to another printer, handled (services/print_problems.py; print_jobs.resolved_by / redirected_to, Alembic 0036); live event print.problems from the print paths - phone: the red printer button opens the problems sheet, the table page warns (usePrintProblems replaces the 8 s poll); counter POS: a red button under the modes with the shared panel (@xenia/ordering PrintProblemsPanel + pure rules); manager: a card on the overview (top), the Tables page and the order page - manager: Settings -> Printing (printers with reachability, test print, network scan; ticket layout + test ticket, beep, fonts with previews, dot leader, dividers) and Management -> Prep zones (cards + zone dialog with the ticket language, printers, copies, sorting, category order, kitchen screen) rebuilt in src/pages/printing; v1 PrintFontsTab, PrepZonesConfigPage, PendingPrints and /api/orders/pending-prints removed - access: printer add/edit/delete/scan need core.settings.manage, prep zone changes catalog.menu.manage (were any dashboard user) - tests: test_print_problems.py, @xenia/ordering printProblems, manager printing.test.mjs, e2e print_problems.mjs (done-when) + manager.mjs printing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -224,6 +224,9 @@ CODES: dict[str, tuple[int, str]] = {
|
||||
"printer.not_found": (404, "That printer isn't there or is turned off."),
|
||||
"print_job.not_found": (404, "That print job isn't there any more."),
|
||||
"print_job.not_pending": (400, "Only tickets still waiting to print can be cancelled."),
|
||||
"print_job.done": (409, "That ticket isn't waiting any more: it was printed or dealt with on another screen."),
|
||||
"print.printer_off": (409, "The printer {printer} is turned off in the settings."),
|
||||
"print.redirect_failed": (502, "{printer} didn't print it either ({error}). The ticket is still waiting."),
|
||||
"table.not_found": (404, "Table not found."),
|
||||
"floor_plan.not_found": (404, "Floor plan not found."),
|
||||
"floor_plan.bad_outline": (422, "The floor's shape needs 3 to 100 corners, all inside the plan."),
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""A print job's way out besides printing (plan step 6.10): who resolved it and, when the
|
||||
ticket was sent to another printer, which one. `status` gains no new value: a ticket sent
|
||||
elsewhere ends as 'success' (redirected_to set), one marked as handled as 'cancelled' with
|
||||
cancel_reason 'handled'.
|
||||
|
||||
Revision ID: 0036_print_job_resolution
|
||||
Revises: 0035_floor_plans
|
||||
Create Date: 2026-11-19 09:00:00
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = '0036_print_job_resolution'
|
||||
down_revision = '0035_floor_plans'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
|
||||
batch_op.add_column(sa.Column('resolved_by', sa.Integer(), nullable=True))
|
||||
batch_op.add_column(sa.Column('redirected_to', sa.Integer(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table('print_jobs', schema=None) as batch_op:
|
||||
batch_op.drop_column('redirected_to')
|
||||
batch_op.drop_column('resolved_by')
|
||||
@@ -181,7 +181,9 @@ class PrintJob(Base):
|
||||
last_attempted_at = Column(UTCDateTime, nullable=True)
|
||||
succeeded_at = Column(UTCDateTime, nullable=True)
|
||||
cancelled_at = Column(UTCDateTime, nullable=True)
|
||||
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed"
|
||||
cancel_reason = Column(String, nullable=True) # "staff_cancelled" | "order_closed" | "handled" (6.10)
|
||||
resolved_by = Column(Integer, nullable=True) # 6.10: who sent it elsewhere / marked it handled
|
||||
redirected_to = Column(Integer, nullable=True) # 6.10: the printer it was sent to instead (status success)
|
||||
|
||||
order = relationship("Order", back_populates="print_jobs")
|
||||
printer = relationship("Printer", back_populates="print_jobs")
|
||||
|
||||
@@ -51,5 +51,6 @@ MODULE = Module(
|
||||
Mount('routers.business_day', '/api/business-day'),
|
||||
Mount('routers.shifts', '/api/shifts'),
|
||||
Mount('routers.flags', '/api/flags'),
|
||||
Mount('routers.print_problems', '/api/print-problems'), # 6.10
|
||||
),
|
||||
)
|
||||
|
||||
@@ -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}
|
||||
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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)
|
||||
@@ -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()}
|
||||
|
||||
|
||||
@@ -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}
|
||||
@@ -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()
|
||||
|
||||
@@ -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"] == []
|
||||
Reference in New Issue
Block a user