Repository navigation
feat(regional): adopt resolveRegionalSnapshot() in server app /info - #782
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]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (2)
Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review. 📝 WalkthroughWalkthroughThe Server App info route now uses ChangesRegional snapshot integration
Priority: ⬇️ Low Estimated code review effort: 2 (Simple) | ~10 minutes Change: Bug fix 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 1📝 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 customer phone normalization and migration safety, regional and currency configuration, stale or missing setting fallbacks, dependent-record preservation, request-order handling, and settings persistence. It exercises happy paths, invalid and boundary inputs, retry and upgrade behavior, cross-record data integrity, and user-facing regional and formatting flows. Safe to merge — the run found no regressions, new failures, or previously flagged failures attributable to this PR, and all exercised behaviors passed. No merge-blocking risk is indicated; overall risk is low. Tests run by Ito
Tip 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 SummaryThe run covered core order and receipt behavior, customer phone handling, regional settings, migrations, reporting time boundaries, and server configuration errors. Coverage included normal business flows, edge cases such as missing or invalid regional data and duplicate receipt sends, data-integrity safeguards, and key order-screen rendering and actions. Safe to merge — the exercised behavior is healthy with no PR-attributable regressions, new failures, or previously flagged failures. The remaining untested areas are coverage gaps rather than merge blockers. Tests run by Ito
Tip Reply with @itoqa to send us feedback on this test run. |
|
Diff SummaryCoverage spans setup and regional-configuration behavior, including valid flows, invalid and missing country/timezone inputs, concurrent setup attempts, legacy and fresh stores, and downstream POS, dashboard, printer, and order-processing behavior. The exercised paths include both normal business flows and adversarial edge cases, with overall behavior consistent and no application regressions identified. Safe to merge — the exercised behaviors show no PR-attributable regressions, new failures, or previously flagged failures; all reported checks passed. Remaining untested areas are coverage gaps rather than merge blockers. Tests run by Ito
Tip Reply with @itoqa to send us feedback on this test run. |

What
Adopts
resolveRegionalSnapshot()in the standalone server app's (:3003)/api/server-app/infoendpoint — the first of the design note's two "initial surfaces."main/server-app.tspreviously resolved country/currency/symbol/position/fraction-digits inline, with its own duplicatedcurrencyPosition()helper, and preferred the storedcurrency_symbolsetting over the CLDR-derived value when present. That "stored symbol wins" behavior is exactly what docs/regional-snapshot.md explicitly rejects. This PR replaces that block with a singleresolveRegionalSnapshot(settings)call, mappingRegionalNotConfiguredErrorto the existing409 { error: 'regional_not_configured' }response (behavior unchanged for that case — it previously also 409'd whengetCountryByCodecouldn't resolve a country).The frontend side of this surface (
frontend/src/app/server-standalone/page.tsx) needed no changes — it already renders fromregional?.country || ''/regional?.currency || ''with no INR fallback (fixed in #781).Why this test change
tests/server-app-server-role.test.tshad COP and KWD fixtures that wrote a value into thecurrency_symbolsetting and asserted that literal value came back as the symbol — for KWD it wrote the string'KWD'and asserted the endpoint returned'KWD'as the symbol. That was testing the override behavior the design rejects. Updated to assert the real CLDR narrow symbol ('د.ك.'forar-KW, verified directly against Node'sIntl) and added a case asserting409when no country is configured yet.I also switched this test's settings mutations from
UPDATE ... WHERE key = 'x'to an upsert (INSERT ... ON CONFLICT(key) DO UPDATE). This test bypasses the shared test harness (initDatabase()directly, notinitTestDb()), so once #779 (seed removal) merges andseedInstallDefaults()stops inserting acountryrow, a plainUPDATEwould silently no-op against a table with no matching row — breaking this test invisibly. The upsert works regardless of merge order.Stack / merge order
Based on #781 (frontend fallback sweep), which is based on #780 (backend fallback sweep), based on #778 (resolver). Independent of #779 (seed removal) — no shared files touched, but #779 should merge before or alongside this for the reasons above.
Verification
npx tsc --noEmitcleannpx eslint main/server-app.ts— 9 pre-existing warnings, unchanged (confirmed viagit stashA/B)npm run buildcleannpm run test:server-app-server-role,test:currency,test:country-localization,test:issue-266-currency-symbol-print,test:first-runall passCompliance grep
returns nothing.
🤖 Generated with Claude Code
Summary by CodeRabbit
regional_not_configuredresponse when country or currency settings are incomplete.