Skip to content

Issue #922: Added WhatsApp Business Cloud API messaging. - #4590

Closed
joshua1234511 wants to merge 7 commits into
opensourcepos:masterfrom
joshua1234511:feature/922-whatsapp-messaging-support
Closed

joshua1234511 wants to merge 7 commits into
opensourcepos:masterfrom
joshua1234511:feature/922-whatsapp-messaging-support

Conversation

@joshua1234511

@joshua1234511 joshua1234511 commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds WhatsApp as a first-class messaging channel alongside SMS and email, using Meta's WhatsApp Business Cloud API. Resolves #922.

Merchants can now configure WhatsApp credentials, send free-form messages to customers, send a bill/invoice PDF over WhatsApp the same way it's emailed today, and view the full conversation (outbound sends + inbound replies) with each customer.

What's included

  • Config page — new Configuration → System → WhatsApp tab: enable toggle, Phone Number ID, WABA ID, encrypted access token, API URL/version, default country code, saved message, and webhook settings (verify token, encrypted app secret, callback URL).
  • Messaging page (/whatsapp) — mirrors /messages: send a free-form message, browse recent conversations, and a per-customer modal with the message thread.
  • Send bill via WhatsApp — a WhatsApp button next to the email button on invoice / receipt / quote / work order. Reuses the existing PDF generation and delivers it as a document.
  • Conversation history — every outbound message is logged; a public webhook receives inbound replies and delivery-status updates, rendered as a chat thread.

Key components

Area File
Cloud API client (text + PDF document, media upload, phone normalization) app/Libraries/Whatsapp_lib.php
Messaging controller + views app/Controllers/Whatsapp.php, app/Views/whatsapp/*
Public webhook (verify + inbound + signature check) app/Controllers/Whatsapp_webhook.php
Message log model + table app/Models/Whatsapp_message.php, migration 20260703000000_AddWhatsappModule
Send-bill wiring app/Controllers/Sales.php (getSendWhatsapp) + sale views
Config save/decrypt app/Controllers/Config.php (postSaveWhatsapp)

Also: module/permission/grant seeding (migration + initial_schema.sql), routes + CSRF exemption for the webhook, a menu icon, and English language keys.

Security

  • Access token and app secret are stored encrypted (same pattern as SMTP/SMS credentials).
  • Webhook validates the X-Hub-Signature-256 HMAC when an app secret is configured; the verify handshake uses text/plain so nothing is injected into the challenge echo.
  • Webhook route is the only addition to the CSRF exemption list.

Testing

  • Migration runs cleanly; module/permission/grant/config rows and the whatsapp_messages table are created.
  • WhatsApp appears in the menu; /whatsapp and the config tab render (HTTP 200), config saves with the token encrypted and round-tripping.
  • Webhook GET returns the exact challenge; POST stores inbound messages and updates statuses.
  • Send with invalid credentials fails gracefully (success:false), logs the row with Meta's real API error, and does not fatal.
  • All new PHP passes php-cs-fixer (CodeIgniter4 standard) and lint.

Out of scope (follow-ups)

  • Template messages / sending outside the 24-hour customer service window.
  • Non-English translations for the new language keys.

Screenshots

Summary by CodeRabbit

  • New Features
    • Added WhatsApp messaging for customers, including a conversation screen with recent history and free-form text sending.
    • Added “send via WhatsApp” actions for invoices, quotes, receipts, and work orders when a customer phone number is available.
    • Added WhatsApp configuration in system settings, including seeded access/permissions and webhook details.
  • Bug Fixes
    • Improved webhook reliability with signature verification, CSRF exemption for the webhook, and safer inbound event/status handling.
  • Documentation
    • Updated the README to mention WhatsApp sending and customer conversation history.

…pensourcepos#922)

Add WhatsApp config tab, a messaging page with customer conversation
history, send-bill-via-WhatsApp buttons on invoices/receipts/quotes/
work orders, and a public webhook for inbound replies and status updates.

Includes Whatsapp_lib (Cloud API text + PDF document send), Whatsapp
controller + views, Whatsapp_webhook, Whatsapp_message model, a
whatsapp_messages table, module/permission/grant seeding, and language keys.
@joshua1234511

Copy link
Copy Markdown
Contributor Author
whatsapp-config-tab whatsapp-page

@coderabbitai

coderabbitai Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds WhatsApp Business Cloud API support for configuration, outbound sending, inbound webhook processing, conversation storage, sales document delivery, and related UI and localization.

Changes

WhatsApp Messaging Feature

Layer / File(s) Summary
Schema, seed data, and strings
app/Database/Migrations/20260703000000_AddWhatsappModule.php, app/Database/Migrations/sqlscripts/initial_schema.sql, app/Language/en/Config.php, app/Language/en/Module.php, app/Language/en/Sales.php, app/Language/en/Whatsapp.php, README.md, LICENSE
Adds the WhatsApp module, permissions, grants, seeded config values, the whatsapp_messages table, and English strings for configuration, sales actions, module text, WhatsApp UI, and project text updates.
Outbound library and message model
app/Libraries/Whatsapp_lib.php, app/Models/Whatsapp_message.php
Adds WhatsApp API sending, phone normalization, token handling, outbound logging, conversation retrieval, and status updates.
Webhook routing and processing
app/Config/Filters.php, app/Config/Routes.php, app/Controllers/Whatsapp_webhook.php
Exposes whatsapp/webhook, exempts it from CSRF, verifies subscription requests, validates signed POSTs, logs inbound messages, and updates delivery states.
Config storage and settings UI
app/Controllers/Config.php, app/Views/configs/system_config.php, app/Views/configs/whatsapp_config.php
Loads and saves WhatsApp settings, decrypts stored secrets for display, and adds the WhatsApp configuration tab and form with webhook fields and validation.
Sales document sending
app/Controllers/Sales.php, app/Views/sales/invoice.php, app/Views/sales/quote.php, app/Views/sales/receipt.php, app/Views/sales/work_order.php
Adds WhatsApp sending for invoices, quotes, receipts, and work orders when a customer phone is present.
WhatsApp page and conversation views
app/Controllers/Whatsapp.php, app/Views/whatsapp/whatsapp.php, app/Views/whatsapp/form_whatsapp.php, app/Views/whatsapp/conversation.php
Adds the WhatsApp landing page, per-person send form, conversation rendering, and AJAX endpoints for viewing and sending messages.

Estimated code review effort: 4 (Complex) | ~75 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Meta as Meta WhatsApp Cloud API
  participant Webhook as Whatsapp_webhook
  participant MessageModel as Whatsapp_message

  Meta->>Webhook: GET verify request
  Webhook-->>Meta: hub_challenge or 403

  Meta->>Webhook: POST signed payload
  Webhook->>Webhook: validate X-Hub-Signature-256
  Webhook->>MessageModel: log inbound messages / update_status
  Webhook-->>Meta: HTTP 200
Loading
sequenceDiagram
  participant User
  participant Sales as Sales Controller
  participant WhatsappLib as Whatsapp_lib
  participant GraphAPI as WhatsApp Graph API

  User->>Sales: getSendWhatsapp(sale_id, type)
  Sales->>Sales: generate PDF + caption
  Sales->>WhatsappLib: sendDocument(phone, pdf, caption)
  WhatsappLib->>GraphAPI: upload media + send document
  GraphAPI-->>WhatsappLib: message id
  Sales-->>User: JSON success/message
Loading

Related issues: #922

Suggested labels: enhancement, CodeIgniter4

Suggested reviewers: jekkos, objecttothis

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The LICENSE copyright-name change is unrelated to WhatsApp messaging and appears out of scope. Remove the LICENSE attribution edit unless it was intentionally requested; keep the PR focused on WhatsApp messaging changes.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: adding WhatsApp Business Cloud API messaging.
Linked Issues check ✅ Passed The PR delivers WhatsApp messaging support with configuration, sending, and conversation tracking as requested in #922.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@joshua1234511

Copy link
Copy Markdown
Contributor Author
Screenshot 2026-07-02 at 10 35 16 PM

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

🧹 Nitpick comments (2)
app/Database/Migrations/20260703000000_AddWhatsappModule.php (1)

53-71: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Add an index on wa_message_id.

Whatsapp_message::update_status() filters by wa_message_id on every inbound status webhook callback, but no key is defined for that column here (only message_id, phone, person_id, created_at are indexed). As conversation volume grows this becomes an unindexed lookup on every delivery/read receipt.

⚡ Proposed fix
         $this->forge->addKey('message_id', true);
         $this->forge->addKey('phone');
         $this->forge->addKey('person_id');
         $this->forge->addKey('created_at');
+        $this->forge->addKey('wa_message_id');
         $this->forge->createTable('whatsapp_messages', true);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/Database/Migrations/20260703000000_AddWhatsappModule.php` around lines 53
- 71, Add an index for wa_message_id in the whatsapp_messages table definition.
Update the migration’s addKey calls in AddWhatsappModule so that
Whatsapp_message::update_status() can efficiently look up rows by wa_message_id
during inbound status webhook handling; keep the existing keys and add a
dedicated key for that column.
app/Libraries/Whatsapp_lib.php (1)

206-231: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Hand-rolled phone normalization is fragile; consider a proven library.

The "already has country code" check is a heuristic: if a national number happens to start with the same digits as the configured country code without actually being prefixed, it's skipped and a malformed number is sent to the Graph API. Also, the comment says "drop a single leading trunk '0'" but ltrim($digits, '0') strips all leading zeros, not just one.

giggsey/libphonenumber-for-php (based on Google's libphonenumber, actively maintained) handles this parsing/E.164 formatting robustly and would remove this class of edge-case bugs.

♻️ Illustrative refactor using libphonenumber
+use libphonenumber\PhoneNumberUtil;
+use libphonenumber\PhoneNumberFormat;
+
     public function normalizePhone(string $phone): string
     {
-        $digits = preg_replace('/\D+/', '', $phone) ?? '';
-
-        if ($digits === '') {
-            return '';
-        }
-
-        $country = preg_replace('/\D+/', '', (string) ($this->config['whatsapp_default_country_code'] ?? '')) ?? '';
-
-        if ($country !== '' && ! str_starts_with($digits, $country)) {
-            // Drop a single leading trunk '0' before prefixing the country code.
-            $digits = $country . ltrim($digits, '0');
-        }
-
-        return $digits;
+        try {
+            $util   = PhoneNumberUtil::getInstance();
+            $region = $this->config['whatsapp_default_country_region'] ?? null; // e.g. 'US'
+            $parsed = $util->parse($phone, $region);
+
+            return ltrim($util->format($parsed, PhoneNumberFormat::E164), '+');
+        } catch (Throwable $e) {
+            return '';
+        }
     }

Since this introduces a new composer dependency, please confirm it's acceptable to add for this project before adopting.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/Libraries/Whatsapp_lib.php` around lines 206 - 231, The current
normalizePhone method in Whatsapp_lib::normalizePhone uses a fragile prefix
check and strips all leading zeros, which can produce invalid numbers. Replace
the hand-rolled parsing with a robust E.164 formatter such as libphonenumber if
adding the dependency is approved, and keep the behavior centralized in
normalizePhone. If you do not adopt the library, at minimum change the
trunk-prefix handling so only a single leading zero is removed and rework the
country-code detection to avoid mistaking local numbers for already-prefixed
ones.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/Controllers/Config.php`:
- Around line 596-612: In postSaveWhatsapp, both whatsapp_token and
whatsapp_app_secret are only updated inside the check_encryption() branch, so
when encryption is disabled the submitted values are ignored and the old config
stays in place. Update the logic in this method to read the raw POST values in
an else fallback when check_encryption() is false, storing them as plaintext,
while keeping the existing encrypted path and remove_backup() behavior
unchanged.

In `@app/Controllers/Sales.php`:
- Around line 1048-1061: The temp PDF handling in Sales::getSendPdf() and the
WhatsApp send flow reuses the same deterministic filename, which can cause
concurrent requests to collide and leaves orphaned files behind. Update the PDF
creation/sending path to generate a unique temp filename per request in the
Sales controller before calling create_pdf() and whatsapp_lib->sendDocument(),
and make sure the file is deleted after sendDocument() completes (including
failure paths). Keep the logic localized around the existing $filename,
create_pdf(), and sendDocument() usage so the email and WhatsApp flows no longer
share a writable temp path.
- Around line 1023-1046: The getSendWhatsapp() method is rendering a template
using the user-controlled $type value, which can reach sales/$type_email without
validation. Add a whitelist check in getSendWhatsapp() before the
Services::renderer()->render() call so only the supported sale types used
elsewhere (invoice, quote, receipt, work_order) are allowed, and reject or
default any other value before building the template name.

In `@app/Controllers/Whatsapp_webhook.php`:
- Around line 149-153: The fail-open path in signatureValid() is allowing
unauthenticated webhook payloads to be accepted when appSecret is empty. Update
Whatsapp_webhook::signatureValid() so missing config does not return true;
instead reject the request or short-circuit processing in the webhook handler
before any persistence occurs. Make sure the inbound message/status handling
path in Whatsapp_webhook only inserts into whatsapp_messages or updates statuses
after a successful signature check, with signature verification treated as
mandatory once the feature is enabled.
- Around line 66-74: The webhook signature check in receive() is using the
encrypted whatsapp_app_secret from config directly, so signatureValid() never
sees the real secret. Decrypt whatsapp_app_secret the same way
Whatsapp_lib::token() handles whatsapp_token before passing it into
signatureValid(), and keep the existing invalid-signature handling and logging
intact.

In `@app/Controllers/Whatsapp.php`:
- Around line 74-113: The WhatsApp send actions are sanitizing the outgoing
message with FILTER_SANITIZE_FULL_SPECIAL_CHARS, which converts user-typed text
into HTML entities before it is passed to Whatsapp_lib::sendText and then shown
to recipients. Update postSend and postSend_form to read the message without
HTML entity encoding, keeping only appropriate input validation, so the text is
sent as authored. Make the same adjustment in both controller methods so
outbound messages are not corrupted.

In `@app/Database/Migrations/sqlscripts/initial_schema.sql`:
- Around line 73-82: The baseline schema seeds the WhatsApp config rows but
never creates the backing table, so fresh installs will break when WhatsApp
features reference it. Update the initial_schema.sql migration by adding the
missing ospos_whatsapp_messages CREATE TABLE definition alongside the other
table creation statements, using the same schema conventions as the rest of the
initial setup so the WhatsApp feature can access it on a clean install.

In `@app/Models/Whatsapp_message.php`:
- Around line 78-87: The recent conversation lookup in
get_recent_conversations() is using both phone and person_id as the grouping
key, which splits one conversation into multiple rows when person_id is null for
inbound/outbound WhatsApp messages. Update the query in
Whatsapp_message::get_recent_conversations() to group and aggregate by phone
only, and keep the existing last_activity/message_count ordering so it matches
the conversation semantics used by get_conversation().

In `@app/Views/sales/invoice.php`:
- Around line 56-73: The WhatsApp send action in the invoice view is being
triggered through a GET request, but `sales/sendWhatsapp` is side-effecting and
should not be callable via GET. Update the click handler in `invoice.php` (and
the same `sendWhatsapp` usage in the matching `quote.php`, `receipt.php`, and
`work_order.php` views) to use a POST request with CSRF protection instead of
`$.get`, and disable the `#show_whatsapp_button` after the first click to avoid
duplicate sends from repeated submissions.
- Around line 56-73: The inline WhatsApp request URL in the invoice view is
being echoed without escaping, unlike the matching logic in the sibling views.
Update the `invoice.php` script block around the
`$("`#show_whatsapp_button`").click(...)` handler to wrap the interpolated
`site_url() . "sales/sendWhatsapp/$sale_id_num"` value with `esc()`, keeping the
same behavior while hardening the output consistently with `quote.php`,
`receipt.php`, and `work_order.php`.

In `@app/Views/whatsapp/form_whatsapp.php`:
- Around line 74-83: The `rules.phone` validation in `form_whatsapp.php` is too
strict because `number: true` rejects formatted phone input that
`Whatsapp_lib::normalizePhone()` already cleans up. Update the jQuery Validate
rules in this form to allow common phone formats by removing the numeric-only
restriction and keeping validation aligned with the landing-page form’s phone
field. Ensure the `phone` rule in the form validation block still requires a
value but no longer blocks `+`, spaces, dashes, or parentheses.

---

Nitpick comments:
In `@app/Database/Migrations/20260703000000_AddWhatsappModule.php`:
- Around line 53-71: Add an index for wa_message_id in the whatsapp_messages
table definition. Update the migration’s addKey calls in AddWhatsappModule so
that Whatsapp_message::update_status() can efficiently look up rows by
wa_message_id during inbound status webhook handling; keep the existing keys and
add a dedicated key for that column.

In `@app/Libraries/Whatsapp_lib.php`:
- Around line 206-231: The current normalizePhone method in
Whatsapp_lib::normalizePhone uses a fragile prefix check and strips all leading
zeros, which can produce invalid numbers. Replace the hand-rolled parsing with a
robust E.164 formatter such as libphonenumber if adding the dependency is
approved, and keep the behavior centralized in normalizePhone. If you do not
adopt the library, at minimum change the trunk-prefix handling so only a single
leading zero is removed and rework the country-code detection to avoid mistaking
local numbers for already-prefixed ones.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d62bd686-d9d1-4397-9f04-ac68338516f9

📥 Commits

Reviewing files that changed from the base of the PR and between 632d4ea and 48c090b.

📒 Files selected for processing (23)
  • app/Config/Filters.php
  • app/Config/Routes.php
  • app/Controllers/Config.php
  • app/Controllers/Sales.php
  • app/Controllers/Whatsapp.php
  • app/Controllers/Whatsapp_webhook.php
  • app/Database/Migrations/20260703000000_AddWhatsappModule.php
  • app/Database/Migrations/sqlscripts/initial_schema.sql
  • app/Language/en/Config.php
  • app/Language/en/Module.php
  • app/Language/en/Sales.php
  • app/Language/en/Whatsapp.php
  • app/Libraries/Whatsapp_lib.php
  • app/Models/Whatsapp_message.php
  • app/Views/configs/system_config.php
  • app/Views/configs/whatsapp_config.php
  • app/Views/sales/invoice.php
  • app/Views/sales/quote.php
  • app/Views/sales/receipt.php
  • app/Views/sales/work_order.php
  • app/Views/whatsapp/conversation.php
  • app/Views/whatsapp/form_whatsapp.php
  • app/Views/whatsapp/whatsapp.php

Comment thread app/Controllers/Config.php Resolved
Comment thread app/Controllers/Sales.php Resolved
Comment thread app/Controllers/Sales.php Resolved
Comment thread app/Controllers/Whatsapp_webhook.php Resolved
Comment thread app/Controllers/Whatsapp_webhook.php Resolved
Comment thread app/Controllers/Whatsapp.php Resolved
Comment thread app/Models/Whatsapp_message.php Resolved
Comment thread app/Views/sales/invoice.php Resolved
Comment thread app/Views/whatsapp/form_whatsapp.php Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/Controllers/Whatsapp_webhook.php (1)

136-140: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Prevent status regressions in webhook updates update_status() overwrites the stored status unconditionally, so a late delivered event can downgrade an already read message. Ignore backward transitions and only persist forward status changes.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/Controllers/Whatsapp_webhook.php` around lines 136 - 140, The webhook
status loop in Whatsapp_webhook.php currently calls update_status() for every
incoming status and can overwrite a newer state with an older one. Update the
logic around update_status() to compare the incoming status against the stored
message status and ignore backward transitions, only allowing forward progress
such as sent → delivered → read. Keep the fix localized to the foreach over
$value['statuses'] and the Whatsapp_message update_status() path so late webhook
events cannot downgrade an already read message.
🧹 Nitpick comments (1)
app/Controllers/Sales.php (1)

936-977: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicate PDF-generation/token logic between getSendPdf() and getSendWhatsapp().

The token construction (Token_invoice_sequence, Token_invoice_count, Token_customer), logo tag setup, and sales/{type}_email rendering are duplicated almost verbatim between getSendPdf() (Lines 936-966) and getSendWhatsapp() (Lines 1039-1052). Extracting a shared private helper (e.g. _render_sale_pdf(array $sale_data, string $type): array returning [html, tempFilePath] or similar) would reduce drift risk if one path is updated without the other.

♻️ Suggested extraction
+    private function _render_sale_document(array $sale_data, string $type): string
+    {
+        $sale_data['mimetype'] = $this->email_lib->getLogoMimeType();
+        $sale_data['img_tag'] = $this->email_lib->buildLogoImgTag();
+
+        $view = Services::renderer();
+        return $view->setData($sale_data)->render("sales/$type" . '_email', $sale_data);
+    }

Both getSendPdf() and getSendWhatsapp() can then call $this->_render_sale_document($sale_data, $type) instead of duplicating the render call.

Also applies to: 1039-1069

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/Controllers/Sales.php` around lines 936 - 977, The PDF/token rendering
flow is duplicated in getSendPdf() and getSendWhatsapp(), including token setup,
logo image preparation, and sales/{type}_email rendering. Extract that shared
logic into a private helper such as _render_sale_document() or
_render_sale_pdf() that takes $sale_data and $type and returns the rendered HTML
and any needed temp file data, then have both getSendPdf() and getSendWhatsapp()
call the helper to keep the two paths in sync.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/Controllers/Whatsapp_webhook.php`:
- Around line 136-140: The webhook status loop in Whatsapp_webhook.php currently
calls update_status() for every incoming status and can overwrite a newer state
with an older one. Update the logic around update_status() to compare the
incoming status against the stored message status and ignore backward
transitions, only allowing forward progress such as sent → delivered → read.
Keep the fix localized to the foreach over $value['statuses'] and the
Whatsapp_message update_status() path so late webhook events cannot downgrade an
already read message.

---

Nitpick comments:
In `@app/Controllers/Sales.php`:
- Around line 936-977: The PDF/token rendering flow is duplicated in
getSendPdf() and getSendWhatsapp(), including token setup, logo image
preparation, and sales/{type}_email rendering. Extract that shared logic into a
private helper such as _render_sale_document() or _render_sale_pdf() that takes
$sale_data and $type and returns the rendered HTML and any needed temp file
data, then have both getSendPdf() and getSendWhatsapp() call the helper to keep
the two paths in sync.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f6b9c5af-4583-4457-8429-48654e713506

📥 Commits

Reviewing files that changed from the base of the PR and between 37bbd24 and 1608237.

📒 Files selected for processing (11)
  • LICENSE
  • app/Controllers/Config.php
  • app/Controllers/Sales.php
  • app/Controllers/Whatsapp.php
  • app/Controllers/Whatsapp_webhook.php
  • app/Models/Whatsapp_message.php
  • app/Views/sales/invoice.php
  • app/Views/sales/quote.php
  • app/Views/sales/receipt.php
  • app/Views/sales/work_order.php
  • app/Views/whatsapp/form_whatsapp.php
✅ Files skipped from review due to trivial changes (1)
  • LICENSE
🚧 Files skipped from review as they are similar to previous changes (8)
  • app/Views/sales/receipt.php
  • app/Views/sales/invoice.php
  • app/Views/sales/quote.php
  • app/Controllers/Config.php
  • app/Views/whatsapp/form_whatsapp.php
  • app/Models/Whatsapp_message.php
  • app/Views/sales/work_order.php
  • app/Controllers/Whatsapp.php

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/Models/Whatsapp_message.php`:
- Around line 104-126: The update_status method in Whatsapp_message currently
reads the row and then updates it, which can race and allow older statuses to
overwrite newer ones. Make the transition check atomic by moving the rank
comparison into the whatsapp_messages UPDATE itself or by locking the selected
row before updating, so only forward status changes from sent to delivered to
read can commit. Keep the logic centered in update_status and use the existing
status rank mapping to guard the write.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c6664af1-432d-434e-9b86-ba98e862467a

📥 Commits

Reviewing files that changed from the base of the PR and between 1608237 and 8ce1d6f.

📒 Files selected for processing (3)
  • app/Database/Migrations/20260703000000_AddWhatsappModule.php
  • app/Models/Whatsapp_message.php
  • app/Views/sales/invoice.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • app/Views/sales/invoice.php
  • app/Database/Migrations/20260703000000_AddWhatsappModule.php

Comment thread app/Models/Whatsapp_message.php Resolved
@objecttothis

Copy link
Copy Markdown
Member

Great work here. I think this is a very useful addition, however, I think this needs to be implemented as a plugin. See #4407 which will be merged shortly after the 3.4.2 release and will be the staple change in the 3.5.0 release. In that PR, you can see how Mailchimp was implemented as a plugin and there is a detailed README.md explaining how to create a plugin. @jekkos, what do you think here? WhatsApp is fairly ubiquitous but this kind of a change fits the mold of a plugin. @jekkos, I think we need to potentially create a repo to store publicly available plugins or potentially a repo for each publicly available plugin. I lean toward the first option, so that publicly shared plugins are stored in the same place. I'm not completely against storing publicly available plugins in this repo, though. However, they do need to be written as plugins, which means not touching the core code.

@joshua1234511, if you need to add specific event triggers for this plugin to work, then create a branch from the one in #4407 and submit a PR for the event triggers you want to add. You'll need to potentially add a view trigger, but I think there may already be one exactly where you need it, since I added it for another plugin.

@objecttothis

Copy link
Copy Markdown
Member

@joshua1234511 the good news is that you've already done the legwork of developing the feature. All that needs to be done now is package it into a plugin and let the plugin system do the injecting. If you get stuck on it, let me know and I can help get you unstuck. If you are using AI to help the development, I would create a branch from #4407, and point your AI at this PR, then tell it to read the README.md and AGENTS.md then turn the changes in this PR into a plugin. That should get you most of the way there.

@joshua1234511

Copy link
Copy Markdown
Contributor Author

Great work here. I think this is a very useful addition, however, I think this needs to be implemented as a plugin. See #4407 which will be merged shortly after the 3.4.2 release and will be the staple change in the 3.5.0 release. In that PR, you can see how Mailchimp was implemented as a plugin and there is a detailed README.md explaining how to create a plugin. @jekkos, what do you think here? WhatsApp is fairly ubiquitous but this kind of a change fits the mold of a plugin. @jekkos, I think we need to potentially create a repo to store publicly available plugins or potentially a repo for each publicly available plugin. I lean toward the first option, so that publicly shared plugins are stored in the same place. I'm not completely against storing publicly available plugins in this repo, though. However, they do need to be written as plugins, which means not touching the core code.

@joshua1234511, if you need to add specific event triggers for this plugin to work, then create a branch from the one in #4407 and submit a PR for the event triggers you want to add. You'll need to potentially add a view trigger, but I think there may already be one exactly where you need it, since I added it for another plugin.

Thanks for the feedback and moving this to a plugin makes sense, and I agree it's the better long-term approach.
I'll take a look at this sometime next week. I'll review the changes in #4407 along with the README.md and AGENTS.md, then work on converting this PR into a plugin. If I find that any additional event triggers are needed, I'll create a separate PR for those.

@joshua1234511

Copy link
Copy Markdown
Contributor Author

Thanks @objecttothis — converted this to a plugin as you suggested. Replaced by two PRs so the core changes stay reviewable on their own:

#4605 — core enablers: view hooks for the invoice, quote and work order documents, plus a CSRF exemption for plugin webhook routes.
#4606 — the WhatsApp plugin itself, at app/Plugins/WhatsappPlugin/. No core file is touched.
You were right that the hook I needed mostly existed already: view:sales_receipt_buttons at app/Views/sales/receipt.php:51 was exactly the right spot. Only the other three sale document views needed one, so #4605 adds them with the same name and payload shape, and the plugin registers one callback for all four.

The other thing I needed was a way to expose the inbound Meta webhook. A server-to-server callback has no CSRF token and no session, so #4605 exempts plugins/*/webhook from the global filter and the plugin authenticates the caller itself — it verifies Meta's X-Hub-Signature-256 HMAC against the app secret and stores nothing if that fails or if no secret is configured.

Everything else moved into the plugin: settings to plugin_config instead of app_config (with the token and app secret encrypted at rest), the conversation table to a plugin migration, the menu entry and permission to registerModule(), the config tab to the plugin's own config view, and the four copies of the button block to a single plugin view. initial_schema.sql is back to untouched.

One open question in #4605 that I'd like your and @jekkos's read on: Sales::_load_sale_data() is private, so the plugin has to rebuild the sale document data itself to render the PDF. My version only calls existing public APIs and reimplements no totals or tax logic, but it's still ~80 lines mirroring core and it will drift. If you'd rather core exposed that reusably — a public method, or moved into Sale_lib — I'm happy to add it to #4605 and delete the plugin-side copy.

#4606
#4605
#4606
Closing this in favour of those two. Thanks for the steer, the plugin version is a lot cleaner.

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.

[Feature]: WhatsApp messaging support

2 participants