# WhatsApp Business Linked Devices

The requested QR mode is now implemented separately from the official Cloud API transport. It uses the official npm distribution of **@whiskeysockets/baileys 7.0.0-rc14**, the same protocol family used by the supplied WA-AKG gateway. This is an unofficial WhatsApp Web integration, not a Meta Cloud API feature.

## Link your phone

1. Open the RouteFlow dashboard and select **Linked Devices**.
2. Click **Generate / refresh QR**. The Node bridge starts locally and negotiates a real QR with WhatsApp. A static sample QR is never used.
3. On your phone: **WhatsApp Business → Settings / ⋮ → Linked devices → Link a device**. Scan the live browser QR yourself.
4. The connection reports **connected**, then available chat/contact/history events are imported. Keep the phone online during the initial sync.
5. Open **WhatsApp Inbox → Your WhatsApp chats**. Select a chat. Names and known phone numbers populate Customers and dashboard counts. Live direct-message order conversations also appear in the original business inbox section.

The browser polls for QR replacements; expired codes are cleared when the connection closes. Session keys remain under `data/linked-device/auth.json`; never share that directory. They let this computer reconnect without scanning again. **Pause connection** retains the session. **Unlink device** logs out this device but keeps the imported business records. You can also unlink it in the phone's Linked Devices settings.

## Manual keyword flows

Use **Keyword Flows → Create flow**:

- **Keywords**: comma-separated phrases, for example `order,bhej,chahiye`.
- **Match mode**: `any`, `all` or `exact` (case-insensitive).
- **Action**: `reply` sends the saved reply; `order` starts the existing product/area/address/confirmation workflow; `review` creates a staff notification.
- **Priority**: higher values run first; only the first matching enabled rule executes.
- **Enabled**: new flows start disabled. Enable when you are ready for it to handle new incoming linked direct messages.
- **Receiving number**: optional restriction to the linked number or a configured number. The test tool respects this restriction.

**Test keywords** only reports the matching rule; it does not send a message. The original local simulator remains available for testing catalogue/order/cutoff logic and never sends through the linked phone. The flow test previews keyword rules independently.

Historical messages, messages you sent, group messages, stale messages and chats without a reliably resolved phone number do not trigger keyword replies or order creation. Imported history is read-only input. Human takeover and the global automation pause block automatic linked replies too. A pending order draft can consume YES/HAAN or area/address follow-ups without matching the initial trigger keyword again.

## What is automatic vs what needs your business configuration

Automatic: real QR negotiation, receiving number record, synced chat archive, known customer names/phones, dashboard counts, incoming messages, enabled keyword rules, confirmed orders, date/route calculation using your saved route map, and generated daily sheets.

You configure: product master/units, actual delivery areas/routes/weekday/cutoff, customer shop addresses when absent, drivers/vehicles and keyword rules. A chat contact does not contain a trustworthy delivery weekday or vehicle route; the system does not invent these. Missing area/address is collected during order booking. Existing routes and delivery sheets stay editable.

## History boundaries

WhatsApp decides which history chunks become available to a new device. Full historical recovery is not guaranteed. The library requests history synchronization and imports the events WhatsApp actually provides; the interface never claims that every past message was scraped. Text and media metadata/captions are retained; binary media downloads, OCR and voice transcription are not implemented. Unresolved LID contacts remain viewable until a trustworthy phone mapping arrives. Groups are viewable but do not become retail customers or orders.

Messages are first spooled to disk as import batches. The bridge deletes a batch only after the backend has committed it. Stable provider message IDs deduplicate retry batches. Old messages never activate automation just because the backend restarted. Large import backlogs remain visible as queued batches.

## Start / troubleshoot

Python backend: `python server.py`. Node.js 20+ is required for this optional bridge. Dependencies are installed on this machine. On another machine:

```powershell
cd bridge
npm ci
cd ..
python server.py
```

Generate QR from the dashboard. The bridge listens on `127.0.0.1:8766`; the backend defaults to `127.0.0.1:8765`. Both bridge APIs and event callbacks require a backend-generated local shared secret. QR/status endpoints additionally require an admin browser session. Session files, QR previews, logs and spooled chats are excluded from source packaging.

If no QR appears, check the visible connection error and `data/bridge.log` or `data/bridge-error.log`. Ensure WhatsApp WebSocket connectivity is available. The tested Web/Chrome handshake uses the installed library's protocol version; independently substituting a newer WhatsApp Web revision caused pre-pairing disconnects in testing and is not done by default. No TLS validation or security protections are disabled.

Verification: **28 automated tests passed** including history isolation, groups/unresolved identities, flow priority/modes, duplicate import, takeover/pause and explicit order confirmation. A real QR was generated and visibly verified in the dashboard. Actual account linkage and private chat history require your phone-side scan; no account has been assumed connected from merely generating a QR.

**Live verification update:** the user completed the phone-side link during this session. The connection subsequently reported `connected`; the import queue reached zero with **2,538 chats, 8,583 unique messages and 1,644 total customer/contact records** committed. Contact totals include the existing fictional demo records. No keyword flow was enabled and no real automatic reply was sent. Additional history/live events may change these counts.

Sources: [Baileys connection documentation](https://github.com/WhiskeySockets/baileys.wiki-site/blob/main/docs/socket/connecting.md), [history synchronization documentation](https://github.com/WhiskeySockets/baileys.wiki-site/blob/main/docs/socket/history-sync.md), [official package releases](https://github.com/WhiskeySockets/Baileys/releases).
