# WhatsApp-Web Bridge (Baileys)

Server-side bridge that links a real WhatsApp number to the ERP by QR scan — no
browser, no Chromium. **One process per channel (number).**

This is only needed for channels whose **Connection Type = WhatsApp Web (QR scan)**.
Meta Cloud API channels need no bridge.

## How it fits together

```
WhatsApp phone ──QR link──► [ Node bridge ] ──HTTPS (bearer token)──► ERP /api/whatsapp/agent
                                  ▲  pulls queued messages, posts QR / state / inbound / acks
```

- The bridge pushes the QR to the ERP; staff scan it on the channel's **Connect** screen.
- It sends a heartbeat; if it stops, the ERP flags the channel **disconnected**, alerts
  admins to re-scan, and **holds** pending messages.
- On reconnect the ERP re-drives the held messages automatically — nothing is lost.

## Install & run

Requires Node 18+.

```bash
cd Modules/WhatsApp/node-bridge
npm install
cp .env.example .env          # then edit ERP_BASE_URL + CHANNEL_TOKEN
npm start
```

`CHANNEL_TOKEN` is shown on the channel row in **WhatsApp → Channels** (the
"bridge token", regenerate with the key button). `ERP_BASE_URL` must end in
`/api/whatsapp/agent`.

### Multiple numbers

Run one copy per number, each with its own folder / `AUTH_DIR` and its own
`CHANNEL_TOKEN`:

```bash
AUTH_DIR=./auth-branch1 CHANNEL_TOKEN=xxxx npm start
AUTH_DIR=./auth-branch2 CHANNEL_TOKEN=yyyy npm start
```

Use pm2/systemd to keep them alive:

```bash
pm2 start index.js --name wa-branch1 --update-env
```

## Re-scanning

If the phone unlinks the device (or you click **Disconnect device** in the ERP),
delete the `AUTH_DIR` folder and restart the process; a fresh QR appears on the
Connect screen.

## Notes / limits

- Baileys is an **unofficial** WhatsApp client. Keep volume modest and use the
  built-in send jitter to reduce ban risk. For high-volume automated blasts,
  prefer a Meta Cloud API channel.
- Group messages are ignored on inbound by default.
```
