Skip to content

fix: business day differed between UI and reports - #876

Merged
khaira777 merged 4 commits into
mainfrom
fm/flocafe-arch-slice5-business-date-r2
Sep 26, 2026
Merged

khaira777 merged 4 commits into
mainfrom
fm/flocafe-arch-slice5-business-date-r2

Conversation

@khaira777

@khaira777 khaira777 commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

api_response:
body: "This is a fix, not a relocation. A store's business day was computed in three different ways, the copies disagreed, and the disagreement was user-visible: the UI could name a different business day than the store's own reports for the same instant. Specifically, the renderer computed the day from wall-clock minutes in frontend/src/lib/business-date.ts with no daylight-saving handling, so on a transition day it picked a boundary the store's reports never used; the dashboard page asked a third question with its own getLocalDateString helper that dropped the store's day-start offset entirely. AGENTS.md invariant 4 says the configured store timezone governs day boundaries, and it was being restated — and contradicted — in every surface that used it.\n\nThe mechanism is consolidation: shared/business-date.ts now holds the rule and the day-bounds arithmetic it needs, the backend resolves it through main/db.ts, and the renderer imports it through the existing @shared/* path, with both copies deleted rather than left behind as a re-export so there is one implementation to read. dayBoundsInTimezone and utcDayBounds moved with it because businessDateForInstant needs the same offset fixup loop that computes a day's start instant, and leaving a second copy of that loop in main/db.ts would have recreated the defect this removes.\n\nExactly one case moves a business day, and it is a correction. It is a store whose configured start time lands inside a daylight-saving gap or fold in its own zone, on the transition day only: 00:30 in America/Santiago, 01:00–02:30 in Europe/Madrid, 01:30 and 02:30 in America/New_York and America/Los_Angeles, 03:00 and 03:30 in Pacific/Chatham, 01:00–02:30 in Antarctica/Troll, and so on depending on the zone, for the one to three hours the transition window covers. In a gap the nominal local start time does not exist that day and in a fold it happens twice; the wall-clock reading had no way to tell the two passes apart, so it put the second pass of the repeated hour on the previous day while the store's own reports have always put it on the current one. I swept the old and new implementations against each other over sixteen timezones — fixed-offset, half-hour, 45-minute, both DST hemispheres, a midnight transition, a two-hour DST shift, and a deliberately invalid zone — at five-minute resolution through every offset change in 2025-2027 and across the whole start-time space including the parse edges: that is the complete set of instants whose business day changes. Everything else is byte-identical, and the backend does not move at all. Separately, and as its own commit, the renderer was briefly made to honour afternoon start times the tenant contract does not allow; that turned out to invent a divergence rather than remove one and is described in the fourth commit.\n\nSeparately, and as its own commit with its own test, the dashboard now applies the store's business_day_start_time to its "today". That one is a user-visible date bug, not a relocation: a store whose business day starts at 04:00 saw the dashboard show the current calendar date for the first four hours of its own business day, with the day picker's upper bound a day ahead of the day a cash close would land on, while the cash-close modal on the same screen already showed the previous business day. The page resolves the date through the same shared rule the close and drawer-movement hooks use, and its local helper is gone.\n\nThe fourth commit exists because a reviewer caught something I got wrong, and it is worth reading on its own. The consolidated rule initially honoured any 00:00–23:59 day start, but the backend never does: tenantBusinessDayStartTime holds the stored setting to the 00:00–11:59 contract the settings endpoint enforces and normalises anything wider to midnight, which the renderer's old copy also did. For a store holding an afternoon value — reachable only by writing the setting directly, since the endpoint rejects it — the unified rule moved the renderer onto a day the backend does not use: at 09:00 UTC the backend, the old renderer and the reports all said 2026-04-21 and the unified rule said 2026-04-20, so the cash-close modal would have offered a date the backend's own future-date guard reads as tomorrow, against a report range the backend computes differently. Midnight was the contract in three places and two independent sides already agreed on it, so the contract now lives in one place: businessDateForInstant normalises through the exported normalizeBusinessDayStartTime, and tenantBusinessDayStartTime delegates to it instead of keeping its own copy of the regex. No backend behaviour changes, because every call site normalises before the rule is reached; comparing old and new along that real path gives 8.4M comparisons and zero mismatches. dayBoundsInTimezone deliberately keeps the full range, pinned by a test, because the report paths depend on it.\n\nThe unified function takes named arguments because the two historical callers passed the same three values in opposite orders, and a Date and a string are each valid in either position, so a swapped call typechecks and moves money between days with no error. main/db.ts keeps a positional localDateInTimezone alias rather than a bare rename for the same reason: renaming a live export would have changed its argument order without a single caller changing.\n\nmain/db.ts re-exports dayBoundsInTimezone, utcDayBounds and the positional alias temporarily, for one release only, and they must be removed in a follow-on commit together with the importers listed here: main/routes/reports.ts, main/routes/cash-closures.ts, main/routes/cash-sessions.ts, main/routes/bills.ts, main/routes/orders.ts, main/services/refund.ts, main/services/daily-sales-export.ts, main/services/cloud-sync.ts, and the four test files that still import the shimmed symbols: tests/business-date.test.ts, tests/cash-closures.test.ts, tests/reports-insights.test.ts and tests/timezone-report-boundaries.test.ts. This is not a decorative shim: I deleted the three re-exports and recompiled, and the build fails at 11 import sites across those 8 production modules, so the follow-on is a real diff rather than a one-line deletion. Leaving them in place after the next release would be the same as not having moved the rule at all.\n\nTest protection landed first, as tests/business-date.test.ts, and was red before the move. It is table-driven over start times of midnight, 04:00 and 13:00, crossed with the 2026 America/New_York spring-forward instant, plus the fall-back fold and a no-daylight-saving afternoon case, and it pins the expected business date per row so a divergence fails on its own value rather than by comparing two implementations to each other. The afternoon row is required and earned its place: it is where the two copies' validators disagreed, and it is what turned into the fourth commit. A further table pins the start-time contract itself, and one assertion pins dayBoundsInTimezone's wider range so the two cannot be conflated again. tests/dashboard-business-date.test.ts guards the dashboard wiring separately, so the page cannot grow its own date helper again. Both are wired into npm test.\n\nVerified on this head: both new suites, test:timezone-report-boundaries, test:issue-389-timezone-override, test:cash-closures (320/320), test:cash-sessions, test:reports-insights (34/34), test:refunds, test:daily-sales-export, test:sequence, test:order-numbering-settings, test:decoupled-ui-locale, the browser end-to-end suite (82 passed), npm run lint (997 backend warnings against a 1000 budget, 5 frontend against 5), npm run lint:budget, npm run build, npm run build:frontend, frontend tsc --noEmit, test:script-coverage, and the whole pretest/test chain in seven bounded groups, all green. The four-platform matrix is green on this head: run 36238530051, all four rows, each running that platform's full test suite before packaging. Locally I packaged macOS x64 and arm64 (dmg and zip), Linux x64 (AppImage) and Windows x64 (win-unpacked); the Linux deb/rpm/snap targets and the Windows NSIS and appx installers need a native host or wine and were not run here. Because the renderer and the backend resolve the boundary through two different ICU builds, I also ran the parity table in headless Chromium against the compiled module: 10/10 rows agree with Node's answers, which is the cross-process date-boundary agreement this repository keeps breaking.\n\nOne open question for a decision, not changed here: the 00:00–11:59 contract in main/routes/settings.ts is narrower than a café's real needs, since a business that opens at 13:00 or 02:00 cannot express it at all, and the settings form has no input for the field. Widening it is a product decision that would move existing stores' report boundaries, so it is deliberately out of scope for a consolidation; this change makes the contract explicit and single-sourced so that decision has somewhere to land."
truncated: false

The backend resolves the business date from an instant; the renderer resolves it
from wall-clock minutes and only accepts a 00:00-11:59 start time, so the two
copies disagree on afternoon day starts and through the repeated hour of a
daylight-saving fall-back. The table crosses 00:00, 04:00 and 13:00 with the
2026 America/New_York spring-forward and fall-back instants and pins the
expected business date per row, so a divergence fails on its own value instead
of by comparing two implementations against each other. Red on the 13:00 and
12:00 rows and on the fall-back fold, which the renderer copy got wrong.
The business day was answered in three places: main/db.ts from an instant,
frontend/src/lib/business-date.ts from wall-clock minutes, and the dashboard
page with no day-start offset at all. This moves the rule and the day-bounds
arithmetic it needs into shared/business-date.ts, deletes both copies rather
than leaving one behind as a re-export, points the renderer hooks at it, and
leaves main/db.ts re-exporting dayBoundsInTimezone, utcDayBounds and a
positional localDateInTimezone alias so every remaining importer of the old
home is visible in a review. Those re-exports have to go in a follow-on,
together with the routes, services and tests that still import them from
main/db; if they are left there the boundary is cosmetic.

This is not a relocation. The two implementations were different algorithms
and merging them changes behaviour wherever the renderer copy was the wrong
one. A store whose business day starts at 12:00 or later previously had that
offset silently ignored in every renderer surface, because the copy only
accepted 00:00-11:59 and fell back to the plain calendar date; the shared
rule accepts the 00:00-23:59 range the backend has always accepted, so the
renderer now rolls those instants back to the previous business day. A store
with a start time inside a daylight-saving fall-back also sees one hour a year
change day, the repeated hour that the wall-clock comparison placed on the
previous day and the instant comparison places on the current one. Neither is
reachable through the settings form, which has no input for the value and
whose API validator caps it at 11:59, so both are corrections to buckets that
were already wrong. Everything else is unchanged: every backend reporting
boundary, the instant-based rule itself, and requireTenantTimezone's refusal
to fall back to UTC.

The unified function takes named arguments because the two historical callers
passed the same three values in opposite orders, and a Date and a string are
each valid in either position, so a swapped call typechecked and moved money
between days. main/db.ts keeps a positional alias rather than a bare rename
for the same reason: renaming would have changed the argument order of a live
export without any of its callers changing.
The dashboard page derived today from the tenant timezone alone, so it was the
third copy of the business-day rule and the one that dropped the day-start
offset entirely. A store whose business day starts at 04:00 saw the dashboard
show the current calendar date for the first four hours of its own business
day, with the day picker's upper bound a day ahead of the day a cash close
would land on, while the cash-close modal on the same screen already showed
the previous business day. The page now resolves the date through the same
shared rule the close and drawer-movement hooks use, and its local
getLocalDateString helper is gone. This is a user-visible date correction, not
a relocation, and it is separate from the move that made the rule shareable.
@coderabbitai

coderabbitai Bot commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

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

Review profile: CHILL

Plan: Advanced

Run ID: 23860b30-3495-488d-8d57-4feab293a1c0

📥 Commits

Reviewing files that changed from the base of the PR and between bbfa80f and c3caa5f.

📒 Files selected for processing (3)
  • main/db.ts
  • shared/business-date.ts
  • tests/business-date.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

Business-date calculations now use a shared helper that applies the tenant timezone and configured business-day start time. Backend date and day-bound functions delegate to or re-export shared calculations. The dashboard and cash-related hooks use the shared helper.

Changes

Business-date calculation

Layer / File(s) Summary
Shared business-date rules and tests
shared/business-date.ts, frontend/src/lib/business-date.ts, tests/business-date.test.ts
Adds shared business-date and day-bound calculations, removes the frontend business-date helper, and tests start-time normalization and date results.
Backend normalization and compatibility wrapper
main/db.ts
Normalizes configured business-day start times through the shared function. Re-exports shared day-bound functions and keeps localDateInTimezone as a wrapper around the shared business-date calculation.
Frontend business-date callers
frontend/src/app/(dashboard)/dashboard/page.tsx, frontend/src/hooks/useCashClose.ts, frontend/src/hooks/useCashDrawerMovements.ts, tests/dashboard-business-date.test.ts
The dashboard and hooks use the shared helper with the configured business-day start time. Dashboard tests cover an instant before the cutoff and a midnight start.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Merge Risk: ⚪ Minimal · up to c3caa

The dashboard and reports use consistent business-date boundaries. No actionable merge-blocking risk remains after normal checks.

Security Architecture Review

Security architecture risk: 🔵 Low · up to c3caa

The shared rule addresses a visible disagreement between the dashboard and reports. Cash routes still apply their existing permissions and transaction controls. No introduced security issue was established, although complete before-and-after parity and deployment behavior remain unverified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The security-relevant reach of a wrong date calculation is chiefly the selection and labeling of a store’s cash activity and reporting period; the reviewed calculation does not itself select an actor or grant a cash permission.

Trust Boundaries and Controls

  • observed — A client-supplied day-close date remains behind the route permission and calendar-date validation. Backend tenant settings, rather than the client’s calculated bounds, supply the persisted period window.

Resilience and Maintainability Implications

  • observed — The shared calculation includes UTC fallbacks when timezone formatting or local-start resolution fails. Those fallbacks preserve a calculable date but make the configured timezone an important input to cash-period correctness.

Hardening Proposals

  • proposed — Make the distinction between normalized date bucketing and raw-offset day bounds explicit for future direct callers, so the same unvalidated setting cannot silently produce different cash-date labels and period bounds.
🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 20 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides extensive technical context, scope, implementation details, tests, and compatibility information, but it does not follow the repository template. Required headings and structu… Rewrite the description using the repository template. Preserve the existing technical details, but place them under the required headings. Complete or mark as not applicable the related work, scope, verification commands and results, compa…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly and concisely identifies the primary fix: aligning business-day calculations between the UI and reports.
Full details: Description check

Explanation

The description provides extensive technical context, scope, implementation details, tests, and compatibility information, but it does not follow the repository template. Required headings and structured sections are missing, including Related work, Summary, Scope, Verification with Commands run and Results, Compatibility & data safety, Cross-cutting surfaces, Developer documentation, and the Contributor checklist.

Resolution

Rewrite the description using the repository template. Preserve the existing technical details, but place them under the required headings. Complete or mark as not applicable the related work, scope, verification commands and results, compatibility and data safety, cross-cutting surfaces, developer documentation, and contributor checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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

❤️ Share

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

@khaira777 khaira777 changed the title fix: one business-date rule across processes fix: business day differed between UI and reports Sep 26, 2026
The consolidation in the previous commit made the shared rule honour any
00:00-23:59 day start, but the backend never does: tenantBusinessDayStartTime
holds the stored setting to the 00:00-11:59 contract the settings endpoint
enforces and normalises anything wider to midnight. The renderer, whose copy
had the same cap, agreed with that. So for a store holding an afternoon value
- only reachable by writing the setting directly, since the endpoint rejects it -
the shared rule moved the renderer onto a business day the backend does not
use: at 09:00 UTC the backend, the old renderer copy and the reports all said
2026-04-21, and the unified rule said 2026-04-20. The cash-close modal would
then have offered a date the backend's own future-date guard reads as tomorrow,
against a report range the backend computes differently.

The afternoon values were not the renderer copy being wrong. Midnight was the
contract in three places - the settings endpoint, the backend read path and the
renderer - and two independent sides already agreed on it, so unifying on the
wider regex would have invented a divergence rather than removed one. The
contract now lives in one place: businessDateForInstant normalises the start
time through the exported normalizeBusinessDayStartTime, and
tenantBusinessDayStartTime delegates to that same function instead of keeping
its own copy of the regex, so the two cannot drift apart again.

No backend behaviour changes. Every call site resolves the setting through
tenantBusinessDayStartTime first, so the rule is always handed an already
normalised value; comparing the old and new backend rules along that real path
across five zones, 24 stored values and every fifteen minutes of 2025-2027 -
including a deliberately invalid zone - gives 8.4M comparisons and zero
mismatches. dayBoundsInTimezone keeps its full 00:00-23:00 range, which the
report paths depend on and which the parity test now pins, because every
backend caller normalises before reaching it and narrowing the primitive would
move an existing store's report range.

The parity table's 13:00 and 12:00 rows now pin midnight on both sides, and the
contract itself is covered by a table, so widening the renderer's range again
turns them red.
@khaira777
khaira777 merged commit 96f2fbd into main Sep 26, 2026
20 checks passed
@khaira777
khaira777 deleted the fm/flocafe-arch-slice5-business-date-r2 branch September 26, 2026 11:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant