Skip to content

fix(main): harden WhatsApp offline abort, split-bill deduplication, loyalty rounding, and auto-settlement automation - #1323

Merged
khaira777 merged 2 commits into
mainfrom
fm/ship-whatsapp-and-settlement-audit-fixes
Oct 23, 2026
Merged

khaira777 merged 2 commits into
mainfrom
fm/ship-whatsapp-and-settlement-audit-fixes

Conversation

@khaira777

Copy link
Copy Markdown
Contributor

Intent

Verify and fix the WhatsApp offline/concurrency regressions and the exact-balance auto-settlement paid-bill automation regression from the merged-PR release audit, plus fix 3-decimal and 0-decimal loyalty rounding in main/services/whatsapp.ts:

  1. Cancel pending WhatsApp lookups in main/services/whatsapp.ts: Version requests (resolveWaWebVersion) continue, and Baileys fallback requests (fetchLatestWaWebVersion) can start, after enabling Offline mode (suspendForOfflineMode).
  2. Deduplicate concurrent milestones in main/services/whatsapp.ts: Concurrent split payments (triggerBillPaidAutomation) can send duplicate nth_visit messages for one visit while the first call is still awaiting onWhatsApp.
  3. Dispatch automation after auto-settlement in main/routes/bills.ts: Exact-balance auto-settlement (completeExactBalanceSettlement) when syncing an unpaid order bill (syncUnpaidOrderBills) or generating a bill (POST /api/bills/generate) marks the bill paid and awards loyalty points, but skips configured paid-bill automation (triggerBillPaidAutomation).
  4. Honor tenant currency precision (regional.currencyFractionDigits) in roundLoyaltyAmount inside main/services/whatsapp.ts so 3-decimal (KWD) and 0-decimal (JPY) currencies are rounded accurately instead of hardcoded 2-decimal rounding.

What Changed

  • Abort in-flight WhatsApp version lookups and connection attempts (resolveWaWebVersion, startSocketImpl, connectWithQr, connectWithPairingCode) when Offline mode is enabled (suspendForOfflineMode), preventing fallback Baileys version fetches from starting while offline.
  • Deduplicate nth_visit milestone sends across concurrent and sequential split-bill settlements per order and customer (inFlightNthVisitKeys and hasNthVisitMessageForOrder), and round loyalty amounts in roundLoyaltyAmount and buildWhatsAppTemplateContext using the tenant currency's currencyFractionDigits (supporting 0-decimal and 3-decimal currencies).
  • Queue and flush whatsapp.triggerBillPaidAutomation after committed exact-balance auto-settlements (completeExactBalanceSettlement in main/routes/bills.ts), update docs/architecture/cloud-integrations.md, and add regression tests in tests/whatsapp-service.test.ts and tests/issue-exact-balance-settlement.test.ts.

Risk Assessment

✅ Low: The changes are tightly scoped to the four requested WhatsApp offline/concurrency/rounding fixes and exact-balance auto-settlement automation dispatch, with transaction-safe post-commit flushing and behavioral regression tests.

Testing

Ran the focused WhatsApp service, exact-balance settlement, offline-mode, and script-coverage suites, then stood up an isolated FloCafe Express API and SQLite instance to drive all six scenarios (including two adversarial boundary checks) live over HTTP and capture API response and database evidence; no UI surface was modified by this backend-only change, and all checks passed.

  • Live validation: ✅ go - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Enabling Offline Mode via PUT /api/settings/offline-mode while POST /api/whatsapp/connect is fetching the WhatsApp web version immediately aborts the in-flight version request, blocks the Baileys fall… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Attempting POST /api/whatsapp/connect (QR or pairing code) while Offline Mode is active is rejected with "Offline mode is on." without initiating outbound version lookups or sockets ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Paying two split checks of the same dine-in order concurrently via POST /api/bills/:id/payment while the first nth_visit milestone lookup is awaiting onWhatsApp sends and persists only one nth_visit m… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Auto-settling a partially paid bill to exact balance via order item edit (PATCH /api/orders/:id/items/:itemId/edit), bill discount (POST /api/bills/:id/applyDiscount), or bill resync (POST /api/bills/… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Attempting a bill discount below already-collected funds via POST /api/bills/:id/applyDiscount fails with HTTP 409 (below_collected_funds) and does not dispatch WhatsApp paid-bill automation ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Rendering WhatsApp loyalty templates and sending paid-bill messages under 3-decimal (KWD) and 0-decimal (JPY) tenant currencies honors currencyFractionDigits instead of hardcoded 2-decimal rounding ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Evidence: Live scenario API responses and persisted SQLite state
{
  "baseUrl": "http://127.0.0.1:65131",
  "scenarios": {
    "scenario1": {
      "offlineModePutResponse": {
        "offline_mode": true
      },
      "versionFetchSignalAbortedImmediately": true,
      "baileysFallbackVersionCalls": 0,
      "connectResponse": {
        "ok": false,
        "error": "Offline mode is on."
      },
      "whatsappStatus": {
        "enabled": true,
        "state": "disconnected",
        "connectedPhone": null,
        "lastError": null,
        "lastErrorReason": null,
        "cooldownUntil": null,
        "filterGroups": true
      }
    },
    "scenario2": {
      "qrConnectWhileOffline": {
        "ok": false,
        "error": "Offline mode is on."
      },
      "pairingConnectWhileOffline": {
        "ok": false,
        "error": "Offline mode is on."
      },
      "outboundVersionFetchCalls": 0,
      "socketCreations": 0
    },
    "scenario3": {
      "orderId": 1,
      "splitBillIds": [
        1,
        2
      ],
      "nthVisitMessagesInDb": [
        {
          "id": 1,
          "bill_id": 1,
          "customer_id": "cust-split-live",
          "kind": "auto_followup",
          "status": "sent",
          "created_by_user_id": "rule:nth_visit",
          "body": "Thank you for 1 visits to Store, Split Milestone Guest!\nTotal spent with us: $400.00. Current points balance: 40 ($40.00).\nWe appreciate your loyalty and look forward to seeing you again!\nReply STOP to opt out."
        }
      ],
      "apiMessagesResponse": [
        {
          "id": 1,
          "phone_e164": "+14089961099",
          "bill_id": 1,
          "customer_id": "cust-split-live",
          "direction": "outbound",
          "kind": "auto_followup",
          "status": "sent",
          "body": "Thank you for 1 visits to Store, Split Milestone Guest!\nTotal spent with us: $400.00. Current points balance: 40 ($40.00).\nWe appreciate your loyalty and look forward to seeing you again!\nReply STOP to opt out.",
          "error": null,
          "queued_at": "2026-10-23 05:27:52",
          "seen_at": null,
          "typing_at": "2026-10-23 05:27:52",
          "sent_at": "2026-10-23 05:28:03",
          "delivered_at": null,
          "read_at": null,
          "failed_at": null,
          "created_by_user_id": "rule:nth_visit",
          "trigger_rule": "nth_visit"
        }
      ]
    },
    "scenario5": {
      "billId": 4,
      "rejectedDiscountStatus": 409,
      "rejectedDiscountBody": {
        "error": "Discount cannot reduce bill total below collected payments",
        "reason_code": "discount.rejected",
        "operation": "bill.discount",
        "stage": "validation",
        "classification": "expected_rejection",
        "outcome": "not_applied",
        "correlation_id": "3ba596c5-bb5f-42ee-af71-196797b86a35",
        "display_code": "below_collected_funds"
      },
      "whatsappMessagesAfter409": []
    },
    "scenario4": {
      "itemEditAutoSettlement": {
        "billId": 3,
        "message": {
          "id": 2,
          "phone_e164": "+14155550191",
          "bill_id": 3,
          "customer_id": "cust-eb-4a",
          "direction": "outbound",
          "kind": "bill_receipt",
          "status": "sent",
          "body": "Receipt {order_number}: Paid $400.00. Earned 40 pts (Balance: 40 pts = $40.00).",
          "error": null,
          "queued_at": "2026-10-23 05:28:03",
          "seen_at": null,
          "typing_at": "2026-10-23 05:28:03",
          "sent_at": "2026-10-23 05:28:05",
          "delivered_at": null,
          "read_at": null,
          "failed_at": null,
          "created_by_user_id": "rule:after_payment",
          "trigger_rule": "after_payment"
        }
      },
      "billDiscountAutoSettlement": {
        "billId": 4,
        "message": {
          "id": 3,
          "phone_e164": "+14155550192",
          "bill_id": 4,
          "customer_id": "cust-eb-4b",
          "direction": "outbound",
          "kind": "bill_receipt",
          "status": "sent",
          "body": "Receipt {order_number}: Paid $600.00. Earned 60 pts (Balance: 60 pts = $60.00).",
          "error": null,
          "queued_at": "2026-10-23 05:28:06",
          "seen_at": null,
          "typing_at": "2026-10-23 05:28:06",
          "sent_at": "2026-10-23 05:28:07",
          "delivered_at": null,
          "read_at": null,
          "failed_at": null,
          "created_by_user_id": "rule:after_payment",
          "trigger_rule": "after_payment"
        }
      },
      "billGenerateResyncAutoSettlement": {
        "billId": 5,
        "message": {
          "id": 4,
          "phone_e164": "+14155550193",
          "bill_id": 5,
          "customer_id": "cust-eb-4c",
          "direction": "outbound",
          "kind": "bill_receipt",
          "status": "sent",
          "body": "Receipt {order_number}: Paid $600.00. Earned 60 pts (Balance: 60 pts = $60.00).",
          "error": null,
          "queued_at": "2026-10-23 05:28:07",
          "seen_at": null,
          "typing_at": "2026-10-23 05:28:07",
          "sent_at": "2026-10-23 05:28:09",
          "delivered_at": null,
          "read_at": null,
          "failed_at": null,
          "created_by_user_id": "rule:after_payment",
          "trigger_rule": "after_payment"
        }
      }
    },
    "scenario6": {
      "kwdMessage": {
        "id": 5,
        "phone_e164": "+96550123456",
        "bill_id": 8801,
        "customer_id": "cust-kwd-live",
        "direction": "outbound",
        "kind": "bill_receipt",
        "status": "sent",
        "body": "Receipt {order_number}: Paid ‏١٢٫٣٤٥ د.ك.‏. Earned 1.235 pts (Balance: 12.346 pts = ‏١٢٫٣٤٦ د.ك.‏).",
        "error": null,
        "queued_at": "2026-10-23 05:28:09",
        "seen_at": null,
        "typing_at": "2026-10-23 05:28:09",
        "sent_at": "2026-10-23 05:28:12",
        "delivered_at": null,
        "read_at": null,
        "failed_at": null,
        "created_by_user_id": "rule:after_payment",
        "trigger_rule": "after_payment"
      },
      "jpyMessage": {
        "id": 6,
        "phone_e164": "+819012345678",
        "bill_id": 8802,
        "customer_id": "cust-jpy-live",
        "direction": "outbound",
        "kind": "bill_receipt",
        "status": "sent",
        "body": "Receipt {order_number}: Paid ¥1,260. Earned 13 pts (Balance: 13 pts = ¥13).",
        "error": null,
        "queued_at": "2026-10-23 05:28:12",
        "seen_at": null,
        "typing_at": "2026-10-23 05:28:12",
        "sent_at": "2026-10-23 05:28:16",
        "delivered_at": null,
        "read_at": null,
        "failed_at": null,
        "created_by_user_id": "rule:after_payment",
        "trigger_rule": "after_payment"
      }
    }
  }
}
Evidence: Live scenario execution transcript
[LiveServer] Started isolated FloCafe API server at http://127.0.0.1:65131 (dataDir=/var/folders/y_/1ltcxtwj0zd_w1dg9jv4jl580000gn/T/flo-live-validation-DR63mc)

=== Scenario 1: Cancel in-flight WhatsApp version lookup on PUT /api/settings/offline-mode ===
S1 result: {"offlineModePutResponse":{"offline_mode":true},"versionFetchSignalAbortedImmediately":true,"baileysFallbackVersionCalls":0,"connectResponse":{"ok":false,"error":"Offline mode is on."},"whatsappStatus":{"enabled":true,"state":"disconnected","connectedPhone":null,"lastError":null,"lastErrorReason":null,"cooldownUntil":null,"filterGroups":true}}

=== Scenario 2 (Adversarial): Reject QR & pairing-code connect while Offline Mode is active ===
S2 result: {"qrConnectWhileOffline":{"ok":false,"error":"Offline mode is on."},"pairingConnectWhileOffline":{"ok":false,"error":"Offline mode is on."},"outboundVersionFetchCalls":0,"socketCreations":0}

=== Scenario 3: Deduplicate concurrent split-check nth_visit milestone messages ===
S3 result: {"orderId":1,"splitBillIds":[1,2],"nthVisitMessagesInDb":[{"id":1,"bill_id":1,"customer_id":"cust-split-live","kind":"auto_followup","status":"sent","created_by_user_id":"rule:nth_visit","body":"Thank you for 1 visits to Store, Split Milestone Guest!\nTotal spent with us: $400.00. Current points balance: 40 ($40.00).\nWe appreciate your loyalty and look forward to seeing you again!\nReply STOP to opt out."}],"apiMessagesResponse":[{"id":1,"phone_e164":"+14089961099","bill_id":1,"customer_id":"cust-split-live","direction":"outbound","kind":"auto_followup","status":"sent","body":"Thank you for 1 visits to Store, Split Milestone Guest!\nTotal spent with us: $400.00. Current points balance: 40 ($40.00).\nWe appreciate your loyalty and look forward to seeing you again!\nReply STOP to opt out.","error":null,"queued_at":"2026-10-23 05:27:52","seen_at":null,"typing_at":"2026-10-23 05:27:52","sent_at":"2026-10-23 05:28:03","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:nth_visit","trigger_rule":"nth_visit"}]}

=== Scenario 4 & 5: Exact-balance auto-settlement automation dispatch & 409 guard ===
S5 result: {"billId":4,"rejectedDiscountStatus":409,"rejectedDiscountBody":{"error":"Discount cannot reduce bill total below collected payments","reason_code":"discount.rejected","operation":"bill.discount","stage":"validation","classification":"expected_rejection","outcome":"not_applied","correlation_id":"3ba596c5-bb5f-42ee-af71-196797b86a35","display_code":"below_collected_funds"},"whatsappMessagesAfter409":[]}
S4 result: {"itemEditAutoSettlement":{"billId":3,"message":{"id":2,"phone_e164":"+14155550191","bill_id":3,"customer_id":"cust-eb-4a","direction":"outbound","kind":"bill_receipt","status":"sent","body":"Receipt {order_number}: Paid $400.00. Earned 40 pts (Balance: 40 pts = $40.00).","error":null,"queued_at":"2026-10-23 05:28:03","seen_at":null,"typing_at":"2026-10-23 05:28:03","sent_at":"2026-10-23 05:28:05","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:after_payment","trigger_rule":"after_payment"}},"billDiscountAutoSettlement":{"billId":4,"message":{"id":3,"phone_e164":"+14155550192","bill_id":4,"customer_id":"cust-eb-4b","direction":"outbound","kind":"bill_receipt","status":"sent","body":"Receipt {order_number}: Paid $600.00. Earned 60 pts (Balance: 60 pts = $60.00).","error":null,"queued_at":"2026-10-23 05:28:06","seen_at":null,"typing_at":"2026-10-23 05:28:06","sent_at":"2026-10-23 05:28:07","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:after_payment","trigger_rule":"after_payment"}},"billGenerateResyncAutoSettlement":{"billId":5,"message":{"id":4,"phone_e164":"+14155550193","bill_id":5,"customer_id":"cust-eb-4c","direction":"outbound","kind":"bill_receipt","status":"sent","body":"Receipt {order_number}: Paid $600.00. Earned 60 pts (Balance: 60 pts = $60.00).","error":null,"queued_at":"2026-10-23 05:28:07","seen_at":null,"typing_at":"2026-10-23 05:28:07","sent_at":"2026-10-23 05:28:09","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:after_payment","trigger_rule":"after_payment"}}}

=== Scenario 6: 3-decimal (KWD) and 0-decimal (JPY) loyalty rounding ===
S6 result: {"kwdMessage":{"id":5,"phone_e164":"+96550123456","bill_id":8801,"customer_id":"cust-kwd-live","direction":"outbound","kind":"bill_receipt","status":"sent","body":"Receipt {order_number}: Paid ‏١٢٫٣٤٥ د.ك.‏. Earned 1.235 pts (Balance: 12.346 pts = ‏١٢٫٣٤٦ د.ك.‏).","error":null,"queued_at":"2026-10-23 05:28:09","seen_at":null,"typing_at":"2026-10-23 05:28:09","sent_at":"2026-10-23 05:28:12","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:after_payment","trigger_rule":"after_payment"},"jpyMessage":{"id":6,"phone_e164":"+819012345678","bill_id":8802,"customer_id":"cust-jpy-live","direction":"outbound","kind":"bill_receipt","status":"sent","body":"Receipt {order_number}: Paid ¥1,260. Earned 13 pts (Balance: 13 pts = ¥13).","error":null,"queued_at":"2026-10-23 05:28:12","seen_at":null,"typing_at":"2026-10-23 05:28:12","sent_at":"2026-10-23 05:28:16","delivered_at":null,"read_at":null,"failed_at":null,"created_by_user_id":"rule:after_payment","trigger_rule":"after_payment"}}

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 - 6 of 6 scenarios driven live against the product
Scenario Result Live Evidence
Enabling Offline Mode via PUT /api/settings/offline-mode while POST /api/whatsapp/connect is fetching the WhatsApp web version immediately aborts the in-flight version request, blocks the Baileys fall… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Attempting POST /api/whatsapp/connect (QR or pairing code) while Offline Mode is active is rejected with "Offline mode is on." without initiating outbound version lookups or sockets ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Paying two split checks of the same dine-in order concurrently via POST /api/bills/:id/payment while the first nth_visit milestone lookup is awaiting onWhatsApp sends and persists only one nth_visit m… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Auto-settling a partially paid bill to exact balance via order item edit (PATCH /api/orders/:id/items/:itemId/edit), bill discount (POST /api/bills/:id/applyDiscount), or bill resync (POST /api/bills/… ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Attempting a bill discount below already-collected funds via POST /api/bills/:id/applyDiscount fails with HTTP 409 (below_collected_funds) and does not dispatch WhatsApp paid-bill automation ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
Rendering WhatsApp loyalty templates and sending paid-bill messages under 3-decimal (KWD) and 0-decimal (JPY) tenant currencies honors currencyFractionDigits instead of hardcoded 2-decimal rounding ✅ pass live ~/.no-mistakes/evidence/01M5KJGKNGD0WQ08D92AQRNZWZ/live-scenarios-evidence.json
  • npm run test:whatsapp-service
  • npm run test:issue-exact-balance-settlement
  • npm run test:offline-mode
  • npm run test:script-coverage
  • Live end-to-end HTTP + SQLite scenario run against isolated Express server (POST /api/whatsapp/enable, POST /api/whatsapp/connect, PUT /api/settings/offline-mode, GET /api/whatsapp/status, PUT /api/whatsapp/automation, POST /api/orders, POST /api/bills/generate, POST /api/bills/:id/split-check, POST /api/bills/:id/payment, PATCH /api/orders/:id/items/:itemId/edit, POST /api/bills/:id/applyDiscount, GET /api/whatsapp/messages)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

coderabbitai Bot commented Oct 23, 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

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
khaira777 merged commit d70fd86 into main Oct 23, 2026
23 checks passed
@khaira777
khaira777 deleted the fm/ship-whatsapp-and-settlement-audit-fixes branch October 23, 2026 05: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.

1 participant