Files
uberbringer/internal/pkg/receipt/job.go
T
57_WolveandClaude Opus 5.5 4562f0cebb
Security / Vulnerability check (push) Successful in 50s
Test / Lint and test (push) Successful in 1m59s
Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.

- receipt: box, rule and kv elements, laid out when the job renders from
  the printer profile, size and font (never fixed widths). Boxes take a
  title (inline or capped), a footer, padding, fit and columns, and a
  body of text or children (text, feed, kv, and rules as dividers joined
  to the borders). Glyphs a code page lacks fall back per set: double-h
  and double-v to double, then single, then ascii; a missing junction
  switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
  checks fields per block type, allows one level of children and counts
  them toward the 500-element limit. Block fields on the older types are
  problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
  look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
  trademark), as the owner approved on 2026-11-29. An emoji sequence
  prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
  command stream back as the printer would print it. It takes the
  profile so that it can follow the printer's own wrapping and
  alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
  prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
  too_many_lines on preview; printer.box_line_spacing (default 0).

Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.

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

494 lines
13 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.
type Job struct {
Elements []Element `json:"elements"`
// Copies is how many times the receipt is printed, each with its own
// cut. Zero means one.
Copies int `json:"copies,omitempty"`
}
// Element is one item on a receipt. 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.
type Element struct {
Type string `json:"type"`
// Text.
Text string `json:"text,omitempty"`
Bold bool `json:"bold,omitempty"`
Size int `json:"size,omitempty"`
Width int `json:"width,omitempty"`
Height int `json:"height,omitempty"`
Font string `json:"font,omitempty"`
Align string `json:"align,omitempty"`
Underline int `json:"underline,omitempty"`
Invert bool `json:"invert,omitempty"`
Newline *bool `json:"newline,omitempty"`
Wrap *bool `json:"wrap,omitempty"`
// Feed.
Lines int `json:"lines,omitempty"`
// QR code and barcode.
Data string `json:"data,omitempty"`
Correction string `json:"correction,omitempty"`
Symbology string `json:"symbology,omitempty"`
HRI string `json:"hri,omitempty"`
// Image.
URL string `json:"url,omitempty"`
Base64 string `json:"base64,omitempty"`
// Raw.
Hex string `json:"hex,omitempty"`
// Cut.
Mode string `json:"mode,omitempty"`
// Blocks. Style is the border or line style of a box or rule. Children
// are the body of a box, one level deep.
Children []Element `json:"children,omitempty"`
Title string `json:"title,omitempty"`
TitleStyle string `json:"title_style,omitempty"`
Footer string `json:"footer,omitempty"`
Style string `json:"style,omitempty"`
Padding *int `json:"padding,omitempty"`
Fit bool `json:"fit,omitempty"`
Columns int `json:"columns,omitempty"`
Pairs []Pair `json:"pairs,omitempty"`
Leader string `json:"leader,omitempty"`
}
// Pair is one row of a kv block: a key, a leader and a value.
type Pair struct {
Key string `json:"key"`
Value string `json:"value"`
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")
}