// 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, kv and list 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" TypeList = "list" ) // Job limits. MaxElements counts the children of boxes too. const ( MaxElements = 500 MaxCopies = 5 MaxPairs = 100 MaxItems = 200 ) // 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, kv and list) 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, kv and list 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,enum=list"` // 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, made smaller for a code that could be wider // than the paper, its width worked out as if its data were bytes. 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"` // Optional prints the line [image unavailable] in place of an image // that cannot be fetched or decoded, instead of failing the whole job, // and shrinks an image whose width is wider than the paper to it. Optional bool `json:"optional,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, kv and list. 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"` // TitleBold prints a box's title bold. TitleBold bool `json:"title_bold,omitempty"` // 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=─"` // Items are a list's items, 1-200, none empty; required for list. An // item too long for its line wraps with a hanging indent. Items []string `json:"items,omitempty" jsonschema:"minItems=1,maxItems=200,minLength=1"` // Bullet marks each item of a list: dot, the default, dash, number // (right-aligned to the widest number) or checkbox. Bullet string `json:"bullet,omitempty" jsonschema:"enum=dot,enum=dash,enum=number,enum=checkbox"` // Done are the indexes into items, from 0, of a checkbox list's ticked // items, each once. They print as [√], or [x] on code pages without √. Done []int `json:"done,omitempty" jsonschema:"uniqueItems=true,minimum=0,maximum=199"` } // 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, TypeList: 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, kv or list)", 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 TypeList: _, err = el.listSpec() problems = append(problems, el.itemProblems()...) case "": err = fmt.Errorf("type is required") default: err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)", 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") }