Skip to content

fix(reports): use paid_at window for profit - #1377

Merged
khaira777 merged 3 commits into
mainfrom
fm/flocafe-financial-summary-paid-window
Oct 26, 2026
Merged

khaira777 merged 3 commits into
mainfrom
fm/flocafe-financial-summary-paid-window

Conversation

@khaira777

@khaira777 khaira777 commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1371

Fixes #1371

Intent

Fix the P2 release-readiness issue from PR #1332 (#1332) interacting with PR #1318 (#1318) at main/routes/reports.ts:677-708: align financial-summary profitability with its settlement window. In main/routes/reports.ts, /financial-summary computes collections using settled bills in the [windowStart, windowEnd) bills.paid_at window, while computePeriodProfitabilitySummary filters order_items by orders.created_at in [windowStart, windowEnd). For an order created before midnight and paid after midnight, /financial-summary reports its profit on the creation day instead of the payment day, disagreeing with buildDailySalesExportDataset in main/services/daily-sales-export.ts:196-251. Align computePeriodProfitabilitySummary with the settled bills.paid_at window and split-bill bill_items allocation.

[P2] Preserve the creation-date aggregate for /topProducts - #1377, main/routes/reports.ts:719
The changed helper also serves /topProducts, whose product rows still use orders.created_at. Confirmed over HTTP: a cross-midnight sale returns two product units and $11.02 profit alongside an aggregate of zero units/null profit on creation day. Payment day returns an empty product list alongside two aggregate units/$11.02 profit. Keep the new settlement query scoped to /financial-summary, preserving the creation-date aggregate for /topProducts, and cover both responses with a regression test.

What Changed

  • Add computeSettledProfitabilitySummary in main/routes/reports.ts and wire /financial-summary to compute profitability over the settled [windowStart, windowEnd) bills.paid_at window with bill_items proportional quantity, revenue, and ingredient cost allocation for split bills.
  • Preserve computePeriodProfitabilitySummary (orders.created_at window) for /topProducts so its aggregate profitability matches its creation-date product rows.
  • Add regression tests in tests/ingredient-cost-lifecycle.test.ts covering cross-midnight order creation versus settlement across /financial-summary, buildDailySalesExportDataset, and /topProducts, plus split bills settled across separate date windows.

Risk Assessment

✅ Low: The change scopes settled paid_at and split-bill bill_items profitability aggregation to /financial-summary (matching buildDailySalesExportDataset) while preserving the orders.created_at aggregate for /topProducts, with end-to-end HTTP regression tests covering both endpoints.

Testing

Ran the focused npm run test:ingredient-cost and npm run test:daily-sales-export suites, built the backend and desktop frontend, stood up an isolated live FloCafe server and SQLite database, and drove all four scenarios end-to-end over HTTP and through the rendered Dashboard UI in headless Chromium, capturing full-page Dashboard screenshots for creation day, settlement day, and both split-bill windows along with JSON/CSV reconciliation evidence. All scenarios passed.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Cross-midnight order creation day (2026-10-18): /api/reports/financial-summary reports zero settled units and null profit on creation day while /api/reports/topProducts preserves the creation-date agg… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-creation-day-2026-10-18.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-e…
Cross-midnight order settlement day (2026-10-19): /api/reports/financial-summary attributes 2 units, $13.00 known-cost revenue, $1.98 ingredient cost, and $11.02 profit (84.77% margin) matching /api/r… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-payment-day-2026-10-19.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-ev…
Split-bill settlement across separate payment windows (2026-10-20 and 2026-10-21): /api/reports/financial-summary allocates quantity, revenue, ingredient cost, and profit proportionally via bill_items… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-split-day1-2026-10-20.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-split-day2-…
Adversarial boundary & guard checks: unpaid orders in window, cancelled/voided/void_adjustment items, unlinked order_items on split bills, proportional inclusive-tax deduction on split bills, and mana… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-evidence.json and npm run test:ingredient-cost

Dashboard on Cross-Midnight Order Creation Day (2026-10-18)
Dashboard on Cross-Midnight Order Settlement Day (2026-10-19)
Dashboard on Split-Bill Settlement Window 1 (2026-10-20)
Dashboard on Split-Bill Settlement Window 2 (2026-10-21)

Evidence: Live HTTP API & Daily Sales Export Reconciliation Evidence

{ "scenario1_cross_midnight_creation_day_2026_10_18": { "financialSummaryProfitability": { "total_quantity": 0, "net_revenue": 0, "known_cost_revenue": 0, "known_cost_quantity": 0, "unknown_cost_quantity": 0, "cost_status": "unknown", "ingredient_cost": null, "profit": null, "margin_percent": null }, "topProductsProfitability": { "total_quantity": 2, "net_revenue": 13, "known_cost_revenue": 13, "known_cost_quantity": 2, "unknown_cost_quantity": 0, "cost_status": "known", "ingredient_cost": 1.98, "profit": 11.02, "margin_percent": 84.77 } }, "scenario2_cross_midnight_payment_day_2026_10_19": { "financialSummaryProfitability": { "total_quantity": 2, "net_revenue": 13, "known_cost_revenue": 13, "known_cost_quantity": 2, "unknown_cost_quantity": 0, "cost_status": "known", "ingredient_cost": 1.98, "profit": 11.02, "margin_percent": 84.77 }, "topProductsProfitability": { "total_quantity": 0, "net_revenue": 0, "known_cost_revenue": 0, "known_cost_quantity": 0, "unknown_cost_quantity": 0, "cost_status": "unknown", "ingredient_cost": null, "profit": null, "margin_percent": null } } }

{
  "scenario1_cross_midnight_creation_day_2026_10_18": {
    "financialSummary": {
      "startDate": "2026-10-18",
      "endDate": "2026-10-18",
      "grossCollected": 0,
      "refunded": 0,
      "netCollected": 0,
      "billCount": 0,
      "refundCount": 0,
      "averageOrderValue": 0,
      "paymentMethods": [],
      "refunds": [],
      "profitability": {
        "total_quantity": 0,
        "net_revenue": 0,
        "known_cost_revenue": 0,
        "known_cost_quantity": 0,
        "unknown_cost_quantity": 0,
        "cost_status": "unknown",
        "ingredient_cost": null,
        "profit": null,
        "margin_percent": null
      }
    },
    "topProducts": {
      "topProducts": [
        {
          "product_id": "prod-latte",
          "product_name": "Latte",
          "total_quantity": 2,
          "total_revenue": 13,
          "order_count": 1,
          "net_revenue": 13,
          "known_cost_revenue": 13,
          "known_cost_quantity": 2,
          "unknown_cost_quantity": 0,
          "cost_status": "known",
          "ingredient_cost": 1.98,
          "profit": 11.02,
          "margin_percent": 84.77
        }
      ],
      "profitability": {
        "total_quantity": 2,
        "net_revenue": 13,
        "known_cost_revenue": 13,
        "known_cost_quantity": 2,
        "unknown_cost_quantity": 0,
        "cost_status": "known",
        "ingredient_cost": 1.98,
        "profit": 11.02,
        "margin_percent": 84.77
      }
    },
    "dailySalesExportSummaryCsv": "metric,value\nbusiness_date,2026-10-18\ntimezone,UTC\nbusiness_day_start,00:00\ncurrency,USD\norder_count,0\npaid_bill_count,0\ngross_collected,0\nrefunds_issued,0\nnet_collected,0\ntax_total,0\ndiscount_total,0\nservice_charge_total,0\npackaging_charge_total,0\ndelivery_charge_total,0\nknown_cost_net_item_sales,0\ningredient_cost_total,\ngross_profit_total,\ngross_margin_percent,\ncost_coverage_status,unknown"
  },
  "scenario2_cross_midnight_payment_day_2026_10_19": {
    "financialSummary": {
      "startDate": "2026-10-19",
      "endDate": "2026-10-19",
      "grossCollected": 13,
      "refunded": 0,
      "netCollected": 13,
      "billCount": 1,
      "refundCount": 0,
      "averageOrderValue": 13,
      "paymentMethods": [
        {
          "method": "cash",
          "count": 1,
          "total": 13
        }
      ],
      "refunds": [],
      "profitability": {
        "total_quantity": 2,
        "net_revenue": 13,
        "known_cost_revenue": 13,
        "known_cost_quantity": 2,
        "unknown_cost_quantity": 0,
        "cost_status": "known",
        "ingredient_cost": 1.98,
        "profit": 11.02,
        "margin_percent": 84.77
      }
    },
    "topProducts": {
      "topProducts": [],
      "profitability": {
        "total_quantity": 0,
        "net_revenue": 0,
        "known_cost_revenue": 0,
        "known_cost_quantity": 0,
        "unknown_cost_quantity": 0,
        "cost_status": "unknown",
        "ingredient_cost": null,
        "profit": null,
        "margin_percent": null
      }
    },
    "dailySalesExportSummaryCsv": "metric,value\nbusiness_date,2026-10-19\ntimezone,UTC\nbusiness_day_start,00:00\ncurrency,USD\norder_count,1\npaid_bill_count,1\ngross_collected,13\nrefunds_issued,0\nnet_collected,13\ntax_total,0\ndiscount_total,0\nservice_charge_total,0\npackaging_charge_total,0\ndelivery_charge_total,0\nknown_cost_net_item_sales,13\ningredient_cost_total,1.98\ngross_profit_total,11.02\ngross_margin_percent,84.77\ncost_coverage_status,known\npayment_cash,13"
  },
  "scenario3_split_bill_settlement_windows": {
    "window1_2026_10_20": {
      "financialSummaryProfitability": {
        "total_quantity": 1,
        "net_revenue": 6.5,
        "known_cost_revenue": 6.5,
        "known_cost_quantity": 1,
        "unknown_cost_quantity": 0,
        "cost_status": "known",
        "ingredient_cost": 0.99,
        "profit": 5.51,
        "margin_percent": 84.77
      },
      "dailySalesExportSummaryCsv": "metric,value\nbusiness_date,2026-10-20\ntimezone,UTC\nbusiness_day_start,00:00\ncurrency,USD\norder_count,1\npaid_bill_count,1\ngross_collected,6.5\nrefunds_issued,0\nnet_collected,6.5\ntax_total,0\ndiscount_total,0\nservice_charge_total,0\npackaging_charge_total,0\ndelivery_charge_total,0\nknown_cost_net_item_sales,6.5\ningredient_cost_total,0.99\ngross_profit_total,5.51\ngross_margin_percent,84.77\ncost_coverage_status,known\npayment_cash,6.5"
    },
    "window2_2026_10_21": {
      "financialSummaryProfitability": {
        "total_quantity": 2,
        "net_revenue": 13,
        "known_cost_revenue": 13,
        "known_cost_quantity": 2,
        "unknown_cost_quantity": 0,
        "cost_status": "known",
        "ingredient_cost": 1.98,
        "profit": 11.02,
        "margin_percent": 84.77
      },
      "dailySalesExportSummaryCsv": "metric,value\nbusiness_date,2026-10-21\ntimezone,UTC\nbusiness_day_start,00:00\ncurrency,USD\norder_count,1\npaid_bill_count,1\ngross_collected,13\nrefunds_issued,0\nnet_collected,13\ntax_total,0\ndiscount_total,0\nservice_charge_total,0\npackaging_charge_total,0\ndelivery_charge_total,0\nknown_cost_net_item_sales,13\ningredient_cost_total,1.98\ngross_profit_total,11.02\ngross_margin_percent,84.77\ncost_coverage_status,known\npayment_card,13"
    }
  },
  "scenario4_adversarial_guards_and_rbac_2026_10_22": {
    "settledSplitInclusiveAndExcludedStatuses": {
      "total_quantity": 1,
      "net_revenue": 10,
      "known_cost_revenue": 10,
      "known_cost_quantity": 1,
      "unknown_cost_quantity": 0,
      "cost_status": "known",
      "ingredient_cost": 2.5,
      "profit": 7.5,
      "margin_percent": 75
    },
    "dailySalesExportSummaryCsv": "metric,value\nbusiness_date,2026-10-22\ntimezone,UTC\nbusiness_day_start,00:00\ncurrency,USD\norder_count,1\npaid_bill_count,1\ngross_collected,11\nrefunds_issued,0\nnet_collected,11\ntax_total,0\ndiscount_total,0\nservice_charge_total,0\npackaging_charge_total,0\ndelivery_charge_total,0\nknown_cost_net_item_sales,10\ningredient_cost_total,2.5\ngross_profit_total,7.5\ngross_margin_percent,75\ncost_coverage_status,known\npayment_cash,11",
    "managerTopProductsWithoutFinancialPermission": {
      "topProducts": [
        {
          "product_id": "prod-latte",
          "product_name": "Latte",
          "total_quantity": 2,
          "total_revenue": 13,
          "order_count": 1
        }
      ]
    }
  }
}

Pipeline

Updates from git push no-mistakes

✅ **intent** - passed

✅ No issues found.

✅ **Rebase** - passed

✅ No issues found.

✅ **Review** - passed

✅ No issues found.

✅ **Test** - passed

✅ No issues found.

  • Live validation: ✅ go - 4 of 4 scenarios driven live against the product
Scenario Result Live Evidence
Cross-midnight order creation day (2026-10-18): /api/reports/financial-summary reports zero settled units and null profit on creation day while /api/reports/topProducts preserves the creation-date agg… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-creation-day-2026-10-18.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-e…
Cross-midnight order settlement day (2026-10-19): /api/reports/financial-summary attributes 2 units, $13.00 known-cost revenue, $1.98 ingredient cost, and $11.02 profit (84.77% margin) matching /api/r… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-payment-day-2026-10-19.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-ev…
Split-bill settlement across separate payment windows (2026-10-20 and 2026-10-21): /api/reports/financial-summary allocates quantity, revenue, ingredient cost, and profit proportionally via bill_items… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-split-day1-2026-10-20.png, ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/dashboard-split-day2-…
Adversarial boundary & guard checks: unpaid orders in window, cancelled/voided/void_adjustment items, unlinked order_items on split bills, proportional inclusive-tax deduction on split bills, and mana… ✅ pass live ~/.no-mistakes/evidence/01M5WNSR1D6DPV6NGF98VMTHVT/live-verification-evidence.json and npm run test:ingredient-cost
  • npm run test:ingredient-cost
  • npm run test:daily-sales-export
  • GET /api/reports/financial-summary?start_date=2026-10-18&end_date=2026-10-18 (live server + Chromium Dashboard UI)
  • GET /api/reports/topProducts?start_date=2026-10-18&end_date=2026-10-18&limit=10 (live server + Chromium Dashboard UI)
  • GET /api/reports/financial-summary?start_date=2026-10-19&end_date=2026-10-19 (live server + Chromium Dashboard UI)
  • GET /api/reports/topProducts?start_date=2026-10-19&end_date=2026-10-19&limit=10 (live server + Chromium Dashboard UI)
  • GET /api/reports/daily-sales/export?date=2026-10-19&format=csv&part=summary (live server)
  • GET /api/reports/financial-summary?start_date=2026-10-20&end_date=2026-10-20 and 2026-10-21 (split-bill windows live server + Chromium Dashboard UI)
  • GET /api/reports/financial-summary?start_date=2026-10-22&end_date=2026-10-22 (adversarial unpaid, cancelled/voided/void_adjustment, unlinked split item, and tax-inclusive split item checks)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Important

Review skipped

Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 8282f3a and 590eb29.

Files selected for processing: 2
  • main/routes/reports.ts
  • tests/ingredient-cost-lifecycle.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

The financial-summary profitability query now uses bills paid within the requested period and applies bill-item allocations to split bills. Tests cover cross-midnight settlement and split bills paid on separate dates.

Changes

Profitability reporting

Layer / File(s) Summary
Settlement-period profitability
main/routes/reports.ts, tests/ingredient-cost-lifecycle.test.ts
The query attributes profitability to the bill payment period. It prorates split-bill revenue and ingredient cost by allocated quantity. It excludes cancelled, voided, and void-adjustment items, but no longer excludes refunded items or cancelled orders. Tests cover settlement-date attribution and split-bill calculations.

Priority: Normal

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

Change: Bug fix · Severity of issue fixed: Low

Possibly related issues

  • Sales reports metrics: This change updates financial-summary profitability calculations, but does not add or expose the revenue, ingredient cost, profit, and margin fields described in the issue.
Merge Risk: Minimal · up to 590eb

The profitability change is mergeable after normal checks; the reported mismatch reflects the intended settlement-window reporting behavior.

Pre-merge checks: Passed 4 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Docstring Coverage Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 4 passed
Check name Status Explanation
Linked Issues check Passed Issue [#1371] requires profitability to use the settled bills.paid_at window and to match split-bill allocation. main/routes/reports.ts now filters bills.paid_at >= ? AND b.paid_at < ?, joins `b…
Out of Scope Changes check Passed The reviewed changes are limited to the profitability query in main/routes/reports.ts and regression tests in tests/ingredient-cost-lifecycle.test.ts. The query changes support issue [#1371] by al…
Title check Passed The title clearly summarizes the primary change: using the paid_at window for profitability reporting.
Description check Passed The description explains the problem, intended change, scope, risks, and verification results. It also includes screenshots and regression evidence. It does not use several template headings or explic…
Full details: Linked Issues check

Explanation

Issue [#1371] requires profitability to use the settled bills.paid_at window and to match split-bill allocation. main/routes/reports.ts now filters bills.paid_at &gt;= ? AND b.paid_at &lt; ?, joins bill_items, prorates quantity, ex-tax revenue, and known ingredient cost, and excludes void or cancelled item rows. main/services/daily-sales-export.ts uses the same paid-window and allocation rules. The reported regression tests cover cross-midnight settlement and split bills paid in separate windows.

Full details: Out of Scope Changes check

Explanation

The reviewed changes are limited to the profitability query in main/routes/reports.ts and regression tests in tests/ingredient-cost-lifecycle.test.ts. The query changes support issue [#1371] by aligning financial-summary profitability with paid bills and daily-sales allocation. The tests verify the required behavior. No unrelated product area or unrelated feature change is shown.

Full details: Description check

Explanation

The description explains the problem, intended change, scope, risks, and verification results. It also includes screenshots and regression evidence. It does not use several template headings or explicitly cover compatibility and data safety, cross-cutting surfaces, developer documentation, or the contributor checklist, but the core information is complete.

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
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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(main): align financial-summary profitability with settled bills window fix(reports): use paid_at window for profit Oct 26, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@khaira777
khaira777 force-pushed the fm/flocafe-financial-summary-paid-window branch from 590eb29 to 9d6b2a9 Compare October 26, 2026 18:17
@khaira777 khaira777 changed the title fix(reports): use paid_at window for profit fix(main): align financial-summary profitability with settled bills window Oct 26, 2026
@khaira777 khaira777 changed the title fix(main): align financial-summary profitability with settled bills window fix(reports): use paid_at window for profit Oct 26, 2026
@khaira777
khaira777 enabled auto-merge (squash) October 26, 2026 18:32
@khaira777
khaira777 merged commit 27bfd1f into main Oct 26, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/flocafe-financial-summary-paid-window branch October 26, 2026 18:42
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.

fix(reports): financial-summary profitability uses order creation window instead of paid_at

1 participant