// 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 ( "encoding/base64" "encoding/hex" "fmt" "net/url" "strings" "uberbringer/internal/pkg/escpos" ) // Element types. const ( TypeText = "text" TypeFeed = "feed" TypeQR = "qr" TypeBarcode = "barcode" TypeImage = "image" TypeRaw = "raw" TypeCut = "cut" ) // Job limits. const ( MaxElements = 500 MaxCopies = 5 ) // 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; fields // that do not apply to the type are ignored. Width and Height mean character // multipliers for text, module width and bar height for barcodes, and target // width in dots for images. 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"` } // 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 switch { case len(j.Elements) == 0: problems = append(problems, "elements: at least one element is required") case len(j.Elements) > MaxElements: problems = append(problems, fmt.Sprintf("elements: %d elements, limit is %d", len(j.Elements), 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 { if err := el.validate(); err != nil { problems = append(problems, fmt.Sprintf("elements[%d] (%s): %v", i, el.Type, err)) } } if len(problems) > 0 { return &ValidationError{Problems: problems} } return nil } func (j Job) copies() int { return max(j.Copies, 1) } func (el Element) validate() error { var err error switch el.Type { case TypeText: _, err = el.textSpec() 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 "": err = fmt.Errorf("type is required") default: err = fmt.Errorf("unknown type %q (want text, feed, qr, barcode, image, raw or cut)", el.Type) } return err } 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 } switch el.Underline { case 0, 1, 2: s.underline = escpos.Underline(el.Underline) default: return s, fmt.Errorf("underline must be 0, 1 or 2") } return s, nil } 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") }