Repository navigation
feat: add auditable cash drawer movements and close integration - #772
Conversation
ChatThere are 3 ways to chat with CodeRabbit:
CodeRabbit commands
Other keywords and placeholders
Status, support, documentation and community
|
|
@coderabbitai rate limit |
|
Your plan includes PR reviews subject to rate limits. More reviews will be available in 56 minutes. |
|
SummaryCoverage spans cash movement recording and reporting, including validation boundaries, date handling, concurrency, role permissions, voids, closed-day protections, migration compatibility, reconciliation, printing, and localized labels. It includes normal workflows, edge cases, adversarial actions, business-rule checks, and UI/report rendering, with the exercised behavior appearing healthy overall. Safe to merge — the run shows no regressions, new failures, or previously flagged failures attributable to this PR. No merge-blocking behavior was identified; any unrelated observations are suitable for later follow-up. Tests run by Ito
Tip Reply with @itoqa to send us feedback on this test run. |
…/Z report contracts
…iness-date calculation
f3a6cf6 to
82db963
Compare
|
Warning Review limit reachedNext included review available in 29 minutes. View limit detailsLimit details: You’ve used the included review currently available. You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Review configuration: ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Advanced Run ID: ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (25)
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 |
Commit: SummaryCoverage spans core cash movement recording and history, reporting and closure rules, database upgrades, role permissions, printing, currency precision, accessibility, and recovery behavior. It also exercises concurrency and rapid-repeat edge cases, with broad happy-path behavior passing but a duplicate-record risk remaining in rapid submissions. Not safe to merge yet — a high-severity, PR-attributable failure allows rapid repeat payments to create duplicate active cash records, which can distort drawer totals and reports. The issue is a durable data-integrity problem in a changed business-critical flow and is a merge blocker. Tests run by ItoTip Reply with @itoqa to send us feedback on this test run. |
| } | ||
| }); | ||
|
|
||
| router.post('/movements', requireRole(...ROLE_ACCESS.ownerManagerCashier), (req: Request, res: Response) => { |
There was a problem hiding this comment.
Rapid Pay In creates a duplicate record
What failed: Two identical Pay In submissions both succeeded, and movement history showed two active rows for 500 cents instead of one.
Impact · Steps · Stub / mock · Analysis · Why this is likely a bug
- Severity: High
- Impact: A rapid repeat payment entry can create two active cash records instead of one. This can make drawer totals wrong and require staff to correct the records.
- Steps to Reproduce:
- Open an available business date with an authenticated cashier session.
- Submit a Pay In of 500 cents with reason BF-RAPID-1 twice at the same time.
- Reload movement history for that date and compare the active rows with the submitted action.
- Stub / mock content: A loopback-only Playwright authentication bypass supplied a local cashier identity. No production services or customer data were used.
- Code Analysis: The runtime result is supported by the production write path. In main/routes/cash-closures.ts:492-518, POST /movements validates the request and checks only whether the business date is closed at line 503, then executes an unconditional INSERT into cash_drawer_movements at lines 505-509. The only conflict handling at lines 511-515 is for the partial unique index on an active opening_float; Pay In rows have no uniqueness constraint, request key, or transaction-level deduplication. Migration 84 in main/db.ts:4078-4094 creates the table and indexes business_date/created_at, but its only unique index is cash_drawer_one_opening_float for movement_type = 'opening_float'. Therefore two simultaneous valid Pay In requests can both commit as separate active rows, exactly matching the observed ids 2 and 3. The smallest practical fix is to add an idempotency key for a user submission and enforce it with a database uniqueness constraint, or otherwise add a narrowly scoped duplicate-submission key/check for Pay In writes; the fix must be applied to the changed movement write path rather than relying on the UI button state.
- Why this is likely a bug: This is an accidental duplicate durable record, not a display-only mismatch: both requests returned 201 and both rows remained active in the history. Pay In amounts feed the cash movement totals used by the drawer reports, so the duplicate can make recorded cash differ from the physical drawer. The API documentation describes an append-only movement history, while the baseline correctness requirement is that a valid action must not create an accidental duplicate record. The new PR code protects only opening floats and leaves ordinary Pay In writes open to this race. A targeted server-side idempotency or duplicate-submission guard is practical and would preserve legitimate separate Pay Ins when their submission keys differ.
Relevant code
main/routes/cash-closures.ts:492-526
router.post('/movements', ...); const id = withTxn(() => { if (closedDayExists(db, businessDate)) ...; const result = db.prepare(`INSERT INTO cash_drawer_movements (...) VALUES (?, ?, ?, ?, ?, ?)`).run(...); return Number(result.lastInsertRowid); });main/db.ts:4078-4094
CREATE TABLE IF NOT EXISTS cash_drawer_movements (...); CREATE UNIQUE INDEX IF NOT EXISTS cash_drawer_one_opening_float ON cash_drawer_movements(business_date) WHERE movement_type = 'opening_float' AND voided_at IS NULL;docs/API.md:1116-1153
List the append-only cash-drawer movement history ... Append a cash-drawer movement to an open tenant business date.Evidence Package
Copy prompt for an agent
Ito QA identified the following failure during automated PR testing. Please investigate and propose a fix.
**High severity — Rapid Pay In creates a duplicate record**
**What failed:** Two identical Pay In submissions both succeeded, and movement history showed two active rows for 500 cents instead of one.
- **Impact:** A rapid repeat payment entry can create two active cash records instead of one. This can make drawer totals wrong and require staff to correct the records.
- **Steps to reproduce:**
1. Open an available business date with an authenticated cashier session.
2. Submit a Pay In of 500 cents with reason BF-RAPID-1 twice at the same time.
3. Reload movement history for that date and compare the active rows with the submitted action.
- **Stub / mock content:** A loopback-only Playwright authentication bypass supplied a local cashier identity. No production services or customer data were used.
- **Code analysis:** The runtime result is supported by the production write path. In main/routes/cash-closures.ts:492-518, POST /movements validates the request and checks only whether the business date is closed at line 503, then executes an unconditional INSERT into cash_drawer_movements at lines 505-509. The only conflict handling at lines 511-515 is for the partial unique index on an active opening_float; Pay In rows have no uniqueness constraint, request key, or transaction-level deduplication. Migration 84 in main/db.ts:4078-4094 creates the table and indexes business_date/created_at, but its only unique index is cash_drawer_one_opening_float for movement_type = 'opening_float'. Therefore two simultaneous valid Pay In requests can both commit as separate active rows, exactly matching the observed ids 2 and 3. The smallest practical fix is to add an idempotency key for a user submission and enforce it with a database uniqueness constraint, or otherwise add a narrowly scoped duplicate-submission key/check for Pay In writes; the fix must be applied to the changed movement write path rather than relying on the UI button state.
- **Why this is likely a bug:** This is an accidental duplicate durable record, not a display-only mismatch: both requests returned 201 and both rows remained active in the history. Pay In amounts feed the cash movement totals used by the drawer reports, so the duplicate can make recorded cash differ from the physical drawer. The API documentation describes an append-only movement history, while the baseline correctness requirement is that a valid action must not create an accidental duplicate record. The new PR code protects only opening floats and leaves ordinary Pay In writes open to this race. A targeted server-side idempotency or duplicate-submission guard is practical and would preserve legitimate separate Pay Ins when their submission keys differ.
**Relevant code:**
`main/routes/cash-closures.ts:492-526`
~~~typescript
router.post('/movements', ...); const id = withTxn(() => { if (closedDayExists(db, businessDate)) ...; const result = db.prepare(`INSERT INTO cash_drawer_movements (...) VALUES (?, ?, ?, ?, ?, ?)`).run(...); return Number(result.lastInsertRowid); });
~~~
`main/db.ts:4078-4094`
~~~typescript
CREATE TABLE IF NOT EXISTS cash_drawer_movements (...); CREATE UNIQUE INDEX IF NOT EXISTS cash_drawer_one_opening_float ON cash_drawer_movements(business_date) WHERE movement_type = 'opening_float' AND voided_at IS NULL;
~~~
`docs/API.md:1116-1153`
~~~markdown
List the append-only cash-drawer movement history ... Append a cash-drawer movement to an open tenant business date.
~~~

Intent
Verify the focused FloCafe cash-drawer implementation, run it through no-mistakes, and land the resulting pull request. The accepted scope is opening float, Pay In, Pay Out, Safe Drop, append-only movement history with auditable soft voids, integration with Day Close X/Z and printed output, the compact dashboard workflow, the additive migration, and regression coverage. Publish a new focused pull request from current main rather than modifying or closing the broad draft #680. Preserve and credit the contributor history from that draft where relevant, and merge the new pull request when the required checks are green.
What Changed
Risk Assessment
Testing
Built the target backend/frontend, ran focused cash-closure, migration, and print checks, then drove the real native FloCafe app through movement recording, soft voiding, X preview, counting, and Z creation. Live API evidence confirms audit metadata, Z totals, and post-close rejection. Physical printer dispatch and startup migration were not live-driven; UI screenshots were captured inline by CUA, while macOS file export lacked Screen Recording permission. The worktree is clean.
Evidence: Live cash API evidence
GET movements after close: HTTP 200; four rows returned including voided Pay in with void_reason=Entered twice POST movement after close: HTTP 409; This day is already closed GET Z after close: HTTP 200; expected_cash_cents=8500; counted_cash_cents=8500; variance_cents=0Evidence: Live FloCafe UI evidence
Pipeline
Updates from git push no-mistakes
✅ **intent** - passed
✅ No issues found.
✅ **Rebase** - passed
✅ No issues found.
🔧 **Review** - 3 issues found → auto-fixed (6) ✅
frontend/src/hooks/useCashDrawerMovements.ts:46- The movement modal uses the calendar date, while the backend and day-close flow use the configured business-day start. With a 04:00 start at 02:00, the modal defaults to tomorrow's calendar date; the API rejects it as future or assigns it to the wrong close. Derive the default/max date using the tenant business-day start.frontend/src/hooks/useCashDrawerMovements.ts:57- Concurrent history requests can overwrite each other: open the modal for date A, select date B, then let A's slower response resolve after B's. The UI displays A's movements while B is selected. Abort prior requests or ignore responses whose requested date is no longer current.main/routes/reports.ts:679- The X-report calculation now includes pay-ins and subtracts pay-outs/safe drops, but the close modal still labels that value “Expected cash (sales only).” For any non-zero movement, the displayed value contradicts its label and can mislead counting. Confirm whether to rename the label to movement-adjusted expected cash or change the displayed calculation.🔧 Fix applied.
2 warnings still open:
main/routes/reports.ts:679- The X-report formula now includes pay-ins and subtracts pay-outs/safe drops, but the modal still labels it “Expected cash (sales only)” (frontend/src/components/dashboard/CashCloseModal.tsx:130). With any non-zero movement, this misstates the displayed value; confirm whether to rename the label or change the calculation.frontend/src/hooks/useCashDrawerMovements.ts:106- An empty opening-float input is coerced by Number('') to 0, and zero is allowed for opening_float, so recording with no amount creates a zero active opening float and can block a later correct opening float via the unique index. Reject blank input before numeric conversion.🔧 Fix applied.
1 warning still open:
main/routes/reports.ts:679- The X-report calculation now includes pay-ins and subtracts pay-outs/safe drops, but the close modal still labels this value “Expected cash (sales only)” at frontend/src/components/dashboard/CashCloseModal.tsx:130. Any non-zero movement makes the label contradict the displayed amount and can mislead cash counting. Confirm whether to rename the label or change the calculation.🔧 Fix applied.
1 warning still open:
main/routes/reports.ts:679- The changed X-report formula now includes Pay In, Pay Out, and Safe Drop, and the response adds opening/movement fields, but docs/API.md still documents expectedCashCents as cash-sales-only and omits the new movement endpoint/response contract. Update the public API documentation to match the shipped behavior so clients are not guided to compute or display stale values.🔧 Fix applied.
3 issues (1 error, 2 warnings) still open:
frontend/src/components/dashboard/CashCloseModal.tsx:131- The Step 1 close preview rendersxReport.expectedCashCents, but that API field deliberately excludes the opening float. After an opening float is recorded, the preview shows a lower drawer expectation than Step 2 and the stored Z (for example, 10,000 float + 50,000 sales + movements yields 52,000 here versus 62,000 at close). Include the active opening float in this displayed total or label it explicitly as excluding float.main/routes/cash-closures.ts:205- If any stored snapshot JSON is malformed,safeJsonlogs the error and substitutes an empty array, so printing can return success with payment, tax, staff, or cash-movement sections silently omitted. This contradicts the comment that corrupt immutable financial data must surface; fail the print with an explicit error instead of claiming a complete Z was printed.docs/API.md:1118- The new API documentation says the movement-history endpoint returns only unvoided rows, but the route callslistCashDrawerMovementswith its defaultincludeVoided=trueand the accepted audit-history behavior exposes soft-void metadata. The same document's printed-Z layout also omits the cash-movements section now emitted bythermal.ts. Update both descriptions to match the shipped contracts.🔧 Fix applied.
2 warnings still open:
main/routes/cash-closures.ts:481- Simplification: the new movement-history route accepts bothbusiness_dateand an undocumented-by-intentdatealias at this line. The focused scope does not require a second matching path; remove the alias and keep the requiredbusiness_datecontract unless backward compatibility is explicitly intended.frontend/src/hooks/useCashDrawerMovements.ts:30- Simplification and drift risk: this new local business-date calculator duplicates the existing close-hook calculation and accepts 00:00-23:59, while the backend canonical setting parser accepts only 00:00-11:59. A stale value such as 20:00 can make the movement UI select a different date from the backend. Remove the parallel definition and reuse one canonical supported-range calculation.🔧 Fix applied.
✅ Re-checked - no issues remain.
🔧 **Test** - 2 issues found → no changes applied (2) ✅
npm ci --ignore-scriptsnpm run buildFLO_DEV_USER_DATA=/tmp/flocafe-cash-drawer-live-01M2S7W06P2EVF6C9RE9S4HNHS JWT_SECRET=<test-only> node dev-server.jsLive setup/login and cash-drawer API scenarios via curlTCP thermal-printer capture on ports 9100 and 9101npm run test:cash-closuresnpm run test:migration-v81-cash-closuresgit diff --check🔧 No changes applied.
1 warning still open:
npm run test:cash-closuresnpm run test:migration-v81-cash-closuresnpm run test:print-kernelnpm run buildnpm run build:frontendnpx playwright test e2e/cash-drawer-live.tmp.electron.spec.ts --config=playwright.electron.config.ts --project=electron-desktop🔧 No changes applied.
✅ Re-checked - no issues remain.
npm run buildcd frontend && npm run buildnpm run test:cash-closuresnpm run test:migration-v81-cash-closuresnpm run test:print-kernelCUA native FloCafe setup and loginCUA dashboard cash-movement workflowCUA Opening float, Pay in, Pay out, Safe drop recordingCUA soft void with audit reasonCUA close preview, count, and Z previewLive movement-history, post-close rejection, and Z-report API checksFinalgit status --short --branchand transient-artifact cleanup audit✅ **Document** - passed
✅ No issues found.
✅ **Lint** - passed
✅ No issues found.
✅ **Push** - passed
✅ No issues found.