Repository navigation
fix(regional): remove India fallbacks from frontend call sites - #781
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]>
|
Note Currently processing new changes in this PR. This may take a few minutes, please wait... ⚙️ Run configurationConfiguration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (75)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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 spans regional setup and currency behavior, locale and timezone persistence, phone validation and historical data handling, plus dashboard and point-of-sale display flows. It includes normal user journeys and edge cases such as missing or unsupported regional settings, with the application behaving correctly across the exercised PR-relevant areas. Safe to merge — the only observed failure is a pre-existing, medium-severity setup behavior unrelated to this PR, with no regression or PR-attributable failure identified. It is a flag for later rather than a merge blocker. Tests run by ItoAdditional Findings DetailsThese findings are unrelated to the current changes but were observed during testing. 🟡 Setup accepts a store without a country
Evidence PackageTip Reply with @itoqa to send us feedback on this test run. |
…lback sweep
Ito QA (high severity, reproduced): resolveTenantCurrency checked an
explicit currency BEFORE validating the country, so a syntactically-
valid-but-bogus currency (e.g. 'ZZZ') masked an unresolvable country
('ZZ') and the function never threw. A bill could be created and taxed
under completely invalid regional settings, and a later corrected
retry reused that same bad bill. Reordered to validate the country
first — an explicit currency override is still honored for a real
country (e.g. a US store priced in KES), but a bogus country now
always throws RegionalNotConfiguredError regardless of currency.
Also gave RegionalNotConfiguredError a `statusCode = 409` so it maps
correctly through the ~40 existing `error.statusCode || 500` route
catch blocks without each needing its own instanceof check, and fixed
the one bills.ts catch block (POST /generate, the exact endpoint Ito
QA reproduced against) that hardcoded 500 instead of using that
pattern.
CodeRabbit (5 findings, same root cause): order/bill numbering
(main/db.ts), cash closures, reports, and refunds all resolved a
missing timezone to '' and let the date-math helpers silently fall
back to UTC. At a tenant-local day/month/financial-year boundary that
produces the wrong period segment, sequence bucket, closure total, or
refund-window decision — a real correctness bug, not just a display
one. All four now reject with RegionalNotConfiguredError before any
date math runs. The printer test-page route gets the same treatment
via an explicit 409 (not a thrown error, since CodeRabbit noted this
route's catch block converts errors to a generic 500).
CodeRabbit (1 finding): parsePhoneE164 required defaultCountry even
for a number already in full E.164 form, which libphonenumber-js
parses correctly regardless of defaultCountry — so the pre-login
support-ticket route (no resolvable tenant country) rejected valid
international phone numbers. Now only national-format input requires
a resolvable country.
Found while verifying the resolver reorder: two synthetic "business
truly unknown" placeholders in main/printers/thermal.ts relied on the
OLD currency-first short-circuit (explicit currency: 'USD', no
country) to avoid ever reaching the country check. The reorder broke
this — reproduced via tests/printer-fallback-and-popup-verification.ts
throwing RegionalNotConfiguredError. Fixed by giving both placeholders
a matching country: 'US' alongside their currency.
Co-Authored-By: Claude Sonnet 5 <[email protected]>
# Conflicts: # main/countries.ts # tests/regional-snapshot.test.ts
# Conflicts: # frontend/src/app/(dashboard)/orders/page.tsx
|
Diff SummaryCoverage spans core business flows and UI behavior for regional settings, currencies, time zones, phone handling, receipt delivery and status updates, printing, language preferences, orders, and payments. It includes successful user journeys, boundary and invalid-input cases, persistence checks, and protection against incorrect regional defaults, with the exercised behavior broadly healthy. Safe to merge — the only observed failure is a pre-existing setup defect unrelated to this PR, with no regression, new failure, or previously reported PR issue remaining. The unrelated defect is a flag for later rather than a merge blocker. Tests run by ItoAdditional Findings DetailsThese findings are unrelated to the current changes but were observed during testing. 🟠 Setup creates an India store without a country
Evidence PackageTip Reply with @itoqa to send us feedback on this test run. |
…xture Regional settings are no longer auto-seeded on install (#779) — this fixture built its database directly via initDatabase() without going through /setup/initialize, so /print-bill now throws RegionalNotConfiguredError instead of resolving IN/INR as before. Co-Authored-By: Claude Sonnet 5 <[email protected]>
Regional settings are no longer auto-seeded on install (#779) — this fixture built its database directly via initDatabase() without going through /setup/initialize, so /print-bill now throws RegionalNotConfiguredError instead of resolving IN/INR as before. Co-Authored-By: Claude Sonnet 5 <[email protected]>
|
Diff SummaryCoverage focuses on first-time setup and regional behavior: country and phone validation, automatic currency and timezone selection, manual timezone retention, safe retries after invalid input, concurrent setup protection, and country-change persistence. It also exercises the setup interface’s required-field messaging and successful completion flows across common and edge-case scenarios. Safe to merge — the run found no failures attributable to this PR, including no regressions, new failures, or previously reported failures that remain unresolved. Previously passing areas were not exercised in this run and remain flag-for-later coverage gaps, not merge blockers. Tests run by Ito
Tip Reply with @itoqa to send us feedback on this test run. |
Regional settings are no longer auto-seeded on install (#779). These fixtures built their database directly via initDatabase() and set timezone/currency explicitly but never country, so resolveRegionalSnapshot() now throws RegionalNotConfiguredError where it previously resolved IN implicitly. Co-Authored-By: Claude Sonnet 5 <[email protected]>
…t fixtures Regional settings are no longer auto-seeded on install (#779). These fixtures build their database directly via initDatabase() and create real orders through the API (generateOrderNumber requires a resolvable country and timezone), so they now throw RegionalNotConfiguredError where they previously resolved IN/Asia-Kolkata implicitly. Co-Authored-By: Claude Sonnet 5 <[email protected]>

Related work
Design: docs/regional-snapshot.md (#777, ACTIVE DESIGN). PR 3b of the sequence — the frontend half of the fallback sweep (#780 was the backend half). Stacked on #780, which is itself stacked on #778 — this branch is based on #780's tip since the frontend's
@countriesalias resolves directly tomain/countries.ts, so the frontend build needs #780's required-parameter signatures to even type-check. Please merge #778 then #780 first; this will then show a clean diff against main.Summary
Removes the ~59 remaining
|| 'IN'/?? 'INR'fallback sites acrossfrontend/src(hooks, dashboard pages, print encoders,whatsapp-share.ts, the frontend's ownphone.ts), using the same approach as #780: functions the frontend depends on that got required params in #780 (formatCurrencyForTenant,formatNumberForTenant,formatDateForTenant,resolveTenantCurrency,getCurrencyUnitAdapter) now drive real compile errors at every call site that was silently passingundefined; the frontend's ownphone.tshelpers (parsePhone,normalizeOptionalPhone,formatPhoneDisplay) lost their own= 'IN'defaults the same waymain/lib/phone.tsdid in #780.Excluded:
frontend/src/app/setup/page.tsx's one site — already fixed in #779 (the wizard PR). Touching it here would conflict.A real bug found and fixed while verifying this
countryName('')throws —Intl.DisplayNames.of()rejects an empty region code (verified directly in Node). Removing the guaranteed-non-empty'IN'fallback ahead of it made this reachable in five places (the "invalid phone" toast on the customers/tables pages and all three customer modals). Fixed by adding atry/catchtocountryName()itself inmain/countries.tsrather than patching each call site — it's a shared low-level utility, and any future caller would hit the same crash otherwise.Two more fixes in the same spirit — not literal
'INR'/'IN'tokens, but the same category of silent India default:dialCodeFor(...) || '+91'on the tables and customers pages —dialCodeFor()already returns''gracefully on empty input, so the outer fallback was redundant and India-specific (used only as UI placeholder text).print-test/page.tsx's synthetic test tenant only overrodetimezonefrom the real signed-in tenant, leavingcountry/currencyhard-coded to the synthetic'IN'/'INR'defaults fromcreateTestTenant()— a non-Indian merchant testing their printer would see a rupee-denominated test receipt regardless of their actual store's currency. Now overrides all three from the real tenant, consistent with thetimezoneoverride that was already there.Scope
Frontend only. This completes the design note's compliance-grep sweep (backend #780 + frontend, here) — the two initial surfaces (server app, currency input) are the remaining PRs per the note's sequencing, not started here.
Verification
Commands run:
npx tsc --noEmit(frontend) — cleannpx eslint src/(frontend) — 0 errors, 4 warnings, identical to the pre-change baseline (confirmed viagit stashA/B comparison)npm run build:frontend— succeedsnpm test(166+ chained scripts) — clean end-to-end on the first run, 13,811 log lines, exit 0npx tsc --noEmit -p tests/tsconfig.json, filtered to the functions this PR touches — found and fixed two realTS2554(wrong argument count) errors intests/phone.test.tsthatts-node --transpile-only(whatnpm testactually runs) silently skipsCompatibility & data safety
countryName('')crash fix and the print-test currency fix are net-positive behavior changes.Summary by CodeRabbit