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