Files
uberbringer/internal/pkg/receipt/job.go
T
57_WolveandClaude Opus 5.5 bdd337e2dc
Security / Vulnerability check (push) Successful in 38s
Test / Lint and test (push) Successful in 1m53s
Generate the OpenAPI document from a route table
The server registers its routes from one table in server/routes.go, and
tools/genopenapi (run by go generate) writes docs/swagger.json, an
OpenAPI 3.1 document, from the same table and the Go types it names.
Schemas are reflected with invopop/jsonschema: descriptions from the
first paragraph of the doc comments, enums and limits from jsonschema
tags. Request schemas are strict, as the decoder is; response schemas
allow fields added later. The daemon serves the embedded document at
GET /openapi.json without a token, internal/app passes it to the server
in its config, and release archives and the Docker build include it.

Tests keep it honest: a golden test and a CI step fail when the
document is stale, every registered route must be in the table, and the
tags are held to validation, to the Go constants and to the values the
handlers send. receipt.Element and printqueue.Status gain field doc
comments for the descriptions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 09:30:42 -06:00

552 lines
18 KiB
Go

// Package receipt defines print jobs, validates them, and lays them out as
// ESC/POS command streams with code page transcoding and word wrapping.
package receipt
import (
"bytes"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"net/url"
"strings"
"uberbringer/internal/pkg/escpos"
)
// ErrTrailingData is returned by DecodeJob for input with more after the
// job.
var ErrTrailingData = errors.New("trailing data after the job")
// Element types. Box, rule and kv are blocks: they are laid out to the
// paper width when the job is rendered.
const (
TypeText = "text"
TypeFeed = "feed"
TypeQR = "qr"
TypeBarcode = "barcode"
TypeImage = "image"
TypeRaw = "raw"
TypeCut = "cut"
TypeBox = "box"
TypeRule = "rule"
TypeKV = "kv"
)
// Job limits. MaxElements counts the children of boxes too.
const (
MaxElements = 500
MaxCopies = 5
MaxPairs = 100
)
// Element defaults.
const (
defaultQRSize = 6
defaultBarcodeHeight = 80
defaultBarcodeWidth = 3
)
// Job is a receipt to print.
//
// The jsonschema tags on Job, Element and Pair give the JSON Schema of a
// job; Validate enforces the rules.
type Job struct {
// Elements are the items on the receipt, in order: 1-500, box children
// counted.
Elements []Element `json:"elements" jsonschema:"required,minItems=1,maxItems=500"`
// Copies is how many times the receipt is printed, each with its own
// cut. Zero means one.
Copies int `json:"copies,omitempty" jsonschema:"minimum=0,maximum=5"`
}
// Element is one item on a receipt. Its type selects which fields apply. On
// the blocks (box, rule and kv) and inside a box, a field that does not
// apply is an error; on the other types it is ignored, except for the block
// fields. width and height mean character multipliers for text, module width
// and bar height for barcodes, and target width in dots for images. A
// block's width is set by columns, in characters of its own size and font,
// never by width; without columns a block spans the line. The enums list
// the canonical spellings: apart from type and leader, other letter case is
// accepted too, and so are a few aliases such as centre and ean-13.
type Element struct {
// Type is the kind of element. box, rule and kv are blocks, laid out to
// the printer model's width when the job prints.
Type string `json:"type" jsonschema:"required,enum=text,enum=feed,enum=qr,enum=barcode,enum=image,enum=raw,enum=cut,enum=box,enum=rule,enum=kv"`
// Text is a text element's UTF-8 text, a box's body or a rule's label.
// \n starts a new line.
Text string `json:"text,omitempty"`
// Bold prints the text in bold: a box's text, a rule's label.
Bold bool `json:"bold,omitempty"`
// Size sets width and height together: 1-8 for text, 1-3 for a block,
// whose borders scale with its text. For a QR code it is the module size
// in dots, 1-16, default 6. 0 means the default.
Size int `json:"size,omitempty" jsonschema:"minimum=0,maximum=16"`
// Width is the character width for text (1-8), the module width of a
// barcode (2-6, default 3), or the target width of an image in dots. 0
// means the default.
Width int `json:"width,omitempty" jsonschema:"minimum=0"`
// Height is the character height for text (1-8), or the bar height of a
// barcode in dots (1-255, default 80). 0 means the default.
Height int `json:"height,omitempty" jsonschema:"minimum=0,maximum=255"`
// Font is a, the default, or b, the smaller font; on a block it sets
// the font of its borders and text.
Font string `json:"font,omitempty" jsonschema:"enum=a,enum=b"`
// Align places text, a QR code, a barcode or an image, a box's text, or
// a rule's label. Default left, center for a rule's label.
Align string `json:"align,omitempty" jsonschema:"enum=left,enum=center,enum=right"`
// Underline is 0, 1 for thin or 2 for thick.
Underline int `json:"underline,omitempty" jsonschema:"minimum=0,maximum=2"`
// Invert prints white on black.
Invert bool `json:"invert,omitempty"`
// Newline false keeps the next element on the same line. Default true.
Newline *bool `json:"newline,omitempty"`
// Wrap false sends the text as it is and lets the printer wrap it,
// or inside a box splits lines at the box edge. Default true: wrap at
// spaces.
Wrap *bool `json:"wrap,omitempty"`
// Lines is a feed's number of lines, 1-255. 0 means the default, 1.
Lines int `json:"lines,omitempty" jsonschema:"minimum=0,maximum=255"`
// Data is a QR code's data, up to 7089 bytes of UTF-8, or a barcode's:
// digits for EAN and UPC, A-Z 0-9 -.$/+% and space for CODE39, printable
// ASCII for CODE128.
Data string `json:"data,omitempty"`
// Correction is a QR code's error correction level. Default M.
Correction string `json:"correction,omitempty" jsonschema:"enum=L,enum=M,enum=Q,enum=H"`
// Symbology is a barcode's type; required for a barcode.
Symbology string `json:"symbology,omitempty" jsonschema:"enum=ean13,enum=ean8,enum=upca,enum=upce,enum=code39,enum=code128"`
// HRI places a barcode's human-readable text. Default below.
HRI string `json:"hri,omitempty" jsonschema:"enum=none,enum=above,enum=below,enum=both"`
// URL is an image's http or https URL. Set url or base64.
URL string `json:"url,omitempty"`
// Base64 is an image's data in base64, or a data:image/...;base64, URI:
// PNG, JPEG, GIF or WebP.
Base64 string `json:"base64,omitempty"`
// Hex is a raw element's ESC/POS bytes in hex, spaces allowed, e.g.
// "1B 61 01". It is sent as given.
Hex string `json:"hex,omitempty"`
// Mode is a cut's mode. Default partial.
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
// Children are a box's body as elements, one level deep: text, feed,
// rule and kv. Set text or children, not both.
Children []Element `json:"children,omitempty"`
// Title is text set into a box's top border.
Title string `json:"title,omitempty"`
// TitleStyle is inline, the default, or capped.
TitleStyle string `json:"title_style,omitempty" jsonschema:"enum=inline,enum=capped"`
// Footer is text set into a box's bottom border, on the right.
Footer string `json:"footer,omitempty"`
// Style is a box's border style (single, double, double-h, double-v or
// ascii) or a rule's line style (single, double, light, medium, dark,
// solid, dashed, dotted or ascii). Default single.
Style string `json:"style,omitempty" jsonschema:"enum=single,enum=double,enum=double-h,enum=double-v,enum=ascii,enum=light,enum=medium,enum=dark,enum=solid,enum=dashed,enum=dotted"`
// Padding is the spaces between a box's side borders and its body, 0-3.
// Default 1.
Padding *int `json:"padding,omitempty" jsonschema:"minimum=0,maximum=3"`
// Fit shrinks a box to its widest line, title and footer included, and
// centres it. columns is then the most it may take.
Fit bool `json:"fit,omitempty"`
// Columns is a block's width in characters of its own size and font,
// 1-255, cut to the line. A narrower block is centred. 0 means the
// default, the whole line.
Columns int `json:"columns,omitempty" jsonschema:"minimum=0,maximum=255"`
// Pairs are a kv block's rows, 1-100; required for kv.
Pairs []Pair `json:"pairs,omitempty" jsonschema:"minItems=1,maxItems=100"`
// Leader is the fill between a kv row's key and value: ".", the
// default, "·", " " (or "space"), "_", "-" or "─".
Leader string `json:"leader,omitempty" jsonschema:"enum=.,enum=·,enum= ,enum=space,enum=_,enum=-,enum=─"`
}
// Pair is one row of a kv block: a key, a leader and a value.
type Pair struct {
// Key is the row's key, on the left. A key too long for the line is cut
// with "...".
Key string `json:"key" jsonschema:"required,minLength=1"`
// Value is the row's value, on the right. A long value wraps into the
// room after the key.
Value string `json:"value"`
// Bold prints the key and the value bold.
Bold bool `json:"bold,omitempty"`
}
// DecodeJob strictly decodes one JSON job. An unknown field is an error, so
// that a typo fails loudly instead of being ignored, and so is anything
// after the job. It does not validate the job.
func DecodeJob(data []byte) (Job, error) {
var job Job
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&job); err != nil {
return Job{}, err
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return Job{}, ErrTrailingData
}
return job, nil
}
// ValidationError lists every problem found in a job.
type ValidationError struct {
Problems []string
}
// Error implements error.
func (e *ValidationError) Error() string {
return "invalid job: " + strings.Join(e.Problems, "; ")
}
// Validate checks the whole job and reports every problem, so nothing is sent
// to the printer unless the entire receipt can be printed.
func (j Job) Validate() error {
var problems []string
children := 0
for _, el := range j.Elements {
children += len(el.Children)
}
switch total := len(j.Elements) + children; {
case len(j.Elements) == 0:
problems = append(problems, "elements: at least one element is required")
case total > MaxElements && children > 0:
problems = append(problems, fmt.Sprintf("elements: %d elements including %d box children, limit is %d", total, children, MaxElements))
case total > MaxElements:
problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", total, MaxElements))
}
if j.Copies < 0 || j.Copies > MaxCopies {
problems = append(problems, fmt.Sprintf("copies must be 1-%d", MaxCopies))
}
for i, el := range j.Elements {
problems = append(problems, el.problems(fmt.Sprintf("elements[%d]", i), false)...)
}
if len(problems) > 0 {
return &ValidationError{Problems: problems}
}
return nil
}
func (j Job) copies() int {
return max(j.Copies, 1)
}
// problems returns every problem with el, and with its children when it is
// a box, each prefixed with its path, e.g. "elements[0].children[3] (qr): ".
func (el Element) problems(path string, inBox bool) []string {
prefix := fmt.Sprintf("%s (%s): ", path, el.Type)
var messages []string
for _, msg := range el.validate(inBox) {
messages = append(messages, prefix+msg)
}
if el.Type == TypeBox && !inBox {
for i, child := range el.Children {
messages = append(messages, child.problems(fmt.Sprintf("%s.children[%d]", path, i), true)...)
}
}
return messages
}
// validate checks el's own fields. inBox is set for the children of a box,
// which allow fewer types and fields.
func (el Element) validate(inBox bool) []string {
if inBox {
switch el.Type {
case TypeText, TypeFeed, TypeRule, TypeKV:
case TypeBox, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut:
return []string{"not allowed inside a box; place it after the box"}
case "":
return []string{"type is required"}
default:
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule or kv)", el.Type)}
}
}
problems := el.checkFields(inBox)
var err error
switch el.Type {
case TypeText:
_, err = el.textSpec()
if err == nil && inBox && el.Newline != nil && !*el.Newline {
err = fmt.Errorf("newline:false is not allowed inside a box")
}
case TypeFeed:
_, err = el.feedLines()
case TypeQR:
_, err = el.qrSpec()
case TypeBarcode:
_, err = el.barcodeSpec()
case TypeImage:
_, err = el.imageSpec()
case TypeRaw:
_, err = el.rawBytes()
case TypeCut:
_, err = el.cutMode()
case TypeBox:
_, err = el.boxSpec()
case TypeRule:
_, err = el.ruleSpec(inBox)
case TypeKV:
_, err = el.kvSpec()
problems = append(problems, el.pairProblems()...)
case "":
err = fmt.Errorf("type is required")
default:
err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule or kv)", el.Type)
}
if err != nil {
problems = append(problems, err.Error())
}
return problems
}
type textSpec struct {
width, height int
bold bool
font escpos.Font
align escpos.Justification
underline escpos.Underline
invert bool
newline bool
wrap bool
}
func (el Element) textSpec() (textSpec, error) {
s := textSpec{
width: 1,
height: 1,
bold: el.Bold,
invert: el.Invert,
newline: el.Newline == nil || *el.Newline,
wrap: el.Wrap == nil || *el.Wrap,
}
if el.Size != 0 {
s.width, s.height = el.Size, el.Size
}
if el.Width != 0 {
s.width = el.Width
}
if el.Height != 0 {
s.height = el.Height
}
if s.width < 1 || s.width > escpos.MaxCharacterScale || s.height < 1 || s.height > escpos.MaxCharacterScale {
return s, fmt.Errorf("size, width and height must be 1-%d", escpos.MaxCharacterScale)
}
var err error
if s.font, err = parseFont(el.Font); err != nil {
return s, err
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
if s.underline, err = parseUnderline(el.Underline); err != nil {
return s, err
}
return s, nil
}
func parseUnderline(n int) (escpos.Underline, error) {
switch n {
case 0, 1, 2:
return escpos.Underline(n), nil
}
return 0, fmt.Errorf("underline must be 0, 1 or 2")
}
func (el Element) feedLines() (uint8, error) {
switch {
case el.Lines == 0:
return 1, nil
case el.Lines < 1 || el.Lines > 255:
return 0, fmt.Errorf("lines must be 1-255")
}
return uint8(el.Lines), nil
}
type qrSpec struct {
size int
correction escpos.QRCorrection
align escpos.Justification
}
func (el Element) qrSpec() (qrSpec, error) {
s := qrSpec{size: defaultQRSize, correction: escpos.QRCorrectionM}
if el.Size != 0 {
s.size = el.Size
}
switch {
case el.Data == "":
return s, fmt.Errorf("data is required")
case len(el.Data) > escpos.MaxQRData:
return s, fmt.Errorf("data is %d bytes, limit is %d", len(el.Data), escpos.MaxQRData)
case s.size < escpos.MinQRModuleSize || s.size > escpos.MaxQRModuleSize:
return s, fmt.Errorf("size must be %d-%d", escpos.MinQRModuleSize, escpos.MaxQRModuleSize)
}
var err error
if el.Correction != "" {
if s.correction, err = escpos.ParseQRCorrection(el.Correction); err != nil {
return s, fmt.Errorf("correction must be L, M, Q or H")
}
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
type barcodeSpec struct {
symbology escpos.Symbology
height int
width int
hri escpos.HRIPosition
align escpos.Justification
}
func (el Element) barcodeSpec() (barcodeSpec, error) {
s := barcodeSpec{height: defaultBarcodeHeight, width: defaultBarcodeWidth, hri: escpos.HRIBelow}
if el.Symbology == "" {
return s, fmt.Errorf("symbology is required (ean13, ean8, upca, upce, code39 or code128)")
}
var err error
if s.symbology, err = escpos.ParseSymbology(el.Symbology); err != nil {
return s, fmt.Errorf("unknown symbology %q (want ean13, ean8, upca, upce, code39 or code128)", el.Symbology)
}
if err := escpos.ValidateBarcode(s.symbology, el.Data); err != nil {
return s, fmt.Errorf("data: %w", err)
}
if el.Height != 0 {
s.height = el.Height
}
if el.Width != 0 {
s.width = el.Width
}
if s.height < 1 || s.height > 255 {
return s, fmt.Errorf("height must be 1-255 dots")
}
if s.width < escpos.MinBarcodeWidth || s.width > escpos.MaxBarcodeWidth {
return s, fmt.Errorf("width must be %d-%d", escpos.MinBarcodeWidth, escpos.MaxBarcodeWidth)
}
switch strings.ToLower(el.HRI) {
case "", "below":
s.hri = escpos.HRIBelow
case "none":
s.hri = escpos.HRINone
case "above":
s.hri = escpos.HRIAbove
case "both":
s.hri = escpos.HRIBoth
default:
return s, fmt.Errorf("hri must be none, above, below or both")
}
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
type imageSpec struct {
url string
data []byte
width int
align escpos.Justification
}
func (el Element) imageSpec() (imageSpec, error) {
s := imageSpec{width: el.Width}
switch {
case el.URL != "" && el.Base64 != "":
return s, fmt.Errorf("set url or base64, not both")
case el.URL != "":
u, err := url.Parse(el.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" {
return s, fmt.Errorf("url must be an absolute http or https URL")
}
s.url = el.URL
case el.Base64 != "":
data, err := decodeBase64Image(el.Base64)
if err != nil {
return s, fmt.Errorf("base64: %w", err)
}
s.data = data
default:
return s, fmt.Errorf("url or base64 is required")
}
if s.width < 0 {
return s, fmt.Errorf("width must be positive")
}
var err error
if s.align, err = parseAlign(el.Align); err != nil {
return s, err
}
return s, nil
}
// decodeBase64Image accepts standard base64, with or without padding, and
// data URIs such as "data:image/png;base64,....".
func decodeBase64Image(s string) ([]byte, error) {
if rest, ok := strings.CutPrefix(s, "data:"); ok {
_, payload, found := strings.Cut(rest, ",")
if !found {
return nil, fmt.Errorf("malformed data URI")
}
s = payload
}
s = strings.TrimSpace(s)
if data, err := base64.StdEncoding.DecodeString(s); err == nil {
return data, nil
}
data, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(s, "="))
if err != nil {
return nil, fmt.Errorf("not valid base64")
}
return data, nil
}
func (el Element) rawBytes() ([]byte, error) {
if el.Hex == "" {
return nil, fmt.Errorf("hex is required")
}
data, err := hex.DecodeString(strings.ReplaceAll(el.Hex, " ", ""))
if err != nil {
return nil, fmt.Errorf("hex: %v", err)
}
return data, nil
}
func (el Element) cutMode() (escpos.CutMode, error) {
switch strings.ToLower(el.Mode) {
case "", "partial":
return escpos.CutPartial, nil
case "full":
return escpos.CutFull, nil
}
return 0, fmt.Errorf("mode must be partial or full")
}
func parseAlign(s string) (escpos.Justification, error) {
switch strings.ToLower(s) {
case "", "left":
return escpos.JustifyLeft, nil
case "center", "centre":
return escpos.JustifyCenter, nil
case "right":
return escpos.JustifyRight, nil
}
return 0, fmt.Errorf("align must be left, center or right")
}
func parseFont(s string) (escpos.Font, error) {
switch strings.ToLower(s) {
case "", "a":
return escpos.FontA, nil
case "b":
return escpos.FontB, nil
}
return 0, fmt.Errorf("font must be a or b")
}