Add the list block and the module layer with the note module
Security / Vulnerability check (push) Successful in 41s
Test / Lint and test (push) Successful in 1m50s

The list block prints items with a dot, dash, number or checkbox bullet,
wrapping a long item with a hanging indent; a checkbox list ticks its
done items as [√], or [x] on code pages without √. It stands alone or
inside a box, and its items, bullet and done fields carry their enums
and limits as jsonschema tags.

internal/pkg/modules holds modules that build ordinary jobs from their
own payloads: a registry by name, an Env with the clock, time zone and
time layout, strict payload decoding that reports every problem, ErrSkip
and PayloadError. The note module prints a boxed note with an optional
checklist and a time stamp in the footer.

Three routes join the route table: POST /api/v1/print/{module} and
POST /api/v1/preview/{module}, which take ?copies and a reserved
?printer, and GET /api/v1/modules. Print and the module route share one
submit path, and preview shares one too. New error codes:
invalid_payload, invalid_query, unknown_printer, module_not_found and
module_failed; a module that builds an invalid receipt is logged and
reported to Sentry once. [format] gains timezone and time_layout, the
binary embeds the time zone database, and uberbringer preview takes
--module.

The note receipt passed on the TM-T88IV, and its bytes are pinned in
TestPaperReceipts. docs/api.md describes the list block, the module
routes and the note payload; docs/swagger.json is regenerated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-30 10:55:50 -06:00
1 parent 6b2e402f1a
commit 3e9779f71a
69 files changed
+3092 -262

No files matched your search

+27
View File
@@ -0,0 +1,27 @@
package uberbringer
import (
"fmt"
"time"
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/modules"
)
// newModules returns the registry of every module the daemon offers.
func newModules() (*modules.Registry, error) {
return modules.NewRegistry(modules.Note())
}
// moduleEnv returns a func that gives modules the time now, in the zone and
// layout cfg's [format] names.
func moduleEnv(cfg *config.Config) (func() modules.Env, error) {
loc, err := time.LoadLocation(cfg.Format.Timezone)
if err != nil {
return nil, fmt.Errorf("config format.timezone: %w", err)
}
layout := cfg.Format.TimeLayout
return func() modules.Env {
return modules.Env{Now: time.Now(), Location: loc, TimeLayout: layout}
}, nil
}
+60 -8
View File
@@ -13,17 +13,20 @@ import (
"uberbringer/internal/pkg/config"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
func newPreviewCommand(configPath *string) *cobra.Command {
return &cobra.Command{
Use: "preview [file.json|-]",
var module string
cmd := &cobra.Command{
Use: "preview [--module name] [file.json|-]",
Short: "Shows the lines a job would print, without printing it.",
Long: "Reads a job, as POST /api/v1/print takes it, from the file or from standard input,\n" +
"lays it out for the printer in the config and writes the lines it would print.\n" +
"On a terminal, bold, underlined and inverted text is shown as such. Images are\n" +
"not loaded; each shows as a placeholder.",
"With --module, the input is that module's payload, as POST /api/v1/print/<module>\n" +
"takes it. On a terminal, bold, underlined and inverted text is shown as such.\n" +
"Images are not loaded; each shows as a placeholder.",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load(*configPath)
@@ -35,9 +38,11 @@ func newPreviewCommand(configPath *string) *cobra.Command {
return err
}
out := cmd.OutOrStdout()
return preview(cmd.Context(), cfg, data, out, cmd.ErrOrStderr(), isTerminal(out))
return preview(cmd.Context(), cfg, data, module, out, cmd.ErrOrStderr(), isTerminal(out))
},
}
cmd.Flags().StringVar(&module, "module", "", "read the input as this module's payload, e.g. note")
return cmd
}
// readJobInput reads the job from the file named in args, or from stdin when
@@ -59,10 +64,15 @@ func readJobInput(stdin io.Reader, args []string) ([]byte, error) {
// preview writes the lines the job in data would print on the printer cfg
// describes to out, styled when styled is set, and its warnings to errOut.
func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut io.Writer, styled bool) error {
job, err := receipt.DecodeJob(data)
// With a module name, data is that module's payload.
func preview(ctx context.Context, cfg *config.Config, data []byte, module string, out, errOut io.Writer, styled bool) error {
job, ok, err := previewJob(ctx, cfg, data, module)
if err != nil {
return fmt.Errorf("not a valid job: %w", err)
return err
}
if !ok {
_, err := fmt.Fprintf(errOut, "module %s has nothing to print\n", module)
return err
}
options, err := rendererOptions(cfg)
if err != nil {
@@ -71,6 +81,8 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
p, err := receipt.NewRenderer(options, noFetch{}).Preview(ctx, job)
var ve *receipt.ValidationError
switch {
case errors.As(err, &ve) && module != "":
return fmt.Errorf("module %q built an invalid receipt:\n %s", module, strings.Join(ve.Problems, "\n "))
case errors.As(err, &ve):
return fmt.Errorf("invalid job:\n %s", strings.Join(ve.Problems, "\n "))
case err != nil:
@@ -87,6 +99,46 @@ func preview(ctx context.Context, cfg *config.Config, data []byte, out, errOut i
return nil
}
// previewJob returns the job to preview: data itself, or with a module name,
// the job that module builds from data as its payload, at the time now. ok
// is false when the module has nothing to print.
func previewJob(ctx context.Context, cfg *config.Config, data []byte, module string) (job receipt.Job, ok bool, err error) {
if module == "" {
job, err := receipt.DecodeJob(data)
if err != nil {
return job, false, fmt.Errorf("not a valid job: %w", err)
}
return job, true, nil
}
registry, err := newModules()
if err != nil {
return job, false, err
}
m, found := registry.Get(module)
if !found {
var names []string
for _, info := range registry.List() {
names = append(names, info.Name)
}
return job, false, fmt.Errorf("unknown module %q; the modules are: %s", module, strings.Join(names, ", "))
}
env, err := moduleEnv(cfg)
if err != nil {
return job, false, err
}
job, err = m.Build(ctx, data, env())
var pe *modules.PayloadError
switch {
case errors.Is(err, modules.ErrSkip):
return job, false, nil
case errors.As(err, &pe):
return job, false, fmt.Errorf("invalid payload for module %q:\n %s", module, strings.Join(pe.Problems, "\n "))
case err != nil:
return job, false, fmt.Errorf("module %s: %w", module, err)
}
return job, true, nil
}
// noFetch refuses image fetches. A preview loads no images, but a renderer
// needs a fetcher.
type noFetch struct{}
+66
View File
@@ -3,10 +3,12 @@ package uberbringer
import (
"bytes"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/receipt"
@@ -110,6 +112,70 @@ func TestPreviewCommandErrors(t *testing.T) {
}
}
func TestPreviewCommandModule(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out, errOut bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&errOut)
cmd.SetIn(strings.NewReader(`{"title":"Shopping","text":"Bread.","items":["Milk","Eggs"],"done":[1],"footer":"kitchen"}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", "note"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Bread. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [√] Eggs │\n" +
"└───────────────────────────── kitchen ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if out.String() != want || errOut.Len() != 0 {
t.Errorf("output:\n%s\nwant:\n%s\nstandard error: %q", out.String(), want, errOut.String())
}
}
// The note's stamp is the time now in format.timezone and time_layout.
func TestPreviewCommandModuleStamp(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetIn(strings.NewReader(`{"text":"x"}`))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, "[format]\ntimezone = \"UTC\"\ntime_layout = \"2006\"\n"), "--module", "note"})
before := time.Now().UTC().Year()
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
after := time.Now().UTC().Year()
lines := strings.Split(out.String(), "\n")
if len(lines) < 3 || (!strings.Contains(lines[2], fmt.Sprintf(" %d ", before)) && !strings.Contains(lines[2], fmt.Sprintf(" %d ", after))) {
t.Errorf("bottom border %q, want the year in it", lines[2])
}
}
func TestPreviewCommandModuleErrors(t *testing.T) {
tests := []struct {
name, module, payload, want string
}{
{"unknown module", "notx", `{}`, `unknown module "notx"; the modules are: note`},
{"invalid payload", "note", `{"title":"x","items":["a"],"done":[1,2]}`,
"invalid payload for module \"note\":\n text: required\n done[0]: index 1 is out of range\n done[1]: index 2 is out of range"},
{"not an object", "note", `[]`, "invalid payload for module \"note\":\n body: expected a JSON object, got array"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cmd := newRootCommand(BuildInfo{})
cmd.SetOut(&bytes.Buffer{})
cmd.SetIn(strings.NewReader(tt.payload))
cmd.SetArgs([]string{"preview", "-c", writePreviewConfig(t, ""), "--module", tt.module})
err := cmd.Execute()
if err == nil || !strings.Contains(err.Error(), tt.want) {
t.Errorf("err = %v, want it to contain %q", err, tt.want)
}
})
}
}
func TestWritePreviewStyled(t *testing.T) {
p := receipt.Preview{Lines: []escpos.PreviewLine{
{Kind: escpos.LineText, Text: "a <b> c", Runs: []escpos.Run{
+15 -1
View File
@@ -56,6 +56,14 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
return err
}
profile, codePage := options.Profile, options.CodePage
registry, err := newModules()
if err != nil {
return err
}
env, err := moduleEnv(cfg)
if err != nil {
return err
}
flushSentry, err := initSentry(cfg.Sentry, build, logger)
if err != nil {
@@ -99,7 +107,13 @@ func run(ctx context.Context, cfg *config.Config, build BuildInfo, out io.Writer
IdleTimeout: cfg.WebServer.IdleTimeout,
RequestID: newRequestID,
OpenAPI: docs.OpenAPI(),
}, server.Deps{Jobs: queue, Printer: printerClient, Previewer: renderer}, logger)
}, server.Deps{
Jobs: queue,
Printer: printerClient,
Previewer: renderer,
Modules: registry,
ModuleEnv: env,
}, logger)
addr := net.JoinHostPort(cfg.WebServer.BindIP, strconv.Itoa(cfg.WebServer.Port))
ln, err := listen(ctx, addr)
+31
View File
@@ -141,6 +141,37 @@ level = "error"
return bytes.Contains(printer.received(), []byte("Gr\x81\xE1e aus dem Test"))
})
req, _ = http.NewRequest(http.MethodGet, base+"/api/v1/modules", nil)
req.Header.Set("Authorization", "Bearer "+token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
var listed []struct{ Name string }
if err := json.NewDecoder(resp.Body).Decode(&listed); err != nil {
t.Fatal(err)
}
resp.Body.Close()
if len(listed) == 0 || listed[0].Name != "note" {
t.Errorf("GET /api/v1/modules = %+v, want note listed", listed)
}
req, _ = http.NewRequest(http.MethodPost, base+"/api/v1/print/note",
strings.NewReader(`{"title":"Notiz","text":"Milch kaufen","items":["Brot"],"done":[0]}`))
req.Header.Set("Authorization", "Bearer "+token)
resp, err = http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("POST /api/v1/print/note = %d", resp.StatusCode)
}
waitFor(t, func() bool {
// "[√] Brot" in CP437: √ is 0xFB.
return bytes.Contains(printer.received(), []byte("[\xFB] Brot"))
})
cancel()
select {
case err := <-served:
+10 -2
View File
@@ -25,15 +25,20 @@ type errorCode struct {
var (
codeBadRequest = errorCode{fiber.StatusBadRequest, "bad_request", "malformed request"}
codeInvalidJob = errorCode{fiber.StatusBadRequest, "invalid_job", "invalid job"}
codeInvalidPayload = errorCode{fiber.StatusBadRequest, "invalid_payload", "invalid payload"}
codeInvalidQuery = errorCode{fiber.StatusBadRequest, "invalid_query", "invalid query parameter"}
codeUnknownPrinter = errorCode{fiber.StatusBadRequest, "unknown_printer", "unknown printer"}
codeUnauthorized = errorCode{fiber.StatusUnauthorized, "unauthorized", "missing or invalid bearer token"}
codeNotFound = errorCode{fiber.StatusNotFound, "not_found", "not found"}
codeJobNotFound = errorCode{fiber.StatusNotFound, "job_not_found", "job not found"}
codeModuleNotFound = errorCode{fiber.StatusNotFound, "module_not_found", "module not found"}
codeMethodNotAllowed = errorCode{fiber.StatusMethodNotAllowed, "method_not_allowed", "method not allowed"}
codeRequestTimeout = errorCode{fiber.StatusRequestTimeout, "request_timeout", "request was not received in time"}
codeBodyTooLarge = errorCode{fiber.StatusRequestEntityTooLarge, "body_too_large", "request body is too large"}
codeRateLimited = errorCode{fiber.StatusTooManyRequests, "rate_limited", "too many requests, try again later"}
codeHeadersTooLarge = errorCode{fiber.StatusRequestHeaderFieldsTooLarge, "headers_too_large", "request headers are too large"}
codeTooManyLines = errorCode{fiber.StatusUnprocessableEntity, "too_many_lines", "receipt would print too many lines"}
codeModuleFailed = errorCode{fiber.StatusUnprocessableEntity, "module_failed", "module built an invalid receipt"}
codeInternal = errorCode{fiber.StatusInternalServerError, "internal_error", "internal server error"}
codeNotImplemented = errorCode{fiber.StatusNotImplemented, "not_implemented", "not implemented"}
codeQueueFull = errorCode{fiber.StatusServiceUnavailable, "queue_full", "print queue is full, try again shortly"}
@@ -83,8 +88,11 @@ type errorResponse struct {
Error string `json:"error"`
// Code is stable and meant for clients to match on.
Code string `json:"code"`
// Details lists every problem when an invalid_job fails validation, each
// naming the element by its path, e.g. elements[0].children[3] (qr).
// Details lists every problem when a job fails validation (invalid_job),
// a module payload is invalid (invalid_payload) or a module builds an
// invalid receipt (module_failed). A job problem names the element by
// its path, e.g. elements[0].children[3] (qr); a payload problem names
// the field, e.g. done[0].
Details []string `json:"details,omitempty"`
}
@@ -66,7 +66,12 @@ func (s *Server) handlePrint(c fiber.Ctx) error {
if err != nil {
return err
}
return s.submit(c, job)
}
// submit queues a validated job and answers 202 with its status and a
// Location header, or refuses it when the queue is full or closed.
func (s *Server) submit(c fiber.Ctx, job receipt.Job) error {
status, err := s.jobs.Submit(job)
switch {
case errors.Is(err, printqueue.ErrQueueFull):
@@ -0,0 +1,161 @@
package server
import (
"errors"
"fmt"
"log/slog"
"strconv"
"strings"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/requestid"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// defaultPrinter is the only name ?printer= accepts while one printer is
// configured.
const defaultPrinter = "default"
// modulePayload is a module's payload: a JSON object whose fields the
// module defines, such as a note's title, text and items.
type modulePayload map[string]any
// moduleList is the body of GET /api/v1/modules: every module, sorted by
// name.
type moduleList []moduleInfo
// moduleInfo describes one module.
type moduleInfo struct {
// Name is the module's name in the module routes' paths, e.g. note.
Name string `json:"name"`
// Description says in one line what the module prints.
Description string `json:"description"`
}
// handleModules lists the modules, sorted by name.
func (s *Server) handleModules(c fiber.Ctx) error {
infos := s.modules.List()
list := make(moduleList, len(infos))
for i, info := range infos {
list[i] = moduleInfo(info)
}
return c.JSON(list)
}
// handlePrintModule builds a job from the body with the module the route
// names and queues it. A module with nothing to print answers 204.
func (s *Server) handlePrintModule(c fiber.Ctx) error {
job, skip, err := s.moduleJob(c)
switch {
case err != nil:
return err
case skip:
return c.SendStatus(fiber.StatusNoContent)
}
return s.submit(c, job)
}
// handlePreviewModule builds a job as handlePrintModule does and answers
// with its preview instead of queueing it.
func (s *Server) handlePreviewModule(c fiber.Ctx) error {
job, skip, err := s.moduleJob(c)
switch {
case err != nil:
return err
case skip:
return c.SendStatus(fiber.StatusNoContent)
}
return s.preview(c, job)
}
// moduleJob builds the job the route's module makes of the request body,
// with the copies the query asks for, and validates it. skip is set when
// the module has nothing to print. A job that fails validation is a bug in
// the module: it is logged and reported, and answered 422 with the
// problems.
func (s *Server) moduleJob(c fiber.Ctx) (job receipt.Job, skip bool, err error) {
// Clone: fasthttp reuses the buffer behind route params.
name := strings.Clone(c.Params("module"))
module, ok := s.modules.Get(name)
if !ok {
return job, false, newAPIError(codeModuleNotFound.withMessage(fmt.Sprintf("module %q not found", name)))
}
copies, err := moduleQuery(c)
if err != nil {
return job, false, err
}
job, err = module.Build(c.Context(), c.Body(), s.moduleEnv())
var payloadErr *modules.PayloadError
switch {
case errors.Is(err, modules.ErrSkip):
return receipt.Job{}, true, nil
case errors.As(err, &payloadErr):
msg := fmt.Sprintf("invalid payload for module %q", name)
return job, false, newAPIError(codeInvalidPayload.withMessage(msg), payloadErr.Problems...)
case err != nil:
return job, false, fmt.Errorf("module %s: %w", name, err)
}
if copies > 0 {
job.Copies = copies
}
if err := job.Validate(); err != nil {
var ve *receipt.ValidationError
if !errors.As(err, &ve) {
return job, false, err
}
s.reportModuleBug(c, name, len(ve.Problems))
msg := fmt.Sprintf("module %q built an invalid receipt", name)
return job, false, newAPIError(codeModuleFailed.withMessage(msg), ve.Problems...)
}
return job, false, nil
}
// moduleQuery reads the query parameters of a module route: copies, 1 to
// receipt.MaxCopies, and printer, which only "default" may name while one
// printer is configured. Each may be given once. Any other parameter is
// refused, so that a misspelt one is not silently ignored. copies is 0 when
// the query does not set it.
func moduleQuery(c fiber.Ctx) (int, error) {
copies := 0
seen := make(map[string]bool)
for key, value := range c.Request().URI().QueryArgs().All() {
name := string(key)
if seen[name] {
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("query parameter %q is given more than once", name)))
}
seen[name] = true
switch name {
case "copies":
n, err := strconv.Atoi(string(value))
if err != nil || n < 1 || n > receipt.MaxCopies {
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("copies must be 1-%d", receipt.MaxCopies)))
}
copies = n
case "printer":
if p := string(value); p != "" && p != defaultPrinter {
msg := fmt.Sprintf("printer %q is not configured; the only printer is %q", p, defaultPrinter)
return 0, newAPIError(codeUnknownPrinter.withMessage(msg))
}
default:
return 0, newAPIError(codeInvalidQuery.withMessage(fmt.Sprintf("unknown query parameter %q; module routes take copies and printer", name)))
}
}
return copies, nil
}
// reportModuleBug logs and reports a module that built a job validation
// refuses. The problems themselves are left out, since they can quote the
// payload.
func (s *Server) reportModuleBug(c fiber.Ctx, name string, problems int) {
s.logger.LogAttrs(c.Context(), slog.LevelError, "module built an invalid receipt",
slog.String("module", name),
slog.Int("problems", problems),
slog.String("path", c.Path()),
slog.String("request_id", requestid.FromContext(c)),
)
hubFrom(c).CaptureException(fmt.Errorf("module %s built an invalid receipt (%d problems)", name, problems))
}
@@ -0,0 +1,286 @@
package server
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/gofiber/fiber/v3"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
// fakeModule answers according to its body: "skip", "payload", "invalid"
// and "fail" give those outcomes, and any other body prints as one line of
// text with the build time.
type fakeModule struct{}
func (fakeModule) Name() string { return "fake" }
func (fakeModule) Description() string { return "Prints its body" }
func (fakeModule) Build(_ context.Context, body []byte, env modules.Env) (receipt.Job, error) {
switch string(body) {
case "skip":
return receipt.Job{}, modules.ErrSkip
case "payload":
return receipt.Job{}, &modules.PayloadError{Problems: []string{"text: required", "done[0]: index 5 is out of range"}}
case "invalid":
return receipt.Job{Elements: []receipt.Element{{Type: "box"}, {Type: "kv"}}}, nil
case "fail":
return receipt.Job{}, errors.New("module broke")
}
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: string(body) + " at " + env.Stamp()}}}, nil
}
func moduleRequest(t *testing.T, target, body string) *http.Request {
t.Helper()
req := httptest.NewRequest(http.MethodPost, target, strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+validToken(t))
return req
}
const shoppingNote = `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
func TestModulePrintAccepted(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := do(t, s, moduleRequest(t, "/api/v1/print/fake?copies=2&printer=default", "hello"))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("status = %d (%v)", resp.StatusCode, body)
}
if body["id"] != "job_01h455vb4pex5vsknk084sn02q" || body["status"] != "queued" {
t.Errorf("body = %v", body)
}
if loc := resp.Header.Get("Location"); loc != "/api/v1/jobs/job_01h455vb4pex5vsknk084sn02q" {
t.Errorf("Location = %q", loc)
}
if len(jobs.submitted) != 1 {
t.Fatalf("submitted %d jobs", len(jobs.submitted))
}
job := jobs.submitted[0]
if job.Copies != 2 || job.Elements[0].Text != "hello at 29 Nov 21:04" {
t.Errorf("submitted %+v; want 2 copies of the text with the build time", job)
}
}
func TestModuleNotePrints(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
for _, target := range []string{"/api/v1/print/note", "/api/v1/print/note?printer="} {
resp, body := send(t, s, moduleRequest(t, target, shoppingNote))
if resp.StatusCode != http.StatusAccepted {
t.Fatalf("%s: status = %d (%s)", target, resp.StatusCode, body)
}
}
if len(jobs.submitted) != 2 {
t.Fatalf("submitted %d jobs, want 2", len(jobs.submitted))
}
box := jobs.submitted[0].Elements[0]
if box.Type != "box" || box.Title != "Shopping" || box.Footer != "29 Nov 21:04" || jobs.submitted[0].Copies != 0 {
t.Errorf("submitted %+v", jobs.submitted[0])
}
}
func TestModuleSkip(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s := newTestServer(t, jobs, &fakePrinter{})
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
resp, body := send(t, s, moduleRequest(t, target, "skip"))
if resp.StatusCode != http.StatusNoContent || len(body) != 0 {
t.Errorf("%s: status = %d, body %q; want 204 and no body", target, resp.StatusCode, body)
}
}
if len(jobs.submitted) != 0 {
t.Error("a skipped payload was queued")
}
}
func TestModuleRefusals(t *testing.T) {
tests := []struct {
name, target, body string
status int
code, message string
details []string
}{
{"payload problems", "/api/v1/print/fake", "payload", 400, "invalid_payload", `invalid payload for module "fake"`,
[]string{"text: required", "done[0]: index 5 is out of range"}},
{"note payload problems", "/api/v1/print/note", `{"title":"x","colour":"red"}`, 400, "invalid_payload", `invalid payload for module "note"`,
[]string{"colour: unknown field"}},
{"note without text", "/api/v1/preview/note", `{"title":"x"}`, 400, "invalid_payload", `invalid payload for module "note"`,
[]string{"text: required"}},
{"unknown module", "/api/v1/print/notx", "hello", 404, "module_not_found", `module "notx" not found`, nil},
{"unknown module on preview", "/api/v1/preview/notx?copies=9", "hello", 404, "module_not_found", `module "notx" not found`, nil},
{"another printer", "/api/v1/print/fake?printer=office", "hello", 400, "unknown_printer",
`printer "office" is not configured; the only printer is "default"`, nil},
{"another printer on preview", "/api/v1/preview/fake?printer=Default", "hello", 400, "unknown_printer",
`printer "Default" is not configured; the only printer is "default"`, nil},
{"no copies", "/api/v1/print/fake?copies=0", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"too many copies", "/api/v1/print/fake?copies=6", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"copies not a number", "/api/v1/print/fake?copies=two", "hello", 400, "invalid_query", "copies must be 1-5", nil},
{"copies twice", "/api/v1/print/fake?copies=1&copies=2", "hello", 400, "invalid_query", `query parameter "copies" is given more than once`, nil},
{"unknown parameter", "/api/v1/print/fake?copy=2", "hello", 400, "invalid_query",
`unknown query parameter "copy"; module routes take copies and printer`, nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
jobs := &fakeJobs{nextID: newJobID(t)}
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, tt.target, tt.body))
e := expectError(t, resp, raw, tt.status, tt.code)
if e.Error != tt.message {
t.Errorf("error = %q, want %q", e.Error, tt.message)
}
if strings.Join(e.Details, "\n") != strings.Join(tt.details, "\n") {
t.Errorf("details = %q, want %q", e.Details, tt.details)
}
if len(jobs.submitted) != 0 {
t.Error("a refused request was queued")
}
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
t.Errorf("a refusal was logged as a failure: %v", failures)
}
})
}
}
// A module that builds a job validation refuses has a bug: the client gets
// 422 with the problems, and the bug is logged and reported once, without
// the problems, which can quote the payload.
func TestModuleBuiltAnInvalidJob(t *testing.T) {
for _, target := range []string{"/api/v1/print/fake", "/api/v1/preview/fake"} {
t.Run(target, func(t *testing.T) {
events := captureSentryEvents(t)
jobs := &fakeJobs{nextID: newJobID(t)}
s, logs := newLoggedServer(t, jobs, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, target, "invalid"))
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "module_failed")
want := []string{
"elements[0] (box): text or children is required",
"elements[1] (kv): pairs: at least one pair is required",
}
if e.Error != `module "fake" built an invalid receipt` || strings.Join(e.Details, "\n") != strings.Join(want, "\n") {
t.Errorf("error = %q, details = %q", e.Error, e.Details)
}
if len(jobs.submitted) != 0 {
t.Error("an invalid job was queued")
}
failures := errorLines(logs.lines(t))
if len(failures) != 1 || failures[0]["msg"] != "module built an invalid receipt" ||
failures[0]["module"] != "fake" || failures[0]["problems"] != float64(2) {
t.Errorf("error lines = %v, want one for the module", failures)
}
logs.mu.Lock()
logged := logs.buf.String()
logs.mu.Unlock()
if strings.Contains(logged, "pairs: at least one") {
t.Error("the problems were logged")
}
if n := events.count(); n != 1 {
t.Errorf("%d Sentry events, want 1", n)
}
})
}
}
func TestModuleUnexpectedError(t *testing.T) {
events := captureSentryEvents(t)
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
resp, raw := send(t, s, moduleRequest(t, "/api/v1/print/fake", "fail"))
expectError(t, resp, raw, http.StatusInternalServerError, "internal_error")
failures := errorLines(logs.lines(t))
if len(failures) != 1 || failures[0]["err"] != "module fake: module broke" {
t.Errorf("error lines = %v", failures)
}
if n := events.count(); n != 1 {
t.Errorf("%d Sentry events, want 1", n)
}
}
func TestModuleQueueRefusals(t *testing.T) {
tests := []struct {
err error
code string
wantRetryAfter bool
}{
{printqueue.ErrQueueFull, "queue_full", true},
{printqueue.ErrClosed, "shutting_down", false},
}
for _, tt := range tests {
t.Run(tt.code, func(t *testing.T) {
s := newTestServer(t, &fakeJobs{submitErr: tt.err}, &fakePrinter{})
resp, body := send(t, s, moduleRequest(t, "/api/v1/print/note", shoppingNote))
expectError(t, resp, body, http.StatusServiceUnavailable, tt.code)
if got := resp.Header.Get("Retry-After") == "10"; got != tt.wantRetryAfter {
t.Errorf("Retry-After = %q", resp.Header.Get("Retry-After"))
}
})
}
}
func TestModuleList(t *testing.T) {
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
req := httptest.NewRequest(http.MethodGet, "/api/v1/modules", nil)
req.Header.Set("Authorization", "Bearer "+validToken(t))
resp, body := send(t, s, req)
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := `[{"name":"fake","description":"Prints its body"},{"name":"note","description":"Boxed note with an optional checklist"}]`
if string(body) != want {
t.Errorf("body = %s, want %s", body, want)
}
if cc := resp.Header.Get(fiber.HeaderCacheControl); cc != "no-store" {
t.Errorf("Cache-Control = %q, want no-store", cc)
}
}
func TestModulePreview(t *testing.T) {
jobs := &fakeJobs{}
s := newTestServer(t, jobs, &fakePrinter{})
resp, body := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
if resp.StatusCode != http.StatusOK {
t.Fatalf("status = %d (%s)", resp.StatusCode, body)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if string(body) != want {
t.Errorf("body =\n%s\nwant\n%s", body, want)
}
if len(jobs.submitted) != 0 {
t.Error("a preview was queued for printing")
}
req := moduleRequest(t, "/api/v1/preview/fake?copies=3", "hi")
req.Header.Set("Accept", "application/json")
resp, raw := do(t, s, req)
if resp.StatusCode != http.StatusOK || raw["line_count"] != float64(3) {
t.Errorf("status %d, body %v; want three copies of one line", resp.StatusCode, raw)
}
}
func TestModulePreviewTooManyLines(t *testing.T) {
s, logs := newLoggedServer(t, &fakeJobs{}, &fakePrinter{})
s.previewer = testRenderer(5)
resp, raw := send(t, s, moduleRequest(t, "/api/v1/preview/note", shoppingNote))
e := expectError(t, resp, raw, http.StatusUnprocessableEntity, "too_many_lines")
if e.Error != "receipt would print 8 lines, limit is 5" {
t.Errorf("error = %q", e.Error)
}
if failures := errorLines(logs.lines(t)); len(failures) != 0 {
t.Errorf("a refusal was logged as a failure: %v", failures)
}
}
@@ -19,6 +19,12 @@ func (s *Server) handlePreview(c fiber.Ctx) error {
if err != nil {
return err
}
return s.preview(c, job)
}
// preview answers with the lines a validated job would print, as
// handlePreview describes.
func (s *Server) preview(c fiber.Ctx, job receipt.Job) error {
preview, err := s.previewer.Preview(c.Context(), job)
var limit *receipt.LineLimitError
switch {
+71
View File
@@ -229,9 +229,80 @@ func Routes() []Route {
errors: []errorCode{codeJobNotFound},
handle: (*Server).handleJob,
},
{
Method: http.MethodPost,
Path: BasePath + "/print/{module}",
OperationID: "printModule",
Summary: "Queue the receipt a module builds from its payload",
Description: "The module named in the path builds a receipt from the body, its own payload, " +
"which is decoded strictly: an unknown field or one of the wrong type is refused, with " +
"every problem listed. The receipt is then validated and queued as on /api/v1/print. A " +
"module with nothing to print answers 204.",
Tag: "modules",
Auth: true,
Request: modulePayload{},
Params: moduleParams,
Responses: []Response{
{Status: http.StatusAccepted, Description: "The receipt is queued",
Content: []Content{{MediaType: mediaJSON, Body: printqueue.Status{}}},
Headers: []Header{{Name: fiber.HeaderLocation, Description: "The job's URL, which answers " +
"with its status."}}},
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeQueueFull, codeShuttingDown},
handle: (*Server).handlePrintModule,
},
{
Method: http.MethodPost,
Path: BasePath + "/preview/{module}",
OperationID: "previewModule",
Summary: "Show the lines a module's receipt prints, without printing it",
Description: "Builds the receipt as /api/v1/print/{module} does and answers as /api/v1/preview " +
"does: JSON with the lines' styles when the Accept header prefers application/json to " +
"text/plain, and plain text otherwise. It prints nothing and fetches no images.",
Tag: "modules",
Auth: true,
Request: modulePayload{},
Params: moduleParams,
Responses: []Response{
{Status: http.StatusOK, Description: "The lines the printer would print",
Content: []Content{
{MediaType: mediaText, Body: ""},
{MediaType: mediaJSON, Body: previewResponse{}},
}},
{Status: http.StatusNoContent, Description: "The module had nothing to print"},
},
errors: []errorCode{codeInvalidPayload, codeInvalidQuery, codeUnknownPrinter, codeModuleNotFound,
codeModuleFailed, codeTooManyLines},
handle: (*Server).handlePreviewModule,
},
{
Method: http.MethodGet,
Path: BasePath + "/modules",
OperationID: "listModules",
Summary: "List the modules",
Description: "Every module the module routes take, sorted by name.",
Tag: "modules",
Auth: true,
Responses: []Response{{Status: http.StatusOK, Description: "The modules",
Content: []Content{{MediaType: mediaJSON, Body: moduleList{}}}}},
handle: (*Server).handleModules,
},
}
}
// moduleParams are the parameters of the module routes.
var moduleParams = []Param{
{Name: "module", In: "path", Required: true,
Description: "The module's name, e.g. note. GET /api/v1/modules lists them."},
{Name: "copies", In: "query",
Description: "How many copies to print, each cut separately: a whole number, 1-5. Default 1."},
{Name: "printer", In: "query",
Description: "Reserved for a second printer: only default is accepted. Any other query parameter " +
"is refused."},
}
// pathParam finds the {name} parameters in a route path.
var pathParam = regexp.MustCompile(`\{([^/{}]+)\}`)
+25 -1
View File
@@ -17,6 +17,7 @@ import (
"github.com/gofiber/fiber/v3/middleware/requestid"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
)
@@ -41,11 +42,22 @@ type Previewer interface {
Preview(ctx context.Context, job receipt.Job) (receipt.Preview, error)
}
// Modules are the modules the module routes build jobs with.
type Modules interface {
Get(name string) (modules.Module, bool)
List() []modules.Info
}
// Deps are the services the handlers use.
type Deps struct {
Jobs Jobs
Printer Printer
Previewer Previewer
Modules Modules
// ModuleEnv returns what a module may know when it builds a job: the
// time now, and the zone and layout times print in.
ModuleEnv func() modules.Env
}
// Info describes the running build for the index route.
@@ -100,6 +112,8 @@ type Server struct {
jobs Jobs
printer Printer
previewer Previewer
modules Modules
moduleEnv func() modules.Env
logger *slog.Logger
}
@@ -108,6 +122,8 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
switch {
case deps.Jobs == nil || deps.Printer == nil || deps.Previewer == nil || logger == nil:
panic("server.New: jobs, printer, previewer and logger must not be nil")
case deps.Modules == nil || deps.ModuleEnv == nil:
panic("server.New: modules and module env must not be nil")
case len(config.Secret) == 0:
panic("server.New: secret must not be empty")
case config.RequestID == nil:
@@ -116,7 +132,15 @@ func New(config Config, deps Deps, logger *slog.Logger) *Server {
if config.HealthRecheckDelay <= 0 {
config.HealthRecheckDelay = defaultHealthRecheckDelay
}
s := &Server{config: config, jobs: deps.Jobs, printer: deps.Printer, previewer: deps.Previewer, logger: logger}
s := &Server{
config: config,
jobs: deps.Jobs,
printer: deps.Printer,
previewer: deps.Previewer,
modules: deps.Modules,
moduleEnv: deps.ModuleEnv,
logger: logger,
}
s.app = fiber.New(fiber.Config{
AppName: config.Info.Project,
+39 -4
View File
@@ -22,6 +22,7 @@ import (
"github.com/golang-jwt/jwt/v5"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/printer"
"uberbringer/internal/pkg/printqueue"
"uberbringer/internal/pkg/receipt"
@@ -135,7 +136,22 @@ func newServer(t *testing.T, jobs *fakeJobs, p Printer, logger *slog.Logger, opt
for _, opt := range opts {
opt(&cfg)
}
return New(cfg, Deps{Jobs: jobs, Printer: p, Previewer: testRenderer(2000)}, logger)
registry, err := modules.NewRegistry(fakeModule{}, modules.Note())
if err != nil {
t.Fatal(err)
}
return New(cfg, Deps{
Jobs: jobs,
Printer: p,
Previewer: testRenderer(2000),
Modules: registry,
ModuleEnv: testModuleEnv,
}, logger)
}
// testModuleEnv is 29 Nov 2026 21:04 UTC.
func testModuleEnv() modules.Env {
return modules.Env{Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC), Location: time.UTC, TimeLayout: "02 Jan 15:04"}
}
// testRenderer is a TM-T88 renderer in CP437 that previews jobs of up to
@@ -709,9 +725,12 @@ func TestRoutesConform(t *testing.T) {
}
// Each authenticated route maps to a path that reaches it.
authenticated := map[string]string{
"POST /api/v1/print": "/api/v1/print",
"POST /api/v1/preview": "/api/v1/preview",
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
"POST /api/v1/print": "/api/v1/print",
"POST /api/v1/preview": "/api/v1/preview",
"POST /api/v1/print/:module": "/api/v1/print/fake",
"POST /api/v1/preview/:module": "/api/v1/preview/fake",
"GET /api/v1/modules": "/api/v1/modules",
"GET /api/v1/jobs/:id": "/api/v1/jobs/" + id.String(),
}
s := newTestServer(t, &fakeJobs{}, &fakePrinter{})
@@ -909,6 +928,22 @@ func TestRefusalsAreNotLoggedAsFailures(t *testing.T) {
status: http.StatusUnauthorized,
level: slog.LevelInfo,
},
{
name: "invalid module payload",
jobs: &fakeJobs{},
printer: &fakePrinter{},
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/note", `{"title":"x"}`) },
status: http.StatusBadRequest,
level: slog.LevelInfo,
},
{
name: "unknown module",
jobs: &fakeJobs{},
printer: &fakePrinter{},
request: func(t *testing.T) *http.Request { return moduleRequest(t, "/api/v1/print/notx", `{}`) },
status: http.StatusNotFound,
level: slog.LevelInfo,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
+27 -1
View File
@@ -118,6 +118,13 @@ type FormatConfig struct {
// MaxLines fails a job that would print more lines, all copies
// counted. It is a backstop against runaway text.
MaxLines int `mapstructure:"max_lines"`
// Timezone is the zone the times modules print are in: an IANA name
// such as "Europe/London", "UTC", or "Local" for the host's zone.
Timezone string `mapstructure:"timezone"`
// TimeLayout is the Go time layout those times are printed in.
TimeLayout string `mapstructure:"time_layout"`
}
// QueueConfig configures the print queue.
@@ -192,7 +199,9 @@ func Default() Config {
RetryDelay: time.Second,
},
Format: FormatConfig{
MaxLines: 2000,
MaxLines: 2000,
Timezone: "Local",
TimeLayout: "02 Jan 15:04",
},
Queue: QueueConfig{
Size: 100,
@@ -574,6 +583,13 @@ func (c *Config) Validate() error {
check(p.RetryDelay > 0, "printer.retry_delay must be positive")
check(c.Format.MaxLines > 0, "format.max_lines must be positive")
if c.Format.Timezone == "" {
errs = append(errs, errors.New(`format.timezone is required: an IANA name such as "Europe/London", "UTC" or "Local"`))
} else if _, err := time.LoadLocation(c.Format.Timezone); err != nil {
errs = append(errs, fmt.Errorf(`format.timezone: %q is not a known time zone; use an IANA name such as "Europe/London", "UTC" or "Local"`, c.Format.Timezone))
}
check(showsTime(c.Format.TimeLayout),
`format.time_layout: %q shows no date or time; write it in Go's layout, such as "02 Jan 15:04"`, c.Format.TimeLayout)
check(c.Queue.Size > 0, "queue.size must be positive")
check(c.Queue.History >= 0, "queue.history must not be negative")
@@ -592,6 +608,16 @@ func (c *Config) Validate() error {
return errors.Join(errs...)
}
// showsTime reports whether layout prints something of the time it
// formats: two times that differ in every field format differently. A
// layout with none of Go's reference values, such as "HH:MM", prints
// itself.
func showsTime(layout string) bool {
a := time.Date(2001, 2, 3, 4, 5, 6, 0, time.UTC)
b := time.Date(2012, 11, 22, 16, 47, 58, 0, time.FixedZone("X", 3600))
return a.Format(layout) != b.Format(layout)
}
func validPort(port int) bool {
return port >= 1 && port <= 65535
}
+41 -1
View File
@@ -7,6 +7,9 @@ import (
"testing"
"time"
// Embeds the zone database, so that IANA names load on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/config"
)
@@ -53,6 +56,9 @@ func TestLoadInstallScriptConfigGetsDefaults(t *testing.T) {
if cfg.Format.MaxLines != 2000 || cfg.Printer.BoxLineSpacing != 0 {
t.Errorf("format defaults not applied: max_lines %d, box_line_spacing %d", cfg.Format.MaxLines, cfg.Printer.BoxLineSpacing)
}
if cfg.Format.Timezone != "Local" || cfg.Format.TimeLayout != "02 Jan 15:04" {
t.Errorf("format defaults not applied: timezone %q, time_layout %q", cfg.Format.Timezone, cfg.Format.TimeLayout)
}
}
func TestLoadOverridesAndDurations(t *testing.T) {
@@ -66,6 +72,8 @@ paper_width = 384
box_line_spacing = 24
[format]
max_lines = 500
timezone = "Europe/London"
time_layout = "2006-01-02 15:04"
[images]
allowed_hosts = ["images.lan"]
[sentry]
@@ -77,6 +85,9 @@ format = "json"
if err != nil {
t.Fatalf("Load: %v", err)
}
if cfg.Format.Timezone != "Europe/London" || cfg.Format.TimeLayout != "2006-01-02 15:04" {
t.Errorf("format = %+v", cfg.Format)
}
if cfg.Printer.DialTimeout != 750*time.Millisecond {
t.Errorf("DialTimeout = %v, want 750ms", cfg.Printer.DialTimeout)
}
@@ -154,6 +165,31 @@ func TestLoadErrors(t *testing.T) {
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\nbox_line_spacing = 256\n",
wantErr: "printer.box_line_spacing must be 0-255",
},
{
name: "unknown time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"Europe/Londn\"\n",
wantErr: `format.timezone: "Europe/Londn" is not a known time zone`,
},
{
name: "time zone that is a path",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"../etc/passwd\"\n",
wantErr: "format.timezone",
},
{
name: "empty time zone",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntimezone = \"\"\n",
wantErr: "format.timezone is required",
},
{
name: "time layout without a time",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"HH:MM\"\n",
wantErr: `format.time_layout: "HH:MM" shows no date or time`,
},
{
name: "empty time layout",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\ntime_layout = \"\"\n",
wantErr: "format.time_layout",
},
{
name: "unknown format key",
body: "[api]\nsecret = \"" + validSecret + "\"\n[printer]\naddress = \"p\"\n[format]\nmax_line = 10\n",
@@ -289,7 +325,8 @@ func TestExampleConfigLoads(t *testing.T) {
}
if def := config.Default(); cfg.WebServer.RateLimit != def.WebServer.RateLimit ||
cfg.Images.MaxBytes != def.Images.MaxBytes || cfg.Printer.Model != def.Printer.Model ||
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing {
cfg.Format.MaxLines != def.Format.MaxLines || cfg.Printer.BoxLineSpacing != def.Printer.BoxLineSpacing ||
cfg.Format.Timezone != def.Format.Timezone || cfg.Format.TimeLayout != def.Format.TimeLayout {
t.Error("example config values drifted from the defaults it documents")
}
}
@@ -447,6 +484,7 @@ func TestLoadEnvironmentErrors(t *testing.T) {
{"only spaces", "UBERBRINGER_IMAGES_ALLOWED_HOSTS", " ", "UBERBRINGER_IMAGES_ALLOWED_HOSTS holds only spaces"},
{"trailing comma", "UBERBRINGER_WEBSERVER_TRUSTED_PROXIES", "10.0.0.1,", "a list item is empty"},
{"number for a flag", "UBERBRINGER_SENTRY_DEBUG", "1", "expected true or false"},
{"unknown time zone", "UBERBRINGER_FORMAT_TIMEZONE", "Mars/Olympus", "format.timezone"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -480,6 +518,8 @@ func TestValue(t *testing.T) {
{key: "webserver.trusted_proxies", want: "127.0.0.1,::1"},
{key: "images.allowed_hosts", want: "a.lan,b.lan"},
{key: "images.allow_private_networks", want: "false"},
{key: "format.timezone", want: "Local"},
{key: "format.time_layout", want: "02 Jan 15:04"},
{key: "printer", wantErr: `"printer" is a section`},
{key: "printer.adress", wantErr: `unknown key "printer.adress"`},
{key: "printer.port.x", wantErr: `unknown key "printer.port.x"`},
+128
View File
@@ -0,0 +1,128 @@
package modules
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"reflect"
"slices"
"strconv"
"strings"
)
// maxNameInProblem caps how much of an unknown field's name a problem
// repeats.
const maxNameInProblem = 64
// DecodeStrict decodes body, which must be one JSON object, into the struct
// v points to. A name must match a field's json tag exactly, so a name in
// another case is unknown. Every problem is reported at once, in a
// *PayloadError: a body that is not one JSON object, each unknown field and
// each field of the wrong type. A field that is null counts as absent.
func DecodeStrict(body []byte, v any) error {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.Elem().Kind() != reflect.Struct {
panic("modules.DecodeStrict: v must point to a struct")
}
var object map[string]json.RawMessage
dec := json.NewDecoder(bytes.NewReader(body))
if err := dec.Decode(&object); err != nil {
return &PayloadError{Problems: []string{bodyProblem(err)}}
}
if object == nil {
return &PayloadError{Problems: []string{"body: expected a JSON object, got null"}}
}
if _, err := dec.Token(); !errors.Is(err, io.EOF) {
return &PayloadError{Problems: []string{"body: trailing data after the payload"}}
}
target := rv.Elem()
fields := jsonFields(target.Type())
var problems []string
for _, name := range slices.Sorted(maps.Keys(object)) {
index, ok := fields[name]
if !ok {
problems = append(problems, fieldName(name)+": unknown field")
continue
}
field := target.Field(index)
if err := json.Unmarshal(object[name], field.Addr().Interface()); err != nil {
problems = append(problems, fmt.Sprintf("%s: expected %s", name, describe(field.Type())))
}
}
if len(problems) > 0 {
return &PayloadError{Problems: problems}
}
return nil
}
// bodyProblem describes why a body is not a JSON object.
func bodyProblem(err error) string {
var typeErr *json.UnmarshalTypeError
switch {
case errors.Is(err, io.EOF):
return "body: empty; expected a JSON object"
case errors.As(err, &typeErr):
return "body: expected a JSON object, got " + typeErr.Value
}
return "body: not valid JSON: " + err.Error()
}
// jsonFields maps the json name of each exported field of the struct type t
// to its index.
func jsonFields(t reflect.Type) map[string]int {
fields := make(map[string]int, t.NumField())
for i := range t.NumField() {
f := t.Field(i)
name, _, _ := strings.Cut(f.Tag.Get("json"), ",")
if !f.IsExported() || name == "-" {
continue
}
if name == "" {
name = f.Name
}
fields[name] = i
}
return fields
}
// fieldName shows a field name from a payload in a problem: as written when
// it is a plain name, quoted otherwise, and cut when it is long.
func fieldName(name string) string {
plain := name != "" && strings.Trim(name, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-") == ""
if r := []rune(name); len(r) > maxNameInProblem {
name = string(r[:maxNameInProblem]) + "..."
}
if plain {
return name
}
return strconv.Quote(name)
}
// describe names the JSON a field of type t takes.
func describe(t reflect.Type) string {
switch t.Kind() {
case reflect.Pointer:
return describe(t.Elem())
case reflect.String:
return "a string"
case reflect.Bool:
return "true or false"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "a whole number"
case reflect.Slice:
switch t.Elem().Kind() {
case reflect.String:
return "an array of strings"
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return "an array of whole numbers"
}
return "an array"
}
return t.String()
}
+88
View File
@@ -0,0 +1,88 @@
package modules_test
import (
"errors"
"strings"
"testing"
"uberbringer/internal/pkg/modules"
)
type decodeTarget struct {
Name string `json:"name"`
Count int `json:"count"`
On *bool `json:"on"`
Tags []string `json:"tags"`
Marks []int `json:"marks"`
Skip string `json:"-"`
}
func TestDecodeStrict(t *testing.T) {
var got decodeTarget
body := `{"name":"n","count":3,"on":false,"tags":["a","b"],"marks":[1,2],"count":4}`
if err := modules.DecodeStrict([]byte(body), &got); err != nil {
t.Fatal(err)
}
if got.Name != "n" || got.Count != 4 || got.On == nil || *got.On || strings.Join(got.Tags, ",") != "a,b" || len(got.Marks) != 2 {
t.Errorf("decoded %+v", got)
}
var empty decodeTarget
if err := modules.DecodeStrict([]byte(` {"name": null} `), &empty); err != nil || empty.Name != "" {
t.Errorf("a null field: %v, %+v; want it treated as absent", err, empty)
}
}
func TestDecodeStrictProblems(t *testing.T) {
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"empty body", "", []string{"body: empty; expected a JSON object"}},
{"blank body", " \n", []string{"body: empty; expected a JSON object"}},
{"array", `[1]`, []string{"body: expected a JSON object, got array"}},
{"string", `"x"`, []string{"body: expected a JSON object, got string"}},
{"null", `null`, []string{"body: expected a JSON object, got null"}},
{"syntax error", `{"name":`, []string{"body: not valid JSON: unexpected EOF"}},
{"trailing data", `{} {}`, []string{"body: trailing data after the payload"}},
{"every problem at once", `{"Name":"x","colour":1,"count":"3","on":"yes","tags":[1],"marks":[1.5],"hidden":"h","Skip":"s","-":1}`, []string{
"-: unknown field",
"Name: unknown field",
"Skip: unknown field",
"colour: unknown field",
"count: expected a whole number",
"hidden: unknown field",
"marks: expected an array of whole numbers",
"on: expected true or false",
"tags: expected an array of strings",
}},
{"number too large", `{"count":1e400}`, []string{"count: expected a whole number"}},
{"odd field names are quoted and cut", `{"a b":1,"` + strings.Repeat("x", 70) + `":2}`, []string{
`"a b": unknown field`,
strings.Repeat("x", 64) + "...: unknown field",
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var v decodeTarget
err := modules.DecodeStrict([]byte(tt.body), &v)
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
func TestDecodeStrictNeedsAStruct(t *testing.T) {
defer func() {
if recover() == nil {
t.Error("DecodeStrict into a map did not panic")
}
}()
var m map[string]any
_ = modules.DecodeStrict([]byte(`{}`), &m)
}
+108
View File
@@ -0,0 +1,108 @@
package modules
import (
"context"
"fmt"
"strings"
"uberbringer/internal/pkg/receipt"
)
// noteStyles are the box styles a note may ask for.
var noteStyles = []string{"single", "double", "double-h", "double-v"}
// Note returns the note module: a box with an optional title, the text and
// an optional checklist, stamped with the time in its bottom border.
func Note() Module {
return note{}
}
type note struct{}
// notePayload is the body of a note.
type notePayload struct {
Title string `json:"title"`
Text string `json:"text"`
Items []string `json:"items"`
Done []int `json:"done"`
Style string `json:"style"`
Footer string `json:"footer"`
Stamp *bool `json:"stamp"`
}
func (note) Name() string { return "note" }
func (note) Description() string { return "Boxed note with an optional checklist" }
// Build lays the note out as a box: the text, then, when there are items,
// an empty line and a checklist. The footer is the payload's, or the build
// time unless stamp is false.
func (note) Build(_ context.Context, body []byte, env Env) (receipt.Job, error) {
var p notePayload
if err := DecodeStrict(body, &p); err != nil {
return receipt.Job{}, err
}
if problems := p.problems(); len(problems) > 0 {
return receipt.Job{}, &PayloadError{Problems: problems}
}
children := []receipt.Element{{Type: receipt.TypeText, Text: p.Text}}
if len(p.Items) > 0 {
children = append(children,
receipt.Element{Type: receipt.TypeFeed},
receipt.Element{Type: receipt.TypeList, Bullet: "checkbox", Items: p.Items, Done: p.Done},
)
}
footer := p.Footer
if footer == "" && (p.Stamp == nil || *p.Stamp) {
footer = env.Stamp()
}
box := receipt.Element{
Type: receipt.TypeBox,
Title: p.Title,
Style: strings.ToLower(p.Style),
Footer: footer,
Children: children,
}
return receipt.Job{Elements: []receipt.Element{box}}, nil
}
// problems checks what the box and its list would refuse, in the payload's
// own terms.
func (p notePayload) problems() []string {
var problems []string
if strings.TrimSpace(p.Text) == "" {
problems = append(problems, "text: required")
}
if p.Style != "" && !containsFold(noteStyles, p.Style) {
problems = append(problems, "style: must be "+strings.Join(noteStyles[:len(noteStyles)-1], ", ")+" or "+noteStyles[len(noteStyles)-1])
}
if n := len(p.Items); n > receipt.MaxItems {
problems = append(problems, fmt.Sprintf("items: %d items, limit is %d", n, receipt.MaxItems))
}
for i, item := range p.Items {
if item == "" {
problems = append(problems, fmt.Sprintf("items[%d]: must not be empty", i))
}
}
seen := make(map[int]bool, len(p.Done))
for i, index := range p.Done {
switch {
case index < 0 || index >= len(p.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
}
func containsFold(list []string, s string) bool {
for _, item := range list {
if strings.EqualFold(item, s) {
return true
}
}
return false
}
+244
View File
@@ -0,0 +1,244 @@
package modules_test
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"time"
// Embeds the zone database, so that Europe/London loads on any host.
_ "time/tzdata"
"uberbringer/internal/pkg/escpos"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
var update = flag.Bool("update", false, "rewrite testdata/note/*.txt from the current output")
// fixedEnv is 29 Nov 2026 21:04:05 UTC in Europe/London, which is on GMT
// then.
func fixedEnv(t *testing.T) modules.Env {
t.Helper()
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
return modules.Env{
Now: time.Date(2026, 11, 29, 21, 4, 5, 0, time.UTC),
Location: london,
TimeLayout: "02 Jan 15:04",
}
}
// previewText previews job on a TM-T88 in CP437: its lines, then its
// warnings.
func previewText(t *testing.T, job receipt.Job) string {
t.Helper()
profile, err := escpos.LookupProfile("tm-t88")
if err != nil {
t.Fatal(err)
}
r := receipt.NewRenderer(receipt.Options{
Profile: profile, CodePage: escpos.CodePage437, MaxPixels: 1000, MaxHeight: 1000, MaxLines: 2000,
}, noFetch{})
p, err := r.Preview(context.Background(), job)
if err != nil {
t.Fatalf("Preview: %v", err)
}
var b strings.Builder
for _, l := range p.Lines {
b.WriteString(l.Text)
b.WriteByte('\n')
}
if len(p.Warnings) > 0 {
b.WriteString("=== warnings\n")
for _, w := range p.Warnings {
b.WriteString(w)
b.WriteByte('\n')
}
}
return b.String()
}
type noFetch struct{}
func (noFetch) Fetch(context.Context, string) ([]byte, error) {
return nil, errors.New("previews do not fetch")
}
// TestNoteGoldens builds each testdata/note/*.json payload with a fixed
// clock and compares its preview with NAME.txt. Run with -update to rewrite
// the .txt files, then review the diff.
func TestNoteGoldens(t *testing.T) {
paths, err := filepath.Glob(filepath.Join("testdata", "note", "*.json"))
if err != nil {
t.Fatal(err)
}
if len(paths) == 0 {
t.Fatal("no payloads in testdata/note")
}
for _, path := range paths {
name := strings.TrimSuffix(filepath.Base(path), ".json")
t.Run(name, func(t *testing.T) {
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
job, err := modules.Note().Build(context.Background(), body, fixedEnv(t))
if err != nil {
t.Fatalf("Build: %v", err)
}
if err := job.Validate(); err != nil {
t.Fatalf("the note built an invalid job: %v", err)
}
got := previewText(t, job)
golden := filepath.Join("testdata", "note", name+".txt")
if *update {
if err := os.WriteFile(golden, []byte(got), 0o644); err != nil {
t.Fatal(err)
}
return
}
want, err := os.ReadFile(golden)
if err != nil {
t.Fatalf("%v (run go test -run TestNoteGoldens -update)", err)
}
if got != string(want) {
t.Errorf("preview differs from %s:\ngot:\n%s\nwant:\n%s", golden, got, want)
}
})
}
}
// TestNoteMockup pins the note the formatters plan shows as mockup 5.
func TestNoteMockup(t *testing.T) {
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Fatal(err)
}
want := "" +
"┌─ Shopping ─────────────────────────────┐\n" +
"│ Milk, eggs and the good bread from the │\n" +
"│ bakery on Elm St. │\n" +
"│ │\n" +
"│ [ ] Milk │\n" +
"│ [ ] Eggs │\n" +
"│ [√] Bread │\n" +
"└──────────────────────── 29 Nov 21:04 ──┘\n" +
" - - - - - - - partial cut - - - - - - - -\n"
if got := previewText(t, job); got != want {
t.Errorf("preview:\n%s\nwant:\n%s", got, want)
}
}
// TestNoteBuildsThePaperJob checks that the note still builds the job whose
// printed result was checked on the TM-T88IV, and whose bytes the receipt
// package pins: the shopping note, built at 08:56 on a host at UTC-6.
func TestNoteBuildsThePaperJob(t *testing.T) {
env := modules.Env{
Now: time.Date(2026, 11, 30, 14, 56, 39, 0, time.UTC),
Location: time.FixedZone("UTC-6", -6*60*60),
TimeLayout: "02 Jan 15:04",
}
body := `{"title":"Shopping","text":"Milk, eggs and the good bread from the bakery on Elm St.","items":["Milk","Eggs","Bread"],"done":[2]}`
job, err := modules.Note().Build(context.Background(), []byte(body), env)
if err != nil {
t.Fatal(err)
}
data, err := os.ReadFile(filepath.Join("..", "receipt", "testdata", "paper", "note.json"))
if err != nil {
t.Fatal(err)
}
paper, err := receipt.DecodeJob(data)
if err != nil {
t.Fatal(err)
}
got, err := json.Marshal(job)
if err != nil {
t.Fatal(err)
}
want, err := json.Marshal(paper)
if err != nil {
t.Fatal(err)
}
if string(got) != string(want) {
t.Errorf("the note builds\n%s\nbut the job checked on paper is\n%s", got, want)
}
}
func TestNotePayloadProblems(t *testing.T) {
items := make([]string, receipt.MaxItems+1)
for i := range items {
items[i] = fmt.Sprintf("%q", "item")
}
tests := []struct {
name, body string
want []string // the complete list of problems
}{
{"unknown field", `{"text":"x","colour":"red"}`, []string{"colour: unknown field"}},
{"field in another case", `{"Text":"x"}`, []string{"Text: unknown field"}},
{"wrong type", `{"text":"x","items":"Milk","stamp":"no"}`, []string{"items: expected an array of strings", "stamp: expected true or false"}},
{"missing text", `{"title":"Shopping"}`, []string{"text: required"}},
{"blank text", `{"text":" \n "}`, []string{"text: required"}},
{"done index out of range", `{"text":"x","items":["Milk","Eggs"],"done":[5,-1]}`,
[]string{"done[0]: index 5 is out of range", "done[1]: index -1 is out of range"}},
{"done without items", `{"text":"x","done":[0]}`, []string{"done[0]: index 0 is out of range"}},
{"done repeated", `{"text":"x","items":["a","b"],"done":[1,1]}`, []string{"done[1]: index 1 is repeated"}},
{"more than 200 items", `{"text":"x","items":[` + strings.Join(items, ",") + `]}`, []string{"items: 201 items, limit is 200"}},
{"empty item", `{"text":"x","items":["a",""]}`, []string{"items[1]: must not be empty"}},
{"style", `{"text":"x","style":"ascii"}`, []string{"style: must be single, double, double-h or double-v"}},
{"every problem at once", `{"style":"bold","items":[""],"done":[3]}`, []string{
"text: required",
"style: must be single, double, double-h or double-v",
"items[0]: must not be empty",
"done[0]: index 3 is out of range",
}},
{"not an object", `["text"]`, []string{"body: expected a JSON object, got array"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.Note().Build(context.Background(), []byte(tt.body), fixedEnv(t))
var pe *modules.PayloadError
if !errors.As(err, &pe) {
t.Fatalf("err = %v, want *PayloadError", err)
}
if strings.Join(pe.Problems, "\n") != strings.Join(tt.want, "\n") {
t.Errorf("problems:\n%s\nwant:\n%s", strings.Join(pe.Problems, "\n"), strings.Join(tt.want, "\n"))
}
})
}
}
// TestNoteBuildsValidJobs checks that a payload the note accepts always
// builds a job that passes validation, at the limits too.
func TestNoteBuildsValidJobs(t *testing.T) {
items := make([]string, receipt.MaxItems)
for i := range items {
items[i] = fmt.Sprintf("%q", fmt.Sprint("item ", i))
}
bodies := []string{
`{"text":"x"}`,
`{"text":"x","items":[],"done":[]}`,
`{"text":"x","style":"DOUBLE-V","stamp":false}`,
`{"text":"x","items":[` + strings.Join(items, ",") + `],"done":[0,199]}`,
`{"title":"\u001b@","text":"\u0007","footer":"\t","items":["\u001bd"]}`,
}
for _, body := range bodies {
job, err := modules.Note().Build(context.Background(), []byte(body), fixedEnv(t))
if err != nil {
t.Errorf("%s: %v", body, err)
continue
}
if err := job.Validate(); err != nil {
t.Errorf("%s: built an invalid job: %v", body, err)
}
}
}
+119
View File
@@ -0,0 +1,119 @@
// Package modules turns plain payloads, such as a note's title, text and
// items, into receipt jobs built from the layout blocks. Each module owns
// its payload format; the HTTP routes and the command line look modules up
// by name in a Registry.
package modules
import (
"context"
"errors"
"fmt"
"maps"
"regexp"
"slices"
"strings"
"time"
"uberbringer/internal/pkg/receipt"
)
// ErrSkip is returned by Build when the payload asks for nothing to be
// printed.
var ErrSkip = errors.New("nothing to print")
// PayloadError lists every problem with a payload, each prefixed with the
// field it concerns, e.g. "done[0]: index 5 is out of range".
type PayloadError struct {
Problems []string
}
// Error implements error.
func (e *PayloadError) Error() string {
return "invalid payload: " + strings.Join(e.Problems, "; ")
}
// Env is what a module may know about the time a receipt is built at. A
// module never reads the clock itself, so that its output is reproducible.
type Env struct {
// Now is the time the receipt is built at.
Now time.Time
// Location is the time zone times are printed in. Nil means local time.
Location *time.Location
// TimeLayout is the Go time layout times are printed in, e.g.
// "02 Jan 15:04".
TimeLayout string
}
// Stamp returns Now in Location, formatted with TimeLayout.
func (e Env) Stamp() string {
loc := e.Location
if loc == nil {
loc = time.Local
}
return e.Now.In(loc).Format(e.TimeLayout)
}
// Module builds a receipt from its own payload format.
type Module interface {
// Name is the module's name in routes, e.g. "note" in
// /api/v1/print/note.
Name() string
// Description says in one line what the module prints.
Description() string
// Build turns body into a job. It returns a *PayloadError for a body
// that is not a valid payload, and ErrSkip for one that asks for
// nothing to be printed. The job it returns is expected to pass
// Job.Validate; one that does not is a bug in the module.
Build(ctx context.Context, body []byte, env Env) (receipt.Job, error)
}
// Info describes a module for listings.
type Info struct {
Name string
Description string
}
// validName is the form of a module name: it appears as a path segment.
var validName = regexp.MustCompile(`^[a-z][a-z0-9-]{0,31}$`)
// Registry holds the modules by name. It is safe for concurrent use once
// built.
type Registry struct {
modules map[string]Module
}
// NewRegistry returns a registry of mods. Each name must be unique and made
// of lowercase letters, digits and dashes, starting with a letter.
func NewRegistry(mods ...Module) (*Registry, error) {
r := &Registry{modules: make(map[string]Module, len(mods))}
for _, m := range mods {
name := m.Name()
if !validName.MatchString(name) {
return nil, fmt.Errorf("module name %q: want lowercase letters, digits and dashes, starting with a letter", name)
}
if _, ok := r.modules[name]; ok {
return nil, fmt.Errorf("module %q is registered twice", name)
}
r.modules[name] = m
}
return r, nil
}
// Get returns the module called name.
func (r *Registry) Get(name string) (Module, bool) {
m, ok := r.modules[name]
return m, ok
}
// List describes every module, sorted by name.
func (r *Registry) List() []Info {
infos := make([]Info, 0, len(r.modules))
for _, name := range slices.Sorted(maps.Keys(r.modules)) {
infos = append(infos, Info{Name: name, Description: r.modules[name].Description()})
}
return infos
}
+105
View File
@@ -0,0 +1,105 @@
package modules_test
import (
"context"
"strings"
"testing"
"time"
"uberbringer/internal/pkg/modules"
"uberbringer/internal/pkg/receipt"
)
// stubModule is a module that prints one line of text.
type stubModule struct{ name, description string }
func (m stubModule) Name() string { return m.name }
func (m stubModule) Description() string { return m.description }
func (m stubModule) Build(context.Context, []byte, modules.Env) (receipt.Job, error) {
return receipt.Job{Elements: []receipt.Element{{Type: "text", Text: m.name}}}, nil
}
func TestRegistryLookup(t *testing.T) {
r, err := modules.NewRegistry(stubModule{"b", "B"}, modules.Note(), stubModule{"a-2", "A"})
if err != nil {
t.Fatal(err)
}
m, ok := r.Get("note")
if !ok || m.Name() != "note" {
t.Errorf("Get(note) = %v, %v", m, ok)
}
for _, name := range []string{"Note", "nope", ""} {
if _, ok := r.Get(name); ok {
t.Errorf("Get(%q) found a module", name)
}
}
got := r.List()
want := []modules.Info{{"a-2", "A"}, {"b", "B"}, {"note", "Boxed note with an optional checklist"}}
if len(got) != len(want) {
t.Fatalf("List() = %v, want %v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Errorf("List()[%d] = %v, want %v", i, got[i], want[i])
}
}
}
func TestRegistryListIsNeverNil(t *testing.T) {
r, err := modules.NewRegistry()
if err != nil {
t.Fatal(err)
}
if got := r.List(); got == nil || len(got) != 0 {
t.Errorf("List() = %#v, want an empty list", got)
}
}
func TestRegistryRefusals(t *testing.T) {
tests := []struct {
name string
mods []modules.Module
wantErr string
}{
{"duplicate name", []modules.Module{stubModule{"note", ""}, modules.Note()}, `module "note" is registered twice`},
{"upper case", []modules.Module{stubModule{"Note", ""}}, `module name "Note"`},
{"empty", []modules.Module{stubModule{"", ""}}, `module name ""`},
{"slash", []modules.Module{stubModule{"a/b", ""}}, `module name "a/b"`},
{"leading digit", []modules.Module{stubModule{"1a", ""}}, `module name "1a"`},
{"too long", []modules.Module{stubModule{strings.Repeat("a", 33), ""}}, "module name"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, err := modules.NewRegistry(tt.mods...)
if err == nil || !strings.Contains(err.Error(), tt.wantErr) {
t.Errorf("err = %v, want it to contain %q", err, tt.wantErr)
}
})
}
}
func TestEnvStamp(t *testing.T) {
london, err := time.LoadLocation("Europe/London")
if err != nil {
t.Fatal(err)
}
summer := time.Date(2026, 7, 14, 20, 4, 5, 0, time.UTC)
tests := []struct {
env modules.Env
want string
}{
{modules.Env{Now: summer, Location: london, TimeLayout: "02 Jan 15:04"}, "14 Jul 21:04"},
{modules.Env{Now: summer, Location: time.UTC, TimeLayout: "02 Jan 15:04"}, "14 Jul 20:04"},
{modules.Env{Now: summer, Location: london, TimeLayout: "2006-01-02 15:04 MST"}, "2026-07-14 21:04 BST"},
}
for _, tt := range tests {
if got := tt.env.Stamp(); got != tt.want {
t.Errorf("Stamp() in %v with %q = %q, want %q", tt.env.Location, tt.env.TimeLayout, got, tt.want)
}
}
local := modules.Env{Now: summer, TimeLayout: time.RFC3339}
if got, want := local.Stamp(), summer.In(time.Local).Format(time.RFC3339); got != want {
t.Errorf("Stamp() without a location = %q, want local time %q", got, want)
}
}
+1
View File
@@ -0,0 +1 @@
{"title": "Packing", "text": "All done.", "items": ["Passport", "Charger", "Tickets"], "done": [0, 1, 2]}
+8
View File
@@ -0,0 +1,8 @@
┌─ Packing ──────────────────────────────┐
│ All done. │
│ │
│ [√] Passport │
│ [√] Charger │
│ [√] Tickets │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Footer", "text": "A footer replaces the time.", "footer": "from the kitchen"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Footer ───────────────────────────────┐
│ A footer replaces the time. │
└──────────────────── from the kitchen ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"text": "No title, but a checklist.", "items": ["One", "Two"]}
+7
View File
@@ -0,0 +1,7 @@
┌────────────────────────────────────────┐
│ No title, but a checklist. │
│ │
│ [ ] One │
│ [ ] Two │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "A title that is far too long to fit into the top border of the box", "text": "First paragraph.\nSecond paragraph, which is long enough to wrap inside the box.", "items": ["An item that is long enough to wrap onto a second line with a hanging indent", "“Curly quotes” — and an emoji 🎉"], "done": [1]}
+13
View File
@@ -0,0 +1,13 @@
┌─ A title that is far too long to f... ─┐
│ First paragraph. │
│ Second paragraph, which is long enough │
│ to wrap inside the box. │
│ │
│ [ ] An item that is long enough to │
│ wrap onto a second line with a │
│ hanging indent │
│ [√] "Curly quotes" -- and an emoji ? │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
=== warnings
elements[0]: 1 character not in cp437 printed as ?
+1
View File
@@ -0,0 +1 @@
{"title": "Shopping", "text": "Milk, eggs and the good bread from the bakery on Elm St.", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
+9
View File
@@ -0,0 +1,9 @@
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "No stamp", "text": "stamp false leaves the bottom border plain.", "stamp": false}
+5
View File
@@ -0,0 +1,5 @@
┌─ No stamp ─────────────────────────────┐
│ stamp false leaves the bottom border │
│ plain. │
└────────────────────────────────────────┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-h", "text": "style double-h", "style": "double-h", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╒═ Double-h ═════════════════════════════╕
│ style double-h │
│ │
│ [ ] a │
╘════════════════════════ 29 Nov 21:04 ══╛
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Double-v", "text": "style double-v", "style": "double-v", "items": ["a"]}
+6
View File
@@ -0,0 +1,6 @@
╓─ Double-v ─────────────────────────────╖
║ style double-v ║
║ ║
║ [ ] a ║
╙──────────────────────── 29 Nov 21:04 ──╜
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Double", "text": "style double", "style": "double", "items": ["a"], "done": [0]}
+6
View File
@@ -0,0 +1,6 @@
╔═ Double ═══════════════════════════════╗
║ style double ║
║ ║
║ [√] a ║
╚════════════════════════ 29 Nov 21:04 ══╝
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"title": "Single", "text": "style single, written in capitals", "style": "SINGLE"}
+4
View File
@@ -0,0 +1,4 @@
┌─ Single ───────────────────────────────┐
│ style single, written in capitals │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+1
View File
@@ -0,0 +1 @@
{"text": "Back at 3."}
+4
View File
@@ -0,0 +1,4 @@
┌────────────────────────────────────────┐
│ Back at 3. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
@@ -0,0 +1 @@
{"title": "Reminder", "text": "Call the plumber about the kitchen tap before Friday."}
+5
View File
@@ -0,0 +1,5 @@
┌─ Reminder ─────────────────────────────┐
│ Call the plumber about the kitchen tap │
│ before Friday. │
└──────────────────────── 29 Nov 21:04 ──┘
- - - - - - - partial cut - - - - - - - -
+79 -1
View File
@@ -80,16 +80,20 @@ var fields = []field{
{"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 footer style padding fit columns pairs leader")
var blockOnly = fieldSet("children title title_style footer style padding fit columns pairs leader items bullet done")
// 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 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.
@@ -98,6 +102,7 @@ var childFields = map[string]map[string]bool{
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.
@@ -334,3 +339,76 @@ func (el Element) pairProblems() []string {
}
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
}
+86 -1
View File
@@ -1,6 +1,8 @@
package receipt
import (
"fmt"
"strconv"
"strings"
"uberbringer/internal/pkg/escpos"
@@ -67,6 +69,7 @@ const (
itemFeed
itemDivider
itemKV
itemList
)
// boxItem is one part of a box body, with its text already normalized.
@@ -88,6 +91,9 @@ type boxItem struct {
// itemKV.
pairs []kvRow
leader string
// itemList.
list []listRow
}
// kvRow is a Pair with its text normalized.
@@ -189,6 +195,9 @@ func (lo *layout) boxItems(el Element, spec boxSpec) []boxItem {
case TypeKV:
ks, _ := child.kvSpec()
items = append(items, boxItem{kind: itemKV, pairs: lo.kvRows(child.Pairs), leader: leaderFor(ks.leader, lo.cp)})
case TypeList:
ls, _ := child.listSpec()
items = append(items, boxItem{kind: itemList, list: lo.listRows(child, ls)})
}
}
return items
@@ -211,6 +220,16 @@ func (it boxItem) naturalWidth(limit int) int {
widest = max(widest, runeLen(p.key)+4+runeLen(p.value))
}
return min(widest, limit)
case itemList:
widest := 0
for _, row := range it.list {
bullet := runeLen(row.bullet)
room := max(limit-bullet, 1)
for _, text := range wrap(row.text, room, room) {
widest = max(widest, bullet+runeLen(text))
}
}
return min(widest, limit)
}
return 0
}
@@ -232,7 +251,8 @@ func (it boxItem) rows(width int) []string {
return rows
}
// contentLines lays out a text, feed or kv item at exactly width cells.
// contentLines lays out a text, feed, kv or list item at exactly width
// cells.
func (it boxItem) contentLines(width int) []blockLine {
switch it.kind {
case itemFeed:
@@ -243,6 +263,8 @@ func (it boxItem) contentLines(width int) []blockLine {
return lines
case itemKV:
return kvLines(it.pairs, it.leader, width)
case itemList:
return listLines(it.list, width)
}
var lines []blockLine
for _, row := range it.rows(width) {
@@ -387,6 +409,69 @@ func kvLines(rows []kvRow, leader string, width int) []blockLine {
return lines
}
// list lays out a list block on a line of cols cells.
func (lo *layout) list(el Element, spec listSpec, cols int) []blockLine {
width := blockWidth(spec.columns, cols)
return centre(listLines(lo.listRows(el, spec), width), width, cols)
}
// listRow is one list item: its bullet, with the space after it, and its
// text, normalized.
type listRow struct {
bullet, text string
}
// listRows gives each item of a list its bullet: "· ", "- ", a number
// right-aligned to the widest, or a checkbox, ticked for the done items.
func (lo *layout) listRows(el Element, spec listSpec) []listRow {
done := make(map[int]bool, len(el.Done))
for _, index := range el.Done {
done[index] = true
}
digits := len(strconv.Itoa(len(el.Items)))
rows := make([]listRow, len(el.Items))
for i, item := range el.Items {
var bullet string
switch spec.bullet {
case bulletDash:
bullet = "- "
case bulletNumber:
bullet = fmt.Sprintf("%*d. ", digits, i+1)
case bulletCheckbox:
bullet = "[ ] "
if done[i] {
bullet = "[" + checkMark(lo.cp) + "] "
}
default:
bullet = listDot(lo.cp) + " "
}
rows[i] = listRow{bullet: bullet, text: lo.text(item)}
}
return rows
}
// listLines lays out rows at exactly width cells: each bullet, then the
// item's text wrapped to the room after it, its further lines indented to
// line up with the first. On a line too narrow for the whole bullet, the
// bullet is cut so that one cell is left for the text.
func listLines(rows []listRow, width int) []blockLine {
width = max(width, 1)
var lines []blockLine
for _, row := range rows {
bullet := []rune(row.bullet)
indent := min(len(bullet), width-1)
room := width - indent
for i, text := range wrap(row.text, room, room) {
lead := spaces(indent)
if i == 0 {
lead = string(bullet[:indent])
}
lines = append(lines, blockLine{plain(lead + text + spaces(room-runeLen(text)))})
}
}
return lines
}
// narrowKVLines lays out rows on lines too narrow for a key, a leader and a
// value side by side: the key on a line of its own, then the value,
// right-aligned.
+1
View File
@@ -78,6 +78,7 @@ var updatePaper = flag.Bool("update-paper", false, "rewrite testdata/paper/*.hex
// TM-T88 in CP437 with the default options.
var paperReceipts = []struct{ job, hex string }{
{filepath.Join("..", "..", "..", "examples", "blocks.json"), filepath.Join("testdata", "paper", "blocks.hex")},
{filepath.Join("testdata", "paper", "note.json"), filepath.Join("testdata", "paper", "note.hex")},
}
// TestPaperReceipts fails when the bytes of a receipt checked on paper
+34 -8
View File
@@ -10,16 +10,19 @@ import (
"uberbringer/internal/pkg/receipt"
)
// FuzzBlocks lays out random boxes, rules and kv blocks on random printers
// and code pages, and checks that every line is exactly the block's width,
// no wider than the line, with the borders in the first and last columns,
// and that no control byte reaches the printer inside the text.
// FuzzBlocks lays out random boxes, rules, kv blocks and lists on random
// printers and code pages, and checks that every line is exactly the
// block's width, no wider than the line, with the borders in the first and
// last columns, and that no control byte reaches the printer inside the
// text.
func FuzzBlocks(f *testing.F) {
f.Add(uint8(0), uint8(0), uint8(0), uint8(1), uint8(0), uint8(1), false, uint8(0), "Title", "Footer", "Some text that wraps", "key", "value")
f.Add(uint8(0x3C), uint8(1), uint8(9), uint8(2), uint8(1), uint8(3), true, uint8(12), "“A long title” — with folds…", "", "line\nline\ttab 🎉👨\u200D👩\u200D👧", "k", "")
f.Add(uint8(1), uint8(2), uint8(6), uint8(0), uint8(0), uint8(0), false, uint8(200), "", "", "Label", "", "")
f.Add(uint8(2), uint8(3), uint8(4), uint8(1), uint8(1), uint8(2), false, uint8(7), "", "", "", "A key that is long", "a value that wraps over several lines")
f.Add(uint8(0xF8), uint8(4), uint8(3), uint8(2), uint8(0), uint8(0), true, uint8(3), "\x1b@\x00", "\x07", "\x1bd\x05 text \x1dV", "\x0a", "\x09")
f.Add(uint8(3), uint8(1), uint8(3), uint8(0), uint8(1), uint8(2), true, uint8(5), "A done item", "", "An item that wraps\nwith a hanging indent", "k", "v")
f.Add(uint8(0x80), uint8(0x83), uint8(2), uint8(0), uint8(0), uint8(1), true, uint8(0), "Title", "", "text", "", "")
f.Fuzz(func(t *testing.T, kind, printerSel, style, size, font, padding uint8, fit bool, columns uint8,
title, footer, text, key, value string) {
el := fuzzBlock(kind, style, size, font, padding, fit, columns, title, footer, text, key, value)
@@ -95,8 +98,9 @@ func fontOf(name string) escpos.Font {
return escpos.FontA
}
// fuzzBlock builds a box, rule or kv element from the fuzzer's values. The
// low bits of kind pick the type; for a box, the others pick its children.
// fuzzBlock builds a box, rule, kv or list element from the fuzzer's values.
// The low bits of kind pick the type; for a box, the others pick its
// children.
func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8, title, footer, text, key, value string) receipt.Element {
boxStyles := []string{"single", "double", "double-h", "double-v", "ascii"}
ruleStyles := []string{"single", "double", "light", "medium", "dark", "solid", "dashed", "dotted", "ascii"}
@@ -106,7 +110,7 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if font%2 == 1 {
el.Font = "b"
}
switch kind % 3 {
switch kind % 4 {
case 0:
el.Type = "box"
el.Style = boxStyles[int(style)%len(boxStyles)]
@@ -136,15 +140,37 @@ func fuzzBlock(kind, style, size, font, padding uint8, fit bool, columns uint8,
if children&8 != 0 {
el.Children = append(el.Children, receipt.Element{Type: "feed", Lines: 1 + int(padding)%3})
}
if children&0x20 != 0 {
list := fuzzList(style, fit, title, text, value)
list.Size, list.Columns, list.Font = 0, 0, ""
el.Children = append(el.Children, list)
}
case 1:
el.Type = "rule"
el.Style = ruleStyles[int(style)%len(ruleStyles)]
el.Text = text
el.Align = aligns[int(padding)%3]
default:
case 2:
el.Type = "kv"
el.Leader = leaders[int(style)%len(leaders)]
el.Pairs = []receipt.Pair{{Key: key + "k", Value: value}, {Key: title + "t", Value: text, Bold: fit}}
default:
list := fuzzList(style, fit, title, text, value)
el.Type, el.Bullet, el.Items, el.Done = list.Type, list.Bullet, list.Items, list.Done
}
return el
}
// fuzzList builds a list whose items are the fuzzer's strings. style picks
// the bullet, and fit marks the first item done on a checklist.
func fuzzList(style uint8, fit bool, items ...string) receipt.Element {
bullets := []string{"dot", "dash", "number", "checkbox"}
el := receipt.Element{Type: "list", Bullet: bullets[int(style)%len(bullets)]}
for _, item := range items {
el.Items = append(el.Items, item+"i")
}
if fit && el.Bullet == "checkbox" {
el.Done = []int{0}
}
return el
}
+11
View File
@@ -113,6 +113,17 @@ var leaderFallbacks = map[string][]string{
"─": {"─", "-"},
}
// checkMark is the tick of a done checklist item: √, or x on code pages
// without it.
func checkMark(cp escpos.CodePage) string {
return firstPrintable([]string{"√"}, cp, "x")
}
// listDot is the bullet of a dotted list: ·, or . on code pages without it.
func listDot(cp escpos.CodePage) string {
return firstPrintable([]string{"·"}, cp, ".")
}
// rulePattern returns the fill of style that cp can print.
func rulePattern(style ruleStyle, cp escpos.CodePage) string {
return firstPrintable(rulePatterns[style], cp, "-")
+32 -17
View File
@@ -20,8 +20,8 @@ import (
// 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.
// 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"
@@ -33,6 +33,7 @@ const (
TypeBox = "box"
TypeRule = "rule"
TypeKV = "kv"
TypeList = "list"
)
// Job limits. MaxElements counts the children of boxes too.
@@ -40,6 +41,7 @@ const (
MaxElements = 500
MaxCopies = 5
MaxPairs = 100
MaxItems = 200
)
// Element defaults.
@@ -64,18 +66,19 @@ type Job struct {
}
// Element is one item on a receipt. Its 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. 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.
// 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 and kv 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"`
// 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.
@@ -138,7 +141,7 @@ type Element struct {
Mode string `json:"mode,omitempty" jsonschema:"enum=partial,enum=full"`
// Children are a box's body as elements, one level deep: text, feed,
// rule and kv. Set text or children, not both.
// 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"`
@@ -165,6 +168,15 @@ type Element struct {
// 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.
@@ -258,13 +270,13 @@ func (el Element) problems(path string, inBox bool) []string {
func (el Element) validate(inBox bool) []string {
if inBox {
switch el.Type {
case TypeText, TypeFeed, TypeRule, TypeKV:
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 or kv)", el.Type)}
return []string{fmt.Sprintf("unknown type %q (inside a box, want text, feed, rule, kv or list)", el.Type)}
}
}
problems := el.checkFields(inBox)
@@ -294,10 +306,13 @@ func (el Element) validate(inBox bool) []string {
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 or kv)", el.Type)
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())
+10 -3
View File
@@ -246,7 +246,7 @@ func (p *printer) element(el Element, img *image.Paletted) error {
switch el.Type {
case TypeText:
return p.text(el)
case TypeBox, TypeRule, TypeKV:
case TypeBox, TypeRule, TypeKV, TypeList:
return p.block(el)
case TypeFeed:
lines, err := el.feedLines()
@@ -361,8 +361,8 @@ func (p *printer) resetStyle() error {
return nil
}
// block lays out a box, rule or kv element and prints it line by line,
// each line left-justified and exactly as wide as the layout made it.
// block lays out a box, rule, kv or list element and prints it line by
// line, each line left-justified and exactly as wide as the layout made it.
func (p *printer) block(el Element) error {
lo := layout{cp: p.codePage}
var (
@@ -386,6 +386,13 @@ func (p *printer) block(el Element) error {
}
size, font = spec.size, spec.font
lines = lo.rule(el, spec, p.blockColumns(font, size))
case TypeList:
spec, err := el.listSpec()
if err != nil {
return err
}
size, font = spec.size, spec.font
lines = lo.list(el, spec, p.blockColumns(font, size))
default:
spec, err := el.kvSpec()
if err != nil {
+11
View File
@@ -111,6 +111,9 @@ func TestEnumTagsMatchValidation(t *testing.T) {
{"Leader", "leader", func(v string) []Element {
return []Element{{Type: TypeKV, Pairs: []Pair{{Key: "k", Value: "v"}}, Leader: v}}
}},
{"Bullet", "bullet", func(v string) []Element {
return []Element{{Type: TypeList, Items: []string{"i"}, Bullet: v}}
}},
}
for _, tt := range tests {
t.Run(tt.field, func(t *testing.T) {
@@ -193,6 +196,14 @@ func TestBoundTagsMatchValidation(t *testing.T) {
func(n int) Job { return one(kv(n, "k")) }},
{reflect.TypeFor[Pair](), "Key", "key", "minLength", "",
func(n int) Job { return one(kv(1, strings.Repeat("k", n))) }},
{reflect.TypeFor[Element](), "Items", "items", "minItems", "maxItems",
func(n int) Job { return one(Element{Type: TypeList, Items: slices.Repeat([]string{"i"}, n)}) }},
{reflect.TypeFor[Element](), "Items", "items", "minLength", "",
func(n int) Job { return one(Element{Type: TypeList, Items: []string{strings.Repeat("i", n)}}) }},
{reflect.TypeFor[Element](), "Done", "done", "minimum", "maximum",
func(n int) Job {
return one(Element{Type: TypeList, Bullet: "checkbox", Items: slices.Repeat([]string{"i"}, MaxItems), Done: []int{n}})
}},
}
for _, tt := range tests {
t.Run(tt.json, func(t *testing.T) {
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
+- NAS REPORT ---------------------------+
| Host ........................... nas01 |
| Pool ................... tank (raidz2) |
| Used ............................. 94% |
+-- Services ----------------------------+
| · grafana up |
| · offsite-backup DOWN since 19:00 |
+------------------------ 29 Nov 21:04 --+
+- Shopping -----------------------------+
| Milk, eggs and the good bread from the |
| bakery on Elm St. |
| |
| [ ] Milk |
| [ ] Eggs |
| [x] Bread |
+------------------------ 29 Nov 21:04 --+
+------------------------+
| 1. A fit box |
| 2. shrinks to its list |
+------------------------+
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[√] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[√] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[√N
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [√] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+64
View File
@@ -0,0 +1,64 @@
· Replace drive bay 3
· Order 2x 8 TB
- Dashes
- for a plain list
1. First item that is long enough to wrap
with a hanging indent
2. Second
[x] Done item
[ ] Open item
··········································
1. One
2. Two
3. Three
4. Four
5. Five
6. Six
7. Seven
8. Eight
9. Nine
10. Ten
11. Eleven
12. Twelve, which wraps to a hanging
indent past the widest number
· A paragraph
and a second one, both indented under
the bullet
· A tab
· https://example.com/a/very/long/path/wit
hout/any/spaces/in/it
[ ] Centred in 24
columns
[x] Done
1. Size 2
2. Wraps at 21
columns of its own
- Font B is fifty-six columns wide, so this line wraps
later
[xN
a
r
r
o
w
┌─ NAS REPORT ───────────────────────────┐
│ Host ........................... nas01 │
│ Pool ................... tank (raidz2) │
│ Used ............................. 94% │
├── Services ────────────────────────────┤
│ · grafana up │
│ · offsite-backup DOWN since 19:00 │
└──────────────────────── 29 Nov 21:04 ──┘
┌─ Shopping ─────────────────────────────┐
│ Milk, eggs and the good bread from the │
│ bakery on Elm St. │
│ │
│ [ ] Milk │
│ [ ] Eggs │
│ [x] Bread │
└──────────────────────── 29 Nov 21:04 ──┘
╔════════════════════════╗
║ 1. A fit box ║
║ 2. shrinks to its list ║
╚════════════════════════╝
- - - - - - - partial cut - - - - - - - -
+27
View File
@@ -0,0 +1,27 @@
{"elements": [
{"type": "list", "items": ["Replace drive bay 3", "Order 2x 8 TB"]},
{"type": "list", "bullet": "dash", "items": ["Dashes", "for a plain list"]},
{"type": "list", "bullet": "number", "items": ["First item that is long enough to wrap with a hanging indent", "Second"]},
{"type": "list", "bullet": "checkbox", "items": ["Done item", "Open item"], "done": [0]},
{"type": "rule", "style": "dotted"},
{"type": "list", "bullet": "number", "items": ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve, which wraps to a hanging indent past the widest number"]},
{"type": "list", "items": ["A paragraph\nand a second one, both indented under the bullet", "\tA tab"]},
{"type": "list", "items": ["https://example.com/a/very/long/path/without/any/spaces/in/it"]},
{"type": "list", "bullet": "CHECKBOX", "columns": 24, "items": ["Centred in 24 columns", "Done"], "done": [1]},
{"type": "list", "size": 2, "bullet": "number", "items": ["Size 2", "Wraps at 21 columns of its own"]},
{"type": "list", "font": "b", "bullet": "dash", "items": ["Font B is fifty-six columns wide, so this line wraps later"]},
{"type": "list", "columns": 3, "bullet": "checkbox", "items": ["Narrow"], "done": [0]},
{"type": "box", "title": "NAS REPORT", "footer": "29 Nov 21:04", "children": [
{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"}, {"key": "Pool", "value": "tank (raidz2)"}, {"key": "Used", "value": "94%", "bold": true}]},
{"type": "rule", "text": "Services", "align": "left"},
{"type": "list", "items": ["grafana up", "offsite-backup DOWN since 19:00"]}
]},
{"type": "box", "title": "Shopping", "footer": "29 Nov 21:04", "children": [
{"type": "text", "text": "Milk, eggs and the good bread from the bakery on Elm St."},
{"type": "feed"},
{"type": "list", "bullet": "checkbox", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
]},
{"type": "box", "fit": true, "style": "double", "children": [
{"type": "list", "bullet": "number", "items": ["A fit box", "shrinks to its list"]}
]}
]}
+13
View File
@@ -0,0 +1,13 @@
1b401b74001b61001b4d001d21001b45001b2d001d4200dac42053686f707069
6e6720c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4
bf0ab3204d696c6b2c206567677320616e642074686520676f6f642062726561
642066726f6d2074686520b30ab32062616b657279206f6e20456c6d2053742e
20202020202020202020202020202020202020202020b30ab320202020202020
2020202020202020202020202020202020202020202020202020202020202020
20b30ab3205b205d204d696c6b20202020202020202020202020202020202020
202020202020202020202020b30ab3205b205d20456767732020202020202020
2020202020202020202020202020202020202020202020b30ab3205bfb5d2042
7265616420202020202020202020202020202020202020202020202020202020
2020b30ac0c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4c4203330
204e6f762030383a353620c4c4d90a1b45001b2d001d42001d21001b4d001d56
4200
+7
View File
@@ -0,0 +1,7 @@
{"elements": [
{"type": "box", "title": "Shopping", "footer": "30 Nov 08:56", "children": [
{"type": "text", "text": "Milk, eggs and the good bread from the bakery on Elm St."},
{"type": "feed"},
{"type": "list", "bullet": "checkbox", "items": ["Milk", "Eggs", "Bread"], "done": [2]}
]}
]}
+39 -2
View File
@@ -44,8 +44,10 @@ func TestValidateBlocks(t *testing.T) {
"elements[0].children[3] (cut): not allowed inside a box; place it after the box",
"elements[0].children[4] (barcode): not allowed inside a box; place it after the box",
}},
{"unknown child type", box(receipt.Element{Type: "list"}),
[]string{`elements[0].children[0] (list): unknown type "list" (inside a box, want text, feed, rule or kv)`}},
{"unknown child type", box(receipt.Element{Type: "table"}),
[]string{`elements[0].children[0] (table): unknown type "table" (inside a box, want text, feed, rule, kv or list)`}},
{"unknown type", receipt.Element{Type: "table"},
[]string{`elements[0] (table): unknown type "table" (want text, feed, qr, barcode, image, raw, cut, box, rule, kv or list)`}},
{"child without a type", box(receipt.Element{}),
[]string{"elements[0].children[0] (): type is required"}},
{"divider style", box(text, receipt.Element{Type: "rule", Style: "dark"}),
@@ -83,6 +85,31 @@ func TestValidateBlocks(t *testing.T) {
{"no pairs", receipt.Element{Type: "kv"}, []string{"elements[0] (kv): pairs: at least one pair is required"}},
{"too many pairs", receipt.Element{Type: "kv", Pairs: manyPairs(101)}, []string{"elements[0] (kv): pairs: 101 pairs, limit is 100"}},
{"kv size", receipt.Element{Type: "kv", Size: 9, Pairs: []receipt.Pair{{Key: "a"}}}, []string{"elements[0] (kv): size must be 1-3"}},
{"no items", receipt.Element{Type: "list"}, []string{"elements[0] (list): items: at least one item is required"}},
{"too many items", receipt.Element{Type: "list", Items: manyItems(201)}, []string{"elements[0] (list): items: 201 items, limit is 200"}},
{"empty item", receipt.Element{Type: "list", Items: []string{"a", ""}}, []string{"elements[0] (list): items[1]: must not be empty"}},
{"bullet", receipt.Element{Type: "list", Bullet: "star", Items: []string{"a"}},
[]string{"elements[0] (list): bullet must be dot, dash, number or checkbox"}},
{"done without checkboxes", receipt.Element{Type: "list", Bullet: "number", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (list): done: only a list with bullet "checkbox" has done items`}},
{"done out of range and repeated", receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1, 2, -1, 1}},
[]string{
"elements[0] (list): done[1]: index 2 is out of range",
"elements[0] (list): done[2]: index -1 is out of range",
"elements[0] (list): done[3]: index 1 is repeated",
}},
{"list size and columns", receipt.Element{Type: "list", Size: 4, Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): size must be 1-3"}},
{"list columns", receipt.Element{Type: "list", Columns: 300, Items: []string{"a"}},
[]string{"elements[0] (list): columns must be 1-255"}},
{"field that does not apply to a list", receipt.Element{Type: "list", Items: []string{"a"}, Bold: true, Leader: "."},
[]string{`elements[0] (list): field "bold" does not apply to list`, `elements[0] (list): field "leader" does not apply to list`}},
{"list fields on an old type", receipt.Element{Type: "text", Text: "x", Items: []string{"a"}, Done: []int{0}},
[]string{`elements[0] (text): field "items" does not apply to text`, `elements[0] (text): field "done" does not apply to text`}},
{"list fields inside a box", box(receipt.Element{Type: "list", Items: []string{"a"}, Columns: 10, Font: "b"}),
[]string{"elements[0].children[0] (list): font is inherited from the box", `elements[0].children[0] (list): field "columns" does not apply to list inside a box`}},
{"list problems inside a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a"}, Done: []int{3}}),
[]string{"elements[0].children[0] (list): done[0]: index 3 is out of range"}},
{"old types stay lenient", receipt.Element{Type: "feed", Text: "ignored", Bold: true}, nil},
{"a full box", receipt.Element{
@@ -95,6 +122,8 @@ func TestValidateBlocks(t *testing.T) {
}}, nil},
{"a full rule", receipt.Element{Type: "rule", Style: "dashed", Text: "l", Align: "right", Bold: true, Columns: 255, Size: 3, Font: "a"}, nil},
{"a full kv", receipt.Element{Type: "kv", Leader: "space", Columns: 1, Size: 1, Font: "B", Pairs: manyPairs(100)}, nil},
{"a full list", receipt.Element{Type: "list", Bullet: "Checkbox", Columns: 1, Size: 3, Font: "b", Items: manyItems(200), Done: []int{0, 199}}, nil},
{"a list in a box", box(receipt.Element{Type: "list", Bullet: "checkbox", Items: []string{"a", "b"}, Done: []int{1}}), nil},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
@@ -106,6 +135,14 @@ func TestValidateBlocks(t *testing.T) {
}
}
func manyItems(n int) []string {
items := make([]string, n)
for i := range items {
items[i] = "item"
}
return items
}
func TestValidateCountsChildren(t *testing.T) {
children := make([]receipt.Element, receipt.MaxElements)
for i := range children {