Repository navigation
fix: business day differed between UI and reports - #876
Conversation
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.
|
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 configurationConfiguration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (3)
Included review availability: This review used your included allowance. Your plan provides up to 2 included reviews per hour; 1 remain after this review. 📝 WalkthroughWalkthroughBusiness-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. ChangesBusiness-date calculation
Priority: ➖ Normal Estimated code review effort: 3 (Moderate) | ~20 minutes Change: Bug fix Merge Risk: ⚪ Minimal · up to The dashboard and reports use consistent business-date boundaries. No actionable merge-blocking risk remains after normal checks. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation 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.
✨ 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 |
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.
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.tswith 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 owngetLocalDateStringhelper 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.tsnow holds the rule and the day-bounds arithmetic it needs, the backend resolves it throughmain/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.dayBoundsInTimezoneandutcDayBoundsmoved with it becausebusinessDateForInstantneeds the same offset fixup loop that computes a day's start instant, and leaving a second copy of that loop inmain/db.tswould 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:30in America/Santiago,01:00–02:30in Europe/Madrid,01:30and02:30in America/New_York and America/Los_Angeles,03:00and03:30in Pacific/Chatham,01:00–02:30in 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'sbusiness_day_start_timeto its "today". That one is a user-visible date bug, not a relocation: a store whose business day starts at04:00saw 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 any00:00–23:59day start, but the backend never does:tenantBusinessDayStartTimeholds the stored setting to the00:00–11:59contract 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: at09:00 UTCthe backend, the old renderer and the reports all said2026-04-21and the unified rule said2026-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:businessDateForInstantnormalises through the exportednormalizeBusinessDayStartTime, andtenantBusinessDayStartTimedelegates 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.dayBoundsInTimezonedeliberately 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 aDateand astringare each valid in either position, so a swapped call typechecks and moves money between days with no error.main/db.tskeeps a positionallocalDateInTimezonealias 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.tsre-exportsdayBoundsInTimezone,utcDayBoundsand 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.tsandtests/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, astests/business-date.test.ts, and was red before the move. It is table-driven over start times of midnight,04:00and13: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 pinsdayBoundsInTimezone's wider range so the two cannot be conflated again.tests/dashboard-business-date.test.tsguards the dashboard wiring separately, so the page cannot grow its own date helper again. Both are wired intonpm 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, frontendtsc --noEmit,test:script-coverage, and the wholepretest/testchain 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: the00:00–11:59contract inmain/routes/settings.tsis 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