# WhatsApp Connect Module — Install Guide

Portable UltimatePOS module that sends WhatsApp notifications for new sales, sale updates, payment reminders, and manual sends. Supports two providers per template:

- **Unofficial** — MultiCRM personal instance (QR-paired WhatsApp)
- **Meta Official Cloud API** — billable, template-only, higher deliverability

Built for UltimatePOS on Laravel 10+ (nWidart/laravel-modules structure).

---

## 1. Copy the module folder

Place the whole `WhatsappNotification/` folder into the target app's `Modules/` directory so the final path is:

```
<your-ultimatepos-root>/Modules/WhatsappNotification/
```

## 2. Register the module

Open `<app-root>/modules_statuses.json` and add (or verify):

```json
"WhatsappNotification": true
```

## 3. Autoload & discover

From the app root, run:

```bash
composer dump-autoload
php artisan module:list
```

`module:list` should now show `WhatsappNotification` as **Enabled**.

## 4. Install (creates DB tables + system version marker)

Log in to the app **as an admin** and visit:

```
/whatsapp-notification/install
```

This runs the module's migrations (creates `whatsapp_notification_settings`, `whatsapp_notification_templates`, `whatsapp_notification_logs`) and writes `system.whatsappnotification_version = 1.0`.

Alternatively, from the CLI:

```bash
php artisan module:migrate WhatsappNotification --force
```

## 5. Add the Laravel scheduler cron (for payment reminders)

The module's `pos:SendWhatsappPaymentReminders` command runs every 15 minutes via Laravel's scheduler. Make sure your crontab has:

```
* * * * * /usr/bin/php /path/to/app/artisan schedule:run >/dev/null 2>&1
```

Skip this step if you don't need scheduled payment-due reminders (manual + new-sale still work without it).

## 6. Configure credentials

As admin, open the sidebar → **WhatsApp Connect** (green icon) → **Settings**:

**For the Unofficial provider (personal WhatsApp / QR-paired):**
1. Set **API URL** (default: `https://multicrm.bigbrainscrm.com/api/send_template`).
2. Click **Create Instance** → **Get QR Code** → scan with the store's WhatsApp.
3. Paste the **Access Token** from your MultiCRM dashboard.
4. Tick **Active** and **Notify on new sale** → **Save**.
5. Test: enter your own number in the **Send Test** box → **Send Test**.

**For the Meta Official Cloud API (optional):**
1. Fill **Meta API Key** (from MultiCRM → API Keys) and **Meta Connection ID** (from Connections).
2. Save.
3. On any Template, switch **Send via** to **Meta Official Cloud API** and click **Load templates** — the dropdown fills from your approved Meta templates.

## 7. Set up templates

Go to **WhatsApp Connect → Templates → Add**:

- Pick a **trigger type**: `new_sale`, `sale_update`, `payment_reminder`, or `manual`.
- Pick a **provider**: Unofficial or Meta Official.
- **Unofficial:** write the message title + footer using placeholders (see list below), optionally add buttons.
- **Meta Official:** pick an approved Meta template, list the body-parameter tags in order (one per line), optionally set a header media URL.
- **Payment reminder** trigger also lets you set `reminder_days_overdue` + `reminder_send_time`.
- Save. Only one template per (trigger_type) should be Active at a time.

### Available placeholders

Auto-substituted at send time by `WhatsappNotificationUtil::replaceTags()`:

```
{customer_name}   {invoice_no}     {total_amount}
{business_name}   {business_phone} {invoice_url}
{invoice_pdf_url} {overdue_days}   {due_date}
```

## 8. Wire the core-app integration points (three small patches)

The module ships all the code it needs, but three tiny hooks live in the
core UltimatePOS files and have to be pasted in once. Ready-to-copy
snippets are inside `Modules/WhatsappNotification/Integrations/`:

| Snippet file | Where to paste it | Purpose |
|---|---|---|
| `Integrations/SellController.patch.php` | `app/Http/Controllers/SellController.php` — right after the `new_sale_notification` `<li>` line (~line 500) | Adds the "Send WhatsApp" entry to the row-action dropdown on the Sells list |
| `Integrations/sell-index.snippet.blade.php` | `resources/views/sell/index.blade.php` — inside `@section('javascript') ... @endsection` | JS handler for the row-action click above |
| `Integrations/show-payments.snippet.blade.php` | `resources/views/transaction_payment/show_payments.blade.php` — see the two "PASTE" markers inside the snippet | Adds the "WhatsApp Reminder" button + JS to the payments modal |

Every patch is wrapped in a `class_exists(...)` / `app('modules')->find(...)`
guard, so pasting them is safe even if the module is later disabled.

## 9. Connector API (optional — for the mobile app)

If the target app also has the **Connector** module, do both:

1. Copy `Integrations/Connector/WhatsappNotificationController.php` into
   `<app-root>/Modules/Connector/Http/Controllers/Api/`.
2. Add the line from `Integrations/Connector/route.php` to
   `<app-root>/Modules/Connector/Routes/api.php`, inside the existing
   `Route::middleware('auth:api', ...)->group(...)` block.

Skip this section if you're not using the Connector module.

## 10. Uninstall

```
/whatsapp-notification/install/uninstall
```

Drops the 3 tables and removes the version marker.

---

## Triggers & endpoints reference

| Trigger | How it fires |
|---|---|
| **New Sale** | Listener `SendWhatsappOnNewSale` on `SellCreatedOrModified` event — controlled by `settings.notify_on_new_sale` |
| **Sale Update** | Same listener — controlled by `settings.notify_on_sale_update` |
| **Payment Reminder** | Scheduled command `pos:SendWhatsappPaymentReminders` (every 15 min) — matches active `payment_reminder` templates whose `reminder_days_overdue` + `reminder_send_time` fit the current invoice |
| **Manual Send** | "Send WhatsApp" action on the Sells row dropdown → `POST /whatsapp-notification/send/{transaction_id}` |
| **Test Send** | Settings page → **Send Test** box → `POST /whatsapp-notification/send-test` |

## Troubleshooting

- **Nothing sends** — check settings `is_active=1`, `notify_on_new_sale=1`, and a template exists with `trigger_type='new_sale'` + `is_active=1` for that business.
- **"Instance ID Invalidated"** — unofficial WhatsApp instance disconnected → Settings → **Reconnect Instance** (or scan a new QR).
- **Meta templates dropdown empty** — save your Meta API key first, then click Load. If still empty, your Meta account has no approved templates yet.
- **Payment reminders don't fire** — verify `php artisan schedule:list` shows `pos:SendWhatsappPaymentReminders` and that a system crontab runs `schedule:run`.
- **Send failures** — check `/whatsapp-notification/logs` for per-attempt request/response with a **Retry** button.
