Skip to content

feat: add WhatsApp message templates, automated rules, and safety controls - #1315

Merged
khaira777 merged 8 commits into
mainfrom
fm/ship-1239-whatsapp-automation
Oct 23, 2026
Merged

khaira777 merged 8 commits into
mainfrom
fm/ship-1239-whatsapp-automation

Conversation

@khaira777

@khaira777 khaira777 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Intent

Implement WhatsApp message templates, automated sending rules, and anti-ban safety controls for Issue #1239

What Changed

  • Added shared WhatsApp automation contracts and single-pass placeholder template rendering (shared/whatsapp-automation.ts) for customizable templates (receipt, feedback, loyalty_milestone, visit_milestone, winback), five trigger rules (after_payment, feedback_delay, winback, points_threshold, nth_visit), and safety settings stored under whatsapp_automation_config.
  • Extended main/services/whatsapp.ts, main/routes/whatsapp.ts, and main/routes/bills.ts with post-payment rule evaluation, a 5-minute scheduled sweep (POST /api/whatsapp/automation/run-sweep), filtered segment broadcasts (POST /api/whatsapp/automation/broadcast), inbound STOP/UNSUBSCRIBE auto-opt-out blocklisting, store-timezone quiet hours, per-customer weekly caps, and trigger_rule message attribution.
  • Added a localized Templates & Rules management tab on the WhatsApp dashboard (frontend/src/app/(dashboard)/whatsapp/page.tsx and 25 locale bundles), expanded tests/whatsapp-service.test.ts coverage, and updated API and cloud-integration documentation.

Risk Assessment

✅ Low: All 32 changed files across shared automation contracts, backend WhatsApp service and routes, bill payment hooks, frontend WhatsApp automation UI, i18n locale bundles, documentation, and unit tests were inspected. Prior review findings and Greptile feedback (quiet-hours timezone resolution, split-bill item scoping and nth-visit order deduplication, sweep lookback window and recipient cooldowns, failed-row retry caps, blocklist re-verification after typing delay, and frontend load-error save protection) are cleanly resolved with comprehensive test coverage.

Testing

Built the backend and static desktop frontend, ran focused WhatsApp and translation test suites (test:whatsapp-service, test:whatsapp-middleware, test:whatsapp-schema, test:translations), and drove 5 live end-to-end browser and API scenarios against the running FloCafe server and headless Chromium with 6 UI screenshots and structured API/DB evidence captured under ~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5.

  • Live validation: ✅ go - 5 of 5 scenarios driven live against the product
Scenario Result Live Evidence
Owner customizes WhatsApp message templates with placeholder chips, previews live interpolated sample data, enables automated sending rules and safety settings in the Templates & Rules tab, and persis… ✅ pass live WhatsApp Templates & Rules tab — Message template builder, placeholder chips, and live preview bubble; WhatsApp Templates & Rules tab — Automated sending rules, segment broadcast, and safety controls…
Settling a customer bill via POST /api/bills/:id/payment automatically dispatches the interpolated digital receipt (after_payment), loyalty points milestone (points_threshold), and visit milestone (nt… ✅ pass live WhatsApp Sent tab — Post-payment receipt, loyalty points milestone, and Nth visit milestone messages with rule badges; Live WhatsApp automation E2E API and database evidence JSON
Running scheduled rules (feedback_delay and winback) and sending a filtered customer segment broadcast from the Templates & Rules tab dispatches deduplicated follow-up and broadcast messages with corr… ✅ pass live WhatsApp Sent tab — Delayed feedback follow-up, inactive customer win-back, and segment broadcast messages with rule badges; Live WhatsApp automation E2E API and database evidence JSON
Adversarial / Guard: Receiving an inbound STOP keyword DM automatically adds the sender to whatsapp_blocklist with reason 'Auto opt-out: STOP', marks the sender Blocked in the Inbox tab, and rejects s… ✅ pass live WhatsApp Inbox tab — Inbound STOP message automatically marked as Blocked; WhatsApp Connection tab — Blocklist entry created automatically with reason Auto opt-out: STOP; Live WhatsApp automation E2E…
Adversarial / Guard: Quiet hours and weekly per-customer caps block automated sends (reasons 'quiet_hours' and 'weekly_cap') while still permitting manual staff replies, URL shortener links (bit.ly) a… ✅ pass live Live WhatsApp automation E2E API and database evidence JSON; npm run test:whatsapp-service

WhatsApp Templates & Rules tab — Message template builder, placeholder chips, and live preview bubble
WhatsApp Templates & Rules tab — Automated sending rules, segment broadcast, and safety controls saved
WhatsApp Sent tab — Post-payment receipt, loyalty points milestone, and Nth visit milestone messages with rule badges
WhatsApp Sent tab — Delayed feedback follow-up, inactive customer win-back, and segment broadcast messages with rule badges
WhatsApp Inbox tab — Inbound STOP message automatically marked as Blocked
WhatsApp Connection tab — Blocklist entry created automatically with reason Auto opt-out: STOP

Evidence: Live WhatsApp automation E2E API and database evidence JSON

{ "scenario1_template_and_rule_configuration": { "savedSafety": { "autoOptOutEnabled": true, "quietHoursEnabled": false, "quietHoursStart": "22:00", "quietHoursEnd": "09:00", "maxPerCustomerPerWeek": 5, "feedbackLink": "https://flocafe.example.com/feedback"
}
},
"scenario2_post_payment_automation": { "billId": 503, "billNumber": "INV-20261023-0001", "loyaltyPointsEarned": 150, "rulesTriggered": ["after_payment", "points_threshold", "nth_visit"] }, "scenario3_sweep_and_broadcast": { "outboundCount": 6, "rulesObserved": ["feedback_delay", "winback", "broadcast", "after_payment", "points_threshold", "nth_visit"] }, "scenario4_inbound_stop_auto_opt_out": { "blockedPhone": "+14089961099", "blockedSendResponse": { "status": 400, "data": { "error": "This number asked to stop receiving messages.", "reason": "blocked" } } }, "scenario5_adversarial_safety_guards": { "quietAutoSend": { "ok": false, "reason": "quiet_hours" }, "quietManualReply": { "ok": true }, "weeklyAuto2": { "ok": false, "reason": "weekly_cap" }, "weeklyManualReply": { "ok": true }, "shortenerRejected": { "status": 400, "data": { "reason": "content_blocked" } } } }

{
  "startedAt": "2026-10-23T00:14:40.169Z",
  "baseUrl": "http://127.0.0.1:14301",
  "scenarios": {
    "scenario1_template_and_rule_configuration": {
      "savedSafety": {
        "autoOptOutEnabled": true,
        "quietHoursEnabled": false,
        "quietHoursStart": "22:00",
        "quietHoursEnd": "09:00",
        "maxPerCustomerPerWeek": 5,
        "feedbackLink": "https://flocafe.example.com/feedback"
      },
      "savedRules": [
        {
          "id": "after_payment",
          "trigger": "after_payment",
          "enabled": true,
          "templateId": "receipt"
        },
        {
          "id": "feedback_delay",
          "trigger": "feedback_delay",
          "enabled": true,
          "templateId": "feedback",
          "delayHours": 2
        },
        {
          "id": "winback",
          "trigger": "winback",
          "enabled": true,
          "templateId": "winback",
          "inactiveDays": 14
        },
        {
          "id": "points_threshold",
          "trigger": "points_threshold",
          "enabled": true,
          "templateId": "loyalty_milestone",
          "pointsThreshold": 100
        },
        {
          "id": "nth_visit",
          "trigger": "nth_visit",
          "enabled": true,
          "templateId": "visit_milestone",
          "nthVisit": 1
        }
      ],
      "screenshots": [
        "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-automation-templates-preview.png",
        "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-automation-rules-safety.png"
      ]
    },
    "scenario2_post_payment_automation": {
      "billId": 503,
      "billNumber": "INV-20261023-0001",
      "loyaltyPointsEarned": 150,
      "messages": [
        {
          "id": 1,
          "kind": "bill_receipt",
          "trigger_rule": "after_payment",
          "status": "delivered",
          "body": "Dear Maya Lin,\nYour purchase at Flo Bistro Live has been completed.\nBill #: INV-20261023-0001 (Oct 23, 2026, 12:14 AM)\n\nItems:\n2x Artisan Cappuccino - $50.00\n\nTotal: $50.00 (Card)\nYou have earned 150 points on this purchase.\nUpdated balance: 150 ($150.00)\nShare feedback: https://flocafe.example.com/feedback\nReply STOP to opt out.@flobistrolive"
        },
        {
          "id": 2,
          "kind": "auto_followup",
          "trigger_rule": "points_threshold",
          "status": "delivered",
          "body": "Congratulations Maya Lin!\nYou have earned 150 points at Flo Bistro Live and your loyalty balance is now 150 points (worth $150.00).\nRedeem your points on your next visit!\nReply STOP to opt out."
        },
        {
          "id": 3,
          "kind": "auto_followup",
          "trigger_rule": "nth_visit",
          "status": "delivered",
          "body": "Thank you for 1 visits to Flo Bistro Live, Maya Lin!\nTotal spent with us: $50.00. Current points balance: 150 ($150.00).\nWe appreciate your loyalty and look forward to seeing you again!\nReply STOP to opt out."
        }
      ],
      "screenshot": "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-sent-post-payment-rules.png"
    },
    "scenario3_sweep_and_broadcast": {
      "outboundCount": 6,
      "rulesObserved": [
        "feedback_delay",
        "winback",
        "broadcast",
        "after_payment",
        "points_threshold",
        "nth_visit"
      ],
      "sampleSweepAndBroadcastMessages": [
        {
          "id": 4,
          "phone": "+14089961021",
          "trigger_rule": "feedback_delay",
          "status": "delivered",
          "body": "Hi Ethan Brooks, thank you for visiting Flo Bistro Live!\nWe would love to hear how your order (#INV-501) was today.\nShare your feedback: https://flocafe.example.com/feedback\nFollow us: @flobistrolive\nReply STOP to opt out."
        },
        {
          "id": 5,
          "phone": "+14089961022",
          "trigger_rule": "winback",
          "status": "delivered",
          "body": "Hi Sofia Alvarez, we miss you at Flo Bistro Live!\nYour last visit was on Oct 3, 2026, and you have 250 points ($250.00) ready to use.\nSee you soon! Contact: +14155550100\nReply STOP to opt out."
        },
        {
          "id": 6,
          "phone": "+14089961022",
          "trigger_rule": "broadcast",
          "status": "delivered",
          "body": "Congratulations Sofia Alvarez!\nYou have earned 0 points at Flo Bistro Live and your loyalty balance is now 250 points (worth $250.00).\nRedeem your points on your next visit!\nReply STOP to opt out."
        }
      ],
      "screenshot": "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-sent-sweep-and-broadcast.png"
    },
    "scenario4_inbound_stop_auto_opt_out": {
      "blockedPhone": "+14089961099",
      "blockedSendResponse": {
        "status": 400,
        "ok": false,
        "data": {
          "error": "This number asked to stop receiving messages.",
          "reason": "blocked"
        }
      },
      "screenshots": [
        "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-inbox-auto-opt-out.png",
        "~/.no-mistakes/evidence/01M5K0G1CQ8TVDHJGAN05GW6X5/whatsapp-connection-blocklist.png"
      ]
    },
    "scenario5_adversarial_safety_guards": {
      "quietHoursWindow": {
        "quietStart": "23:00",
        "quietEnd": "02:00"
      },
      "quietAutoSend": {
        "ok": false,
        "error": "Automated messages are paused during quiet hours.",
        "reason": "quiet_hours"
      },
      "quietManualReply": {
        "ok": true,
        "messageId": 8
      },
      "weeklyAuto1": {
        "ok": true,
        "messageId": 9
      },
      "weeklyAuto2": {
        "ok": false,
        "error": "Weekly automated message limit reached for this customer.",
        "reason": "weekly_cap"
      },
      "weeklyManualReply": {
        "ok": true,
        "messageId": 10
      },
      "shortenerRejected": {
        "status": 400,
        "ok": false,
        "data": {
          "error": "Refusing URL shortener link: bit.ly",
          "reason": "content_blocked"
        }
      },
      "injectionSafeReceiptBody": "Dear Priya {total} Verma,\nYour purchase at Flo Bistro Live has been completed.\nBill #: INV-20261023-0002 (Oct 23, 2026, 12:14 AM)\n\nItems:\n1x Artisan Cappuccino - $25.00\n\nTotal: $25.00 (Card)\nYou have earned 75 points on this purchase.\nUpdated balance: 75 ($75.00)\nShare feedback: https://flocafe.example.com/feedback\nReply STOP to opt out.@flobistrolive"
    }
  },
  "completedAt": "2026-10-23T00:14:48.488Z",
  "wireSentCount": 10
}

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
Owner customizes WhatsApp message templates with placeholder chips, previews live interpolated sample data, enables automated sending rules and safety settings in the Templates & Rules tab, and persis… ✅ pass live WhatsApp Templates & Rules tab — Message template builder, placeholder chips, and live preview bubble; WhatsApp Templates & Rules tab — Automated sending rules, segment broadcast, and safety controls…
Settling a customer bill via POST /api/bills/:id/payment automatically dispatches the interpolated digital receipt (after_payment), loyalty points milestone (points_threshold), and visit milestone (nt… ✅ pass live WhatsApp Sent tab — Post-payment receipt, loyalty points milestone, and Nth visit milestone messages with rule badges; Live WhatsApp automation E2E API and database evidence JSON
Running scheduled rules (feedback_delay and winback) and sending a filtered customer segment broadcast from the Templates & Rules tab dispatches deduplicated follow-up and broadcast messages with corr… ✅ pass live WhatsApp Sent tab — Delayed feedback follow-up, inactive customer win-back, and segment broadcast messages with rule badges; Live WhatsApp automation E2E API and database evidence JSON
Adversarial / Guard: Receiving an inbound STOP keyword DM automatically adds the sender to whatsapp_blocklist with reason 'Auto opt-out: STOP', marks the sender Blocked in the Inbox tab, and rejects s… ✅ pass live WhatsApp Inbox tab — Inbound STOP message automatically marked as Blocked; WhatsApp Connection tab — Blocklist entry created automatically with reason Auto opt-out: STOP; Live WhatsApp automation E2E…
Adversarial / Guard: Quiet hours and weekly per-customer caps block automated sends (reasons 'quiet_hours' and 'weekly_cap') while still permitting manual staff replies, URL shortener links (bit.ly) a… ✅ pass live Live WhatsApp automation E2E API and database evidence JSON; npm run test:whatsapp-service
  • npm run build
  • npm run build:frontend
  • npm run test:whatsapp-service
  • npm run test:whatsapp-middleware
  • npm run test:whatsapp-schema
  • npm run test:translations
  • node tests/_tmp-live-whatsapp-validation.cjs (live Playwright + Express/SQLite E2E validation across 5 scenarios)
✅ **Document** - passed

✅ No issues found.

✅ **Lint** - passed

✅ No issues found.

✅ **Push** - passed

✅ No issues found.

@coderabbitai

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

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

@greptile-apps

greptile-apps Bot commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 0/5 Tier: apex

[Medium impact] The changes extend WhatsApp messaging across one merchant workflow, including automated customer outreach.

Fix the stopped scheduler, blocked recipient batches, missed feedback, duplicate milestones, and settings overwrite before merging.

Findings

  1. P1 Scheduled messages stop after reconnect ▶
  2. P1 Rejected recipients block later customers ▶
  3. P1 Seven-day feedback misses its window ▶
  4. P1 Split checks repeat visit milestones ▶
  5. P1 Failed loading overwrites saved settings ▶
  6. P2 Messages overstate spendable points ▶
  7. P2 Failed feedback is never retried ▶
  8. P2 Opt-outs miss an active send ▶
  9. P2 WhatsApp uses different regional defaults ▶
  10. P2 Automation fields have no names ▶
  11. P2 Documentation overstates duplicate protection ▶
  12. P2 Vietnamese heading mixes languages ▶
  13. P2 Quiet-hours test fails near midnight ▶
  14. P2 Test comment breaks contributor rules ▶

Summary

Adds shared WhatsApp templates, five automated rules, customer broadcasts, safety settings, and dashboard controls.

  • Paid bills and scheduled rules can send tailored WhatsApp messages.
  • Automated WhatsApp sends check opt-outs, quiet hours, and message limits.
  • Message history shows which automation rule sent each message.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  Settings[Templates, rules, and safety settings] --> Config[(Saved configuration)]
  Payment[Bill becomes paid] --> PaidRules[Receipt, points, and visit rules]
  Timer[Five-minute timer] --> Scheduled[Feedback and win-back rules]
  Broadcast[Staff starts a broadcast] --> Segment[Choose matching customers]
  Config --> PaidRules
  Config --> Scheduled
  Config --> Segment
  PaidRules --> Send[Per-phone send lock]
  Scheduled --> Send
  Segment --> Send
  Incoming[Customer sends STOP] --> Blocklist[(Blocklist)]
  Blocklist --> Checks[Safety checks]
  Send --> Checks
  Checks --> History[(Message history)]
  History --> Delivery[WhatsApp delivery]
Loading

Reviews (1) · Last reviewed commit: "no-mistakes(document): docs: document Wh..." · Reviewed by Greptile

Comment thread main/services/whatsapp.ts Resolved
Comment thread main/services/whatsapp.ts Resolved
Comment thread main/services/whatsapp.ts Resolved
Comment thread main/services/whatsapp.ts Resolved
Comment thread docs/architecture/cloud-integrations.md Resolved
Comment thread frontend/src/lib/i18n/messages/vi.json Resolved
Comment thread tests/whatsapp-service.test.ts Resolved
Comment thread tests/whatsapp-service.test.ts Resolved
…yout-integrity.spec.ts` (`drains multiple cursor pages, deduplicates overlapping orders, removes completed orders, and clears on follow-up page 401`) that caused `Playwright E2E (Shard 2/4)`, `End-to-End Playwright Tests`, and `Required Checks Gate` to fail: - **Invariant:** Whenever an E2E test navigates to `/customer-display` with a paused Playwright fake clock (`clock.pauseAt`), the test must advance the paused clock across both sequential mount `setTimeout(..., 0)` ticks - first until the token-resolution timer has committed the `<header>` render and registered the post-token `useEffect`, and second to fire the initial feed `setTimeout(refresh, 0)`. - **Root cause & fix (`frontend/e2e/layout-integrity.spec.ts`):** `budgetPage.clock.pauseAt` was called before `budgetPage.goto`, so a single `budgetPage.clock.runFor(1)` only fired the token-resolution `setTimeout(..., 0)` and left the subsequent `setTimeout(refresh, 0)` frozen on the paused clock, causing `await slowPage1Arrived` to time out after 30s. Closed `displayPage` after its assertions complete, installed the `budgetPage` clock at `initialClockMs - 60_000` before pausing at `initialClockMs`, and polled `clock.runFor(1)` until `<header>` is rendered before advancing `clock.runFor(1)` to trigger the initial feed fetch at both pre-`goto` `clock.pauseAt` sites in `frontend/e2e/layout-integrity.spec.ts`. - **Verification:** Ran `npm run build`, `npm run build:frontend`, `npx playwright test --config=playwright.config.ts --project=chromium e2e/layout-integrity.spec.ts -g "customer display wraps full receipt numbers and pages on TV"` (12 passed), `npm run test:whatsapp-service`, `npm run lint`, `node scripts/ci/check-changed-format.cjs --base 8a0c272`, `npm run docs:check`, `npm run i18n:check`, and `git diff --check`
@khaira777
khaira777 force-pushed the fm/ship-1239-whatsapp-automation branch from 7452e67 to 29671a8 Compare October 22, 2026 22:24
@khaira777 khaira777 changed the title feat: add WhatsApp message templates, automated sending rules, and safety controls feat: add WhatsApp message templates, automated rules, and anti-ban safety controls Oct 22, 2026
@khaira777

Copy link
Copy Markdown
Contributor Author

@greptileai review this at apex

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