Repository navigation
fix(regional): resolve receipt currency symbol from CLDR only, not a stored override - #786
Conversation
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]>
|
Warning Review limit reachedNext included review available in 33 minutes. View limit detailsLimit 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. Review configuration: ⚙️ Run configurationConfiguration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
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. Comment |
|
SummaryCoverage 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
Tip Reply with @itoqa to send us feedback on this test run. |
|
Diff SummaryCoverage 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 ItoTests that are no longer relevantBelow are tests that previously ran and are no longer relevant:
Tip Reply with @itoqa to send us feedback on this test run. |


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.tsandthermal.ts.Three independent implementations resolved a bill's currency symbol, with contradictory precedence:
main/routes/printers.ts(/print-billbusiness object)currency_symbolas fallbackmain/printers/document-classic.tsbuildBillPrintContext()(shared by classic and compact thermal receipts)currency_symbolfirst, CLDR as fallbackmain/printers/thermal.tsrenderEscposLineTemplateV1()(custom merchant template path)currency_symbolfirst, CLDR as fallbackIn the current live call chain this was latent, not actively observable:
printers.tsbuilds thebusinessobject and pre-resolves the CLDR symbol intobusiness.currency_symbolbefore 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 storedcurrency_symbolas 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);
PrintContextdoesn't gain acurrencyPositionfield 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": callsformatReceipt()directly (bypassingprinters.tsentirely) with a business object wherecountry/currencysay Morocco/MAD butcurrency_symbolis 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 throughprinters.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 settingcurrency: '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, soIntlrenders 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 --noEmitcleannpm run lint— 0 errors; warning count unchanged (127, confirmed viagit stashA/B on the three touched files)npm run buildcleannpm 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-capabilitiesall passnpm test(166 scripts) passes clean, real exit code 0 (file-redirected, not piped)🤖 Generated with Claude Code