package receipt import ( "fmt" "slices" "strings" "uberbringer/internal/pkg/escpos" ) // Block limits and defaults. const ( maxBlockSize = 3 maxPadding = 3 maxColumns = 255 defaultPadding = 1 ) // boxStyle selects the border glyphs of a box. type boxStyle int const ( boxSingle boxStyle = iota boxDouble boxDoubleH boxDoubleV boxASCII ) // ruleStyle selects the line a rule is drawn with. type ruleStyle int const ( ruleSingle ruleStyle = iota ruleDouble ruleLight ruleMedium ruleDark ruleSolid ruleDashed ruleDotted ruleASCII ) // field is one JSON field of Element and the test for whether a job set it. type field struct { name string set func(Element) bool } // fields lists every Element field in JSON order. var fields = []field{ {"text", func(e Element) bool { return e.Text != "" }}, {"bold", func(e Element) bool { return e.Bold }}, {"size", func(e Element) bool { return e.Size != 0 }}, {"width", func(e Element) bool { return e.Width != 0 }}, {"height", func(e Element) bool { return e.Height != 0 }}, {"font", func(e Element) bool { return e.Font != "" }}, {"align", func(e Element) bool { return e.Align != "" }}, {"underline", func(e Element) bool { return e.Underline != 0 }}, {"invert", func(e Element) bool { return e.Invert }}, {"newline", func(e Element) bool { return e.Newline != nil }}, {"wrap", func(e Element) bool { return e.Wrap != nil }}, {"lines", func(e Element) bool { return e.Lines != 0 }}, {"data", func(e Element) bool { return e.Data != "" }}, {"correction", func(e Element) bool { return e.Correction != "" }}, {"symbology", func(e Element) bool { return e.Symbology != "" }}, {"hri", func(e Element) bool { return e.HRI != "" }}, {"url", func(e Element) bool { return e.URL != "" }}, {"base64", func(e Element) bool { return e.Base64 != "" }}, {"optional", func(e Element) bool { return e.Optional }}, {"hex", func(e Element) bool { return e.Hex != "" }}, {"mode", func(e Element) bool { return e.Mode != "" }}, {"children", func(e Element) bool { return e.Children != nil }}, {"title", func(e Element) bool { return e.Title != "" }}, {"title_style", func(e Element) bool { return e.TitleStyle != "" }}, {"title_bold", func(e Element) bool { return e.TitleBold }}, {"footer", func(e Element) bool { return e.Footer != "" }}, {"style", func(e Element) bool { return e.Style != "" }}, {"padding", func(e Element) bool { return e.Padding != nil }}, {"fit", func(e Element) bool { return e.Fit }}, {"columns", func(e Element) bool { return e.Columns != 0 }}, {"pairs", func(e Element) bool { return e.Pairs != nil }}, {"leader", func(e Element) bool { return e.Leader != "" }}, {"items", func(e Element) bool { return e.Items != nil }}, {"bullet", func(e Element) bool { return e.Bullet != "" }}, {"done", func(e Element) bool { return e.Done != nil }}, } // blockOnly are the fields no other type takes. var blockOnly = fieldSet("children title title_style title_bold footer style padding fit columns pairs leader items bullet done") // ownFields maps each field that only one of the other types takes to that // type. The rest of the other types refuse it, as they refuse the block // fields. var ownFields = map[string]string{"optional": TypeImage} // blockFields are the fields each block takes at the top level. var blockFields = map[string]map[string]bool{ TypeBox: fieldSet("text bold underline invert align size font children title title_style title_bold footer style padding fit columns"), TypeRule: fieldSet("text bold align size font style columns"), TypeKV: fieldSet("pairs leader size font columns"), TypeList: fieldSet("items bullet done size font columns"), } // childFields are the fields each type takes inside a box. var childFields = map[string]map[string]bool{ TypeText: fieldSet("text bold underline invert align wrap newline"), TypeFeed: fieldSet("lines"), TypeRule: fieldSet("text bold align style"), TypeKV: fieldSet("pairs leader"), TypeList: fieldSet("items bullet done"), } // inherited are the fields a child takes from its box. var inherited = fieldSet("size width height font") func fieldSet(names string) map[string]bool { set := make(map[string]bool) for _, name := range strings.Fields(names) { set[name] = true } return set } // checkFields reports fields set on el that its type does not take. The // blocks and the children of a box take only their own fields; the other // types ignore unrelated fields, except the block fields and the fields // another type owns. func (el Element) checkFields(inBox bool) []string { allowed, strict := blockFields[el.Type] if inBox { allowed, strict = childFields[el.Type] } known := strict || slices.Contains([]string{TypeText, TypeFeed, TypeQR, TypeBarcode, TypeImage, TypeRaw, TypeCut}, el.Type) if !known { return nil } var problems []string for _, f := range fields { if !f.set(el) { continue } switch { case inBox && inherited[f.name]: problems = append(problems, fmt.Sprintf("%s is inherited from the box", f.name)) case inBox && !allowed[f.name]: problems = append(problems, fmt.Sprintf("field %q does not apply to %s inside a box", f.name, el.Type)) case strict && !allowed[f.name], !strict && blockOnly[f.name], !strict && ownFields[f.name] != "" && ownFields[f.name] != el.Type: problems = append(problems, fmt.Sprintf("field %q does not apply to %s", f.name, el.Type)) } } return problems } // blockScale returns the size and font of a block, which scale its borders // and its text together. func (el Element) blockScale() (int, escpos.Font, error) { size := max(el.Size, 1) if el.Size < 0 || el.Size > maxBlockSize { return 0, 0, fmt.Errorf("size must be 1-%d", maxBlockSize) } font, err := parseFont(el.Font) return size, font, err } func checkColumns(columns int) error { if columns < 0 || columns > maxColumns { return fmt.Errorf("columns must be 1-%d", maxColumns) } return nil } type boxSpec struct { style boxStyle capped bool title textStyle text textStyle align escpos.Justification padding int fit bool columns int size int font escpos.Font } func (el Element) boxSpec() (boxSpec, error) { s := boxSpec{ title: textStyle{bold: el.TitleBold}, text: textStyle{bold: el.Bold, invert: el.Invert}, padding: defaultPadding, fit: el.Fit, columns: el.Columns, } var err error if s.size, s.font, err = el.blockScale(); err != nil { return s, err } if s.style, err = parseBoxStyle(el.Style); err != nil { return s, err } switch strings.ToLower(el.TitleStyle) { case "", "inline": case "capped": s.capped = true default: return s, fmt.Errorf("title_style must be inline or capped") } if el.Padding != nil { if *el.Padding < 0 || *el.Padding > maxPadding { return s, fmt.Errorf("padding must be 0-%d", maxPadding) } s.padding = *el.Padding } if err := checkColumns(el.Columns); err != nil { return s, err } if s.text.underline, err = parseUnderline(el.Underline); err != nil { return s, err } if s.align, err = parseAlign(el.Align); err != nil { return s, err } switch { case el.Text != "" && len(el.Children) > 0: return s, fmt.Errorf("set text or children, not both") case el.Text == "" && len(el.Children) == 0: return s, fmt.Errorf("text or children is required") } return s, nil } func parseBoxStyle(s string) (boxStyle, error) { switch strings.ToLower(s) { case "", "single": return boxSingle, nil case "double": return boxDouble, nil case "double-h": return boxDoubleH, nil case "double-v": return boxDoubleV, nil case "ascii": return boxASCII, nil } return 0, fmt.Errorf("style must be single, double, double-h, double-v or ascii") } type ruleSpec struct { style ruleStyle align escpos.Justification bold bool columns int size int font escpos.Font } // ruleSpec checks a rule. Inside a box a rule is a divider, which only // comes in the weights the borders have. func (el Element) ruleSpec(inBox bool) (ruleSpec, error) { s := ruleSpec{align: escpos.JustifyCenter, bold: el.Bold, columns: el.Columns} var err error if s.size, s.font, err = el.blockScale(); err != nil { return s, err } if s.style, err = parseRuleStyle(el.Style); err != nil { return s, err } if inBox && s.style != ruleSingle && s.style != ruleDouble { return s, fmt.Errorf("inside a box, style must be single or double") } if el.Align != "" { if s.align, err = parseAlign(el.Align); err != nil { return s, err } } if err := checkColumns(el.Columns); err != nil { return s, err } return s, nil } func parseRuleStyle(s string) (ruleStyle, error) { switch strings.ToLower(s) { case "", "single": return ruleSingle, nil case "double": return ruleDouble, nil case "light": return ruleLight, nil case "medium": return ruleMedium, nil case "dark": return ruleDark, nil case "solid": return ruleSolid, nil case "dashed": return ruleDashed, nil case "dotted": return ruleDotted, nil case "ascii": return ruleASCII, nil } return 0, fmt.Errorf("style must be single, double, light, medium, dark, solid, dashed, dotted or ascii") } type kvSpec struct { leader string columns int size int font escpos.Font } func (el Element) kvSpec() (kvSpec, error) { s := kvSpec{columns: el.Columns} var err error if s.size, s.font, err = el.blockScale(); err != nil { return s, err } switch el.Leader { case "", ".": s.leader = "." case "·", " ", "_", "-", "─": s.leader = el.Leader case "space": s.leader = " " default: return s, fmt.Errorf(`leader must be ".", "·", " ", "_", "-" or "─"`) } if err := checkColumns(el.Columns); err != nil { return s, err } switch n := len(el.Pairs); { case n == 0: return s, fmt.Errorf("pairs: at least one pair is required") case n > MaxPairs: return s, fmt.Errorf("pairs: %d pairs, limit is %d", n, MaxPairs) } return s, nil } // pairProblems reports every pair without a key. func (el Element) pairProblems() []string { var problems []string for i, p := range el.Pairs { if p.Key == "" { problems = append(problems, fmt.Sprintf("pairs[%d]: key is required", i)) } } return problems } // listBullet selects what marks each item of a list. type listBullet int const ( bulletDot listBullet = iota bulletDash bulletNumber bulletCheckbox ) type listSpec struct { bullet listBullet columns int size int font escpos.Font } func (el Element) listSpec() (listSpec, error) { s := listSpec{columns: el.Columns} var err error if s.size, s.font, err = el.blockScale(); err != nil { return s, err } switch strings.ToLower(el.Bullet) { case "", "dot": s.bullet = bulletDot case "dash": s.bullet = bulletDash case "number": s.bullet = bulletNumber case "checkbox": s.bullet = bulletCheckbox default: return s, fmt.Errorf("bullet must be dot, dash, number or checkbox") } if err := checkColumns(el.Columns); err != nil { return s, err } switch n := len(el.Items); { case n == 0: return s, fmt.Errorf("items: at least one item is required") case n > MaxItems: return s, fmt.Errorf("items: %d items, limit is %d", n, MaxItems) } return s, nil } // itemProblems reports every empty item and every problem with done: done // on a list that is not a checklist, and an index that is out of range or // repeated. func (el Element) itemProblems() []string { var problems []string for i, item := range el.Items { if item == "" { problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i)) } } if len(el.Done) > 0 && !strings.EqualFold(el.Bullet, "checkbox") { return append(problems, `done: only a list with bullet "checkbox" has done items`) } seen := make(map[int]bool, len(el.Done)) for i, index := range el.Done { switch { case index < 0 || index >= len(el.Items): problems = append(problems, fmt.Sprintf("done[%d]: index %d is out of range", i, index)) case seen[index]: problems = append(problems, fmt.Sprintf("done[%d]: index %d is repeated", i, index)) } seen[index] = true } return problems }