"""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}