Files
receipt_maker/receipt_tui.py
T
adamfandClaude Opus 5.5 597bace442
CI / test (3.10) (push) Failing after 56s
CI / test (3.12) (push) Failing after 42s
CI / test (3.13) (push) Failing after 47s
Send each print as one job, queue web prints, and harden deploys
Render every print to a complete ESC/POS payload (reset, content, cut)
and send it once over a fresh connection. Only the connect is retried,
so a link that drops mid-job can no longer print a partial image followed
by a full one, and no text size leaks into the next job. Prints are
capped at about 1 m of paper: tall images shrink, over-long notes are
refused.

Replace the argparse/stdout plumbing with PrinterConfig, InvalidJob and
PrinterUnavailable, and one run_command() dispatcher shared by the CLI
and TUI. Status now really connects; before, escpos's lazy open meant
the web server always reported the printer ready. Rendering with the
TM-T20II profile makes QR centering take effect.

The web server validates and renders jobs in the request (400 on bad
input), queues them for a single worker and answers 202; the page
long-polls /api/jobs/{id}, so no request outlives nginx's proxy timeout
while its job still prints. Status reports busy instead of waiting, and
jobs are logged with the nginx user.

update.sh tests new commits in a scratch worktree before touching the
live clone, and rolls back if /healthz doesn't answer after the restart.
The unit runs from the venv, and the web server defaults to localhost.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 22:07:58 +01:00

224 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""Textual TUI for the receipt printer; launched via `./receipt.py tui`."""
from __future__ import annotations
import argparse
from pathlib import Path
from rich.text import Text
from textual import work
from textual.app import App, ComposeResult
from textual.containers import Horizontal, Vertical
from textual.widgets import (
Button,
ContentSwitcher,
Footer,
Header,
Input,
Label,
ListItem,
ListView,
RichLog,
Switch,
TextArea,
)
import receipt
ACTIONS = [
("note", "Note"),
("image", "Random image"),
("print", "Print file"),
("qr", "QR code"),
("reprint", "Reprint cached"),
("status", "Printer status"),
("cache", "Image cache"),
]
class ReceiptApp(App):
TITLE = "Receipt Maker"
BINDINGS = [("q", "quit", "Quit")]
CSS = """
#nav {
width: 22;
border-right: solid $primary;
}
#panes {
padding: 1 2;
}
#panes Label {
margin-top: 1;
}
#panes Button {
margin-top: 1;
}
#note-text {
height: 8;
}
#reprint-list {
height: 10;
border: solid $primary;
}
.row {
height: auto;
margin-top: 1;
}
.row Label {
margin: 1 0 0 2;
}
#log {
dock: bottom;
height: 30%;
border-top: solid $primary;
}
"""
def __init__(self, base_args: argparse.Namespace):
super().__init__()
self.base_args = base_args
self.last_failure = 0 # exit code of the most recent failed action
def compose(self) -> ComposeResult:
yield Header()
with Horizontal():
yield ListView(
*(ListItem(Label(label), name=key) for key, label in ACTIONS),
id="nav",
)
with ContentSwitcher(initial="pane-note", id="panes"):
with Vertical(id="pane-note"):
yield Label("Note text")
yield TextArea(id="note-text")
with Horizontal(classes="row"):
yield Switch(id="note-timestamp")
yield Label("Date/time header")
yield Button("Print note", id="do-note", variant="primary")
with Vertical(id="pane-image"):
yield Label("How many random /bant/ images")
yield Input(value="1", id="image-count", type="integer")
yield Button("Print", id="do-image", variant="primary")
with Vertical(id="pane-print"):
yield Label("Path to image file")
yield Input(id="print-path", placeholder="/path/to/image.jpg")
yield Label("Caption (optional)")
yield Input(id="print-caption")
yield Button("Print", id="do-print", variant="primary")
with Vertical(id="pane-qr"):
yield Label("Text or URL to encode")
yield Input(id="qr-content", placeholder="https://example.com")
yield Label("Caption (optional)")
yield Input(id="qr-caption")
yield Button("Print QR", id="do-qr", variant="primary")
with Vertical(id="pane-reprint"):
yield Label("Cached images (newest first)")
yield ListView(id="reprint-list")
yield Button("Reprint selected", id="do-reprint", variant="primary")
with Vertical(id="pane-status"):
yield Label("Check whether the printer is reachable")
yield Button("Check status", id="do-status", variant="primary")
with Vertical(id="pane-cache"):
yield Label("Downloaded image cache")
yield Button("List cache", id="do-list", variant="primary")
yield Button("Clean cache", id="do-clean", variant="error")
yield RichLog(id="log", wrap=True, markup=True)
yield Footer()
def on_mount(self) -> None:
target = receipt.PrinterConfig.from_args(self.base_args).target
self.log_panel.write(f"[dim]Printer target: {target}[/dim]")
self.refresh_cache_list()
@property
def log_panel(self) -> RichLog:
return self.query_one("#log", RichLog)
def refresh_cache_list(self) -> None:
lv = self.query_one("#reprint-list", ListView)
lv.clear()
lv.extend(ListItem(Label(f.name), name=f.name) for f in receipt.cached_images())
def on_list_view_highlighted(self, event: ListView.Highlighted) -> None:
if event.list_view.id != "nav" or event.item is None:
return
key = event.item.name
self.query_one("#panes", ContentSwitcher).current = f"pane-{key}"
if key == "reprint":
self.refresh_cache_list()
def on_button_pressed(self, event: Button.Pressed) -> None:
button_id = event.button.id
if button_id == "do-note":
text = self.query_one("#note-text", TextArea).text.strip()
if not text:
self.log_panel.write("[red]Nothing to print.[/red]")
return
timestamp = self.query_one("#note-timestamp", Switch).value
self.run_action_worker("note", text=text, timestamp=timestamp)
elif button_id == "do-image":
raw = self.query_one("#image-count", Input).value or "1"
try:
count = receipt.positive_int(raw)
except (ValueError, argparse.ArgumentTypeError):
self.log_panel.write("[red]Count must be a positive integer.[/red]")
return
self.run_action_worker("image", count=count)
elif button_id == "do-print":
path = self.query_one("#print-path", Input).value.strip()
if not path:
self.log_panel.write("[red]Enter a file path.[/red]")
return
caption = self.query_one("#print-caption", Input).value.strip() or None
self.run_action_worker(
"print", path=Path(path).expanduser(), message=caption
)
elif button_id == "do-qr":
content = self.query_one("#qr-content", Input).value.strip()
if not content:
self.log_panel.write("[red]Enter something to encode.[/red]")
return
caption = self.query_one("#qr-caption", Input).value.strip() or None
self.run_action_worker("qr", content=content, message=caption)
elif button_id == "do-reprint":
selected = self.query_one("#reprint-list", ListView).highlighted_child
self.run_action_worker("reprint", name=selected.name if selected else None)
elif button_id == "do-status":
self.run_action_worker("status")
elif button_id == "do-list":
self.run_action_worker("list")
elif button_id == "do-clean":
self.run_action_worker("clean")
def set_buttons_disabled(self, disabled: bool) -> None:
for button in self.query(Button):
button.disabled = disabled
@work(thread=True, exclusive=True)
def run_action_worker(self, command: str, **params) -> None:
self.call_from_thread(self.set_buttons_disabled, True)
self.call_from_thread(self.log_panel.write, f"[bold]$ {command}[/bold]")
try:
result = receipt.run_action(command, self.base_args, **params)
finally:
self.call_from_thread(self.set_buttons_disabled, False)
self.call_from_thread(self.report, command, result.rc, result.output)
def report(self, command: str, rc: int, output: str) -> None:
if output:
# Captured output is arbitrary text; Text() stops stray [..] parsing as markup.
self.log_panel.write(Text(output))
if rc == 0:
self.log_panel.write("[green]done[/green]")
else:
self.log_panel.write(f"[red]failed (exit {rc})[/red]")
self.last_failure = rc # only the most recent action decides the exit code
if command in ("image", "clean"):
self.refresh_cache_list()
def run_tui(args: argparse.Namespace) -> int:
app = ReceiptApp(args)
app.run()
return app.last_failure