Repository navigation
Description
Context
FloCafe prints receipts, kitchen tickets, tax invoices, and diagnostics through eight-plus distinct code paths spread across three runtimes (browser DOM, WebUSB renderer process, Electron main process). A 2026 architecture audit found:
- Zero shared print-domain abstraction. Item-row layout/truncation is implemented 6× (
itemRowsinmain/printers/thermal.ts,col4Rows+composePluginColumnsin the same file andfrontend/src/lib/printer/receipt-encoder.ts,kot-encoder.tsqty-name lines,tax-bill-encoder.tsfused header literal, HTML<td>s inweb-print.ts). Currency formatting exists in 4 variants; date/time formatting in 3; the REPRINT banner in 4. - ~58 distinct user-visible English strings are hardcoded across thermal/ESC-POS renderers ("Subtotal", "TOTAL", "Invoice #", "KITCHEN ORDER TICKET", payment names…). Only the browser HTML path (
web-print.ts) resolves labels through the canonical i18n messages (the architecture delivered by refactor(i18n): migrate to scalable use-intl architecture #372). - Backend and frontend diverge: backend receipts use bill-scoped item projection (
getOrderWithItems) while backend KOT uses order-scoped items (getEffectiveOrderItems); frontend KOT skips served/ready items, backend KOT does not. The invoice identity itself is labeled "Invoice #" on thermal output and "Bill #" in browser/WebUSB output. - Raw thermal printers cannot render most non-Latin scripts, and today the only mitigation is per-profile
arabicShapingpassthrough plus line-skipping with warnings (Not showing Items in Bill #437 exposure). - Template trust boundaries are implicit: compliance templates live in
installed_print_templatesas denormalized children of signed country-pack artifacts (Ed25519-verified at install and re-verified at activation), but nothing in the data model prevents future confusion between that table and arbitrary merchant JSON.
This epic establishes a multilingual, bidirectional, scalable printing architecture so that adding a language, a template, or a printer transport does not require touching every renderer — and so Persian/Arabic/CJK/Hebrew receipts are a capability question, not an afterthought.
This is not a Persian translation task. Persian (#241) and #437 exposed the problem; the solution must generalize to Arabic, Hebrew, CJK, Hindi, Thai, mixed-script content, and future languages.
Problem Statement
- Hardcoded English thermal strings make non-English receipts half-translated even when product data is localized.
- Duplicated layout/content decisions mean every fix (width math, truncation, currency placement) must be repeated in up to six places — and drift silently (see "Invoice #" vs "Bill #").
- Backend and frontend renderers recompute business presentation independently from authoritative bill data.
- RTL/bidi has no model: direction cannot be expressed per block/value; LTR islands exist only in the HTML path.
- Raw-printer capability (encoding, shaping, bidi, raster) is not modeled; behavior degrades to silent-ish line skipping governed by one boolean.
- Compliance template provenance (signed packs) has no merchant-side counterpart story; nothing defines how merchant-created or imported templates would be stored, versioned, or trusted differently.
- There is no way for a contributor to add a receipt language without understanding TCP printing, or add a transport without editing translations.
Goals
- ONE semantic print model, ONE localization model, MULTIPLE templates, MULTIPLE renderers, MULTIPLE transports:
Bill / Order / Store data (already authoritative)
│
▼
normalized PrintData + PrintContext
│
▼
PrintDocument (semantic blocks)
│
┌─────┼──────┐
▼ ▼ ▼
HTML ESC/POS Raster(future)
│ │ │
└─────┼──────┘
▼
transports: browser · WebUSB · TCP:9100 · OS spooler (CUPS/WinSpool)
- All system labels resolve through canonical i18n messages.
- Receipt language, KOT language, UI language, regional settings, and compliance are independent but inheritable.
- Direction is modeled per document/block/value with explicit LTR islands.
- Renderer-independent semantic merchant templates become possible (later epics build UX on top).
- Offline-first is preserved end to end.
Architectural Principles
- Offline-first. No cloud translation services, remote template registries, remote fonts, SaaS localization, or network dependence for receipt creation. Everything needed for local printing ships in packaged/local data.
- Existing i18n stays canonical. Locale JSON files under
frontend/src/lib/i18n/messages/are the single translation source of truth (per refactor(i18n): migrate to scalable use-intl architecture #372/chore(i18n): add repository-native translation validation and integrity checks #382). No second catalog. Reuse existing keys (receipt.*,pos.*,orders.*, …) before adding new ones; only genuinely new concepts get keys (audit mapping maintained by child issues). - Languages come from the central registry.
frontend/src/lib/i18n/languages.ts(with itsdirectionandselectablefields) is the only authoritative language list. Print code must never hardcode'en' | 'fa' | 'es' | 'pt'. Adding French/German/Japanese/Hebrew to the registry makes it available to printing automatically where technically supported. - UI language ≠ receipt language ≠ KOT language ≠ currency/calendar/country/tax/compliance. Defaults may inherit; the model must permit divergence.
- Structured language policy, no magic strings. Typed policy (e.g.,
primary: {mode:'inherit'} | {mode:'fixed', language}plus orderedadditional[])."auto"is never stored as if it were a locale. v1 UI may cap additional receipt languages at one secondary; the internal model must not need schema replacement later (customer-preferred language, per-station KOT language fit naturally). - Direction is not global. Per-document base direction, per-block label direction, per-value direction. IDs, phones, URLs, SKUs, tax IDs, invoice numbers, amounts get explicit LTR isolation even in RTL documents (reuse the browser path's island principles).
- Bilingual labels are semantic, not concatenated strings. Renderers choose width-safe presentation (inline when room allows, stacked on narrow paper);
"A / B"concatenation never enters the data model. - Printer capabilities are explicit and independent of any single toggle like
printerUseUnicode: encoding/codepage, UTF-8 acceptance, glyph coverage, Arabic/Persian shaping, bidi handling, raster support, QR/barcode/logo, column widths, font modes, cut support. Nothing may overfit to Persian. - No silent data loss. A renderer must natively render, use an explicitly supported fallback, or surface an explicit capability warning/error. Financially/materially important content is always preserved in the semantic document even when a given transport cannot draw it. The current conditional behavior around Not showing Items in Bill #437 is legacy-renderer behavior, not the global print contract.
- Shared print code lives in a neutral shared layer (conceptually
shared/print/), pure by construction: no Electron APIs, DOM, React, DB, filesystem, network, or transport IO. Do not expand the existing@countries-style frontend→backend import into a new pattern; do not park shared code undermain/print/*. - PrintDocument is an explicit milestone, not an indefinite idea — required before the merchant/community template ecosystem. First consumer must be a FloCafe-owned core surface (classic receipt / preview), never a third-party plugin renderer.
- Separate PrintData from rendering. Templates/renderers never fetch the database or recompute tax/totals/order truth; they receive authoritative values and control presentation only.
- Compliance provenance is sacred.
installed_print_templatesremains exclusively denormalized children of signed country-pack versions (Ed25519 trust chain, activation/revocation lifecycle). Four provenance classes stay distinct: core / compliance-pack / merchant-created / imported. - Merchant templates are renderer-independent semantic schemas — never ESC/POS command sequences.
escpos-line-template-v1remains the legacy/compliance contract (may receive safe additive localization support) and must NOT become the public merchant format. - Imports are declarative and non-executable. No JS, eval, SQL, shell, network fetches, arbitrary URLs, or executable HTML. Untrusted input: schema-versioned, size-capped, unknown-field policy defined, rollback/archive semantics defined.
- Internal i18n keys are not public API. Community-facing schemas use stable semantic identifiers (e.g.,
label: "total"), resolved internally. If internal keys are ever exposed deliberately, that is a documented, versioned API decision. - Build determinism. Derived artifacts (e.g., generated backend label views) are committed or generated-to-ignored-output with explicit commands + CI drift checks; ordinary builds consume them and never silently rewrite tracked sources.
- Preserve app weight and Git-native simplicity. No heavy dependencies for what runtime-native facilities can do; no Arabic-specific core dependency merely because Persian exists; adding a normal language stays a translation-files PR.
Target Architecture
Renderer and transport are strictly separated. Transports move bytes/HTML; renderers turn semantic documents into bytes/HTML; documents come from authoritative data via pure builders.
| Layer | Owns | Never owns |
|---|---|---|
| Data preparation | fetching bill/order/business (existing routes/services) | layout, translation |
| PrintData + PrintContext | normalized authoritative values; resolved language policy; paper width; capability hints | rendering |
| PrintDocument | semantic blocks (header, meta, customer, items, tax, totals, payments, messages…) | transports, i18n resolution |
| Template/layout | presentation choice within semantic vocabulary | business truth |
| Renderers | HTML / ESC-POS / raster(future) emission + capability warnings | DB/network access |
| Transports | popup print, WebUSB, TCP:9100, OS spooler | content decisions |
Language Model
- Store/UI language: existing tenant + cashier settings (unchanged).
- Receipt language policy:
{ primary: inherit-store | fixed(lang), additional: [lang] }— v1 supports one additional (bilingual receipts). - KOT language policy:
{ primary: inherit-store | fixed(lang) }; future per-station override slots in without schema change. - Dropdown options are generated from the central registry (respecting
selectable), never hardcoded lists. - Regional formatting (currency digits/symbols, calendar) follows existing tenant regionalization (refactor(regionalization): harden country, regional formatting, and international data boundaries #388/fix(settings): enforce country-scoped regional preference invariants #390 family) — print consumes it, never redefines it.
Direction/Bidi Model
DirectionSpec per document (base = primary language direction) and per block/label/value. Amounts, invoice numbers, phones, tax IDs, SKUs, URLs render as LTR islands regardless of base direction. Thermal renderers express direction honestly through alignment/ordering they can guarantee; HTML uses full bidi isolation as it does today.
Template Provenance Model
| Class | Storage | Trust | Lifecycle |
|---|---|---|---|
| Core | code constants (classic, compact) |
shipped | release |
| Compliance/country-pack | installed_print_templates (children of signed pack versions) |
Ed25519 signature + digest, owner-only install, activation/revocation | pack update/rollback/revocation |
| Merchant-created | dedicated merchant-template storage (future issue) | tenant-scoped, validated schema | draft→active→archived |
| Imported | same storage, origin: imported, checksummed, untrusted-input validation |
declarative-only contract | archive/rollback |
Cloning a compliance template records derivedFrom but confers no compliance trust.
Printer Capability Model
Capabilities are declared/discovered per printer profile and consulted by renderers: encoding/codepage, UTF-8 tolerance, glyph coverage, Arabic/Persian shaping, bidi, raster, QR/barcode/logo, columns, font modes, cut. Capability gaps produce explicit warnings/errors — never quiet omission of financial content.
Current Print Path Inventory (verified)
| Path | Entry → Renderer → Transport | Notes |
|---|---|---|
| Browser receipt | usePrinter.printBill → web-print.generateBillHtml → popup window.print() |
only fully i18n'd path today |
| WebUSB receipt | usePrinter → receipt-encoder classic/compact → PrinterService.transferOut |
hardcoded EN |
| Backend receipt | POST /printers/print-bill → thermal.formatClassic/CompactReceipt → TCP:9100 / CUPS / WinSpool RAW |
hardcoded EN; bill-scoped items |
| Detailed tax receipt | print-test page only → tax-bill-encoder → WebUSB |
legacy/diagnostic |
| Backend KOT | POST /printers/print-kot → station routing → thermal.formatKOT → dispatch |
order-scoped items |
| KOT browser fallback | usePrinter.printKot → kot-encoder bytes → TextDecoder → <pre> HTML → popup |
known-broken semantics (prints raw byte text) |
| Plugin/compliance template | settings.bill_template → loadInstalledPrintTemplate → renderEscposLineTemplateV1 → buildEscPos |
escpos-line-template-v1, fail-closed on renderer mismatch |
| Preview/diagnostics | preview:true → prepareReceipt → escPosToText txt download; lastPrintedBytes bin/hex; test page |
test-page literals policy: human-facing translated, technical literals verbatim |
| Reprints | isReprint banner across classic/compact/browser |
duplicated banner logic ×4 |
Migration Strategy
Strangler, not rewrite. Each child issue is an independently mergeable PR proving value alone. Safety tests land first (parity harness); kernel + labels next; semantic PrintDocument proves itself on ONE FloCafe-owned path (classic receipt via preview) before any broad adoption; plugin/compliance surfaces receive additive localization only; merchant ecosystem waits until PrintDocument exists.
Sequencing
Prerequisite: #437 resolution (standalone bug fix; parity coverage promoted here)
#372/#377 i18n architecture (merged)
Phase 0 A cross-renderer parity & regression contract
Phase 1 B canonical print labels + backend resolution ┐ parallelizable
C shared print kernel + language policy + settings ┘ after A
Phase 2 D PrintDocument v1 (first consumer: classic/preview) [needs B,C]
Phase 3 E backend receipts/KOT/preview migration ┐ parallel [needs D]
F browser/WebUSB/KOT-HTML migration ┘ [needs D]
Phase 4 G compliance template localization [needs B; parallels D–F]
Phase 5 I semantic merchant template model [needs D]
J offline import/export [needs I]
Parallel track: H non-Latin thermal capability study [after A]
Ongoing: K contributor/architecture documentation
Later (separate epics/issues): visual block editor · localized merchant/domain
data · customer-preferred receipt language · per-station KOT language ·
raster implementation (pending H)
Child Issues
Phase 0 — Safety foundation (merge first)
- test(printing): establish cross-renderer receipt parity and regression contract #439 — test(printing): establish cross-renderer receipt parity and regression contract
Phase 1 — Localization foundation (parallelizable once #439 merges)
- refactor(printing): centralize receipt and KOT labels on canonical i18n messages #440 — refactor(printing): centralize receipt and KOT labels on canonical i18n messages · depends: test(printing): establish cross-renderer receipt parity and regression contract #439
- refactor(printing): add shared print kernel, language policy, and receipt language settings #441 — refactor(printing): add shared print kernel, language policy, and receipt language settings · depends: test(printing): establish cross-renderer receipt parity and regression contract #439
Phase 2 — Semantic milestone
- refactor(printing): introduce renderer-independent PrintDocument v1 #442 — refactor(printing): introduce renderer-independent PrintDocument v1 · depends: refactor(printing): centralize receipt and KOT labels on canonical i18n messages #440, refactor(printing): add shared print kernel, language policy, and receipt language settings #441
Phase 3 — Renderer migrations (parallel pair)
- refactor(printing): migrate backend thermal receipts, KOT, and preview to semantic print model #443 — refactor(printing): migrate backend thermal receipts, KOT, and preview · depends: refactor(printing): introduce renderer-independent PrintDocument v1 #442 · parallel with refactor(printing): migrate browser and WebUSB printing to semantic print model #444
- refactor(printing): migrate browser and WebUSB printing to semantic print model #444 — refactor(printing): migrate browser and WebUSB printing · depends: refactor(printing): introduce renderer-independent PrintDocument v1 #442 · parallel with refactor(printing): migrate backend thermal receipts, KOT, and preview to semantic print model #443
Phases 4–5 — Template ecosystem
- feat(printing): add localized label support to compliance print templates #445 — feat(printing): localized label support for compliance templates · depends: refactor(printing): centralize receipt and KOT labels on canonical i18n messages #440 · parallels refactor(printing): introduce renderer-independent PrintDocument v1 #442–refactor(printing): migrate browser and WebUSB printing to semantic print model #444
- feat(printing): add versioned semantic merchant print template model #447 — feat(printing): versioned semantic merchant print template model · depends: refactor(printing): introduce renderer-independent PrintDocument v1 #442
- feat(printing): add validated offline import/export for merchant templates #448 — feat(printing): validated offline import/export for merchant templates · depends: feat(printing): add versioned semantic merchant print template model #447
Parallel research / ongoing docs
- research(printing): evaluate bidi, shaping, and raster fallback for non-Latin thermal printers #446 — research(printing): bidi, shaping, raster fallback study · depends: test(printing): establish cross-renderer receipt parity and regression contract #439 · parallel with all
- docs(printing): document multilingual print architecture and template contribution workflow #449 — docs(printing): architecture & contributor workflow · drafted alongside; final pass after refactor(printing): migrate backend thermal receipts, KOT, and preview to semantic print model #443, refactor(printing): migrate browser and WebUSB printing to semantic print model #444, feat(printing): add versioned semantic merchant print template model #447
Later (separate epics/issues, intentionally not created yet): visual block editor · localized merchant/domain data · customer-preferred receipt language · per-station KOT language · raster implementation (pending #446 outcome).
#437 fix ──► main
│
#438 EPIC
#439 ──┬── #440 ──┬── #445 (compliance labels)
│ ├── #442 ──┬── #443 (backend) ─┐
└── #441 ──┘ ├── #444 (frontend) ─┤ parallel
└── #447 ── #448 │
#446 (research, parallel after #439) │
#449 (docs, ongoing) ◄────────────────────┘
Related Existing Issues
- Not showing Items in Bill #437 — open bug (missing receipt items with Persian products). Remains standalone; this epic's Phase 0 promotes durable regression coverage from it. Epic work must preserve item output and must not stack long-lived branches on the fix branch.
- Feature: Add Online order type, external order ID mapping, & online receipt header banner #284 — open feature (online-order receipt banner). Related consumer: a semantic MessageBlock/banner must make such additions one-block changes instead of N-renderer edits.
- refactor(i18n): migrate to scalable use-intl architecture #372 / refactor(i18n): component migration 5B — POS #377 — closed. The i18n foundation print-localization reuses; no pending work implied.
- feat(i18n): add Persian/Farsi and Iran support #241 — closed. Historical Persian/Iran delivery whose thermal-print limitations this epic addresses properly.
- chore(i18n): add repository-native translation validation and integrity checks #382 — closed translation-validation tooling that label-drift checks extend.
- [Windows] USB thermal printers cannot reliably print raw ESC/POS receipts #206/fix(printing): prevent DOM sanitizer from stripping style tags in thermal receipt templates #185/fix(printing): resolve printWindow.onload race condition in browser thermal printing fallback #184/Keep Electron thermal receipts in sync after Settings currency changes #266/fix(whatsapp): format receipt amounts with Intl.NumberFormat for correct locale currency placement #196 — closed transport/fallback/formatting history informing H and F scope notes.
Explicit Non-Goals
- No visual/Canva-style editor in this epic (later, block-based preferred).
- No cloud/SaaS translation or template dependency; no remote fonts.
- No arbitrary executable plugins; imports stay declarative JSON.
- No changes to tax calculation or financial truth computation.
- No automatic translation of merchant-entered content (products/addons/footers).
- No whole-system printing rewrite in one PR.
- No arbitrary PDF engine unless separately justified.
- No requirement to solve every printer's Arabic firmware inside localization issues (that is H).
- No coupling of receipt language to country or tax pack.
- No second translation system or new npm package for architectural purity without evidence.
- No global RTL flipping of documents because one selected language is RTL.
Contributor Workflow (target experience)
- Add a language: add locale JSON + central-registry entry (existing refactor(i18n): migrate to scalable use-intl architecture #372 flow). Print picks it up automatically; optionally extend label coverage.
- Add a label: edit canonical message files; generator/drift CI updates derived views; no printer knowledge needed.
- Add a renderer: implement against PrintDocument + capability interface; translations come free.
- Add a transport: move what a renderer produced; no content decisions allowed.
- Author a template: declarative semantic schema; validation rejects anything executable; compliance cloning rules documented.
- Tax-pack contributor: existing signed-pack interface unchanged; additive localization fields documented and versioned.
Epic Acceptance Criteria
- All system receipt/KOT/test-page labels resolve through canonical i18n; no hardcoded end-user English remains in migrated print paths except documented exemptions (branding constants; technical literals on the test page such as protocol names, encodings, hex/port values, model identifiers).
- Receipt language can inherit store language or be fixed; optional secondary (bilingual) receipt language supported; KOT language independently configurable.
- Language options everywhere derive from the central registry — zero hardcoded language unions in print code.
- LTR/RTL/mixed-direction semantics represented per document/block/value with correct LTR islands.
- Item/financial content is never silently omitted due to encoding: native render, explicit fallback, or explicit warning/error.
- Classic/compact outputs maintain semantic parity across browser/backend/WebUSB at representative widths (verified actual profiles include 32/36/40/42/44/48-column cases).
- A renderer-independent semantic PrintDocument exists and renderers consume it instead of recomputing business truth.
- Merchant templates have a renderer-independent versioned schema with provenance distinct from compliance packs; imports are declarative, validated, size-capped, non-executable, offline-safe.
- Compliance templates keep their signed-pack lifecycle intact; clones never inherit trust.
- App works fully offline; adding a normal language remains a Git-native translation PR; no ordinary build silently dirties tracked translation-derived files.
- Contributor documentation covers pipeline, schema, language/template/renderer/capability workflows.
- Regression/parity tests cover widths, languages, bilingual layouts, truncation, and Not showing Items in Bill #437 item-output safety.
Progress updates will be added as phase comments; see task list above for live status.
Activity
test(printing): cross-renderer receipt parity contract (#439)
12 remaining items
docs(printing): add non-Latin ESC/POS capability study and hardware-t…
feat: add validated offline merchant template import/export (#477)
khaira777 commentedon Aug 23, 2026
Epic completion summary - the semantic print architecture arc is landed in main:
Follow-ups tracked separately: #475 (picker selection highlight), #284 (online orders - needs maintainer review before any implementation), and the text-shaping dependency decision for a future Phase 1 spike (captain call, pending).
Closing the epic per the captain's directive.
fix(frontend): match bill template highlights by source (#479)
feat(server-app): allow manager and owner logins alongside server (#481)
docs(printing): fix architecture section anchors
khaira777 commentedon Aug 23, 2026
Progress update: multilingual print architecture is ready in #485 for #449, and browser label alignment is in #487 for #480. Both PRs preserve this epic linkage; #485 still needs a current-main update before merge, while #487 is completing CI.
khaira777 commentedon Aug 23, 2026
Completed: browser label alignment merged via #487. Issue #480 is now closed; the PR passed 12 checks with 1 expected Windows skip and had no unresolved review threads.
docs(printing): document multilingual print architecture and template…
docs(printing): fix architecture section anchors
docs(printing): document multilingual print architecture and template…
docs(printing): fix architecture section anchors
docs: document multilingual print architecture and contribution workf…