Skip to content

fix(main): persist customer attribution on zero-balance bill settlement - #1261

Merged
khaira777 merged 5 commits into
mainfrom
fm/remediate-n2-zero-balance-customer
Oct 21, 2026
Merged

khaira777 merged 5 commits into
mainfrom
fm/remediate-n2-zero-balance-customer

Conversation

@khaira777

@khaira777 khaira777 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1254

Intent

Fix finding N2 (GitHub issue #1254) in FreeOpenSourcePOS/FloCafe: when settling a bill whose remaining balance is zero (prepared.length === 0 in applyPaymentBatch in main/routes/bills.ts) via POST /api/bills/:id/payment or POST /api/bills/:id/payments with a newly selected customer_id, persist the validated effectiveCustomerId to bills.customer_id when !bill.customer_id && effectiveCustomerId before re-reading freshBill and computing calculateCashback, matching the positive-payment branch. Ensure single and batch zero-balance settlements bind customer_id on the bill, award eligible loyalty cashback once when freshBill.total > 0, cache the attributed bill in payment_idempotency, and preserve existing customer conflict (customer_mismatch) and missing-customer (customer_unavailable) rejections.

What Changed

  • Updated applyPaymentBatch in main/routes/bills.ts to persist effectiveCustomerId to bills.customer_id during zero-balance settlements (prepared.length === 0) when the bill does not already have a customer bound.
  • Updated docs/architecture/order-lifecycle.md to document that single and batch zero-balance settlements bind newly selected customer IDs and award eligible loyalty cashback when the bill total is positive.
  • Added regression tests in tests/bills-settlement-idempotency.test.ts verifying customer binding, loyalty ledger accrual, idempotency replay caching, and customer mismatch/unavailability validation on zero-balance settlements.

Risk Assessment

✅ Low: The change is a well-bounded, surgical fix that persists validated customer attribution during zero-balance bill settlement matching the positive-payment path, with complete test coverage and documentation.

Testing

Validated finding N2 zero-balance customer attribution and cashback remediation across 5 live end-to-end scenarios against a running FloCafe instance with full SQLite persistence, followed by regression execution of test:financial-safety-remediation and test:issue-zero-balance-settlement. Single and batch zero-balance settlements successfully bind newly selected customers to the bill, award loyalty cashback once on positive-total bills, replay idempotently with cached responses, and preserve customer conflict and missing-customer rejections.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Single payment on zero-remaining-balance bill binds newly selected customer_id in response and SQLite ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-1-single-payment-zero-balance.json
Batch payment on zero-remaining-balance bill binds newly selected customer_id in response and SQLite ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-2-batch-payment-zero-balance.json
Zero-balance settlement on bill with total > 0 awards cashback and supports idempotent replay ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-3-loyalty-cashback-idempotency.json
Adversarial zero-balance settlement with conflicting customer_id is rejected with customer_mismatch ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-4-adversarial-customer-mismatch.json
Adversarial zero-balance settlement with non-existent customer_id is rejected with customer_unavailable ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-5-adversarial-customer-unavailable.json
Evidence: Live Scenarios Markdown Report
# Live Product Verification: Zero-Balance Settlement Customer Attribution & Loyalty Remediation

## Execution Context
- **Target Branch**: `fm/remediate-n2-zero-balance-customer`
- **Base Commit**: `08187174bfa47f08154e2b9b64cdb17b0ef2c459`
- **Target Commit**: `c6fdc6365e9d73371fb3cfbd2019c7c6ea378d95`
- **Test Mode**: Real Live FloCafe Server Execution (`dev-server.js` on port 38101)
- **Isolation**: Ephemeral directory (`/tmp/flo-live-scenario-1792564205993`) with fresh SQLite WAL database

## Scenarios Driven Live

| Scenario | End-User Action | Observable Product Result | Result | Evidence File |
|---|---|---|---|---|
| **1. Single-Payment Customer Binding** | Cashier submits zero-balance single payment with newly selected customer (`cust-live-1`) on comped bill | HTTP 200 OK; response bill binds `customer_id='cust-live-1'`; SQLite `bills.customer_id` persisted as `cust-live-1` | **PASS** | `scenario-1-single-payment-zero-balance.json` |
| **2. Batch-Payment Customer Binding** | Cashier submits zero-balance batch payment (`payments: [{ amount: 0 }]`) with customer (`cust-live-2`) | HTTP 200 OK; response bill binds `customer_id='cust-live-2'`; SQLite `bills.customer_id` persisted as `cust-live-2` | **PASS** | `scenario-2-batch-payment-zero-balance.json` |
| **3. Positive-Total Loyalty Cashback & Idempotency** | Cashier settles partially-paid and discounted bill (net total 500, balance 0) with customer and `Idempotency-Key` | HTTP 200 OK; credits 50 loyalty cashback points; SQLite records 1 `loyalty_ledger` row; replay returns cached response without duplicate cashback | **PASS** | `scenario-3-loyalty-cashback-idempotency.json` |
| **4. Adversarial Conflict Guard** | Cashier attempts to settle a bill pre-assigned to Customer 1 with Customer 2's ID | HTTP 400 Bad Request (`display_code='customer_mismatch'`); bill customer remains Customer 1 | **PASS** | `scenario-4-adversarial-customer-mismatch.json` |
| **5. Adversarial Missing Customer Guard** | Cashier attempts to settle an unassigned zero-balance bill with a non-existent customer UUID | HTTP 400 Bad Request (`display_code='customer_unavailable'`); settlement aborted, bill remains unpaid | **PASS** | `scenario-5-adversarial-customer-unavailable.json` |

## Verification Result
All 5 live product scenarios passed against the running FloCafe Express API server with SQLite persistence.
Evidence: Scenario 1 - Single Payment Customer Binding Evidence
{
  "scenario": "Single payment zero-balance settlement binds customer to bill and persists in SQLite",
  "passed": true,
  "orderId": 1,
  "billId": 1,
  "request": {
    "endpoint": "POST /api/bills/1/payment",
    "body": {
      "method": "cash",
      "amount": null,
      "customer_id": "cust-live-1"
    }
  },
  "response": {
    "statusCode": 200,
    "bill": {
      "id": 1,
      "bill_number": "INV-20261021-0001",
      "order_id": 1,
      "customer_id": "cust-live-1",
      "subtotal": 500,
      "tax_amount": 0,
      "tax_breakdown": [],
      "tax_snapshot": null,
      "discount_amount": 500,
      "discount_type": "percentage",
      "discount_value": 100,
      "discount_reason": "Full comp",
      "delivery_charge": 0,
      "packaging_charge": 0,
      "service_charge": 0,
      "charges_breakdown": null,
      "round_off": 0,
      "total": 0,
      "paid_amount": 0,
      "balance": 0,
      "payment_status": "paid",
      "payment_details": null,
      "paid_at": "2026-10-21 06:30:08",
      "printed_at": null,
      "created_at": "2026-10-21 06:30:08",
      "updated_at": "2026-10-21 06:30:08",
      "split_group_id": null,
      "split_label": null
    }
  },
  "sqliteRecord": {
    "customer_id": "cust-live-1",
    "payment_status": "paid",
    "balance": 0
  }
}
Evidence: Scenario 2 - Batch Payment Customer Binding Evidence
{
  "scenario": "Batch payment zero-balance settlement binds customer to bill and persists in SQLite",
  "passed": true,
  "orderId": 2,
  "billId": 2,
  "request": {
    "endpoint": "POST /api/bills/2/payments",
    "body": {
      "payments": [
        {
          "method": "cash",
          "amount": 0
        }
      ],
      "customer_id": "cust-live-2"
    }
  },
  "response": {
    "statusCode": 200,
    "bill": {
      "id": 2,
      "bill_number": "INV-20261021-0002",
      "order_id": 2,
      "customer_id": "cust-live-2",
      "subtotal": 500,
      "tax_amount": 0,
      "tax_breakdown": [],
      "tax_snapshot": null,
      "discount_amount": 500,
      "discount_type": "percentage",
      "discount_value": 100,
      "discount_reason": "Full comp",
      "delivery_charge": 0,
      "packaging_charge": 0,
      "service_charge": 0,
      "charges_breakdown": null,
      "round_off": 0,
      "total": 0,
      "paid_amount": 0,
      "balance": 0,
      "payment_status": "paid",
      "payment_details": null,
      "paid_at": "2026-10-21 06:30:08",
      "printed_at": null,
      "created_at": "2026-10-21 06:30:08",
      "updated_at": "2026-10-21 06:30:08",
      "split_group_id": null,
      "split_label": null
    }
  },
  "sqliteRecord": {
    "customer_id": "cust-live-2",
    "payment_status": "paid",
    "balance": 0
  }
}
Evidence: Scenario 3 - Loyalty Cashback & Idempotency Evidence
{
  "scenario": "Zero-balance settlement on positive total bill awards cashback once and replays idempotently",
  "passed": true,
  "billId": 3,
  "initialSettlement": {
    "statusCode": 200,
    "loyaltyPointsEarned": 50,
    "customer_id": "cust-live-2"
  },
  "replaySettlement": {
    "statusCode": 200,
    "loyaltyPointsEarned": 50,
    "customer_id": "cust-live-2"
  },
  "loyaltyLedger": [
    {
      "customer_id": "cust-live-2",
      "bill_id": 3,
      "type": "credit",
      "amount": 50
    }
  ]
}
Evidence: Scenario 4 - Adversarial Customer Mismatch Evidence
{
  "scenario": "Adversarial rejection of conflicting customer on zero-balance settlement (customer_mismatch)",
  "passed": true,
  "billId": 4,
  "request": {
    "endpoint": "POST /api/bills/4/payment",
    "body": {
      "method": "cash",
      "amount": 0,
      "customer_id": "cust-live-2"
    }
  },
  "response": {
    "statusCode": 400,
    "body": {
      "error": "Payment customer does not match the bill customer",
      "reason_code": "payment.invalid",
      "operation": "payment.create",
      "stage": "validation",
      "classification": "expected_rejection",
      "outcome": "not_applied",
      "correlation_id": "7007eeb9-2d12-4d49-84e4-63d841ee985b",
      "display_code": "customer_mismatch"
    }
  },
  "sqliteRecord": {
    "customer_id": "cust-live-1",
    "payment_status": "unpaid"
  }
}
Evidence: Scenario 5 - Adversarial Customer Unavailable Evidence
{
  "scenario": "Adversarial rejection of non-existent customer on zero-balance settlement (customer_unavailable)",
  "passed": true,
  "billId": 5,
  "request": {
    "endpoint": "POST /api/bills/5/payment",
    "body": {
      "method": "cash",
      "amount": null,
      "customer_id": "non-existent-customer-live-xyz"
    }
  },
  "response": {
    "statusCode": 400,
    "body": {
      "error": "Customer not found",
      "reason_code": "payment.invalid",
      "operation": "payment.create",
      "stage": "validation",
      "classification": "expected_rejection",
      "outcome": "not_applied",
      "correlation_id": "eb9a1a23-ee21-41de-8bec-ca3fa5c3b79d",
      "display_code": "customer_unavailable"
    }
  },
  "sqliteRecord": {
    "customer_id": null,
    "payment_status": "unpaid"
  }
}

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 - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Single payment on zero-remaining-balance bill binds newly selected customer_id in response and SQLite ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-1-single-payment-zero-balance.json
Batch payment on zero-remaining-balance bill binds newly selected customer_id in response and SQLite ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-2-batch-payment-zero-balance.json
Zero-balance settlement on bill with total > 0 awards cashback and supports idempotent replay ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-3-loyalty-cashback-idempotency.json
Adversarial zero-balance settlement with conflicting customer_id is rejected with customer_mismatch ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-4-adversarial-customer-mismatch.json
Adversarial zero-balance settlement with non-existent customer_id is rejected with customer_unavailable ✅ pass live ~/.no-mistakes/evidence/01M5EJ1VCMQH757E5W9QCMMP0H/scenario-5-adversarial-customer-unavailable.json
  • Live scenario 1: Single payment on zero-remaining-balance bill binds customer_id in response and SQLite
  • Live scenario 2: Batch payment on zero-remaining-balance bill binds customer_id in response and SQLite
  • Live scenario 3: Zero-balance settlement on bill with total > 0 awards cashback and supports idempotent replay
  • Live scenario 4: Adversarial zero-balance settlement with conflicting customer_id is rejected with customer_mismatch
  • Live scenario 5: Adversarial zero-balance settlement with non-existent customer_id is rejected with customer_unavailable
  • npm run test:financial-safety-remediation (tests/financial-safety-remediation.test.ts & tests/bills-settlement-idempotency.test.ts)
  • node tests/run-electron-node-test.cjs tests/issue-zero-balance-settlement.test.ts
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

Ensure single and batch zero-balance settlements bind newly selected customer_id on bills before reading freshBill, award eligible loyalty cashback once, cache the attributed bill in payment_idempotency, and preserve customer conflict/missing customer rejections.

Fixes #1254
@coderabbitai

coderabbitai Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

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
  • Configuration used: Repository: FreeOpenSourcePOS/FloCafe/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 08b3e0d2-de08-44fb-9ddb-8dd9c9416736

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

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@greptile-apps

greptile-apps Bot commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5 Tier: apex

[Medium impact] The PR appears safe to merge; no new actionable issue was found.

Summary

The PR saves the selected customer on zero-balance settlement before cashback and response caching.

  • Single and batch zero-balance settlements save the selected customer on the bill.

No new actionable issues were found. Source checks and git diff --check completed; tests, lint, and builds were not run during this source-only follow-up.

Reviews (2) · Last reviewed commit: "test(bills): refine zero-balance settlem..." · Reviewed by Greptile

@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@khaira777
khaira777 merged commit 9910f23 into main Oct 21, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/remediate-n2-zero-balance-customer branch October 21, 2026 13:52
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(bills): bind validated customer and award eligible cashback on zero-balance settlement

1 participant