Skip to content

chore: unify cross-platform build scripts and configure Windows AppX - #1

Merged
itsbkm merged 2 commits into
FreeOpenSourcePOS:mainfrom
khaira777:main
Jun 10, 2026
Merged

itsbkm merged 2 commits into
FreeOpenSourcePOS:mainfrom
khaira777:main

Conversation

@khaira777

@khaira777 khaira777 commented Jun 9, 2026 •

Copy link
Copy Markdown
Contributor

Overview

This PR introduces several quality-of-life improvements to the build pipeline to ensure local development works seamlessly across all operating systems (specifically fixing Windows PowerShell compatibility) and prepares the app for Windows packaging.

Key Changes

  • Windows Compatibility (cross-env): Added npx cross-env to the build:frontend script. Previously, Windows PowerShell would throw an error trying to parse inline variables like NEXT_BUILD_MODE=desktop, preventing Windows devs from building the frontend.
  • Zombie Process Cleanup (kill-port): Added a clean script that runs before dev to ensure ports 3001 and 3002 are cleared. This prevents the frequent EADDRINUSE crash when restarting the dev server.
  • Submodule Guardrails (predev): Added a git submodule update --init step before the dev server boots to prevent developers from accidentally running stale frontend code against new backend changes.
  • Production Polish (appx): Swapped the boilerplate YOUR_PUBLISHER_DISPLAY_NAME placeholders in package.json with the actual "Codify Apps Private Limited" details to prevent future Microsoft Store certification failures.

Testing

Successfully tested on Windows 11 using PowerShell. The dev server boots cleanly, kills old ports, and compiles Next.js without environment variable errors.

@itsbkm
itsbkm merged commit 07ee2c8 into FreeOpenSourcePOS:main Jun 10, 2026
itsbkm added a commit that referenced this pull request Jul 1, 2026
fix(security): resolve multiple security vulnerabilities (Issues #1–7, #10)
khaira777 pushed a commit that referenced this pull request Jul 6, 2026
chore: unify cross-platform build scripts and configure Windows AppX
khaira777 pushed a commit that referenced this pull request Jul 6, 2026
fix(security): resolve multiple security vulnerabilities (Issues #1–7, #10)
itsbkm added a commit that referenced this pull request Jul 6, 2026
feat: POS UI improvements — topbar table select, customer search, product grid refactor
itsbkm added a commit that referenced this pull request Aug 9, 2026
…gn preview to checkout

Issue #220 item #1 (High): the manual tax builder's category
rename/remove path remapped products.tax_category_id and
addons.tax_category_id, but never touched tax_overrides rows for any
entity type (product, addon, packaging, delivery, service_charge).
Left alone, calculateRawLine throws "resolved unknown tax category"
on checkout for any line still covered by a stale override. Also
found and fixed the deeper cause: validationChecklist's check #20
hard-blocked the save *before* the remap transaction ever ran, so a
local pack could never actually complete this edit — it needed the
same local-pack carve-out check #19 already has.

Issue #220 item #2 (Medium): previewCategoryRate selected rules by
rule.categoryIds alone, while checkout (calculateRawLine) requires
category.ruleIds to also claim the rule. A pack where the two arrays
drift (hand-edited or malformed) could show a rate in the product
picker that checkout never actually charges. previewCategoryRate now
selects the same way checkout does.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
itsbkm added a commit that referenced this pull request Sep 20, 2026
…782)

* feat(regional): add resolveRegionalSnapshot() and contract tests

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]>

* fix(regional): remove India fallbacks from backend call sites

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]>

* fix(regional): remove India fallbacks from frontend call sites

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]>

* feat(regional): adopt resolveRegionalSnapshot() in server app /info

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]>

* fix(regional): address Ito QA + CodeRabbit review findings on the fallback 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]>

* chore: retrigger CI (Actions gap on prior push)

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
itsbkm added a commit that referenced this pull request Sep 20, 2026
…ce path (#783)

* feat(regional): add resolveRegionalSnapshot() and contract tests

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]>

* fix(regional): remove India fallbacks from backend call sites

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]>

* fix(regional): remove India fallbacks from frontend call sites

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]>

* feat(regional): adopt resolveRegionalSnapshot() in server app /info

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]>

* feat(regional): adopt regional snapshot in currency input and CSV price 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]>

* fix(regional): address Ito QA + CodeRabbit review findings on the fallback 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]>

* fix(regional): resolve timezone via resolveRegionalSnapshot with country-profile fallback

Upgrades db.ts, cash-closures.ts, reports.ts, refund.ts, and thermal.ts
(printKOT, buildZReportBody) to derive tenant timezone through
resolveRegionalSnapshot() instead of a bare throw-if-empty check, so a
missing stored timezone gracefully falls back to the country's profile
timezone and only a truly unresolvable country throws
RegionalNotConfiguredError.

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

* chore: retrigger CI (Actions gap on prior push)

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
itsbkm added a commit that referenced this pull request Sep 20, 2026
…stored override (#786)

* feat(regional): add resolveRegionalSnapshot() and contract tests

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]>

* fix(regional): remove India fallbacks from backend call sites

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]>

* fix(regional): remove India fallbacks from frontend call sites

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]>

* feat(regional): adopt resolveRegionalSnapshot() in server app /info

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]>

* feat(regional): adopt regional snapshot in currency input and CSV price 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]>

* fix(regional): resolve receipt currency symbol from CLDR only, not a 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]>

* chore: retrigger CI (Actions gap on prior push)

---------

Co-authored-by: Claude Sonnet 5 <[email protected]>
khaira777 added a commit that referenced this pull request Nov 10, 2026
…Flaky layout scroll assertion in Playwright E2E Shard 2 - **Invariant**: Management list scroll assertions must only run once the asynchronous data payload (supplies) has rendered into the DOM. - **Root Cause**: In [`frontend/e2e/layout-integrity.spec.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/frontend/e2e/layout-integrity.spec.ts#L1635-L1647), the test "inventory actions stay functional after the rows scroll" navigated to `/inventory` and immediately called `scrollToEnd(region)` before the seeded supplies were rendered, measuring `scrollTop: 0`. - **Fix**: Added `await expect(page.getByText('Scroll Layout Supply 01', { exact: true }), 'the seeded supply inventory is loaded').toBeVisible();` before triggering scroll measurement. #### Finding 2: Rate limit cascade (HTTP 429) on test retries and burst traffic - **Invariant**: General API rate limiters must exempt loopback and allowed private IP addresses (`isAllowedPrivateIp`), preventing local POS terminals, kitchen display systems, and automated test runners from encountering false 429 lockouts. - **Root Cause**: When the scroll test failed and Playwright triggered Retry #1, `test.beforeAll` ran synthetic seed functions (`seedSyntheticAddonGroups`, `seedSyntheticMenu`). Multiple route modules (`categories.ts`, `addon-groups.ts`, `customers.ts`, `held-orders.ts`, `kds.ts`, `print-templates.ts`, `settings.ts`, `index.ts`) defined route-level `expressRateLimit` instances with strict 60/min or 120/min windows without setting `skip: isAllowedPrivateIp`, violating the documented architecture invariant (`docs/architecture/authentication-and-authorization.md`). - **Fix**: Sibling sites across all route-level general API rate limiters were updated with `skip: (req: Request) => isAllowedPrivateIp(req.ip || req.socket.remoteAddress || '')`. Added an integration test in [`tests/category-addon-groups.test.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/tests/category-addon-groups.test.ts#L300-L318) verifying that >60 loopback category writes succeed with 201 Created and without HTTP 429. --- ### Verification Summary - `git diff --check`: Clean (no whitespace issues) - `npm run format:check:changed -- --base 400492f`: Passed (0 formatting violations) - `npm run build`: Backend TypeScript compile succeeded - `npm run build:frontend`: Next.js static export succeeded - `npm run lint`: 0 errors backend, 0 errors frontend - `npm run lint:budget`: Backend at 990/1000, frontend at 0/5 - `npm run docs:check`: Markdown lint, link integrity, and policy checks passed - `npm run i18n:check`: Translation parity and print-labels drift checks passed - `npm run test:category-addon-groups`: Passed (including loopback rate-limit bypass test) - `npm run test:release-regressions`: All 10 suites passed - `npm run test:support-ticket`: Passed - `npm run test:cash-sessions`: 366/366 passed - `npm run test:script-coverage`: Passed - *Disclosed check*: The full 4-shard browser E2E suite (`npm run test:e2e:browser`) was not run end-to-end locally due to an external process holding port 3001 outside the worktree
khaira777 added a commit that referenced this pull request Nov 10, 2026
…Flaky layout scroll assertion in Playwright E2E Shard 2 - **Invariant**: Management list scroll assertions must only run once the asynchronous data payload (supplies) has rendered into the DOM. - **Root Cause**: In [`frontend/e2e/layout-integrity.spec.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/frontend/e2e/layout-integrity.spec.ts#L1635-L1647), the test "inventory actions stay functional after the rows scroll" navigated to `/inventory` and immediately called `scrollToEnd(region)` before the seeded supplies were rendered, measuring `scrollTop: 0`. - **Fix**: Added `await expect(page.getByText('Scroll Layout Supply 01', { exact: true }), 'the seeded supply inventory is loaded').toBeVisible();` before triggering scroll measurement. #### Finding 2: Rate limit cascade (HTTP 429) on test retries and burst traffic - **Invariant**: General API rate limiters must exempt loopback and allowed private IP addresses (`isAllowedPrivateIp`), preventing local POS terminals, kitchen display systems, and automated test runners from encountering false 429 lockouts. - **Root Cause**: When the scroll test failed and Playwright triggered Retry #1, `test.beforeAll` ran synthetic seed functions (`seedSyntheticAddonGroups`, `seedSyntheticMenu`). Multiple route modules (`categories.ts`, `addon-groups.ts`, `customers.ts`, `held-orders.ts`, `kds.ts`, `print-templates.ts`, `settings.ts`, `index.ts`) defined route-level `expressRateLimit` instances with strict 60/min or 120/min windows without setting `skip: isAllowedPrivateIp`, violating the documented architecture invariant (`docs/architecture/authentication-and-authorization.md`). - **Fix**: Sibling sites across all route-level general API rate limiters were updated with `skip: (req: Request) => isAllowedPrivateIp(req.ip || req.socket.remoteAddress || '')`. Added an integration test in [`tests/category-addon-groups.test.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/tests/category-addon-groups.test.ts#L300-L318) verifying that >60 loopback category writes succeed with 201 Created and without HTTP 429. --- ### Verification Summary - `git diff --check`: Clean (no whitespace issues) - `npm run format:check:changed -- --base 400492f`: Passed (0 formatting violations) - `npm run build`: Backend TypeScript compile succeeded - `npm run build:frontend`: Next.js static export succeeded - `npm run lint`: 0 errors backend, 0 errors frontend - `npm run lint:budget`: Backend at 990/1000, frontend at 0/5 - `npm run docs:check`: Markdown lint, link integrity, and policy checks passed - `npm run i18n:check`: Translation parity and print-labels drift checks passed - `npm run test:category-addon-groups`: Passed (including loopback rate-limit bypass test) - `npm run test:release-regressions`: All 10 suites passed - `npm run test:support-ticket`: Passed - `npm run test:cash-sessions`: 366/366 passed - `npm run test:script-coverage`: Passed - *Disclosed check*: The full 4-shard browser E2E suite (`npm run test:e2e:browser`) was not run end-to-end locally due to an external process holding port 3001 outside the worktree
khaira777 added a commit that referenced this pull request Nov 10, 2026
* fix(pos): harden POS support log attachment, print failure payloads, and validation guidance

Attach bounded diagnostic log_tail on POS one-click Get Help when opted in while guarding tenant/session switches and idempotent retries, preserve structured printer failure_class/connection_type/correlation_id and sanitized detail through usePrinter into POS support payloads, and present expected_rejection outcomes as validation guidance with non-bug support metadata.

Closes #1463
Closes #1465
Closes #1466

* no-mistakes(review): fix: harden POS support context and failure classification

* no-mistakes(review): fix: scope printer captures and localize validation guidance

* no-mistakes(review): fix: preserve trusted backend printer failure_class verbatim

* fix(pos): narrow backend correlation id type in PrinterOperationError

* no-mistakes(review): validate and preserve POS origin context across async flows

* no-mistakes(review): remove unused metadata permissions and correctiveAction

* no-mistakes(document): update support and print failure docs and fix lint

* no-mistakes(ci): ### Root Cause & Invariant Analysis #### Finding 1: Flaky layout scroll assertion in Playwright E2E Shard 2 - **Invariant**: Management list scroll assertions must only run once the asynchronous data payload (supplies) has rendered into the DOM. - **Root Cause**: In [`frontend/e2e/layout-integrity.spec.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/frontend/e2e/layout-integrity.spec.ts#L1635-L1647), the test "inventory actions stay functional after the rows scroll" navigated to `/inventory` and immediately called `scrollToEnd(region)` before the seeded supplies were rendered, measuring `scrollTop: 0`. - **Fix**: Added `await expect(page.getByText('Scroll Layout Supply 01', { exact: true }), 'the seeded supply inventory is loaded').toBeVisible();` before triggering scroll measurement. #### Finding 2: Rate limit cascade (HTTP 429) on test retries and burst traffic - **Invariant**: General API rate limiters must exempt loopback and allowed private IP addresses (`isAllowedPrivateIp`), preventing local POS terminals, kitchen display systems, and automated test runners from encountering false 429 lockouts. - **Root Cause**: When the scroll test failed and Playwright triggered Retry #1, `test.beforeAll` ran synthetic seed functions (`seedSyntheticAddonGroups`, `seedSyntheticMenu`). Multiple route modules (`categories.ts`, `addon-groups.ts`, `customers.ts`, `held-orders.ts`, `kds.ts`, `print-templates.ts`, `settings.ts`, `index.ts`) defined route-level `expressRateLimit` instances with strict 60/min or 120/min windows without setting `skip: isAllowedPrivateIp`, violating the documented architecture invariant (`docs/architecture/authentication-and-authorization.md`). - **Fix**: Sibling sites across all route-level general API rate limiters were updated with `skip: (req: Request) => isAllowedPrivateIp(req.ip || req.socket.remoteAddress || '')`. Added an integration test in [`tests/category-addon-groups.test.ts`](file:///Users/gurkiratkhaira/.no-mistakes/worktrees/de2296f2e6f8/01M71NMF6BV3RZCFE3EBXRZAX2/tests/category-addon-groups.test.ts#L300-L318) verifying that >60 loopback category writes succeed with 201 Created and without HTTP 429. --- ### Verification Summary - `git diff --check`: Clean (no whitespace issues) - `npm run format:check:changed -- --base 400492f`: Passed (0 formatting violations) - `npm run build`: Backend TypeScript compile succeeded - `npm run build:frontend`: Next.js static export succeeded - `npm run lint`: 0 errors backend, 0 errors frontend - `npm run lint:budget`: Backend at 990/1000, frontend at 0/5 - `npm run docs:check`: Markdown lint, link integrity, and policy checks passed - `npm run i18n:check`: Translation parity and print-labels drift checks passed - `npm run test:category-addon-groups`: Passed (including loopback rate-limit bypass test) - `npm run test:release-regressions`: All 10 suites passed - `npm run test:support-ticket`: Passed - `npm run test:cash-sessions`: 366/366 passed - `npm run test:script-coverage`: Passed - *Disclosed check*: The full 4-shard browser E2E suite (`npm run test:e2e:browser`) was not run end-to-end locally due to an external process holding port 3001 outside the worktree

* fix(pos): address review feedback on diagnostics, log-tail limits, and catalog guidance
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.

2 participants