Skip to content

fix(regional): resolve receipt currency symbol from CLDR only, not a stored override - #786

Merged
itsbkm merged 8 commits into
mainfrom
fix/regional-print-symbol-parity
Sep 20, 2026
Merged

itsbkm merged 8 commits into
mainfrom
fix/regional-print-symbol-parity

Conversation

@itsbkm

@itsbkm itsbkm commented Sep 19, 2026

Copy link
Copy Markdown
Contributor

What

This is the design note's "third surface" — docs/regional-snapshot.md's "Expansion rule" names it directly as "the obvious first candidate": the symbol disagreement between printers.ts and thermal.ts.

Three independent implementations resolved a bill's currency symbol, with contradictory precedence:

Site Precedence
main/routes/printers.ts (/print-bill business object) CLDR first, stored currency_symbol as fallback
main/printers/document-classic.ts buildBillPrintContext() (shared by classic and compact thermal receipts) stored currency_symbol first, CLDR as fallback
main/printers/thermal.ts renderEscposLineTemplateV1() (custom merchant template path) stored currency_symbol first, CLDR as fallback

In the current live call chain this was latent, not actively observable: printers.ts builds the business object and pre-resolves the CLDR symbol into business.currency_symbol before handing it to the thermal renderer, so the renderer's "stored first" read happened to receive an already-correct value. But it meant three contradictory resolution implementations sitting side by side, and any future caller passing a raw business object with a stale stored symbol straight to the thermal renderer would silently diverge from what the browser-facing price shows for the same order. The frontend print encoders (web-print.ts, receipt-encoder.ts, tax-bill-encoder.ts) were already CLDR-only from the earlier fallback sweep (#780/#781) — this was the one remaining gap, confirmed by grepping all three for the same pattern before making this change.

Fix

All three backend sites now derive the symbol from CLDR only (getCurrencySymbol(currency, locale)) and no longer read a stored currency_symbol as an input at all, per the design's hard constraint: "adds any per-store override of a value the snapshot derives (symbol, position, separators)" is explicitly rejected.

Scope was kept tight to just this: country/currency/timezone resolution in these files was already correct and unchanged (handled by the earlier fallback sweep); PrintContext doesn't gain a currencyPosition field since the print pipeline already has its own fixed prefix convention independent of the resolver's locale-position semantics — extending that would be a separate, larger change outside "the symbol disagreement" this PR fixes.

Contract test

Added tests/printer.test.ts "Test 3e": calls formatReceipt() directly (bypassing printers.ts entirely) with a business object where country/currency say Morocco/MAD but currency_symbol is a stale '₹' — proving the renderer's own resolution is correct independent of any caller pre-resolving it, which the existing HTTP-level test (issue-266-currency-symbol-print.test.ts) couldn't prove since it always goes through printers.ts's pre-resolution.

Bug found while writing that test: an existing fixture in the same file ("Narrow receipt reserves 3-char currency codes") was itself exploiting the stored-symbol override — it set currency_symbol: 'USD' without setting currency: 'USD', relying on the override to inject a synthetic 3-character prefix. That stopped working once the override was removed. Replaced with a real, resolvable combination (country: 'US', currency: 'KES' — KES has no dedicated CLDR symbol under en-US, so Intl renders the literal 3-letter code) that exercises the same layout edge case through genuine resolution instead of a shortcut.

Stack / merge order

Based on #783 (currency input surface) → #782 → #781 → #780 → #778.

Verification

  • npx tsc --noEmit clean
  • npm run lint — 0 errors; warning count unchanged (127, confirmed via git stash A/B on the three touched files)
  • npm run build clean
  • npm run test:printer (including the new Test 3e), test:issue-266-currency-symbol-print, test:print-parity, test:print-document, test:print-kernel, test:merchant-print-templates, test:merchant-template-transfer, test:receipt-printing, test:printer-migrations, test:thermal-capabilities all pass
  • Full npm test (166 scripts) passes clean, real exit code 0 (file-redirected, not piped)

🤖 Generated with Claude Code

itsbkm and others added 6 commits September 19, 2026 00:13
Adds the backend resolver from docs/regional-snapshot.md: given a
store's settings, it derives currency symbol, prefix/suffix position,
fraction digits, number separators, and default timezone from the
country/currency pair via Intl/ISO/IANA conventions, throwing
RegionalNotConfiguredError when no country is resolvable rather than
substituting one.

Relocates the locale-preference validation helpers (previously
private to main/routes/settings.ts) into main/countries.ts and
exports them, so the resolver reuses the same per-country option
validation instead of duplicating it — settings.ts now imports them.

Purely additive: no existing seed, wizard, or route behavior changes
in this PR. Removing the India defaults at seedInstallDefaults() and
the setup wizard is deferred to the next PR, which also needs a
central test-harness fix — 107 of 120 test files never go through
/setup/initialize and rely on that seed for a working country.

tests/regional-snapshot.test.ts covers the contract-test matrix from
the design note (USD/COP/EUR/KWD/IRR/INR archetypes, missing/unknown
country, and timezone fallback), wired into npm run test:currency.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
PR 3 of the regional-snapshot sequence (docs/regional-snapshot.md):
sweeps every remaining `|| 'IN'` / `?? 'INR'` / `?? '₹'` / `|| 'Asia/
Kolkata'` fallback out of main/ and shared/, following the "required
parameter, TypeScript drives the caller fixes" approach for the core
functions this depends on (resolveTenantCurrency, formatCurrencyForTenant,
formatNumberForTenant, formatDateForTenant, the print encoders'
options.currencySymbol/currency), and a lower-risk direct fallback
deletion everywhere else once each downstream consumer was confirmed
to already degrade gracefully on an empty/missing value (verified
function-by-function, not assumed).

Two deliberate, documented exceptions, not overlooked:
- main/db.ts migrations v23/v24 keep their 'IN' fallback — one-time
  best-effort cleanup of pre-existing customer phone records on an
  upgrading install, most of which predate multi-country support.
  Historical data heuristic, not a live store's regional identity.
- Login (buildLocalTenant) and the Settings page (businessShape) now
  degrade to empty string rather than throw on a missing regional
  field — unreachable for an authenticated, post-setup store, but a
  login/Settings failure would be far worse than briefly-wrong
  formatting if the invariant were ever violated.

Everywhere else (route handlers building tax/phone/print context,
services/refund.ts, services/tax.ts, services/cloud-sync.ts,
server-app.ts's /info endpoint) either reuses resolveTenantCurrency's
throw or returns 409 { error: 'regional_not_configured' } directly,
matching the design note's contract.

Found and fixed two real, previously-masked bugs while verifying this
against the full test suite (not just the files touched):
- main/printers/thermal.ts had two placeholder "business truly
  unknown" objects (used when no business info is supplied at all,
  e.g. a synthetic preview) missing currency/country entirely — gave
  them an explicit neutral currency: 'USD' rather than let them throw
  or silently resolve to India.
- tests/e2e-argentina-flow.test.ts's "legacy India demo" regression
  scenario called seedSetupProfile(db, 'demo', 'finedine', 'IN') —
  'IN' landed in the *language* parameter slot, not country (which
  was actually omitted and only produced correct-looking Indian demo
  data because the old fallback defaulted it to India regardless).
  Fixed to pass ('en', 'IN') explicitly.

Also relocated two duplicated country→currency resolution helpers
(services/refund.ts, services/tax.ts) to call the shared
resolveTenantCurrency instead of re-implementing the same lookup with
their own 'IN'/'INR' literals.

Verified: npx tsc --noEmit clean; npx eslint main/ shows 0 errors and
the exact same 1003 pre-existing `any` warnings as before this change
(confirmed via git stash comparison, no increase); full npm test
(166+ chained scripts, 13,811 log lines) passes end-to-end.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
PR 3b of the regional-snapshot sequence (docs/regional-snapshot.md),
stacked on #780 (backend sweep) — the frontend sweep. Removes the
~59 remaining `|| 'IN'` / `?? 'INR'` fallback sites across hooks,
pages, and print encoders (frontend/src), following the same approach
as #780: core functions the frontend depends on (formatCurrencyForTenant,
formatNumberForTenant, formatDateForTenant, resolveTenantCurrency,
getCurrencyUnitAdapter, and the frontend's own phone.ts helpers) get
required params; everywhere else gets the fallback deleted once its
downstream consumer is confirmed to degrade gracefully.

Excluded: frontend/src/app/setup/page.tsx's one site — already fixed
in #779 (the wizard PR); touching it here would conflict.

A real crash bug found and fixed while verifying this: `countryName('')`
throws (Intl.DisplayNames.of() rejects an empty region code) — I'm the
one who made this reachable by removing the guaranteed-non-empty 'IN'
fallback ahead of it in five call sites (the "invalid phone" toast
across customers/tables pages and the three customer modals). Added a
try/catch to countryName() itself in main/countries.ts rather than
patching each call site, since it's a shared low-level utility and any
future caller would hit the same crash.

Two additional cleanups in the same spirit, not literal `'INR'`/`'IN'`
tokens but the same category:
- Two `dialCodeFor(...) || '+91'` sites (tables and customers pages) —
  dialCodeFor() already returns '' gracefully on empty input, so the
  outer India-dial-code fallback was redundant and India-specific.
- print-test/page.tsx's synthetic test tenant only overrode `timezone`
  from the real signed-in tenant, leaving country/currency hard-coded
  to the 'IN'/'INR' synthetic defaults — a non-Indian merchant testing
  their printer would see a rupee-denominated test receipt regardless
  of their actual store. Now overrides all three from the real tenant.

Verified: frontend `npx tsc --noEmit` clean; `npx eslint src/` shows
0 errors and the identical 4 pre-existing warnings before/after
(confirmed via git stash A/B); `npm run build:frontend` succeeds;
full npm test (166+ chained scripts, 13,811 log lines) passes clean
end-to-end on the first run. Also fixed two real TS2554 (wrong arg
count) errors in tests/phone.test.ts surfaced by frontend/src/lib/
phone.ts's now-required defaultCountry parameters — found via a
targeted tsc -p tests/tsconfig.json check, since ts-node's
--transpile-only (what npm test actually uses) silently skips type
errors.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
main/server-app.ts's /api/server-app/info endpoint resolved country,
currency, symbol, position, and fraction digits inline and preferred
the stored currency_symbol setting over the CLDR-derived value. Route
it through the shared resolver instead, so the server app renders the
same regional identity as every other adopting surface and the stored
symbol override ("stored symbol wins") that the design explicitly
rejected can no longer take effect.

Updates tests/server-app-server-role.test.ts's COP/KWD fixtures to
assert the real CLDR symbol for KWD (was asserting a literal stored
override) and adds a 409 case for a store with no country configured.

Docs: docs/regional-snapshot.md, "Initial surfaces (exactly two)" #1.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ce path

Implements the second of the design note's two initial surfaces: the
currency input and display path (the surface #697 tried to fix, and
that #693 asks for).

main/countries.ts: adds canonicalizeLocalizedAmount() and
formatAmountForCsv(), pure functions shared by the backend CSV path and
the frontend input widget (via the existing @countries alias) rather
than duplicating locale-parsing logic in two places.

main/routes/menu-csv.ts: product/addon price (and cost) CSV import now
parses through the store's actual decimal/group separators and strips
its own currency symbol, instead of only ever accepting a plain
'.'-decimal token regardless of the store's locale. Export now writes
amounts back in that same locale-formatted shape so a re-imported
export round-trips correctly (previously always emitted plain
'.'-decimal numbers, which would have silently misparsed on a
comma-decimal store once import became locale-aware). Both routes 409
with regional_not_configured if the store has no country yet, via the
same RegionalNotConfiguredError -> 409 mapping used elsewhere.

main/routes/auth.ts: buildLocalTenant() now spreads the full resolved
snapshot into the tenant object (currency_symbol, currency_position,
currency_fraction_digits, decimal_separator, group_separator), per the
design's "Transport (no new state)" section — the desktop renderer
already receives this object at login and via /auth/me, so no new
request or storage is introduced. Also switches currency_display/
number_digits/calendar to the resolver's validated preferences instead
of re-reading the raw, unvalidated setting values.

frontend: new CurrencyAmountInput (components/ui) + useAmountFormat
hook, wired into products/page.tsx and addon-groups/page.tsx's price
and cost fields, replacing native <input type="number">. Groups digits
with the store's own separators as typed and blocks decimal entry
outright when the currency has no fraction digits (COP, JPY, ...).

Found while building this: a first-draft symbol-stripping approach in
canonicalizeLocalizedAmount silently accepted "12abc" as 12 instead of
rejecting it, caught by the existing invalid-price fixtures in
tests/issue-248-menu-csv.test.ts. Tightened it to reject anything that
doesn't reduce cleanly to a plain number.

Docs: docs/regional-snapshot.md, "Initial surfaces (exactly two)" #2.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…stored override

docs/regional-snapshot.md's "Expansion rule" names this as the obvious
first third-surface candidate: main/printers/thermal.ts (via
document-classic.ts's buildBillPrintContext, shared by both the classic
and compact receipt renderers) and its renderEscposLineTemplateV1
plugin-template path preferred a stored currency_symbol setting over
the CLDR-derived one, while main/routes/printers.ts's own /print-bill
business-object construction already did the opposite (CLDR first).

In the current live call chain this was latent rather than actively
observable, because printers.ts pre-resolves the symbol before handing
the business object to the thermal renderer, so the renderer's "stored
first" precedence happened to receive an already-correct value. But it
meant three independent, contradictory implementations of the same
resolution, and any future caller passing a raw business object with a
stale stored symbol straight to the thermal renderer would silently
diverge from the browser-facing price. Frontend print encoders
(web-print.ts, receipt-encoder.ts, tax-bill-encoder.ts) were already
CLDR-only from the earlier fallback sweep; this was the one remaining
gap.

Fix: all three sites now derive the symbol from CLDR only
(getCurrencySymbol(currency, locale)) and no longer read a stored
currency_symbol as an input at all, per the design's "no per-store
override of a value the snapshot derives" hard constraint.

Adds a direct contract test (tests/printer.test.ts, "Test 3e") that
calls formatReceipt() with a business object carrying a stale stored
symbol that contradicts its own country/currency, proving the
renderer's own resolution is correct independent of any caller
pre-resolving it.

Found while adding that test: an existing fixture in the same file
("Narrow receipt reserves 3-char currency codes") was itself relying
on the stored-symbol override to inject a synthetic 'USD' prefix
without a matching currency, which no longer works once the override
is removed. Replaced with a real, resolvable combination (country: US,
currency: KES) that still exercises the same 3-character-prefix layout
edge case through genuine CLDR resolution.

Docs: docs/regional-snapshot.md, "Expansion rule".

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

Next included review available in 33 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used the included review currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml

Review profile: CHILL

Plan: Advanced

Run ID: 11d42488-4152-4cf9-984a-bf7157087ba0

📥 Commits

Reviewing files that changed from the base of the PR and between 3f6fadb and 7eeba69.

📒 Files selected for processing (5)
  • main/printers/document-classic.ts
  • main/printers/thermal.ts
  • main/routes/printers.ts
  • tests/printer.test.ts
  • tests/regional-snapshot.test.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@itoqa

itoqa Bot commented Sep 19, 2026

Copy link
Copy Markdown

Ito QA test results
Commit: fbff3b1: 12 test cases ran, 12 passed ✅.

Summary

Coverage focuses on receipt and printer currency handling, including locale-aware formatting, currency-specific decimal precision, fallback behavior for unknown countries and stale symbols, empty receipts, and both standard and compact output. It also exercises receipt layout and rendering paths across normal, edge-case, and hardware-printing scenarios.

Safe to merge — no regressions, new failures, or still-failing PR-attributable tests were identified. The observed blockers are environment and setup issues rather than product defects, so they are flags for later rather than merge blockers.

Tests run by Ito

View full run

Result Severity Type Description
✅ — General The preview could not run because the local database was not initialized, but the checked print code uses the valid currency and falls back to en-US for an unknown country.
✅ — General The preview could not reach receipt rendering because the local test database had no seeded owner or completed bills. The blocked result is explained by missing test data, not by a confirmed application defect.
✅ — General The printer screen could not be opened because the local browser session stayed at sign-in. No printer retry ran, so this run does not confirm a currency-prefix bug.
✅ — Currency The local database was unavailable before receipt rendering began, so this test did not expose a product failure.
✅ — Currency The hardware-print request was blocked by the local service database setup, but source review confirms that non-preview printing receives the same resolved currency data as preview printing.
✅ — Formatting The receipt preview could not be reached because the local database had no seeded owner or bill, so the request stopped at authentication before any receipt was rendered.
✅ — Formatting The receipt formatter keeps non-zero decimal values and removes trailing .00 only when decimal trimming is enabled. The live preview could not be reached because the local test database had no seeded owner or bills, so this case was confirmed from the production code instead.
✅ — Formatting The empty-item receipt path keeps its resolved currency context and continues to the totals and payment sections. The local check was blocked only because the required owner and bill fixtures were missing.
✅ — Receipt Both classic and compact receipts show MAD950,00 and leave out the old rupee sign.
✅ — Receipt The receipt check could not reach a bill because the local app had no owner or completed bill data. Source review and focused printer coverage support the expected fallback behavior, so the setup block is not treated as a product failure.
✅ — Template The protected print workspace could not be opened because the browser-facing local service did not share the authenticated session accepted by the nested API. The installed receipt renderer was not exercised, so this run confirmed no receipt defect.
✅ — Template The installed receipt renderer was not reachable because the local browser session stayed at the login screen. Source review confirms the renderer uses the resolved currency and falls back to KES instead of using the stale rupee symbol.

Tip

Reply with @itoqa to send us feedback on this test run.

Base automatically changed from feat/regional-currency-input-surface to main September 20, 2026 14:01
@itsbkm
itsbkm merged commit b8d1f31 into main Sep 20, 2026
15 checks passed
@itsbkm
itsbkm deleted the fix/regional-print-symbol-parity branch September 20, 2026 14:16
@itoqa

itoqa Bot commented Sep 20, 2026

Copy link
Copy Markdown

Ito QA test results
Ito Diff Report — fbff3b1 → 7eeba69: 19 test cases ran, 1 new failure ❌, 18 passing ✅.

Diff Summary

Coverage spans currency and locale-aware receipt rendering, setup validation and concurrent updates, order-status business rules, and responsive order-card behavior. It includes happy paths plus invalid-input, boundary, retry, and cancellation edge cases, with the broader product behavior appearing healthy aside from one cancellation-state UI issue.

Merge with caution — the PR introduces a medium-severity, attributable defect in which cancelled orders still expose an enabled reprint action despite indicating that no further actions are available. The remaining exercised currency, setup, receipt, and order-status behaviors do not indicate additional likely application bugs.

Tests run by Ito

View full run

Result State Severity Type Description
❌ ❌ New Failure Medium severity Rev The cancelled card correctly shows the cancellation message, but a focused, enabled Reprint button remains available.
✅ Passing — Amount The payment screen could not be opened because the local target application stopped running. Source inspection confirms the amount input is wired to the tenant locale and currency precision, so this run does not establish a product failure.
✅ Passing — Amount The amount field could not be opened because the local application was stuck on Loading after its target container disappeared.
✅ Passing — General The receipt kept its item, tax, subtotal, total, and cash rows at both 32 and 48 columns. Each amount kept the MAD prefix and comma decimal format.
✅ Passing — General The payment screen stayed on Loading because the local application container disappeared. The blocked run does not show a product failure, and the amount-input code supports the expected precision and grouping behavior.
✅ Passing — General The order list, order details, and order card use the same latest qualifying receipt status. The targeted regression checks passed without surfacing an inconsistent or unrelated ledger row.
✅ Passing — General After an invalid currency was rejected, retrying setup with the same country completed with US currency and time settings.
✅ Passing — General The order status stayed based on the newest qualifying receipt row. A newer failed retry replaced an older sent status, while manual, inbound, and older rows were ignored.
✅ Passing — General Two rapid bill previews completed successfully and both showed the same MAD amounts without the stale rupee symbol.
✅ Passing — General Two setup requests sent at the same time produced one complete US configuration. The other request was rejected, so the saved country, currency, and timezone stayed consistent.
✅ Passing — Currency The bill preview showed MAD amounts for Morocco and ignored the old rupee symbol.
✅ Passing — Format The receipt preview kept the Morocco currency context, comma decimals, two decimal places, trimmed values, selected layout, and all item, tax, total, and payment rows.
✅ Passing — Installed The local app opened the first-run setup screen because the required owner, order, and installed template were missing from the local database. Source review confirms the renderer uses the country and currency locale for financial rows instead of a stale stored symbol.
✅ Passing — Orders Paid orders show the status from their latest outbound bill receipt, while older rows and unrelated messages are ignored.
✅ Passing — Orders The unpaid order stayed Pending and Unpaid, and no receipt status was shown even though the bill had a sent receipt row.
✅ Passing — Receipt The receipt preview could not be opened because the local backend was unavailable. Source checks and the existing printer regression test support the expected currency-prefix behavior.
✅ Passing — Rev Setup returned a clear error for the invalid timezone, and no owner or regional settings were saved.
✅ Passing — Setup Setup completed successfully for the United States and filled in USD and America/New_York from the selected country.
✅ Passing — Setup Submitting the unknown country ZZ returned a clear 400 error, and setup remained available for a later valid request.
⏸️ Skipped — General The preview could not reach receipt rendering because the local test database had no seeded owner or completed bills. The blocked result is explained by missing test data, not by a confirmed application defect.
⏸️ Skipped — General The printer screen could not be opened because the local browser session stayed at sign-in. No printer retry ran, so this run does not confirm a currency-prefix bug.
⏸️ Skipped — Currency The local database was unavailable before receipt rendering began, so this test did not expose a product failure.
⏸️ Skipped — Currency The hardware-print request was blocked by the local service database setup, but source review confirms that non-preview printing receives the same resolved currency data as preview printing.
⏸️ Skipped — Formatting The receipt preview could not be reached because the local database had no seeded owner or bill, so the request stopped at authentication before any receipt was rendered.
⏸️ Skipped — Formatting The receipt formatter keeps non-zero decimal values and removes trailing .00 only when decimal trimming is enabled. The live preview could not be reached because the local test database had no seeded owner or bills, so this case was confirmed from the production code instead.
⏸️ Skipped — Formatting The empty-item receipt path keeps its resolved currency context and continues to the totals and payment sections. The local check was blocked only because the required owner and bill fixtures were missing.
⏸️ Skipped — Receipt Both classic and compact receipts show MAD950,00 and leave out the old rupee sign.
⏸️ Skipped — Template The protected print workspace could not be opened because the browser-facing local service did not share the authenticated session accepted by the nested API. The installed receipt renderer was not exercised, so this run confirmed no receipt defect.
⏸️ Skipped — Template The installed receipt renderer was not reachable because the local browser session stayed at the login screen. Source review confirms the renderer uses the resolved currency and falls back to KES instead of using the stale rupee symbol.
Tests that are no longer relevant

Below are tests that previously ran and are no longer relevant:

Type Test Description
General Unknown country keeps currency fallback Dropped because The fallback asserted by this test was deleted from main/countries.ts: resolveTenantCurrency no longer lets a valid currency bypass country lookup and now throws for an empty or unknown country, eliminating the tested successful receipt fallback.
Receipt Unknown country keeps receipt currency usable Dropped because The unknown-country success path is gone: main/countries.ts now validates the country before accepting an explicit currency in resolveTenantCurrency and throws RegionalNotConfiguredError for an unknown country, so the prior test's successful en-US fallback behavior no longer exists.

Tip

Reply with @itoqa to send us feedback on this test run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant