Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: chatwoot integration updates

Aldino Kemal77db42882185
diff --git a/.gitignore b/.gitignore
index ae37c36b..decba309 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@ bin/
main
main.exe
src/gowa
+.claude
# Build artifacts
src/pkged.go
diff --git a/AGENTS.md b/AGENTS.md
index d985fe50..6da3224f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -1,8 +1,8 @@
# PROJECT KNOWLEDGE BASE
-Generated: 2026-06-05
-Commit: c83de24
-Branch: main
+Generated: 2026-06-06
+Commit: 8c4ea8f
+Branch: fix/chatwoot-postgres
## OVERVIEW
@@ -25,6 +25,7 @@ go-whatsapp-web-multidevice/
| | |-- whatsapp/ # Device manager, events, presence pulse, JID utilities
| | |-- chatstorage/ # chat/message/device SQL repository
| | `-- chatwoot/ # Chatwoot REST sync and direct PG import
+| | `-- pgimport/ # Direct Chatwoot Postgres importer; see child AGENTS
| |-- views/ # Embedded Vue 3 plain JS UI
| |-- statics/ # Runtime media, QR codes, send items
| `-- storages/ # Runtime SQLite DBs and history dumps
@@ -45,10 +46,12 @@ go-whatsapp-web-multidevice/
| Handle WhatsApp event | `src/infrastructure/whatsapp/event_*.go` | Register the concrete event in `event_handler.go`. |
| Presence behavior | `src/infrastructure/whatsapp/event_handler.go`, `presence_pulse.go`, `src/cmd/helpers.go` | Connect-time and scheduled pulse presence. |
| Add chat storage method | `src/domains/chatstorage/interfaces.go`, `sqlite_repository.go`, `chatstorage_wrapper.go` | Update domain, repository, and wrapper together. |
-| Add DB migration | `src/infrastructure/chatstorage/sqlite_repository.go` `getMigrations()` | Append only. Current list has 22 migrations. |
+| Add DB migration | `src/infrastructure/chatstorage/sqlite_repository.go` `getMigrations()` | Append only. Current list has 29 migrations. |
| Add UI component | `src/views/components/`, `src/views/index.html` | Plain JS modules, no `.vue` single-file components. |
| Device management | `src/infrastructure/whatsapp/device_manager.go` | Central registry and purge/load/create logic. |
| Chatwoot integration | `src/infrastructure/chatwoot/` and `src/ui/rest/chatwoot.go` | REST sync, public webhook, optional direct Postgres import. |
+| Direct Chatwoot import | `src/infrastructure/chatwoot/pgimport/` | Direct Chatwoot schema writes; see child AGENTS. |
+| Chatwoot link/retry state | `src/infrastructure/chatstorage/sqlite_repository.go`, `src/infrastructure/whatsapp/webhook_forward.go` | Message links, read/delete sync, and persistent forward retries. |
| CLI flags / config | `src/cmd/root.go`, `src/config/settings.go`, `src/.env.example` | Flags and env mutate config package globals. |
| Shared helpers | `src/pkg/utils/`, `src/pkg/error/`, `src/pkg/sqlite/` | Utilities, aliased package errors, and CGO/purego SQLite driver selection. |
| Docker/release | `docker/golang.Dockerfile`, `.github/workflows/*.yaml` | Multi-arch Docker, tag/manual workflows, generated GoReleaser configs. |
@@ -62,10 +65,12 @@ go-whatsapp-web-multidevice/
| `DeviceManager` | struct | `src/infrastructure/whatsapp/device_manager.go` | Owns active device registry and persisted device records. |
| `DeviceInstance` | struct | `src/infrastructure/whatsapp/device_instance.go` | Wraps per-device ID, JID, client, state, and storage. |
| `IChatStorageRepository` | interface | `src/domains/chatstorage/interfaces.go` | Storage contract for chats, messages, edits, calls, stats, schema, and device records. |
-| `SQLiteRepository` | struct | `src/infrastructure/chatstorage/sqlite_repository.go` | Implements chat storage and inline migrations. |
+| `SQLiteRepository` | struct | `src/infrastructure/chatstorage/sqlite_repository.go` | Implements chat storage, Chatwoot link/retry state, and inline migrations. |
| `deviceChatStorage` | wrapper | `src/infrastructure/whatsapp/chatstorage_wrapper.go` | Injects or enforces device scoping for event-side storage access. |
| `StartPresencePulseScheduler` | function | `src/infrastructure/whatsapp/presence_pulse.go` | Periodically marks connected devices available, then unavailable. |
+| `StartChatwootForwardRetryWorker` | function | `src/infrastructure/whatsapp/webhook_forward.go` | Replays queued WhatsApp-to-Chatwoot forward failures. |
| `NormalizeJIDFromLID` | function | `src/infrastructure/whatsapp/jid_utils.go` | Converts `@lid` JIDs to phone JIDs where whatsmeow can resolve them. |
+| `pgimport.Importer` | struct | `src/infrastructure/chatwoot/pgimport/conn.go` | Direct Chatwoot Postgres importer for historical messages. |
| `DeviceMiddleware` | middleware | `src/ui/rest/middleware/device.go` | Resolves `X-Device-Id` or `device_id` and injects device context. |
| `ContextWithDefaultDevice` | helper | `src/ui/mcp/helpers/context.go` | MCP equivalent of REST device middleware for default/only device. |
@@ -82,6 +87,8 @@ go-whatsapp-web-multidevice/
- MCP handlers do not receive `X-Device-Id`; they resolve the default/only device via `ContextWithDefaultDevice`.
- Optional boolean filters use `*bool` so nil means "not provided".
- Tests are colocated as `*_test.go`, mostly table-driven with `testify/assert` and occasional `testify/suite`.
+- Tests that mutate config, package globals, or background worker state should stay serial and restore state with `defer`.
+- Chatwoot direct Postgres import is for history. Live forwarding still uses REST plus link/retry storage.
## ANTI-PATTERNS
@@ -92,6 +99,7 @@ go-whatsapp-web-multidevice/
- Do not insert migrations in the middle of `getMigrations()`; append new entries only.
- Do not remove the `evt.Sender.Device != 0` receipt check; it prevents duplicate webhook deliveries from linked devices.
- Do not put generated/runtime media, QR codes, SQLite DBs, `.env`, or history dumps into source-oriented docs or commits unless explicitly requested.
+- Do not treat Chatwoot direct Postgres import as the live forwarding path; keep REST media handling and direct DB idempotency separate.
## UNIQUE STYLES
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index 7cca5d5e..39989773 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -23,20 +23,36 @@ Before setting up the integration, ensure you have:
### Environment Variables
-| Variable | Required | Default | Description |
-|----------|----------|---------|-------------|
-| `CHATWOOT_ENABLED` | Yes | `false` | Enable Chatwoot integration |
-| `CHATWOOT_URL` | Yes | - | Your Chatwoot instance URL (e.g., `https://app.chatwoot.com`) |
-| `CHATWOOT_API_TOKEN` | Yes | - | API access token from Chatwoot |
-| `CHATWOOT_ACCOUNT_ID` | Yes | - | Your Chatwoot account ID |
-| `CHATWOOT_INBOX_ID` | Yes | - | The inbox ID for WhatsApp messages |
-| `CHATWOOT_DEVICE_ID` | No | - | Specific device ID for outbound messages (required for multi-device setups) |
-| `CHATWOOT_IMPORT_MESSAGES` | No | `false` | Enable message history sync to Chatwoot |
-| `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES` | No | `3` | Number of days of history to import |
+| Variable | Required | Default | Function |
+|----------|----------|---------|----------|
+| `CHATWOOT_ENABLED` | Yes | `false` | Master switch. When `true`, the app registers the public `POST /chatwoot/webhook` route before basic auth, starts the Chatwoot live-forward retry worker, registers the authenticated `/chatwoot/sync` routes, and forwards WhatsApp messages to Chatwoot. If `false`, Chatwoot webhooks fall through to normal auth/routing and agent replies will not work. |
+| `CHATWOOT_URL` | Yes | - | Base URL of the Chatwoot instance, without a trailing slash, for REST API calls. Example: `https://chatwoot.example.com`. |
+| `CHATWOOT_API_TOKEN` | Yes | - | Chatwoot user API access token. The token is sent as `api_access_token` to create contacts, conversations, messages, inboxes, and attachments. Direct DB import also uses this token to resolve the Chatwoot user that should own imported outgoing messages. |
+| `CHATWOOT_ACCOUNT_ID` | Yes | - | Numeric Chatwoot account ID. This is the number in `/app/accounts/<id>/...`, not an inbox identifier, hmac token, or random API-channel string. |
+| `CHATWOOT_INBOX_ID` | Yes\* | - | Numeric Chatwoot inbox ID for the API-channel inbox. Optional only when `CHATWOOT_AUTO_CREATE=true`, because startup can resolve it automatically. If set, it always wins and auto-provisioning is skipped. |
+| `CHATWOOT_DEVICE_ID` | Multi-device | - | WhatsApp device that should send Chatwoot agent replies. Use either the local device ID or the device JID. Required when more than one device is registered. If empty and exactly one device exists, that device is used automatically. |
+| `CHATWOOT_IMPORT_MESSAGES` | No | `false` | Auto-start history sync when a WhatsApp device connects. Live message forwarding works even when this is `false`. |
+| `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES` | No | `3` | Number of days of stored WhatsApp history to import during auto-sync or when a manual sync omits `days_limit`. |
+| `CHATWOOT_IMPORT_DB_URI` | No | - | PostgreSQL connection URI for direct Chatwoot DB import. When set, history sync writes directly to Chatwoot tables to preserve original timestamps. When empty, history sync uses Chatwoot REST. Live forwarding always uses REST. |
+| `CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE` | No | `true` | Direct-DB import behavior for media that cannot be downloaded. `true` inserts a text placeholder such as `[image]`; `false` leaves the message body empty. |
+| `CHATWOOT_IMPORT_MEDIA_WITH_REST` | No | `false` | Direct-DB import media mode. `true` sends downloadable media rows through Chatwoot REST so ActiveStorage attachments are created; non-media rows still use direct DB. Media uploaded this way gets Chatwoot's upload timestamp. |
+| `CHATWOOT_AUTO_CREATE` | No | `false` | Startup provisioning mode. When `true`, the app lists inboxes, reuses an API-channel inbox named `CHATWOOT_INBOX_NAME`, or creates one using `CHATWOOT_WEBHOOK_URL`; then it fills `CHATWOOT_INBOX_ID` in memory. |
+| `CHATWOOT_INBOX_NAME` | No | `WhatsApp` | Inbox name used only by auto-provisioning. The app reuses a same-name `Channel::Api` inbox, but ignores same-name non-API inboxes because they cannot receive API-channel reply webhooks. |
+| `CHATWOOT_WEBHOOK_URL` | Reply webhook | - | Public URL Chatwoot should call for agent replies: `https://your-gowa.example.com/chatwoot/webhook`. Used when creating an API inbox automatically, and useful as the value to place in an existing API channel's `webhook_url`. Include `?secret=...` when using `CHATWOOT_WEBHOOK_SECRET` and Chatwoot cannot send custom headers. |
+| `CHATWOOT_WEBHOOK_SECRET` | Recommended | - | Shared secret expected by GOWA for incoming Chatwoot webhook calls. If empty, webhooks are accepted without this extra check. If set, the request must send the value via `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, `?secret=...`, or an `X-Hub-Signature-256` HMAC signature. |
+| `CHATWOOT_REOPEN_CONVERSATION` | No | `true` | When a contact has a resolved conversation and messages again, reopen/reuse that conversation instead of starting a new thread. Keeps REST and direct-DB behavior aligned. |
+| `CHATWOOT_CONVERSATION_PENDING` | No | `false` | Create new conversations with status `pending` instead of `open`, so they land in the unassigned queue. Applies to REST and direct-DB paths. |
+| `CHATWOOT_IGNORE_JIDS` | No | - | Comma-separated exact JIDs or wildcards to never mirror to Chatwoot. Supports exact values plus `@g.us`, `@s.whatsapp.net`, and `@lid`. System JIDs such as `status@broadcast` are already ignored. |
+| `CHATWOOT_SIGN_MSG` | No | `false` | Prefix Chatwoot agent replies sent to WhatsApp with the agent name. Example: `*Jane*` plus the delimiter and message body. |
+| `CHATWOOT_SIGN_DELIMITER` | No | `\n\n` | Delimiter inserted between the agent signature and reply body. Literal `\n` sequences are expanded to real newlines. |
+| `CHATWOOT_FORWARD_EDITS` | No | `true` | Mirror WhatsApp message edits into Chatwoot as private/threaded notes attached to the original message. |
+| `CHATWOOT_FORWARD_DELETES` | No | `true` | Mirror WhatsApp delete-for-everyone events into Chatwoot as private/threaded notes attached to the original message. |
+| `CHATWOOT_MESSAGE_READ` | No | `false` | Evolution-compatible read sync. Updates Chatwoot last-seen from WhatsApp receipts and marks WhatsApp messages read after agent replies when durable message links exist. |
+| `CHATWOOT_MESSAGE_DELETE` | No | `false` | Evolution-compatible delete sync. Deletes/revokes the linked message on the opposite side when durable message links exist. Inbound customer messages are not revoked from WhatsApp because this device did not send them. |
### Configuration Examples
-**Environment File (.env):**
+**Minimal environment file (.env):**
```bash
CHATWOOT_ENABLED=true
CHATWOOT_URL=https://app.chatwoot.com
@@ -44,12 +60,37 @@ CHATWOOT_API_TOKEN=your_api_token_here
CHATWOOT_ACCOUNT_ID=12345
CHATWOOT_INBOX_ID=67890
CHATWOOT_DEVICE_ID=my-whatsapp-device
+CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
+CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
# Optional: History sync settings
CHATWOOT_IMPORT_MESSAGES=true
CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7
```
+**Self-hosted Chatwoot example with direct DB history import:**
+```bash
+CHATWOOT_ENABLED=true
+CHATWOOT_URL=https://chatwoot.example.com
+CHATWOOT_API_TOKEN=your_chatwoot_user_api_token
+
+# Numeric IDs from Chatwoot, not API-channel identifier/hmac strings.
+CHATWOOT_ACCOUNT_ID=1
+CHATWOOT_INBOX_ID=1
+
+# Local GOWA device id or device JID.
+
+# Agent reply callback from Chatwoot to GOWA.
+CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
+CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+
+# Optional history import.
+CHATWOOT_IMPORT_MESSAGES=true
+CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7
+CHATWOOT_IMPORT_DB_URI=postgresql://chatwoot:password@chatwoot-db:5432/chatwoot_production?sslmode=disable
+```
+
**CLI Flags:**
```bash
./whatsapp rest \
@@ -69,9 +110,24 @@ services:
- CHATWOOT_ACCOUNT_ID=12345
- CHATWOOT_INBOX_ID=67890
- CHATWOOT_DEVICE_ID=my-device
+ - CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
+ - CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
command: rest
```
+### Setup Checklist
+
+1. In Chatwoot, create or identify an **API channel** inbox.
+2. Copy the numeric `CHATWOOT_ACCOUNT_ID` from the Chatwoot account URL.
+3. Copy the numeric `CHATWOOT_INBOX_ID` from the inbox URL/settings.
+4. Copy a Chatwoot user API token from profile settings.
+5. Choose the WhatsApp device for agent replies and set `CHATWOOT_DEVICE_ID` when more than one device exists.
+6. Make GOWA publicly reachable at `https://your-gowa.example.com/chatwoot/webhook`.
+7. Set the API channel inbox webhook URL to that public GOWA webhook URL.
+8. Set `CHATWOOT_WEBHOOK_SECRET` and send the same value through the webhook URL query string or a supported header.
+9. Restart GOWA after changing `.env`; the webhook and sync routes are registered at process startup.
+10. Verify with `/chatwoot/sync/status` and a webhook curl before going live.
+
## Chatwoot Setup
### Step 1: Create an API Channel Inbox
@@ -99,16 +155,72 @@ Your account ID is visible in the URL when logged into Chatwoot:
https://app.chatwoot.com/app/accounts/[ACCOUNT_ID]/dashboard
```
-### Step 4: Configure the Webhook
+### Step 4: Configure the API Channel Webhook
+
+For agent replies from Chatwoot to WhatsApp, configure the webhook URL on the **API channel inbox** itself:
+
+1. Navigate to **Settings** > **Inboxes**.
+2. Open the API-channel inbox used for WhatsApp.
+3. Set the API channel webhook URL to:
+ ```text
+ https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+ ```
+4. Save the inbox.
+
+> **Important:** The webhook URL must be publicly accessible. If GOWA runs locally, use a tunneling service such as ngrok and set the full tunnel URL, including `/chatwoot/webhook`.
+
+Global Chatwoot webhooks under **Settings > Integrations > Webhooks** are useful for generic event delivery, but they are not the primary API-channel reply path documented here. The API-channel inbox `webhook_url` is what Chatwoot uses to send agent replies for this integration.
+
+## Auto-Provisioning
+
+Instead of creating the inbox by hand (Step 1) and copying its ID, you can let the integration provision it for you in one step.
+
+Set:
+
+```bash
+CHATWOOT_ENABLED=true
+CHATWOOT_URL=https://app.chatwoot.com
+CHATWOOT_API_TOKEN=your_api_token
+CHATWOOT_ACCOUNT_ID=12345
+CHATWOOT_AUTO_CREATE=true
+CHATWOOT_INBOX_NAME=WhatsApp # optional, defaults to "WhatsApp"
+CHATWOOT_WEBHOOK_SECRET=super-secret-key # optional, but recommended
+CHATWOOT_WEBHOOK_URL=https://your-api.com/chatwoot/webhook?secret=super-secret-key
+```
+
+On startup the app will:
+
+1. Look for an inbox named `CHATWOOT_INBOX_NAME` in the account and **reuse it** if present (so restarts never create duplicates).
+2. Otherwise **create** a new API-channel inbox with that name, wired to `CHATWOOT_WEBHOOK_URL`.
+3. Resolve `CHATWOOT_INBOX_ID` automatically for the rest of the integration.
+
+Notes:
-1. Navigate to **Settings** > **Integrations** > **Webhooks**
-2. Click **Add new webhook**
-3. Configure:
- - **URL**: `https://your-whatsapp-api.com/chatwoot/webhook`
- - **Events**: Select `message_created`
-4. Click **Create**
+- If `CHATWOOT_INBOX_ID` is already set, it takes precedence and auto-create is skipped (your explicit value wins).
+- If `CHATWOOT_WEBHOOK_URL` is empty, the inbox is still created but **agent replies won't reach WhatsApp** until you set the webhook — a warning is logged.
+- Provisioning failures are non-fatal; the app keeps running and you can fall back to manual setup.
-> **Important:** The webhook URL must be publicly accessible. If you're running locally, use a tunneling service like ngrok.
+## Webhook Secret
+
+`CHATWOOT_WEBHOOK_SECRET` protects GOWA's public `/chatwoot/webhook` endpoint. It is the value GOWA expects to receive from Chatwoot on every agent-reply webhook.
+
+When `CHATWOOT_WEBHOOK_SECRET` is empty, GOWA accepts Chatwoot webhooks without this extra check. When it is set, GOWA accepts the request only if the same secret arrives in one of these forms:
+
+| Method | Example | When to use |
+|--------|---------|-------------|
+| Header | `X-Chatwoot-Webhook-Secret: strong-shared-secret` | Best when a proxy or webhook sender can set custom headers. |
+| Header | `X-Gowa-Chatwoot-Secret: strong-shared-secret` | Same as above; provided as a GOWA-specific header name. |
+| Query string | `/chatwoot/webhook?secret=strong-shared-secret` | Practical for Chatwoot API-channel inbox webhook URLs because the inbox stores a URL, not custom headers. |
+| HMAC signature | `X-Hub-Signature-256: sha256=<digest>` | Use when an intermediate system can sign the raw request body with the shared secret. |
+
+For a plain Chatwoot API-channel inbox, use:
+
+```bash
+CHATWOOT_WEBHOOK_SECRET=strong-shared-secret
+CHATWOOT_WEBHOOK_URL=https://your-gowa.example.com/chatwoot/webhook?secret=strong-shared-secret
+```
+
+The query-string form is less ideal than a header because URLs may appear in logs. If that is a concern, put a reverse proxy in front of GOWA: let Chatwoot call a secret-free URL on the proxy, then have the proxy add `X-Chatwoot-Webhook-Secret` before forwarding to GOWA.
## Multi-Device Setup
@@ -193,11 +305,181 @@ curl "http://your-api:3000/chatwoot/sync/status?device_id=my-device-id"
### Notes
-- Messages are prefixed with their original timestamp for context: `[2024-01-15 14:30] Hello!`
-- Group messages include the sender name: `[2024-01-15 14:30] John: Hello!`
+- Group messages include the sender name: `John: Hello!`
- Media older than ~2 weeks may be unavailable on WhatsApp servers
- The sync runs in the background and can be monitored via the status endpoint
- Only one sync can run per device at a time
+- For correct timestamps, use the [Direct Database Import](#direct-database-import-recommended) (the REST path cannot set `created_at` on Chatwoot messages)
+
+## Direct Database Import (Recommended)
+
+For **self-hosted Chatwoot** deployments, you can enable direct PostgreSQL import for message history sync. This is the recommended approach because it:
+
+- Preserves **original WhatsApp timestamps** on messages (the REST API always stamps server time)
+- Preserves **correct group names** instead of JID-based fallbacks
+- Runs **significantly faster** than the REST path (one transaction per chat; no HTTP round trips)
+- Is **idempotent** — safe to re-run without creating duplicates (rows are matched on `inbox_id + source_id`)
+
+It writes only to tables that have stayed stable across Chatwoot 2.x, 3.x, and 4.x.
+
+### Setup
+
+1. Ensure your Go WhatsApp API service has **network access** to Chatwoot's PostgreSQL database (port 5432)
+
+2. Set the connection URI:
+ ```bash
+ CHATWOOT_IMPORT_DB_URI=postgresql://postgres:password@chatwoot-db:5432/chatwoot_production?sslmode=disable
+ ```
+
+ > **Note:** if your password contains `@ : / ? #` or other URL-reserved characters, percent-encode them (e.g. `@` → `%40`). libpq will otherwise misparse the DSN and report a confusing "invalid port" error.
+
+3. Enable history import:
+ ```bash
+ CHATWOOT_IMPORT_MESSAGES=true
+ CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7
+ ```
+
+### Docker Compose Example
+
+```yaml
+services:
+ whatsapp-api:
+ image: aldinokemal2104/go-whatsapp-web-multidevice:latest
+ environment:
+ - CHATWOOT_ENABLED=true
+ - CHATWOOT_URL=https://chatwoot.example.com
+ - CHATWOOT_API_TOKEN=your_api_token
+ - CHATWOOT_ACCOUNT_ID=1
+ - CHATWOOT_INBOX_ID=1
+ - CHATWOOT_DEVICE_ID=my-device
+ - CHATWOOT_IMPORT_MESSAGES=true
+ - CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7
+ - CHATWOOT_IMPORT_DB_URI=postgresql://postgres:password@chatwoot-db:5432/chatwoot_production?sslmode=disable
+ command: rest
+
+ chatwoot-db:
+ image: pgvector/pgvector:pg17
+ # ... your existing Chatwoot Postgres config
+```
+
+### How It Works
+
+When `CHATWOOT_IMPORT_DB_URI` is set:
+- **Historical sync** (auto-sync on connect + manual `/chatwoot/sync`) writes directly to Chatwoot's PostgreSQL tables, preserving original timestamps and metadata
+- **Live messages** (incoming WhatsApp messages and Chatwoot webhook replies) continue to use the REST API so Chatwoot's normal event pipeline (assignment rules, automations, agent UI sockets) fires correctly
+- If the database connection, schema table checks, or configured account/inbox pair fail validation, the sync fails instead of silently falling back to the REST path
+- If `CHATWOOT_IMPORT_MEDIA_WITH_REST=true`, downloadable media messages are first uploaded through REST to create Chatwoot ActiveStorage attachments; the direct DB import then skips those rows by the same `WAID:<id>` source id. Media rows uploaded this way use Chatwoot's upload time, while non-media rows keep their original WhatsApp timestamps.
+
+When `CHATWOOT_IMPORT_DB_URI` is **not** set:
+- All sync operations use the Chatwoot REST API (the previous behavior, compatible with Chatwoot Cloud)
+
+### Configuration Options
+
+| Variable | Default | Description |
+|----------|---------|-------------|
+| `CHATWOOT_IMPORT_DB_URI` | - | PostgreSQL connection string to Chatwoot's database |
+| `CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE` | `true` | When `true`, inserts `[image]`, `[video]`, etc. as message body for media messages that could not be downloaded. When `false`, leaves the body empty. |
+| `CHATWOOT_IMPORT_MEDIA_WITH_REST` | `false` | When `true`, direct-DB sync uses REST for downloadable media rows so attachments exist in Chatwoot. |
+
+### Requirements
+
+- **Self-hosted Chatwoot only** — Chatwoot Cloud does not expose database access
+- PostgreSQL network reachability from the Go API service
+- The `CHATWOOT_ACCOUNT_ID` and `CHATWOOT_INBOX_ID` must match an existing account and inbox in the database; this is verified before import starts
+- Chatwoot 2.x, 3.x, or 4.x (the tables used have been stable across these versions)
+- The database URI must point to the Postgres database used by Chatwoot itself, not GOWA's local SQLite databases
+- Current self-hosted Chatwoot images can require Postgres extensions including `vector` and `pg_stat_statements`
+
+### Self-hosted Postgres and pgvector
+
+Current Chatwoot releases can require the `vector` extension during `rails db:chatwoot_prepare`. A plain `postgres:<version>` image may fail with:
+
+```text
+ERROR: extension "vector" is not available
+Could not open extension control file ".../extension/vector.control"
+```
+
+Use a durable Postgres image that includes pgvector, for example:
+
+```yaml
+services:
+ chatwoot-db:
+ image: pgvector/pgvector:pg17
+```
+
+If Chatwoot shares an existing Postgres service with other apps, prefer changing that existing service to the matching pgvector image instead of running a second Postgres server just for Chatwoot. Keep the major Postgres version the same, take a backup first, then verify existing databases after the restart. For example, move from `postgres:17` to `pgvector/pgvector:pg17`, not from `postgres:17` to a different major version.
+
+After the pgvector-capable server is running, create or verify the Chatwoot database and extensions:
+
+```sql
+CREATE DATABASE chatwoot_production OWNER chatwoot;
+\c chatwoot_production
+CREATE EXTENSION IF NOT EXISTS vector;
+CREATE EXTENSION IF NOT EXISTS pg_stat_statements;
+```
+
+Then run Chatwoot's normal database preparation command for the Chatwoot container/image. GOWA only needs the final connection URI in `CHATWOOT_IMPORT_DB_URI`; it does not create or migrate the Chatwoot database itself.
+
+### Outgoing Message Attribution
+
+When `CHATWOOT_API_TOKEN` is set, the importer resolves the Chatwoot user that owns the token from the `access_tokens` table at startup and stamps every imported outgoing message (`IsFromMe == true`) with `sender_type='User'` (or `'AgentBot'`) and `sender_id=<owner_id>`. This makes historical replies render with the agent's name and avatar in Chatwoot's UI instead of as "Unknown sender".
+
+If the token is missing, revoked, or the table is unreachable, outgoing messages still import — they just land with `NULL` sender; a startup warning is logged so operators can fix the token if attribution matters.
+
+### Security
+
+- Use TLS/SSL for the PostgreSQL connection in production (`?sslmode=require`)
+- Consider SSH tunneling or VPN if the database is on a separate network
+- The import connection requires `SELECT` on the `accounts`, `inboxes`, `schema_migrations`, and `access_tokens` tables, plus `INSERT`, `UPDATE`, and `SELECT` on the `contacts`, `contact_inboxes`, `conversations`, and `messages` tables
+
+## Conversation & Message Behavior
+
+### Conversation reopen
+
+By default (`CHATWOOT_REOPEN_CONVERSATION=true`), when a contact who already has a **resolved** conversation messages again, their existing conversation is reopened rather than a new one being spawned — so an agent sees the full history in one thread. Both the REST and direct-DB paths behave this way.
+
+Set it to `false` and the two paths intentionally differ. The REST path opens a fresh conversation for a contact whose only conversation is resolved, so each new session starts a clean thread. The direct-DB importer instead reuses the existing conversation regardless of status, and only creates a conversation when the contact has none yet — this keeps backfilled history in a single thread rather than splitting it, and avoids spawning duplicate threads on re-import.
+
+With `CHATWOOT_CONVERSATION_PENDING=true`, newly-created conversations land in `pending` (the unassigned queue) instead of `open` on both paths.
+
+### Agent signature
+
+With `CHATWOOT_SIGN_MSG=true`, replies sent from Chatwoot are prefixed with the sending agent's name before delivery to WhatsApp, e.g. `*Jane*` followed by the body. The separator is `CHATWOOT_SIGN_DELIMITER` (default two newlines; a literal `\n` is expanded to a real newline).
+
+### Formatting translation
+
+Text formatting is translated in both directions so emphasis survives the bridge:
+
+| WhatsApp | Chatwoot |
+|----------|----------|
+| `*bold*` | `**bold**` |
+| `_italic_` | `*italic*` |
+| `~strike~` | `~~strike~~` |
+
+### Edits & deletions
+
+- **Edits**: when a WhatsApp user edits a message, the new text is mirrored into Chatwoot as a threaded `✏️ **Edited:** …` note (controlled by `CHATWOOT_FORWARD_EDITS`, default on).
+- **Deletions**: a delete-for-everyone is mirrored as a threaded `🗑️ This message was deleted.` note (controlled by `CHATWOOT_FORWARD_DELETES`, default on).
+- **Linked deletes**: with `CHATWOOT_MESSAGE_DELETE=true`, WhatsApp delete-for-everyone events delete the linked Chatwoot message when a durable link exists. Chatwoot `message_updated` delete webhooks revoke linked outgoing WhatsApp messages; inbound customer messages are not revoked because this device did not send them.
+
+Both are threaded onto the original message via Chatwoot's `in_reply_to_external_id` using the shared `WAID:<id>` source-id convention, so they appear as replies to the message they affect.
+
+### Read sync
+
+With `CHATWOOT_MESSAGE_READ=true`, WhatsApp read receipts update Chatwoot `last_seen` for the linked conversation, and successful Chatwoot agent replies mark the latest unread inbound WhatsApp message in that chat as read. This depends on the local durable message-link table populated by live forwarding, REST history sync, and direct-DB import.
+
+### Replies & reactions
+
+Inbound replies and reactions are threaded onto the message they reference (again via the `WAID:` source-id), so a reply or 👍 lands attached to the right message in the Chatwoot conversation.
+
+### Ignoring chats
+
+`CHATWOOT_IGNORE_JIDS` lets you exclude chats from Chatwoot entirely, on top of the always-ignored system JIDs (`status@broadcast`, `[email protected]`). It accepts a comma-separated list of exact JIDs or the wildcards `@g.us` (all groups), `@s.whatsapp.net` (all DMs), or `@lid`:
+
+```bash
+# Ignore all groups and one specific contact
+```
## Supported Features
@@ -216,6 +498,8 @@ curl "http://your-api:3000/chatwoot/sync/status?device_id=my-device-id"
**Outgoing messages (sent from your own WhatsApp device)** are automatically forwarded to Chatwoot as `outgoing` messages.
+Live WhatsApp messages that hit a transient Chatwoot failure (network error, HTTP 429, or HTTP 5xx) are stored in the local chat storage retry queue and replayed in the background with capped exponential backoff. Permanent Chatwoot errors (most HTTP 4xx responses) are logged and not retried.
+
### Outgoing Messages (Chatwoot → WhatsApp)
| Message Type | Supported | Notes |
@@ -315,6 +599,7 @@ curl "http://your-api:3000/chatwoot/sync/status?device_id=my-device-id"
2. **Invalid API credentials**
- Double-check `CHATWOOT_API_TOKEN`
- Verify `CHATWOOT_ACCOUNT_ID` and `CHATWOOT_INBOX_ID`
+ - Both IDs must be numeric Chatwoot IDs. Do not use the API-channel `identifier`, `hmac_token`, or webhook secret as either ID.
3. **Contact/Conversation issues**
- Check API logs for contact creation errors
@@ -350,13 +635,15 @@ Look for log entries starting with:
| `device id is required` | No device ID and multiple devices exist | Set `CHATWOOT_DEVICE_ID` |
| `failed to create contact` | Chatwoot API error | Verify API token and account permissions |
| `Invalid payload` | Malformed webhook request | Check Chatwoot webhook configuration |
+| `401 Unauthorized` on `/chatwoot/webhook` | `CHATWOOT_WEBHOOK_SECRET` is set but the request did not send the expected secret | Add `?secret=<value>` to the API-channel webhook URL, send `X-Chatwoot-Webhook-Secret`, send `X-Gowa-Chatwoot-Secret`, or send a valid `X-Hub-Signature-256` |
+| `CHATWOOT_NOT_CONFIGURED` | Missing URL, token, account ID, or inbox ID | Set `CHATWOOT_URL`, `CHATWOOT_API_TOKEN`, numeric `CHATWOOT_ACCOUNT_ID`, and numeric `CHATWOOT_INBOX_ID`, or enable auto-provisioning |
### Verifying Webhook Connectivity
-Test your webhook endpoint:
+Test your webhook endpoint. If `CHATWOOT_WEBHOOK_SECRET` is set, include it in the query string or a supported header:
```bash
-curl -X POST https://your-api.com/chatwoot/webhook \
+curl -X POST "https://your-api.com/chatwoot/webhook?secret=strong-shared-secret" \
-H "Content-Type: application/json" \
-d '{
"event": "message_created",
@@ -377,6 +664,15 @@ curl -X POST https://your-api.com/chatwoot/webhook \
Expected response: `200 OK` or error with details
+Test the authenticated sync status endpoint:
+
+```bash
+curl -u user:password \
+ "https://your-api.com/chatwoot/sync/status?device_id=my-device-id"
+```
+
+Expected response: `200 OK` with `status` such as `idle`, `running`, or `completed`.
+
## Best Practices
1. **Use a dedicated device** for Chatwoot integration in production
@@ -395,6 +691,7 @@ Expected response: `200 OK` or error with details
- Monitor for unusual activity in Chatwoot logs
- Use strong authentication for the WhatsApp API (`APP_BASIC_AUTH`)
- **Note:** The `/chatwoot/webhook` endpoint is excluded from basic auth to allow Chatwoot to send webhooks without credentials. The `/chatwoot/sync` endpoints require authentication.
+- Set `CHATWOOT_WEBHOOK_SECRET` for the unauthenticated webhook route. Prefer headers or HMAC signatures when possible; use `?secret=...` for Chatwoot API-channel inboxes when no custom header injection is available.
## API Reference
@@ -404,11 +701,16 @@ Expected response: `200 OK` or error with details
**Headers:**
- `Content-Type: application/json`
+- Optional when `CHATWOOT_WEBHOOK_SECRET` is set: `X-Chatwoot-Webhook-Secret`, `X-Gowa-Chatwoot-Secret`, or `X-Hub-Signature-256`
+
+**Query Parameters:**
+- Optional when `CHATWOOT_WEBHOOK_SECRET` is set: `secret=<CHATWOOT_WEBHOOK_SECRET>`
**Request Body:** Standard Chatwoot webhook payload
**Response Codes:**
- `200 OK` - Message processed (or skipped)
+- `401 Unauthorized` - Webhook secret or signature is missing/invalid
- `503 Service Unavailable` - No device available
### Related Endpoints
diff --git a/readme.md b/readme.md
index fa25dd23..03b3103e 100644
--- a/readme.md
+++ b/readme.md
@@ -224,6 +224,8 @@ To use environment variables:
| `CHATWOOT_DEVICE_ID` | WhatsApp device ID for Chatwoot (multi-device setup) | - | `[email protected]` |
| `CHATWOOT_IMPORT_MESSAGES` | Enable message history sync to Chatwoot | `false` | `CHATWOOT_IMPORT_MESSAGES=true` |
| `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES` | Days of history to import | `3` | `CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=7` |
+| `CHATWOOT_IMPORT_DB_URI` | Direct Chatwoot PostgreSQL URI for history sync | - | `CHATWOOT_IMPORT_DB_URI=postgresql://user:pass@host:5432/chatwoot_production?sslmode=disable` |
+| `CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE` | Insert text placeholders for media rows during direct DB import | `true` | `CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=true` |
**Documentation:**
diff --git a/src/.env.example b/src/.env.example
index 24224144..b9d992c0 100644
--- a/src/.env.example
+++ b/src/.env.example
@@ -37,3 +37,24 @@ CHATWOOT_INBOX_ID=000000
CHATWOOT_DEVICE_ID=
CHATWOOT_IMPORT_MESSAGES=false
CHATWOOT_DAYS_LIMIT_IMPORT_MESSAGES=3
+CHATWOOT_IMPORT_DB_URI=
+CHATWOOT_IMPORT_PLACEHOLDER_MEDIA_MESSAGE=true
+CHATWOOT_IMPORT_MEDIA_WITH_REST=false
+# Auto-provisioning: create/reuse the inbox on startup so CHATWOOT_INBOX_ID is optional
+CHATWOOT_AUTO_CREATE=false
+CHATWOOT_INBOX_NAME=WhatsApp
+CHATWOOT_WEBHOOK_URL=
+CHATWOOT_WEBHOOK_SECRET=
+# Conversation handling
+CHATWOOT_REOPEN_CONVERSATION=true
+CHATWOOT_CONVERSATION_PENDING=false
+CHATWOOT_IGNORE_JIDS=
+# Outbound agent signature
+CHATWOOT_SIGN_MSG=false
+CHATWOOT_SIGN_DELIMITER="\n\n"
+# Edit/delete propagation (WhatsApp -> Chatwoot)
+CHATWOOT_FORWARD_EDITS=true
+CHATWOOT_FORWARD_DELETES=true
+# Evolution-compatible read/delete state sync
+CHATWOOT_MESSAGE_READ=false
+CHATWOOT_MESSAGE_DELETE=false
diff --git a/src/cmd/rest.go b/src/cmd/rest.go
index 6de19fa1..1b6cbab2 100644
--- a/src/cmd/rest.go
+++ b/src/cmd/rest.go
@@ -1,11 +1,17 @@
package cmd
import (
+ "context"
"fmt"
"net/http"
+ "os"
+ "os/signal"
"strings"
+ "syscall"
+ "time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/rest/helpers"
@@ -90,9 +96,21 @@ func restServer(_ *cobra.Command, _ []string) {
})
// Chatwoot webhook - registered BEFORE basic auth middleware
- // This allows Chatwoot to send webhooks without authentication
+ // This allows Chatwoot to send webhooks without authentication. The handler
+ // is stateless and shared with the authenticated sync routes registered below.
+ var chatwootHandler *rest.ChatwootHandler
if config.ChatwootEnabled {
- chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase, dm, chatStorageRepo)
+ // Auto-provision the Chatwoot inbox (create or reuse) when enabled, so
+ // CHATWOOT_INBOX_ID is resolved before any message is forwarded. Failures
+ // are logged but non-fatal — the operator can still set the inbox manually.
+ if config.ChatwootAutoCreate {
+ if err := chatwoot.EnsureInbox(chatwoot.GetDefaultClient()); err != nil {
+ logrus.Errorf("Chatwoot auto-create failed: %v", err)
+ }
+ }
+ whatsapp.StartChatwootForwardRetryWorker(chatStorageRepo)
+
+ chatwootHandler = rest.NewChatwootHandler(appUsecase, sendUsecase, messageUsecase, dm, chatStorageRepo)
webhookPath := "/chatwoot/webhook"
if config.AppBasePath != "" {
webhookPath = config.AppBasePath + webhookPath
@@ -141,7 +159,6 @@ func restServer(_ *cobra.Command, _ []string) {
// Chatwoot sync routes - require authentication (webhook is registered earlier without auth)
if config.ChatwootEnabled {
- chatwootHandler := rest.NewChatwootHandler(appUsecase, sendUsecase, dm, chatStorageRepo)
apiGroup.Post("/chatwoot/sync", chatwootHandler.SyncHistory)
apiGroup.Get("/chatwoot/sync/status", chatwootHandler.SyncStatus)
}
@@ -168,7 +185,42 @@ func restServer(_ *cobra.Command, _ []string) {
// Set daily presence pulse scheduler when enabled
startPresencePulseSchedulerIfEnabled()
- if err := app.Listen(config.AppHost + ":" + config.AppPort); err != nil {
- logrus.Fatalln("Failed to start: ", err.Error())
+ // Listen in a goroutine so we can trap SIGINT/SIGTERM and drain the
+ // server cleanly. Without this, Fiber's Listen blocks until the OS
+ // kills the process, leaking the Chatwoot Postgres importer pool and
+ // the chat storage DB connection.
+ listenErr := make(chan error, 1)
+ go func() {
+ listenErr <- app.Listen(config.AppHost + ":" + config.AppPort)
+ }()
+
+ sigCh := make(chan os.Signal, 1)
+ signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
+
+ select {
+ case err := <-listenErr:
+ if err != nil {
+ logrus.Fatalln("Failed to start: ", err.Error())
+ }
+ case sig := <-sigCh:
+ logrus.Infof("Received %s — shutting down", sig)
+ shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ if err := app.ShutdownWithContext(shutdownCtx); err != nil {
+ logrus.Warnf("HTTP server shutdown: %v", err)
+ }
+ // Release the Chatwoot direct-Postgres importer pool if one was
+ // opened. Safe when Chatwoot is disabled or the pool was never
+ // initialized — GetDefaultSyncService() returns nil.
+ if svc := chatwoot.GetDefaultSyncService(); svc != nil {
+ if err := svc.Close(); err != nil {
+ logrus.Warnf("Chatwoot sync close: %v", err)
+ }
+ }
+ if chatStorageDB != nil {
+ if err := chatStorageDB.Close(); err != nil {
+ logrus.Warnf("Chat storage close: %v", err)
+ }
+ }
}
}
diff --git a/src/cmd/root.go b/src/cmd/root.go
index bf759f7f..4d341c13 100644
--- a/src/cmd/root.go
+++ b/src/cmd/root.go
@@ -186,6 +186,65 @@ func initEnvConfig() {
if viper.IsSet("chatwoot_days_limit_import_messages") {
config.ChatwootDaysLimitImportMessages = viper.GetInt("chatwoot_days_limit_import_messages")
}
+ if envChatwootImportDBURI := viper.GetString("chatwoot_import_db_uri"); envChatwootImportDBURI != "" {
+ config.ChatwootImportDBURI = envChatwootImportDBURI
+ }
+ if viper.IsSet("chatwoot_import_placeholder_media_message") {
+ config.ChatwootImportPlaceholderMediaMessage = viper.GetBool("chatwoot_import_placeholder_media_message")
+ }
+ if viper.IsSet("chatwoot_import_media_with_rest") {
+ config.ChatwootImportMediaWithREST = viper.GetBool("chatwoot_import_media_with_rest")
+ }
+ // Chatwoot auto-provisioning settings
+ if viper.IsSet("chatwoot_auto_create") {
+ config.ChatwootAutoCreate = viper.GetBool("chatwoot_auto_create")
+ }
+ if envChatwootInboxName := viper.GetString("chatwoot_inbox_name"); envChatwootInboxName != "" {
+ config.ChatwootInboxName = envChatwootInboxName
+ }
+ if envChatwootWebhookURL := viper.GetString("chatwoot_webhook_url"); envChatwootWebhookURL != "" {
+ config.ChatwootWebhookURL = envChatwootWebhookURL
+ }
+ if envChatwootWebhookSecret := viper.GetString("chatwoot_webhook_secret"); envChatwootWebhookSecret != "" {
+ config.ChatwootWebhookSecret = envChatwootWebhookSecret
+ }
+ // Chatwoot conversation handling settings
+ if viper.IsSet("chatwoot_reopen_conversation") {
+ config.ChatwootReopenConversation = viper.GetBool("chatwoot_reopen_conversation")
+ }
+ if viper.IsSet("chatwoot_conversation_pending") {
+ config.ChatwootConversationPending = viper.GetBool("chatwoot_conversation_pending")
+ }
+ if envChatwootIgnoreJids := viper.GetString("chatwoot_ignore_jids"); envChatwootIgnoreJids != "" {
+ parts := strings.Split(envChatwootIgnoreJids, ",")
+ jids := make([]string, 0, len(parts))
+ for _, p := range parts {
+ if trimmed := strings.TrimSpace(p); trimmed != "" {
+ jids = append(jids, trimmed)
+ }
+ }
+ config.ChatwootIgnoreJids = jids
+ }
+ // Chatwoot outbound signature settings
+ if viper.IsSet("chatwoot_sign_msg") {
+ config.ChatwootSignMsg = viper.GetBool("chatwoot_sign_msg")
+ }
+ if envChatwootSignDelimiter := viper.GetString("chatwoot_sign_delimiter"); envChatwootSignDelimiter != "" {
+ config.ChatwootSignDelimiter = envChatwootSignDelimiter
+ }
+ // Chatwoot edit/delete propagation settings
+ if viper.IsSet("chatwoot_forward_edits") {
+ config.ChatwootForwardEdits = viper.GetBool("chatwoot_forward_edits")
+ }
+ if viper.IsSet("chatwoot_forward_deletes") {
+ config.ChatwootForwardDeletes = viper.GetBool("chatwoot_forward_deletes")
+ }
+ if viper.IsSet("chatwoot_message_read") {
+ config.ChatwootMessageRead = viper.GetBool("chatwoot_message_read")
+ }
+ if viper.IsSet("chatwoot_message_delete") {
+ config.ChatwootMessageDelete = viper.GetBool("chatwoot_message_delete")
+ }
}
func initFlags() {
@@ -354,6 +413,102 @@ func initFlags() {
config.ChatwootDaysLimitImportMessages,
`days of message history to import to Chatwoot --chatwoot-days-limit-import-messages <int> | example: --chatwoot-days-limit-import-messages=7`,
)
+ rootCmd.PersistentFlags().StringVarP(
+ &config.ChatwootImportDBURI,
+ "chatwoot-import-db-uri", "",
+ config.ChatwootImportDBURI,
+ `Postgres URI for direct Chatwoot history import. When set, historical sync bypasses the REST API and INSERTs directly into Chatwoot's database, preserving original WhatsApp timestamps and metadata. Live messages still use REST. Example: --chatwoot-import-db-uri="postgresql://postgres:pass@localhost:5432/chatwoot_production?sslmode=disable"`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootImportPlaceholderMediaMessage,
+ "chatwoot-import-placeholder-media-message", "",
+ config.ChatwootImportPlaceholderMediaMessage,
+ `insert a placeholder body for media messages when media download fails during direct-DB import --chatwoot-import-placeholder-media-message <true/false> | example: --chatwoot-import-placeholder-media-message=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootImportMediaWithREST,
+ "chatwoot-import-media-with-rest", "",
+ config.ChatwootImportMediaWithREST,
+ `upload media history rows through Chatwoot REST while direct-DB import handles non-media rows --chatwoot-import-media-with-rest <true/false> | example: --chatwoot-import-media-with-rest=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootAutoCreate,
+ "chatwoot-auto-create", "",
+ config.ChatwootAutoCreate,
+ `auto-create (or reuse) the Chatwoot API inbox on startup and resolve the inbox id automatically --chatwoot-auto-create <true/false> | example: --chatwoot-auto-create=true`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.ChatwootInboxName,
+ "chatwoot-inbox-name", "",
+ config.ChatwootInboxName,
+ `name of the Chatwoot inbox to create/reuse when auto-create is enabled --chatwoot-inbox-name <string> | example: --chatwoot-inbox-name="WhatsApp"`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.ChatwootWebhookURL,
+ "chatwoot-webhook-url", "",
+ config.ChatwootWebhookURL,
+ `public URL of this app's /chatwoot/webhook endpoint, registered on the auto-created inbox --chatwoot-webhook-url <string> | example: --chatwoot-webhook-url="https://my-api.com/chatwoot/webhook"`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.ChatwootWebhookSecret,
+ "chatwoot-webhook-secret", "",
+ config.ChatwootWebhookSecret,
+ `shared secret required for incoming Chatwoot webhooks --chatwoot-webhook-secret <string> | example: --chatwoot-webhook-secret="super-secret-key"`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootReopenConversation,
+ "chatwoot-reopen-conversation", "",
+ config.ChatwootReopenConversation,
+ `reuse and reopen a resolved Chatwoot conversation for a returning contact instead of opening a new one --chatwoot-reopen-conversation <true/false> | example: --chatwoot-reopen-conversation=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootConversationPending,
+ "chatwoot-conversation-pending", "",
+ config.ChatwootConversationPending,
+ `open newly-created Chatwoot conversations in "pending" instead of "open" status --chatwoot-conversation-pending <true/false> | example: --chatwoot-conversation-pending=true`,
+ )
+ rootCmd.PersistentFlags().StringSliceVarP(
+ &config.ChatwootIgnoreJids,
+ "chatwoot-ignore-jids", "",
+ config.ChatwootIgnoreJids,
+ `comma-separated WhatsApp JIDs (or "@g.us"/"@s.whatsapp.net" wildcards) to never mirror to Chatwoot --chatwoot-ignore-jids <list> | example: --chatwoot-ignore-jids="@g.us,[email protected]"`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootSignMsg,
+ "chatwoot-sign-msg", "",
+ config.ChatwootSignMsg,
+ `prefix Chatwoot agent replies with the agent's name before delivery to WhatsApp --chatwoot-sign-msg <true/false> | example: --chatwoot-sign-msg=true`,
+ )
+ rootCmd.PersistentFlags().StringVarP(
+ &config.ChatwootSignDelimiter,
+ "chatwoot-sign-delimiter", "",
+ config.ChatwootSignDelimiter,
+ `delimiter inserted between the agent signature and the message body --chatwoot-sign-delimiter <string> | example: --chatwoot-sign-delimiter="\n\n"`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootForwardEdits,
+ "chatwoot-forward-edits", "",
+ config.ChatwootForwardEdits,
+ `mirror WhatsApp message edits into the Chatwoot conversation as threaded notes --chatwoot-forward-edits <true/false> | example: --chatwoot-forward-edits=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootForwardDeletes,
+ "chatwoot-forward-deletes", "",
+ config.ChatwootForwardDeletes,
+ `mirror WhatsApp delete-for-everyone events into the Chatwoot conversation as threaded notes --chatwoot-forward-deletes <true/false> | example: --chatwoot-forward-deletes=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootMessageRead,
+ "chatwoot-message-read", "",
+ config.ChatwootMessageRead,
+ `sync read state between WhatsApp and Chatwoot for linked messages --chatwoot-message-read <true/false> | example: --chatwoot-message-read=true`,
+ )
+ rootCmd.PersistentFlags().BoolVarP(
+ &config.ChatwootMessageDelete,
+ "chatwoot-message-delete", "",
+ config.ChatwootMessageDelete,
+ `delete linked Chatwoot/WhatsApp messages when deletion is reported by the opposite side --chatwoot-message-delete <true/false> | example: --chatwoot-message-delete=true`,
+ )
}
func initChatStorage() (*sql.DB, error) {
diff --git a/src/config/settings.go b/src/config/settings.go
index 33ec0a08..862b6a3c 100644
--- a/src/config/settings.go
+++ b/src/config/settings.go
@@ -64,4 +64,71 @@ var (
// Chatwoot History Sync settings
ChatwootImportMessages = false // Enable message history import to Chatwoot
ChatwootDaysLimitImportMessages = 3 // Days of history to import (default: 3)
+
+ // ChatwootImportDBURI, when set, enables the direct-Postgres import path.
+ // Historical sync will INSERT directly into
+ // Chatwoot's schema instead of using the public REST API, which preserves
+ // original WhatsApp timestamps, senders, and group subjects.
+ //
+ // Format: postgresql://user:pass@host:5432/chatwoot_production[?sslmode=disable]
+ // When empty, the REST path is used (unchanged behavior). Live message
+ // forwarding and inbound handling always use REST, regardless of this flag.
+ ChatwootImportDBURI = ""
+
+ // ChatwootImportPlaceholderMediaMessage controls what is inserted as the
+ // message body for media messages when the importer could not download
+ // the media file (e.g., URL expired). When true, inserts a localized
+ // placeholder; when false, leaves the body empty.
+ ChatwootImportPlaceholderMediaMessage = true
+ // ChatwootImportMediaWithREST sends media history rows through Chatwoot's
+ // REST attachment endpoint while direct-DB import handles non-media rows.
+ // This preserves attachments at the cost of Chatwoot assigning media-row
+ // timestamps at upload time.
+ ChatwootImportMediaWithREST = false
+
+ // Chatwoot auto-provisioning. When ChatwootAutoCreate
+ // is true, the integration creates — or reuses, matched by name — an
+ // API-channel inbox on startup and resolves ChatwootInboxID automatically,
+ // so operators only need URL + token + account id. ChatwootWebhookURL is the
+ // publicly reachable URL of this app's /chatwoot/webhook endpoint; when set
+ // it is registered on the inbox so Chatwoot agent replies reach WhatsApp.
+ ChatwootAutoCreate = false
+ ChatwootInboxName = "WhatsApp"
+ ChatwootWebhookURL = ""
+ // Optional shared secret for incoming Chatwoot webhooks. When empty, inbound
+ // webhook requests remain unauthenticated for backward compatibility.
+ ChatwootWebhookSecret = ""
+
+ // Chatwoot conversation handling. ChatwootReopenConversation reuses (and
+ // reopens) a resolved conversation for a returning contact instead of
+ // opening a new one; ChatwootConversationPending opens freshly-created
+ // conversations in "pending" rather than "open" so they land in the agent's
+ // unassigned queue. Both settings keep the REST and direct-DB paths
+ // consistent.
+ ChatwootReopenConversation = true
+ ChatwootConversationPending = false
+
+ // ChatwootIgnoreJids lists WhatsApp JIDs — or the wildcards "@g.us" /
+ // "@s.whatsapp.net" — that must never be mirrored to Chatwoot, on top of the
+ // always-ignored system JIDs (status@broadcast, [email protected]).
+ ChatwootIgnoreJids []string
+
+ // Chatwoot outbound signature. When ChatwootSignMsg is true, agent replies
+ // sent from Chatwoot are prefixed with the agent's name (joined to the body
+ // by ChatwootSignDelimiter) before delivery to WhatsApp.
+ ChatwootSignMsg = false
+ ChatwootSignDelimiter = "\n\n"
+
+ // Chatwoot edit/delete propagation. When enabled, WhatsApp message edits and
+ // delete-for-everyone events are mirrored into the Chatwoot conversation as
+ // threaded notes referencing the original message.
+ ChatwootForwardEdits = true
+ ChatwootForwardDeletes = true
+
+ // Chatwoot Evolution-compatible state propagation. Read sync updates
+ // Chatwoot last-seen from WhatsApp receipts and marks WhatsApp messages read
+ // after agent replies. Delete sync removes the linked Chatwoot/WhatsApp
+ // message when the opposite side reports deletion.
+ ChatwootMessageRead = false
+ ChatwootMessageDelete = false
)
diff --git a/src/domains/AGENTS.md b/src/domains/AGENTS.md
index 9f054160..7fdd5cc8 100644
--- a/src/domains/AGENTS.md
+++ b/src/domains/AGENTS.md
@@ -1,6 +1,6 @@
# DOMAINS
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
@@ -23,6 +23,7 @@ domains/
| Add reply field | `send/text.go`, media request DTOs | Optional `ReplyMessageID *string` serializes as `reply_message_id`. |
| Add usecase contract | `<domain>/interfaces.go` | Return the domain interface from `usecase.New*Service`. |
| Add chat storage method | `chatstorage/interfaces.go` | Also update concrete repository and WhatsApp storage wrapper. |
+| Add Chatwoot storage state | `chatstorage/chatstorage.go`, `chatstorage/interfaces.go` | Link and retry queue contracts must remain device-scoped. |
| Add response field | Matching DTO file | Check REST/MCP serialization expectations before renaming JSON fields. |
## CONVENTIONS
@@ -32,6 +33,7 @@ domains/
- Chat filters use pointer booleans, for example `*bool`, when "not set" differs from `false`.
- Storage entities carry `DeviceID`; preserve it through chat/message/edit flows.
- `GetMessageByIDAndDevice` is the device-scoped ID lookup for user/device-isolated flows.
+- `ChatwootMessageLink` and `ChatwootForwardEvent` are storage contracts, not Chatwoot API DTOs.
- Existing contracts expose whatsmeow types in places. Keep that local to contracts that already need protocol details.
## ANTI-PATTERNS
diff --git a/src/domains/chatstorage/chatstorage.go b/src/domains/chatstorage/chatstorage.go
index 2e760b48..9ea46b13 100644
--- a/src/domains/chatstorage/chatstorage.go
+++ b/src/domains/chatstorage/chatstorage.go
@@ -50,6 +50,39 @@ type MessageEdit struct {
CreatedAt time.Time `db:"created_at"`
}
+// ChatwootMessageLink maps a WhatsApp message to the Chatwoot message created
+// for it. It is device-scoped because the same WhatsApp message ID can appear
+// in independent device stores.
+type ChatwootMessageLink struct {
+ DeviceID string `db:"device_id"`
+ WhatsAppMessageID string `db:"wa_message_id"`
+ WhatsAppChatJID string `db:"wa_chat_jid"`
+ ChatwootMessageID int `db:"chatwoot_message_id"`
+ ChatwootConversationID int `db:"chatwoot_conversation_id"`
+ ChatwootInboxID int `db:"chatwoot_inbox_id"`
+ ChatwootContactInboxSourceID string `db:"chatwoot_contact_inbox_source_id"`
+ SourceID string `db:"source_id"`
+ Direction string `db:"direction"`
+ IsRead bool `db:"is_read"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
+// ChatwootForwardEvent is a durable retry record for a live WhatsApp event
+// that could not be delivered to Chatwoot because of a transient failure.
+type ChatwootForwardEvent struct {
+ ID int64 `db:"id"`
+ DeviceID string `db:"device_id"`
+ EventName string `db:"event_name"`
+ WhatsAppMessageID string `db:"wa_message_id"`
+ PayloadJSON string `db:"payload_json"`
+ Attempts int `db:"attempts"`
+ LastError string `db:"last_error"`
+ NextAttemptAt time.Time `db:"next_attempt_at"`
+ CreatedAt time.Time `db:"created_at"`
+ UpdatedAt time.Time `db:"updated_at"`
+}
+
// MediaInfo represents downloadable media information
type MediaInfo struct {
MessageID string
diff --git a/src/domains/chatstorage/interfaces.go b/src/domains/chatstorage/interfaces.go
index 1fcfd01c..c4fde14f 100644
--- a/src/domains/chatstorage/interfaces.go
+++ b/src/domains/chatstorage/interfaces.go
@@ -35,6 +35,17 @@ type IChatStorageRepository interface {
DeleteMessageByDevice(deviceID, id, chatJID string) error
StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time, msg *waE2E.Message) error
+ // Chatwoot correlation operations
+ UpsertChatwootMessageLink(link *ChatwootMessageLink) error
+ GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*ChatwootMessageLink, error)
+ GetChatwootMessageLinkByChatwootID(deviceID string, chatwootMessageID int) (*ChatwootMessageLink, error)
+ GetLatestChatwootMessageLinkByConversation(conversationID int) (*ChatwootMessageLink, error)
+ GetLatestUnreadChatwootMessageLinkByChat(deviceID, waChatJID string) (*ChatwootMessageLink, error)
+ EnqueueChatwootForwardEvent(event *ChatwootForwardEvent) error
+ ListDueChatwootForwardEvents(now time.Time, limit int) ([]*ChatwootForwardEvent, error)
+ MarkChatwootForwardEventFailed(id int64, lastError string, nextAttemptAt time.Time) error
+ MarkChatwootForwardEventDone(id int64) error
+
// Statistics
GetChatMessageCount(chatJID string) (int64, error)
GetChatMessageCountByDevice(deviceID, chatJID string) (int64, error)
diff --git a/src/go.mod b/src/go.mod
index 90fa69e8..d749ecac 100644
--- a/src/go.mod
+++ b/src/go.mod
@@ -3,6 +3,7 @@ module github.com/aldinokemal/go-whatsapp-web-multidevice
go 1.25.5
require (
+ github.com/DATA-DOG/go-sqlmock v1.5.2
github.com/PuerkitoBio/goquery v1.12.0
github.com/disintegration/imaging v1.6.2
github.com/dustin/go-humanize v1.0.1
diff --git a/src/go.sum b/src/go.sum
index 5985eafd..029a962e 100644
--- a/src/go.sum
+++ b/src/go.sum
@@ -67,6 +67,7 @@ github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
+github.com/kisielk/sqlstruct v0.0.0-20201105191214-5f3e10d3ab46/go.mod h1:yyMNCyc/Ib3bDTKd379tNMpB/7/H5TjM2Y9QJ5THLbE=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
diff --git a/src/infrastructure/chatstorage/AGENTS.md b/src/infrastructure/chatstorage/AGENTS.md
index 86aa7f1b..1d56f5e1 100644
--- a/src/infrastructure/chatstorage/AGENTS.md
+++ b/src/infrastructure/chatstorage/AGENTS.md
@@ -1,6 +1,6 @@
# CHAT STORAGE
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
@@ -12,8 +12,10 @@ Generated: 2026-06-05
|------|----------|-------|
| Repository contract | `../../domains/chatstorage/interfaces.go` | Any method addition must be implemented here and in WhatsApp wrapper. |
| SQL implementation | `sqlite_repository.go` | Single large repository file. |
-| Migrations | `sqlite_repository.go` `getMigrations()` | Append-only list, currently 22 migrations. |
+| Migrations | `sqlite_repository.go` `getMigrations()` | Append-only list, currently 29 migrations. |
| Message edit history | `sqlite_repository.go`, `sqlite_repository_edit_test.go` | `message_edits` is append-only history while original message content updates. |
+| Chatwoot links | `sqlite_repository.go`, `../../domains/chatstorage/chatstorage.go` | Maps WhatsApp and Chatwoot IDs for idempotency, read/delete sync, and webhook routing. |
+| Chatwoot retry queue | `sqlite_repository.go` | Persists live forward retry jobs across restarts. |
| Tests | `sqlite_repository_test.go`, `sqlite_repository_edit_test.go` | Add coverage for schema/data isolation changes. |
## CONVENTIONS
@@ -23,6 +25,8 @@ Generated: 2026-06-05
- `GetMessages` and `SearchMessages` fail fast if device ID is missing.
- Use `GetMessageByIDAndDevice` for device-scoped ID lookups such as quoted replies.
- Use `GetChatByDevice`, `DeleteChatByDevice`, `DeleteMessageByDevice`, and count-by-device variants for scoped flows.
+- `chatwoot_message_links` primary key is `(device_id, wa_message_id)`; link lookups by Chatwoot ID and unread chat are indexed.
+- `chatwoot_forward_queue` uniqueness is `(device_id, event_name, wa_message_id)`; cleanup paths must include it.
- `CreateMessage` and sent-message storage derive the current device identity from the whatsmeow client context.
- `status@broadcast` must always produce display name `Status`.
- Storage tests use real SQLite drivers, including temp DB and in-memory variants.
@@ -33,3 +37,4 @@ Generated: 2026-06-05
- Do not reorder or edit old migrations for a live DB; append a new migration.
- Do not build SQL with untrusted string interpolation. Existing dynamic clauses use fixed fragments plus args.
- Do not forget the device registry operations when changing purge/load behavior.
+- Do not leave Chatwoot link or retry rows behind when truncating all chats or deleting one device.
diff --git a/src/infrastructure/chatstorage/sqlite_repository.go b/src/infrastructure/chatstorage/sqlite_repository.go
index fdb97b07..72f7aeca 100644
--- a/src/infrastructure/chatstorage/sqlite_repository.go
+++ b/src/infrastructure/chatstorage/sqlite_repository.go
@@ -250,6 +250,9 @@ func (r *SQLiteRepository) DeleteChat(jid string) error {
if _, err := tx.Exec("DELETE FROM message_edits WHERE chat_jid = ?", jid); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM chatwoot_message_links WHERE wa_chat_jid = ?", jid); err != nil {
+ return err
+ }
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ?", jid)
@@ -280,6 +283,9 @@ func (r *SQLiteRepository) DeleteChatByDevice(deviceID, jid string) error {
if _, err := tx.Exec("DELETE FROM message_edits WHERE chat_jid = ? AND device_id = ?", jid, deviceID); err != nil {
return err
}
+ if _, err := tx.Exec("DELETE FROM chatwoot_message_links WHERE wa_chat_jid = ? AND device_id = ?", jid, deviceID); err != nil {
+ return err
+ }
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages WHERE chat_jid = ? AND device_id = ?", jid, deviceID)
@@ -693,6 +699,9 @@ func (r *SQLiteRepository) DeleteMessage(id, chatJID string) error {
if _, err := r.db.Exec("DELETE FROM message_reactions WHERE message_id = ? AND chat_jid = ?", id, chatJID); err != nil {
return err
}
+ if _, err := r.db.Exec("DELETE FROM chatwoot_message_links WHERE wa_message_id = ? AND wa_chat_jid = ?", id, chatJID); err != nil {
+ return err
+ }
_, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ?", id, chatJID)
return err
}
@@ -702,10 +711,223 @@ func (r *SQLiteRepository) DeleteMessageByDevice(deviceID, id, chatJID string) e
if _, err := r.db.Exec("DELETE FROM message_reactions WHERE message_id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
return err
}
+ if _, err := r.db.Exec("DELETE FROM chatwoot_message_links WHERE wa_message_id = ? AND wa_chat_jid = ? AND device_id = ?", id, chatJID, deviceID); err != nil {
+ return err
+ }
_, err := r.db.Exec("DELETE FROM messages WHERE id = ? AND chat_jid = ? AND device_id = ?", id, chatJID, deviceID)
return err
}
+// UpsertChatwootMessageLink records the stable mapping between a WhatsApp
+// message and the Chatwoot row created for it.
+func (r *SQLiteRepository) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
+ if link == nil {
+ return fmt.Errorf("chatwoot message link is required")
+ }
+ if strings.TrimSpace(link.DeviceID) == "" {
+ return fmt.Errorf("device_id is required for chatwoot message link")
+ }
+ if strings.TrimSpace(link.WhatsAppMessageID) == "" {
+ return fmt.Errorf("wa_message_id is required for chatwoot message link")
+ }
+
+ now := time.Now()
+ if link.CreatedAt.IsZero() {
+ link.CreatedAt = now
+ }
+ link.UpdatedAt = now
+
+ result, err := r.db.Exec(`
+ UPDATE chatwoot_message_links
+ SET wa_chat_jid = ?, chatwoot_message_id = ?, chatwoot_conversation_id = ?,
+ chatwoot_inbox_id = ?, chatwoot_contact_inbox_source_id = ?, source_id = ?,
+ direction = ?, is_read = ?, updated_at = ?
+ WHERE device_id = ? AND wa_message_id = ?
+ `, link.WhatsAppChatJID, link.ChatwootMessageID, link.ChatwootConversationID,
+ link.ChatwootInboxID, link.ChatwootContactInboxSourceID, link.SourceID,
+ link.Direction, link.IsRead, link.UpdatedAt, link.DeviceID, link.WhatsAppMessageID)
+ if err != nil {
+ return err
+ }
+
+ rowsAffected, _ := result.RowsAffected()
+ if rowsAffected == 0 {
+ _, err = r.db.Exec(`
+ INSERT INTO chatwoot_message_links (
+ device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ `, link.DeviceID, link.WhatsAppMessageID, link.WhatsAppChatJID,
+ link.ChatwootMessageID, link.ChatwootConversationID, link.ChatwootInboxID,
+ link.ChatwootContactInboxSourceID, link.SourceID, link.Direction,
+ link.IsRead, link.CreatedAt, link.UpdatedAt)
+ }
+ return err
+}
+
+func (r *SQLiteRepository) GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*domainChatStorage.ChatwootMessageLink, error) {
+ query := `
+ SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at
+ FROM chatwoot_message_links
+ WHERE device_id = ? AND wa_message_id = ?
+ LIMIT 1
+ `
+
+ link, err := r.scanChatwootMessageLink(r.db.QueryRow(query, deviceID, waMessageID))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return link, err
+}
+
+func (r *SQLiteRepository) GetChatwootMessageLinkByChatwootID(deviceID string, chatwootMessageID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ query := `
+ SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at
+ FROM chatwoot_message_links
+ WHERE device_id = ? AND chatwoot_message_id = ?
+ LIMIT 1
+ `
+
+ link, err := r.scanChatwootMessageLink(r.db.QueryRow(query, deviceID, chatwootMessageID))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return link, err
+}
+
+func (r *SQLiteRepository) GetLatestChatwootMessageLinkByConversation(conversationID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ query := `
+ SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at
+ FROM chatwoot_message_links
+ WHERE chatwoot_conversation_id = ?
+ ORDER BY updated_at DESC, created_at DESC
+ LIMIT 1
+ `
+
+ link, err := r.scanChatwootMessageLink(r.db.QueryRow(query, conversationID))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return link, err
+}
+
+func (r *SQLiteRepository) GetLatestUnreadChatwootMessageLinkByChat(deviceID, waChatJID string) (*domainChatStorage.ChatwootMessageLink, error) {
+ query := `
+ SELECT device_id, wa_message_id, wa_chat_jid, chatwoot_message_id,
+ chatwoot_conversation_id, chatwoot_inbox_id,
+ chatwoot_contact_inbox_source_id, source_id, direction,
+ is_read, created_at, updated_at
+ FROM chatwoot_message_links
+ WHERE device_id = ? AND wa_chat_jid = ? AND direction = 'incoming' AND is_read = 0
+ ORDER BY updated_at DESC, created_at DESC
+ LIMIT 1
+ `
+
+ link, err := r.scanChatwootMessageLink(r.db.QueryRow(query, deviceID, waChatJID))
+ if err == sql.ErrNoRows {
+ return nil, nil
+ }
+ return link, err
+}
+
+func (r *SQLiteRepository) EnqueueChatwootForwardEvent(event *domainChatStorage.ChatwootForwardEvent) error {
+ if event == nil || strings.TrimSpace(event.DeviceID) == "" || strings.TrimSpace(event.EventName) == "" || strings.TrimSpace(event.WhatsAppMessageID) == "" || strings.TrimSpace(event.PayloadJSON) == "" {
+ return fmt.Errorf("chatwoot forward event requires device id, event name, whatsapp message id, and payload")
+ }
+
+ now := time.Now()
+ if event.NextAttemptAt.IsZero() {
+ event.NextAttemptAt = now
+ }
+ if event.CreatedAt.IsZero() {
+ event.CreatedAt = now
+ }
+ event.UpdatedAt = now
+
+ _, err := r.db.Exec(`
+ INSERT INTO chatwoot_forward_queue (
+ device_id, event_name, wa_message_id, payload_json,
+ attempts, last_error, next_attempt_at, created_at, updated_at
+ )
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT(device_id, event_name, wa_message_id) DO UPDATE SET
+ payload_json = excluded.payload_json,
+ last_error = excluded.last_error,
+ next_attempt_at = excluded.next_attempt_at,
+ updated_at = excluded.updated_at
+ `, event.DeviceID, event.EventName, event.WhatsAppMessageID, event.PayloadJSON,
+ event.Attempts, event.LastError, event.NextAttemptAt, event.CreatedAt, event.UpdatedAt)
+ return err
+}
+
+func (r *SQLiteRepository) ListDueChatwootForwardEvents(now time.Time, limit int) ([]*domainChatStorage.ChatwootForwardEvent, error) {
+ if limit <= 0 {
+ limit = 20
+ }
+
+ rows, err := r.db.Query(`
+ SELECT id, device_id, event_name, wa_message_id, payload_json,
+ attempts, last_error, next_attempt_at, created_at, updated_at
+ FROM chatwoot_forward_queue
+ WHERE next_attempt_at <= ?
+ ORDER BY next_attempt_at ASC, id ASC
+ LIMIT ?
+ `, now, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ events := make([]*domainChatStorage.ChatwootForwardEvent, 0)
+ for rows.Next() {
+ event := &domainChatStorage.ChatwootForwardEvent{}
+ if err := rows.Scan(
+ &event.ID, &event.DeviceID, &event.EventName, &event.WhatsAppMessageID,
+ &event.PayloadJSON, &event.Attempts, &event.LastError, &event.NextAttemptAt,
+ &event.CreatedAt, &event.UpdatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ events = append(events, event)
+ }
+ return events, rows.Err()
+}
+
+func (r *SQLiteRepository) MarkChatwootForwardEventFailed(id int64, lastError string, nextAttemptAt time.Time) error {
+ if id == 0 {
+ return fmt.Errorf("chatwoot forward event id is required")
+ }
+ _, err := r.db.Exec(`
+ UPDATE chatwoot_forward_queue
+ SET attempts = attempts + 1,
+ last_error = ?,
+ next_attempt_at = ?,
+ updated_at = ?
+ WHERE id = ?
+ `, lastError, nextAttemptAt, time.Now(), id)
+ return err
+}
+
+func (r *SQLiteRepository) MarkChatwootForwardEventDone(id int64) error {
+ if id == 0 {
+ return fmt.Errorf("chatwoot forward event id is required")
+ }
+ _, err := r.db.Exec(`DELETE FROM chatwoot_forward_queue WHERE id = ?`, id)
+ return err
+}
+
// getCount is a private helper for count queries
func (r *SQLiteRepository) getCount(query string, args ...any) (int64, error) {
var count int64
@@ -735,6 +957,17 @@ func (r *SQLiteRepository) scanChat(scanner interface{ Scan(...any) error }) (*d
return chat, err
}
+func (r *SQLiteRepository) scanChatwootMessageLink(scanner interface{ Scan(...any) error }) (*domainChatStorage.ChatwootMessageLink, error) {
+ link := &domainChatStorage.ChatwootMessageLink{}
+ err := scanner.Scan(
+ &link.DeviceID, &link.WhatsAppMessageID, &link.WhatsAppChatJID,
+ &link.ChatwootMessageID, &link.ChatwootConversationID, &link.ChatwootInboxID,
+ &link.ChatwootContactInboxSourceID, &link.SourceID, &link.Direction,
+ &link.IsRead, &link.CreatedAt, &link.UpdatedAt,
+ )
+ return link, err
+}
+
// GetChatMessageCount returns the number of messages in a chat
func (r *SQLiteRepository) GetChatMessageCount(chatJID string) (int64, error) {
return r.getCount("SELECT COUNT(*) FROM messages WHERE chat_jid = ?", chatJID)
@@ -788,6 +1021,16 @@ func (r *SQLiteRepository) TruncateAllChats() error {
return fmt.Errorf("failed to delete message edits: %w", err)
}
+ _, err = tx.Exec("DELETE FROM chatwoot_message_links")
+ if err != nil {
+ return fmt.Errorf("failed to delete chatwoot message links: %w", err)
+ }
+
+ _, err = tx.Exec("DELETE FROM chatwoot_forward_queue")
+ if err != nil {
+ return fmt.Errorf("failed to delete chatwoot forward queue: %w", err)
+ }
+
// Delete messages after dependent rows to keep cleanup explicit.
_, err = tx.Exec("DELETE FROM messages")
if err != nil {
@@ -823,6 +1066,14 @@ func (r *SQLiteRepository) DeleteDeviceData(deviceID string) error {
return fmt.Errorf("failed to delete device message edits: %w", err)
}
+ if _, err := tx.Exec(`DELETE FROM chatwoot_message_links WHERE device_id = ?`, deviceID); err != nil {
+ return fmt.Errorf("failed to delete device chatwoot message links: %w", err)
+ }
+
+ if _, err := tx.Exec(`DELETE FROM chatwoot_forward_queue WHERE device_id = ?`, deviceID); err != nil {
+ return fmt.Errorf("failed to delete device chatwoot forward queue: %w", err)
+ }
+
// Delete messages after dependent rows via direct device_id filter.
if _, err := tx.Exec(`DELETE FROM messages WHERE device_id = ?`, deviceID); err != nil {
return fmt.Errorf("failed to delete device messages: %w", err)
@@ -1803,5 +2054,54 @@ func (r *SQLiteRepository) getMigrations() []string {
// Migration 22: Index edit history by edit time
`CREATE INDEX IF NOT EXISTS idx_message_edits_edited_at ON message_edits(edited_at)`,
+
+ // Migration 23: Map WhatsApp messages to Chatwoot messages for idempotency and status sync
+ `CREATE TABLE IF NOT EXISTS chatwoot_message_links (
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ wa_message_id VARCHAR(255) NOT NULL,
+ wa_chat_jid VARCHAR(255) NOT NULL DEFAULT '',
+ chatwoot_message_id INTEGER NOT NULL DEFAULT 0,
+ chatwoot_conversation_id INTEGER NOT NULL DEFAULT 0,
+ chatwoot_inbox_id INTEGER NOT NULL DEFAULT 0,
+ chatwoot_contact_inbox_source_id VARCHAR(255) NOT NULL DEFAULT '',
+ source_id VARCHAR(255) NOT NULL DEFAULT '',
+ direction VARCHAR(20) NOT NULL DEFAULT '',
+ is_read BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ PRIMARY KEY (device_id, wa_message_id)
+ )`,
+
+ // Migration 24: Lookup Chatwoot webhooks by device and Chatwoot message id
+ `CREATE INDEX IF NOT EXISTS idx_chatwoot_links_chatwoot_id ON chatwoot_message_links(device_id, chatwoot_message_id)`,
+
+ // Migration 25: Lookup Chatwoot links by source id for replay/idempotency diagnostics
+ `CREATE INDEX IF NOT EXISTS idx_chatwoot_links_source_id ON chatwoot_message_links(device_id, source_id)`,
+
+ // Migration 26: Resolve Chatwoot webhook replies by conversation before falling back to contact attributes
+ `CREATE INDEX IF NOT EXISTS idx_chatwoot_links_conversation ON chatwoot_message_links(chatwoot_conversation_id, updated_at)`,
+
+ // Migration 27: Serve GetLatestUnreadChatwootMessageLinkByChat (mark-as-read
+ // hot path) from an index. Covers the WHERE equality columns plus the
+ // ORDER BY (updated_at, created_at) so SQLite resolves LIMIT 1 without a scan/sort.
+ `CREATE INDEX IF NOT EXISTS idx_chatwoot_links_unread ON chatwoot_message_links(device_id, wa_chat_jid, direction, is_read, updated_at, created_at)`,
+
+ // Migration 28: Persist live Chatwoot forward retries across restarts
+ `CREATE TABLE IF NOT EXISTS chatwoot_forward_queue (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ device_id VARCHAR(255) NOT NULL DEFAULT '',
+ event_name VARCHAR(80) NOT NULL DEFAULT '',
+ wa_message_id VARCHAR(255) NOT NULL DEFAULT '',
+ payload_json TEXT NOT NULL DEFAULT '',
+ attempts INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT NOT NULL DEFAULT '',
+ next_attempt_at TIMESTAMP NOT NULL,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
+ UNIQUE(device_id, event_name, wa_message_id)
+ )`,
+
+ // Migration 29: Fetch due Chatwoot retry jobs in stable order
+ `CREATE INDEX IF NOT EXISTS idx_chatwoot_forward_queue_due ON chatwoot_forward_queue(next_attempt_at, id)`,
}
}
diff --git a/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go
new file mode 100644
index 00000000..4af200d8
--- /dev/null
+++ b/src/infrastructure/chatstorage/sqlite_repository_chatwoot_test.go
@@ -0,0 +1,311 @@
+package chatstorage
+
+import (
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+func TestSQLiteRepositoryStoresAndLooksUpChatwootMessageLinks(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ now := time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC)
+
+ link := &domainChatStorage.ChatwootMessageLink{
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "wa-1",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 101,
+ ChatwootConversationID: 202,
+ ChatwootInboxID: 303,
+ ChatwootContactInboxSourceID: "[email protected]",
+ SourceID: "WAID:wa-1",
+ Direction: "incoming",
+ IsRead: false,
+ CreatedAt: now,
+ UpdatedAt: now,
+ }
+
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("upsert link: %v", err)
+ }
+
+ byWA, err := repo.GetChatwootMessageLinkByWhatsAppID(link.DeviceID, link.WhatsAppMessageID)
+ if err != nil {
+ t.Fatalf("lookup by whatsapp id: %v", err)
+ }
+ if byWA == nil {
+ t.Fatal("expected link by whatsapp id")
+ }
+ if byWA.ChatwootMessageID != 101 || byWA.ChatwootConversationID != 202 || byWA.SourceID != "WAID:wa-1" {
+ t.Fatalf("unexpected link by whatsapp id: %+v", byWA)
+ }
+
+ byCW, err := repo.GetChatwootMessageLinkByChatwootID(link.DeviceID, link.ChatwootMessageID)
+ if err != nil {
+ t.Fatalf("lookup by chatwoot id: %v", err)
+ }
+ if byCW == nil {
+ t.Fatal("expected link by chatwoot id")
+ }
+ if byCW.WhatsAppMessageID != "wa-1" || byCW.WhatsAppChatJID != link.WhatsAppChatJID {
+ t.Fatalf("unexpected link by chatwoot id: %+v", byCW)
+ }
+
+ link.ChatwootConversationID = 404
+ link.IsRead = true
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("update link: %v", err)
+ }
+
+ updated, err := repo.GetChatwootMessageLinkByWhatsAppID(link.DeviceID, link.WhatsAppMessageID)
+ if err != nil {
+ t.Fatalf("lookup updated link: %v", err)
+ }
+ if updated.ChatwootConversationID != 404 || !updated.IsRead {
+ t.Fatalf("expected updated link, got %+v", updated)
+ }
+}
+
+func TestSQLiteRepositoryChatwootMessageLinksAreDeviceScoped(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+
+ if err := repo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "same-wa-id",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 10,
+ SourceID: "WAID:same-wa-id",
+ Direction: "incoming",
+ }); err != nil {
+ t.Fatalf("upsert device A link: %v", err)
+ }
+ if err := repo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "same-wa-id",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 20,
+ SourceID: "WAID:same-wa-id",
+ Direction: "incoming",
+ }); err != nil {
+ t.Fatalf("upsert device B link: %v", err)
+ }
+
+ linkA, err := repo.GetChatwootMessageLinkByWhatsAppID("[email protected]", "same-wa-id")
+ if err != nil {
+ t.Fatalf("lookup device A: %v", err)
+ }
+ linkB, err := repo.GetChatwootMessageLinkByWhatsAppID("[email protected]", "same-wa-id")
+ if err != nil {
+ t.Fatalf("lookup device B: %v", err)
+ }
+
+ if linkA.ChatwootMessageID != 10 {
+ t.Fatalf("device A chatwoot id = %d, want 10", linkA.ChatwootMessageID)
+ }
+ if linkB.ChatwootMessageID != 20 {
+ t.Fatalf("device B chatwoot id = %d, want 20", linkB.ChatwootMessageID)
+ }
+
+ if err := repo.DeleteDeviceData("[email protected]"); err != nil {
+ t.Fatalf("delete device A data: %v", err)
+ }
+ linkA, err = repo.GetChatwootMessageLinkByWhatsAppID("[email protected]", "same-wa-id")
+ if err != nil {
+ t.Fatalf("lookup deleted device A: %v", err)
+ }
+ if linkA != nil {
+ t.Fatalf("expected device A link to be deleted, got %+v", linkA)
+ }
+
+ linkB, err = repo.GetChatwootMessageLinkByWhatsAppID("[email protected]", "same-wa-id")
+ if err != nil {
+ t.Fatalf("lookup remaining device B: %v", err)
+ }
+ if linkB == nil || linkB.ChatwootMessageID != 20 {
+ t.Fatalf("expected device B link to remain, got %+v", linkB)
+ }
+}
+
+func TestSQLiteRepositoryGetsLatestUnreadIncomingChatwootMessageLinkByChat(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ deviceID := "[email protected]"
+ chatJID := "[email protected]"
+
+ links := []*domainChatStorage.ChatwootMessageLink{
+ {
+ DeviceID: deviceID,
+ WhatsAppMessageID: "old-unread",
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: 11,
+ Direction: "incoming",
+ IsRead: false,
+ UpdatedAt: time.Date(2026, time.June, 6, 9, 0, 0, 0, time.UTC),
+ },
+ {
+ DeviceID: deviceID,
+ WhatsAppMessageID: "latest-unread",
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: 12,
+ Direction: "incoming",
+ IsRead: false,
+ UpdatedAt: time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC),
+ },
+ {
+ DeviceID: deviceID,
+ WhatsAppMessageID: "outgoing",
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: 13,
+ Direction: "outgoing",
+ IsRead: false,
+ UpdatedAt: time.Date(2026, time.June, 6, 11, 0, 0, 0, time.UTC),
+ },
+ {
+ DeviceID: deviceID,
+ WhatsAppMessageID: "read",
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: 14,
+ Direction: "incoming",
+ IsRead: true,
+ UpdatedAt: time.Date(2026, time.June, 6, 12, 0, 0, 0, time.UTC),
+ },
+ }
+ for _, link := range links {
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("upsert %s: %v", link.WhatsAppMessageID, err)
+ }
+ }
+
+ link, err := repo.GetLatestUnreadChatwootMessageLinkByChat(deviceID, chatJID)
+ if err != nil {
+ t.Fatalf("lookup latest unread: %v", err)
+ }
+ if link == nil || link.WhatsAppMessageID != "latest-unread" {
+ t.Fatalf("latest unread = %+v, want latest-unread", link)
+ }
+
+ link.IsRead = true
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("mark latest read: %v", err)
+ }
+ next, err := repo.GetLatestUnreadChatwootMessageLinkByChat(deviceID, chatJID)
+ if err != nil {
+ t.Fatalf("lookup next unread: %v", err)
+ }
+ if next == nil || next.WhatsAppMessageID != "old-unread" {
+ t.Fatalf("next unread = %+v, want old-unread", next)
+ }
+}
+
+func TestSQLiteRepositoryGetsLatestChatwootMessageLinkByConversation(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ conversationID := 202
+
+ links := []*domainChatStorage.ChatwootMessageLink{
+ {
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "old",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 11,
+ ChatwootConversationID: conversationID,
+ UpdatedAt: time.Date(2026, time.June, 6, 9, 0, 0, 0, time.UTC),
+ },
+ {
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "latest",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 12,
+ ChatwootConversationID: conversationID,
+ UpdatedAt: time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC),
+ },
+ {
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "other-conversation",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 13,
+ ChatwootConversationID: 303,
+ UpdatedAt: time.Date(2026, time.June, 6, 11, 0, 0, 0, time.UTC),
+ },
+ }
+ for _, link := range links {
+ if err := repo.UpsertChatwootMessageLink(link); err != nil {
+ t.Fatalf("upsert %s: %v", link.WhatsAppMessageID, err)
+ }
+ }
+
+ link, err := repo.GetLatestChatwootMessageLinkByConversation(conversationID)
+ if err != nil {
+ t.Fatalf("lookup latest conversation link: %v", err)
+ }
+ if link == nil || link.WhatsAppMessageID != "latest" || link.DeviceID != "[email protected]" {
+ t.Fatalf("latest conversation link = %+v, want device-b/latest", link)
+ }
+}
+
+func TestSQLiteRepositoryChatwootForwardQueueLifecycle(t *testing.T) {
+ repo := newTestSQLiteRepository(t)
+ now := time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC)
+
+ err := repo.EnqueueChatwootForwardEvent(&domainChatStorage.ChatwootForwardEvent{
+ DeviceID: "[email protected]",
+ EventName: "message",
+ WhatsAppMessageID: "wa-queue-1",
+ PayloadJSON: `{"payload":{"id":"wa-queue-1"}}`,
+ LastError: "chatwoot down",
+ NextAttemptAt: now,
+ })
+ if err != nil {
+ t.Fatalf("enqueue retry: %v", err)
+ }
+
+ due, err := repo.ListDueChatwootForwardEvents(now.Add(-time.Second), 10)
+ if err != nil {
+ t.Fatalf("list early due events: %v", err)
+ }
+ if len(due) != 0 {
+ t.Fatalf("early due len = %d, want 0", len(due))
+ }
+
+ due, err = repo.ListDueChatwootForwardEvents(now, 10)
+ if err != nil {
+ t.Fatalf("list due events: %v", err)
+ }
+ if len(due) != 1 {
+ t.Fatalf("due len = %d, want 1", len(due))
+ }
+ if due[0].DeviceID != "[email protected]" || due[0].WhatsAppMessageID != "wa-queue-1" || due[0].Attempts != 0 {
+ t.Fatalf("unexpected due event: %+v", due[0])
+ }
+
+ nextAttempt := now.Add(2 * time.Minute)
+ if err := repo.MarkChatwootForwardEventFailed(due[0].ID, "still down", nextAttempt); err != nil {
+ t.Fatalf("mark retry failed: %v", err)
+ }
+
+ due, err = repo.ListDueChatwootForwardEvents(nextAttempt.Add(-time.Second), 10)
+ if err != nil {
+ t.Fatalf("list before next attempt: %v", err)
+ }
+ if len(due) != 0 {
+ t.Fatalf("due before next len = %d, want 0", len(due))
+ }
+
+ due, err = repo.ListDueChatwootForwardEvents(nextAttempt, 10)
+ if err != nil {
+ t.Fatalf("list next due events: %v", err)
+ }
+ if len(due) != 1 || due[0].Attempts != 1 || due[0].LastError != "still down" {
+ t.Fatalf("unexpected retried event: %+v", due)
+ }
+
+ if err := repo.MarkChatwootForwardEventDone(due[0].ID); err != nil {
+ t.Fatalf("mark retry done: %v", err)
+ }
+ due, err = repo.ListDueChatwootForwardEvents(nextAttempt.Add(time.Hour), 10)
+ if err != nil {
+ t.Fatalf("list after done: %v", err)
+ }
+ if len(due) != 0 {
+ t.Fatalf("due after done len = %d, want 0", len(due))
+ }
+}
diff --git a/src/infrastructure/chatwoot/AGENTS.md b/src/infrastructure/chatwoot/AGENTS.md
index 0724a98f..a383367b 100644
--- a/src/infrastructure/chatwoot/AGENTS.md
+++ b/src/infrastructure/chatwoot/AGENTS.md
@@ -1,6 +1,6 @@
# CHATWOOT INFRASTRUCTURE
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
@@ -10,11 +10,13 @@ This package handles Chatwoot API calls, live sync, historical import, echo-loop
```text
chatwoot/
-|-- client.go # Chatwoot REST API client, contact lookup, echo-loop cache
-|-- sync.go # Sync service and message import flow
+|-- client.go # Chatwoot REST API client: contacts, conversations (find/reopen),
+| # messages (source_id + reply attrs), inbox list/create, echo-loop cache
+|-- provision.go # EnsureInbox: startup auto-create/reuse of the API inbox
+|-- sync.go # Sync service, message import flow, direct-import orchestration
|-- sync_types.go # Sync DTOs/state
-|-- types.go # Chatwoot API payloads
-`-- pgimport/ # Direct PostgreSQL importer for historical messages
+|-- types.go # Chatwoot API payloads (incl. Inbox, MessageOptions fields)
+`-- pgimport/ # Direct PostgreSQL importer for historical messages; see child AGENTS
```
## WHERE TO LOOK
@@ -23,7 +25,9 @@ chatwoot/
|------|----------|-------|
| REST API behavior | `client.go` | HTTP calls to Chatwoot, contact lookup, sent-message cache. |
| Live/history sync | `sync.go` | Uses app/send usecases, storage, and Chatwoot settings. |
-| Direct DB import | `pgimport/` | SQL writer and identity mapping with sqlmock tests. |
+| Direct DB import | `pgimport/` | SQL writer and identity mapping with sqlmock tests; see child AGENTS. |
+| Message links/read/delete | `sync.go`, `../../ui/rest/chatwoot.go`, `../../domains/chatstorage/` | Store mappings for idempotency, read state, webhook replies, and deletes. |
+| Forward retry worker | `../whatsapp/webhook_forward.go`, `../chatstorage/sqlite_repository.go` | Live WhatsApp-to-Chatwoot retries use persistent queue storage. |
| REST surface | `../../ui/rest/chatwoot.go` | Public webhook plus authenticated manual sync/status endpoints. |
| Config | `../../config/settings.go`, `../../cmd/root.go` | `CHATWOOT_*` env/flags. |
@@ -33,12 +37,17 @@ chatwoot/
- Webhook handling accepts only outgoing Chatwoot messages for WhatsApp send-back and skips IDs marked as sent by this app.
- Outbound Chatwoot messages require a configured/selected device; preserve device context when calling send usecases.
- Direct import is controlled separately from live REST forwarding.
+- Direct import owns historical non-media rows. Media history may pre-pass through REST only when `CHATWOOT_IMPORT_MEDIA_WITH_REST` is enabled.
+- Mirrored WhatsApp rows use `source_id` values like `WAID:<message_id>` and persistent links for idempotency and echo suppression.
+- `SyncService.Close()` owns closing the direct-Postgres importer pool during REST shutdown.
+- Chatwoot webhook can be public relative to Basic Auth and still require `CHATWOOT_WEBHOOK_SECRET`.
- Groups and `@lid` contacts use identifier/custom attributes; private chats use normalized phone lookup.
- Tests include regular sync tests and `pgimport` sqlmock tests.
## ANTI-PATTERNS
- Do not mix direct Postgres historical import with live REST forwarding semantics.
+- Do not treat Chatwoot API inbox identifiers as numeric account or inbox IDs.
- Do not remove the sent-message cache unless another echo-loop guard exists.
- Do not log API tokens or raw secrets from Chatwoot config.
- Do not assume imported media is always downloadable; placeholder behavior is configurable.
diff --git a/src/infrastructure/chatwoot/client.go b/src/infrastructure/chatwoot/client.go
index bd768c7d..0e66c29d 100644
--- a/src/infrastructure/chatwoot/client.go
+++ b/src/infrastructure/chatwoot/client.go
@@ -3,12 +3,14 @@ package chatwoot
import (
"bytes"
"encoding/json"
+ "errors"
"fmt"
"io"
"mime"
"mime/multipart"
"net/http"
"net/textproto"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -26,6 +28,42 @@ type Client struct {
AccountID int
InboxID int
HTTPClient *http.Client
+
+ // InboxIdentifier is the public inbox token used by the contact-facing
+ // endpoints (e.g. update_last_seen). It is immutable for a given inbox, so
+ // it is resolved once (at provisioning or on first use) and cached here to
+ // avoid a full inbox-list GET on every read receipt.
+ InboxIdentifier string
+}
+
+// HTTPStatusError is returned by every Client method that hits Chatwoot's
+// REST API when the response status is outside 2xx. It carries the HTTP
+// status code so callers (notably retrySyncOp in sync.go) can decide
+// whether to retry: 429 and 5xx are transient, 4xx is not.
+type HTTPStatusError struct {
+ StatusCode int
+ Op string
+ Body string
+}
+
+func (e *HTTPStatusError) Error() string {
+ return fmt.Sprintf("chatwoot %s: status %d body %s", e.Op, e.StatusCode, e.Body)
+}
+
+// Retryable reports whether an error represents a transient failure that
+// is worth retrying. Network/IO errors that reach callers without a status
+// code (e.g. connection refused, timeout) are always retryable; HTTP
+// responses are retryable only for 429 and 5xx.
+func Retryable(err error) bool {
+ if err == nil {
+ return false
+ }
+ var httpErr *HTTPStatusError
+ if errors.As(err, &httpErr) {
+ return httpErr.StatusCode == http.StatusTooManyRequests || httpErr.StatusCode >= 500
+ }
+ // Non-HTTP error: network, timeout, json encode, etc. — retry.
+ return true
}
var (
@@ -132,7 +170,7 @@ func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Cont
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
- return nil, fmt.Errorf("failed to search contact: status %d body %s", resp.StatusCode, string(body))
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "search contact", Body: string(body)}
}
var result struct {
@@ -142,14 +180,14 @@ func (c *Client) FindContactByIdentifier(identifier string, isGroup bool) (*Cont
return nil, err
}
- // For groups, match by Identifier field or custom attribute waha_whatsapp_jid
+ // For groups, match by Identifier field or custom attribute gowa_whatsapp_jid
// For private chats, match by phone number
for _, contact := range result.Payload {
if isIdentifierBased {
if contact.Identifier == identifier {
return &contact, nil
}
- if jid, ok := contact.CustomAttributes["waha_whatsapp_jid"].(string); ok && jid == identifier {
+ if jid, ok := contact.CustomAttributes["gowa_whatsapp_jid"].(string); ok && jid == identifier {
return &contact, nil
}
} else {
@@ -181,7 +219,7 @@ func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact,
PhoneNumber: phoneNumber,
Identifier: contactIdentifier,
CustomAttributes: map[string]any{
- "waha_whatsapp_jid": identifier,
+ "gowa_whatsapp_jid": identifier,
},
}
@@ -209,7 +247,7 @@ func (c *Client) CreateContact(name, identifier string, isGroup bool) (*Contact,
// Chatwoot returns 200 OK for contacts
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
- return nil, fmt.Errorf("failed to create contact: status %d body %s", resp.StatusCode, string(bodyBytes))
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "create contact", Body: string(bodyBytes)}
}
// Chatwoot API returns: {"payload": {"contact": {...}, "contact_inbox": {...}}}
@@ -245,8 +283,11 @@ func (c *Client) FindOrCreateContact(name, identifier string, isGroup bool) (*Co
return nil, err
}
if contact != nil {
- // Update contact name if it has changed (e.g., group name changed)
- if contact.Name != name && name != "" {
+ // Preserve manually edited 1:1 contact names; group subjects are
+ // expected to keep following WhatsApp-side name changes. Blank 1:1
+ // names still get the initial fallback for readability.
+ shouldUpdateName := name != "" && contact.Name != name && (isGroup || strings.TrimSpace(contact.Name) == "")
+ if shouldUpdateName {
logrus.Infof("Chatwoot: Updating contact name from '%s' to '%s'", contact.Name, name)
if err := c.UpdateContactName(contact.ID, name); err != nil {
logrus.Warnf("Chatwoot: Failed to update contact name: %v", err)
@@ -256,7 +297,23 @@ func (c *Client) FindOrCreateContact(name, identifier string, isGroup bool) (*Co
}
return contact, nil
}
- return c.CreateContact(name, identifier, isGroup)
+
+ created, err := c.CreateContact(name, identifier, isGroup)
+ if err != nil {
+ // A concurrent creator (another process, the direct-DB importer, or a
+ // Chatwoot agent) can win the race between our find and create, leaving
+ // Chatwoot to reject the duplicate phone/identifier with 422. Re-find
+ // once and reuse the now-existing contact instead of dropping the
+ // message; fall through to the original error if it still can't be found.
+ var httpErr *HTTPStatusError
+ if errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusUnprocessableEntity {
+ if found, ferr := c.FindContactByIdentifier(identifier, isGroup); ferr == nil && found != nil {
+ return found, nil
+ }
+ }
+ return nil, err
+ }
+ return created, nil
}
// UpdateContactName updates the name of an existing contact
@@ -287,20 +344,28 @@ func (c *Client) UpdateContactName(contactID int, name string) error {
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("failed to update contact: status %d body %s", resp.StatusCode, string(body))
+ return &HTTPStatusError{StatusCode: resp.StatusCode, Op: "update contact", Body: string(body)}
}
return nil
}
-func (c *Client) FindConversation(contactID int) (*Conversation, error) {
- // Use contact-specific conversations endpoint for accurate results
+type conversationListItem struct {
+ ID int `json:"id"`
+ InboxID int `json:"inbox_id"`
+ Status string `json:"status"`
+}
+
+// listContactConversations fetches all conversations for a contact via the
+// contact-specific endpoint. Shared by FindConversation (which wants the
+// active one) and FindLatestConversation (which wants the most recent one to
+// reopen).
+func (c *Client) listContactConversations(contactID int) ([]conversationListItem, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/contacts/%d/conversations", c.BaseURL, c.AccountID, contactID)
req, err := http.NewRequest("GET", endpoint, nil)
if err != nil {
return nil, err
}
-
req.Header.Set("api_access_token", c.APIToken)
resp, err := c.HTTPClient.Do(req)
@@ -311,43 +376,117 @@ func (c *Client) FindConversation(contactID int) (*Conversation, error) {
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
- return nil, fmt.Errorf("failed to list contact conversations: status %d body %s", resp.StatusCode, string(body))
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "list contact conversations", Body: string(body)}
}
var result struct {
- Payload []struct {
- ID int `json:"id"`
- InboxID int `json:"inbox_id"`
- Status string `json:"status"`
- } `json:"payload"`
+ Payload []conversationListItem `json:"payload"`
}
-
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, err
}
+ return result.Payload, nil
+}
- // Find an open conversation for this inbox
- for _, conv := range result.Payload {
- if conv.InboxID == c.InboxID && conv.Status != "resolved" {
- return &Conversation{
- ID: conv.ID,
- ContactID: contactID,
- InboxID: conv.InboxID,
- Status: conv.Status,
- }, nil
+// selectOpenConversation returns the first open (non-resolved) conversation in
+// this client's inbox, or nil when none is open.
+func selectOpenConversation(items []conversationListItem, inboxID, contactID int) *Conversation {
+ for _, conv := range items {
+ if conv.InboxID == inboxID && conv.Status != "resolved" {
+ return &Conversation{ID: conv.ID, ContactID: contactID, InboxID: conv.InboxID, Status: conv.Status}
}
}
+ return nil
+}
- return nil, nil
+// selectLatestConversation returns the most recent conversation (highest id) in
+// this client's inbox regardless of status, or nil when the contact has none.
+func selectLatestConversation(items []conversationListItem, inboxID, contactID int) *Conversation {
+ var latest *Conversation
+ for _, conv := range items {
+ if conv.InboxID != inboxID {
+ continue
+ }
+ if latest == nil || conv.ID > latest.ID {
+ latest = &Conversation{ID: conv.ID, ContactID: contactID, InboxID: conv.InboxID, Status: conv.Status}
+ }
+ }
+ return latest
+}
+
+func (c *Client) FindConversation(contactID int) (*Conversation, error) {
+ items, err := c.listContactConversations(contactID)
+ if err != nil {
+ return nil, err
+ }
+ return selectOpenConversation(items, c.InboxID, contactID), nil
}
-func (c *Client) CreateConversation(contactID int) (*Conversation, error) {
+// FindLatestConversation returns the most recent conversation for the contact
+// in this client's inbox, regardless of status. The reopen path uses it to
+// resurrect a resolved conversation instead of opening a new thread. Returns
+// (nil, nil) when the contact has no conversation in this inbox.
+func (c *Client) FindLatestConversation(contactID int) (*Conversation, error) {
+ items, err := c.listContactConversations(contactID)
+ if err != nil {
+ return nil, err
+ }
+ return selectLatestConversation(items, c.InboxID, contactID), nil
+}
+
+// ToggleConversationStatus sets a conversation's status (open/resolved/pending)
+// via POST /conversations/{id}/toggle_status.
+func (c *Client) ToggleConversationStatus(conversationID int, status string) error {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations/%d/toggle_status", c.BaseURL, c.AccountID, conversationID)
+ jsonPayload, err := json.Marshal(map[string]string{"status": status})
+ if err != nil {
+ return fmt.Errorf("failed to marshal toggle status payload: %w", err)
+ }
+ req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return &HTTPStatusError{StatusCode: resp.StatusCode, Op: "toggle conversation status", Body: string(body)}
+ }
+ return nil
+}
+
+// conversationStatusForNew returns the status a newly created or reopened
+// conversation should land in: "pending" routes it to the unassigned queue
+// when ChatwootConversationPending is set, otherwise "open" puts it in the
+// agent's active queue.
+func conversationStatusForNew() string {
+ if config.ChatwootConversationPending {
+ return "pending"
+ }
+ return "open"
+}
+
+// CreateConversation opens a new conversation for the contact. sourceID is the
+// WhatsApp chat JID; it is sent so Chatwoot keys the conversation's
+// contact_inbox by that JID (API-channel inboxes accept any source_id),
+// matching the direct-DB importer. That alignment is what lets the contact
+// public endpoints (e.g. update_last_seen) resolve the conversation later. An
+// empty sourceID is omitted, leaving Chatwoot to generate one.
+func (c *Client) CreateConversation(contactID int, sourceID string) (*Conversation, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations", c.BaseURL, c.AccountID)
payload := CreateConversationRequest{
InboxID: c.InboxID,
ContactID: contactID,
- Status: "open",
+ Status: conversationStatusForNew(),
+ SourceID: sourceID,
}
jsonPayload, err := json.Marshal(payload)
@@ -370,7 +509,7 @@ func (c *Client) CreateConversation(contactID int) (*Conversation, error) {
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
- return nil, fmt.Errorf("failed to create conversation: status %d body %s", resp.StatusCode, string(body))
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "create conversation", Body: string(body)}
}
bodyBytes, _ := io.ReadAll(resp.Body)
@@ -391,28 +530,148 @@ func (c *Client) CreateConversation(contactID int) (*Conversation, error) {
return nil, fmt.Errorf("failed to decode conversation response (no valid ID found): %s", string(bodyBytes))
}
-func (c *Client) FindOrCreateConversation(contactID int) (*Conversation, error) {
- conv, err := c.FindConversation(contactID)
+// FindOrCreateConversation resolves the conversation an inbound message should
+// land in. sourceID is the WhatsApp chat JID, forwarded to CreateConversation
+// when a fresh thread is opened. The contact's conversation list is fetched
+// once and scanned in-process for both the open-conversation and reopen cases.
+func (c *Client) FindOrCreateConversation(contactID int, sourceID string) (*Conversation, error) {
+ items, err := c.listContactConversations(contactID)
if err != nil {
+ // A list failure is logged and we fall through to creation rather than
+ // dropping the message.
logrus.Errorf("Error finding conversation: %v", err)
}
- if conv != nil {
+
+ if conv := selectOpenConversation(items, c.InboxID, contactID); conv != nil {
return conv, nil
}
- return c.CreateConversation(contactID)
+
+ // No active conversation. When reopen is enabled, prefer reopening the
+ // contact's most recent (resolved) conversation over spawning a new thread,
+ // so a returning customer continues their existing conversation — matching
+ // the direct-DB importer, which always reuses the latest conversation row.
+ if config.ChatwootReopenConversation {
+ if latest := selectLatestConversation(items, c.InboxID, contactID); latest != nil {
+ if latest.Status == "resolved" {
+ target := conversationStatusForNew()
+ if terr := c.ToggleConversationStatus(latest.ID, target); terr != nil {
+ logrus.Warnf("Chatwoot: failed to reopen conversation %d: %v", latest.ID, terr)
+ } else {
+ latest.Status = target
+ }
+ }
+ return latest, nil
+ }
+ }
+
+ return c.CreateConversation(contactID, sourceID)
}
-func (c *Client) CreateMessage(conversationID int, content string, messageType string, attachments []string) (int, error) {
+// ListInboxes returns every inbox in the account. Auto-provisioning uses it to
+// reuse an existing inbox of the configured name instead of creating a
+// duplicate on each restart.
+func (c *Client) ListInboxes() ([]Inbox, error) {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/inboxes", c.BaseURL, c.AccountID)
+ req, err := http.NewRequest("GET", endpoint, nil)
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK {
+ body, _ := io.ReadAll(resp.Body)
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "list inboxes", Body: string(body)}
+ }
+
+ var result struct {
+ Payload []Inbox `json:"payload"`
+ }
+ if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
+ return nil, err
+ }
+ return result.Payload, nil
+}
+
+// CreateInbox provisions a new API-channel inbox with the given name and
+// optional webhook URL, returning the created inbox.
+func (c *Client) CreateInbox(name, webhookURL string) (*Inbox, error) {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/inboxes", c.BaseURL, c.AccountID)
+ payload := CreateInboxRequest{
+ Name: name,
+ Channel: CreateInboxChannel{
+ Type: "api",
+ WebhookURL: webhookURL,
+ },
+ }
+ jsonPayload, err := json.Marshal(payload)
+ if err != nil {
+ return nil, fmt.Errorf("failed to marshal inbox payload: %w", err)
+ }
+ req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(jsonPayload))
+ if err != nil {
+ return nil, err
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return nil, err
+ }
+ defer resp.Body.Close()
+
+ bodyBytes, _ := io.ReadAll(resp.Body)
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
+ return nil, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "create inbox", Body: string(bodyBytes)}
+ }
+
+ // Chatwoot returns the inbox at the JSON root for this endpoint; tolerate a
+ // {"payload":{...}} wrapper too for forward-compatibility.
+ var inbox Inbox
+ if err := json.Unmarshal(bodyBytes, &inbox); err == nil && inbox.ID != 0 {
+ return &inbox, nil
+ }
+ var wrapped struct {
+ Payload Inbox `json:"payload"`
+ }
+ if err := json.Unmarshal(bodyBytes, &wrapped); err == nil && wrapped.Payload.ID != 0 {
+ return &wrapped.Payload, nil
+ }
+ return nil, fmt.Errorf("failed to decode inbox response (no valid ID found): %s", string(bodyBytes))
+}
+
+// MessageOptions carries optional fields for CreateMessage. SourceID stamps
+// the Chatwoot message with the WhatsApp "WAID:<id>" identifier - the same
+// convention the direct-DB importer uses - which both strengthens echo dedup
+// and gives later replies a stable thread anchor. ContentAttributes carries
+// reply metadata such as in_reply_to_external_id. Private creates a Chatwoot
+// private note, used for agent-visible send failures. All fields are optional;
+// the zero value reproduces the previous behavior exactly.
+type MessageOptions struct {
+ SourceID string
+ ContentAttributes map[string]any
+ Private bool
+}
+
+func (c *Client) CreateMessage(conversationID int, content string, messageType string, attachments []string, opt MessageOptions) (int, error) {
endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations/%d/messages", c.BaseURL, c.AccountID, conversationID)
if len(attachments) > 0 {
- return c.createMessageWithAttachments(endpoint, content, messageType, attachments)
+ return c.createMessageWithAttachments(endpoint, content, messageType, attachments, opt)
}
payload := CreateMessageRequest{
- Content: content,
- MessageType: messageType,
- Private: false,
+ Content: content,
+ MessageType: messageType,
+ Private: opt.Private,
+ SourceID: opt.SourceID,
+ ContentAttributes: opt.ContentAttributes,
}
jsonPayload, err := json.Marshal(payload)
@@ -436,7 +695,7 @@ func (c *Client) CreateMessage(conversationID int, content string, messageType s
bodyBytes, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
- return 0, fmt.Errorf("failed to create message: status %d body %s", resp.StatusCode, string(bodyBytes))
+ return 0, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "create message", Body: string(bodyBytes)}
}
var result struct {
@@ -449,52 +708,149 @@ func (c *Client) CreateMessage(conversationID int, content string, messageType s
return 0, nil
}
-func (c *Client) createMessageWithAttachments(endpoint, content, messageType string, attachments []string) (int, error) {
+func (c *Client) DeleteMessage(conversationID, messageID int) error {
+ endpoint := fmt.Sprintf("%s/api/v1/accounts/%d/conversations/%d/messages/%d", c.BaseURL, c.AccountID, conversationID, messageID)
+ req, err := http.NewRequest(http.MethodDelete, endpoint, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
+ body, _ := io.ReadAll(resp.Body)
+ return &HTTPStatusError{StatusCode: resp.StatusCode, Op: "delete message", Body: string(body)}
+ }
+ return nil
+}
+
+func (c *Client) UpdateLastSeen(conversationID int, contactInboxSourceID string) error {
+ // inbox_identifier is immutable, so resolve it once and reuse the cached
+ // value — read sync fires this per receipt and a full inbox-list GET each
+ // time is pure overhead.
+ inboxIdentifier := c.InboxIdentifier
+ if inboxIdentifier == "" {
+ inboxes, err := c.ListInboxes()
+ if err != nil {
+ return err
+ }
+ for _, inbox := range inboxes {
+ if inbox.ID == c.InboxID {
+ inboxIdentifier = inbox.InboxIdentifier
+ break
+ }
+ }
+ if inboxIdentifier == "" {
+ return fmt.Errorf("chatwoot inbox %d has no inbox_identifier", c.InboxID)
+ }
+ c.InboxIdentifier = inboxIdentifier
+ }
+
+ endpoint := fmt.Sprintf(
+ "%s/public/api/v1/inboxes/%s/contacts/%s/conversations/%d/update_last_seen",
+ c.BaseURL,
+ url.PathEscape(inboxIdentifier),
+ url.PathEscape(contactInboxSourceID),
+ conversationID,
+ )
+ req, err := http.NewRequest(http.MethodPost, endpoint, nil)
+ if err != nil {
+ return err
+ }
+ req.Header.Set("api_access_token", c.APIToken)
+
+ resp, err := c.HTTPClient.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
+ body, _ := io.ReadAll(resp.Body)
+ return &HTTPStatusError{StatusCode: resp.StatusCode, Op: "update last seen", Body: string(body)}
+ }
+ return nil
+}
+
+func (c *Client) createMessageWithAttachments(endpoint, content, messageType string, attachments []string, opt MessageOptions) (int, error) {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
- _ = writer.WriteField("content", content)
- _ = writer.WriteField("message_type", messageType)
- _ = writer.WriteField("private", "false")
+ if err := writer.WriteField("content", content); err != nil {
+ return 0, fmt.Errorf("write content field: %w", err)
+ }
+ if err := writer.WriteField("message_type", messageType); err != nil {
+ return 0, fmt.Errorf("write message_type field: %w", err)
+ }
+ if opt.Private {
+ if err := writer.WriteField("private", "true"); err != nil {
+ return 0, fmt.Errorf("write private field: %w", err)
+ }
+ } else {
+ if err := writer.WriteField("private", "false"); err != nil {
+ return 0, fmt.Errorf("write private field: %w", err)
+ }
+ }
+ if opt.SourceID != "" {
+ if err := writer.WriteField("source_id", opt.SourceID); err != nil {
+ return 0, fmt.Errorf("write source_id field: %w", err)
+ }
+ }
+ if len(opt.ContentAttributes) > 0 {
+ attrs, err := json.Marshal(opt.ContentAttributes)
+ if err != nil {
+ return 0, fmt.Errorf("marshal content attributes: %w", err)
+ }
+ if err := writer.WriteField("content_attributes", string(attrs)); err != nil {
+ return 0, fmt.Errorf("write content_attributes field: %w", err)
+ }
+ }
for _, filePath := range attachments {
- // Process each file in a closure to ensure proper cleanup of file handles
- // This prevents file descriptor leaks when processing multiple attachments
- func(fp string) {
- file, err := os.Open(fp)
- if err != nil {
- logrus.Errorf("Failed to open file %s: %v", fp, err)
- return
- }
- defer file.Close()
+ file, err := os.Open(filePath)
+ if err != nil {
+ return 0, fmt.Errorf("open attachment %s: %w", filePath, err)
+ }
- fileName := filepath.Base(fp)
- ext := filepath.Ext(fp)
+ fileName := filepath.Base(filePath)
+ ext := filepath.Ext(filePath)
- mimeType := mime.TypeByExtension(ext)
- if mimeType == "" {
- if ext == ".oga" {
- mimeType = "audio/ogg"
- } else {
- mimeType = "application/octet-stream"
- }
+ mimeType := mime.TypeByExtension(ext)
+ if mimeType == "" {
+ if ext == ".oga" {
+ mimeType = "audio/ogg"
+ } else {
+ mimeType = "application/octet-stream"
}
+ }
- // Custom form part with correct Content-Type for Chatwoot to render images inline
- h := make(textproto.MIMEHeader)
- h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="attachments[]"; filename="%s"`, fileName))
- h.Set("Content-Type", mimeType)
+ // Custom form part with correct Content-Type for Chatwoot to render images inline.
+ h := make(textproto.MIMEHeader)
+ h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="attachments[]"; filename="%s"`, fileName))
+ h.Set("Content-Type", mimeType)
- part, err := writer.CreatePart(h)
- if err != nil {
- logrus.Errorf("Failed to create form part for %s: %v", fp, err)
- return
- }
- io.Copy(part, file)
- }(filePath)
+ part, err := writer.CreatePart(h)
+ if err != nil {
+ file.Close()
+ return 0, fmt.Errorf("create attachment part %s: %w", filePath, err)
+ }
+ if _, err := io.Copy(part, file); err != nil {
+ file.Close()
+ return 0, fmt.Errorf("copy attachment %s: %w", filePath, err)
+ }
+ if err := file.Close(); err != nil {
+ return 0, fmt.Errorf("close attachment %s: %w", filePath, err)
+ }
}
- writer.Close()
+ if err := writer.Close(); err != nil {
+ return 0, fmt.Errorf("close multipart writer: %w", err)
+ }
req, err := http.NewRequest("POST", endpoint, body)
if err != nil {
@@ -513,7 +869,7 @@ func (c *Client) createMessageWithAttachments(endpoint, content, messageType str
respBody, _ := io.ReadAll(resp.Body)
if resp.StatusCode != http.StatusOK {
- return 0, fmt.Errorf("failed to create message with attachments: status %d body %s", resp.StatusCode, string(respBody))
+ return 0, &HTTPStatusError{StatusCode: resp.StatusCode, Op: "create message with attachments", Body: string(respBody)}
}
var result struct {
diff --git a/src/infrastructure/chatwoot/client_inbox_test.go b/src/infrastructure/chatwoot/client_inbox_test.go
new file mode 100644
index 00000000..14726548
--- /dev/null
+++ b/src/infrastructure/chatwoot/client_inbox_test.go
@@ -0,0 +1,666 @@
+package chatwoot
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// --- ListInboxes -----------------------------------------------------------
+
+func TestListInboxes_DecodesPayload(t *testing.T) {
+ // ListInboxes hits the account-level inboxes endpoint and decodes the
+ // {"payload":[]Inbox} envelope. We assert the path/method and the fields
+ // provisioning uses to match by name and API channel type.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/accounts/1/inboxes" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{
+ {ID: 2, Name: "WhatsApp", ChannelType: "Channel::Api"},
+ {ID: 3, Name: "Email"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inboxes, err := c.ListInboxes()
+ if err != nil {
+ t.Fatalf("ListInboxes: %v", err)
+ }
+ if len(inboxes) != 2 {
+ t.Fatalf("len(inboxes) = %d, want 2", len(inboxes))
+ }
+ if inboxes[0].ID != 2 || inboxes[0].Name != "WhatsApp" {
+ t.Errorf("inboxes[0] = %+v, want id 2 name WhatsApp", inboxes[0])
+ }
+ if inboxes[0].ChannelType != "Channel::Api" {
+ t.Errorf("inboxes[0] = %+v, want API channel decoded", inboxes[0])
+ }
+}
+
+func TestListInboxes_EmptyPayload(t *testing.T) {
+ // An account with no inboxes decodes to an empty slice, not an error —
+ // provisioning treats this as "no match, create one".
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []Inbox{}})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inboxes, err := c.ListInboxes()
+ if err != nil {
+ t.Fatalf("ListInboxes: %v", err)
+ }
+ if len(inboxes) != 0 {
+ t.Fatalf("len(inboxes) = %d, want 0", len(inboxes))
+ }
+}
+
+func TestListInboxes_Non200(t *testing.T) {
+ // Non-200 is surfaced as *HTTPStatusError with Op "list inboxes" so the
+ // caller (EnsureInbox) can wrap it and abort provisioning.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusUnauthorized, map[string]any{"error": "bad token"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inboxes, err := c.ListInboxes()
+ if inboxes != nil {
+ t.Fatalf("inboxes = %+v, want nil", inboxes)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusUnauthorized || httpErr.Op != "list inboxes" {
+ t.Errorf("err = %+v, want 401 'list inboxes'", httpErr)
+ }
+}
+
+// --- CreateInbox -----------------------------------------------------------
+
+func TestCreateInbox_PostsNameAndChannelWithWebhook(t *testing.T) {
+ // The create body must carry name at the root and a nested channel object
+ // of {type:"api", webhook_url:...}. When a webhook URL is given it rides in
+ // the channel; this is what makes Chatwoot POST agent replies back to us.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/inboxes" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["name"] != "WhatsApp" {
+ t.Errorf("name = %v, want WhatsApp", body["name"])
+ }
+ ch, ok := body["channel"].(map[string]any)
+ if !ok {
+ t.Fatalf("channel missing or wrong type: %v", body["channel"])
+ }
+ if ch["type"] != "api" {
+ t.Errorf("channel.type = %v, want api", ch["type"])
+ }
+ if ch["webhook_url"] != "https://hook.example/webhook" {
+ t.Errorf("channel.webhook_url = %v, want the passed URL", ch["webhook_url"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 42, "name": "WhatsApp"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inbox, err := c.CreateInbox("WhatsApp", "https://hook.example/webhook")
+ if err != nil {
+ t.Fatalf("CreateInbox: %v", err)
+ }
+ if inbox.ID != 42 {
+ t.Fatalf("inbox.ID = %d, want 42", inbox.ID)
+ }
+}
+
+func TestCreateInbox_OmitsWebhookWhenEmpty(t *testing.T) {
+ // webhook_url has the ,omitempty tag: an empty URL must drop the key
+ // entirely (not send "webhook_url":""), so Chatwoot creates the inbox
+ // without a callback rather than registering a blank one.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ ch, _ := body["channel"].(map[string]any)
+ if _, ok := ch["webhook_url"]; ok {
+ t.Errorf("webhook_url should be omitted when empty, got %v", ch["webhook_url"])
+ }
+ if ch["type"] != "api" {
+ t.Errorf("channel.type = %v, want api", ch["type"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 7})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inbox, err := c.CreateInbox("WhatsApp", "")
+ if err != nil {
+ t.Fatalf("CreateInbox: %v", err)
+ }
+ if inbox.ID != 7 {
+ t.Fatalf("inbox.ID = %d, want 7", inbox.ID)
+ }
+}
+
+func TestCreateInbox_DecodesBothShapesAndStatuses(t *testing.T) {
+ // Chatwoot returns the inbox at the JSON root for this endpoint, but we
+ // also tolerate a {"payload":Inbox} wrapper for forward-compatibility. Both
+ // 200 and 201 are accepted (Chatwoot versions differ on which they return).
+ tests := []struct {
+ name string
+ status int
+ body any
+ }{
+ {"root-level inbox, 200", http.StatusOK, map[string]any{"id": 11}},
+ {"root-level inbox, 201", http.StatusCreated, map[string]any{"id": 12}},
+ {"payload-wrapped inbox, 200", http.StatusOK, map[string]any{"payload": map[string]any{"id": 13}}},
+ {"payload-wrapped inbox, 201", http.StatusCreated, map[string]any{"payload": map[string]any{"id": 14}}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, tc.status, tc.body)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inbox, err := c.CreateInbox("WhatsApp", "")
+ if err != nil {
+ t.Fatalf("CreateInbox: %v", err)
+ }
+ if inbox == nil || inbox.ID == 0 {
+ t.Fatalf("inbox = %+v, want non-zero ID", inbox)
+ }
+ })
+ }
+}
+
+func TestCreateInbox_Non2xx(t *testing.T) {
+ // Any status outside {200,201} is an HTTPStatusError with Op "create inbox".
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusUnprocessableEntity, map[string]any{"error": "name taken"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inbox, err := c.CreateInbox("WhatsApp", "")
+ if inbox != nil {
+ t.Fatalf("inbox = %+v, want nil", inbox)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusUnprocessableEntity || httpErr.Op != "create inbox" {
+ t.Errorf("err = %+v, want 422 'create inbox'", httpErr)
+ }
+}
+
+func TestCreateInbox_ZeroIDOrUndecodable(t *testing.T) {
+ // A 2xx whose body yields no valid (non-zero) ID in either shape is a plain
+ // error (not HTTPStatusError) — there is nothing usable to provision with.
+ tests := []struct {
+ name string
+ body string
+ }{
+ {"both shapes give zero id", `{"id":0,"payload":{"id":0}}`},
+ {"unrelated json", `{"unexpected":"field"}`},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, tc.body)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ inbox, err := c.CreateInbox("WhatsApp", "")
+ if inbox != nil {
+ t.Fatalf("inbox = %+v, want nil", inbox)
+ }
+ if err == nil {
+ t.Fatal("expected error for zero/undecodable id, got nil")
+ }
+ var httpErr *HTTPStatusError
+ if errors.As(err, &httpErr) {
+ t.Fatalf("err should not be HTTPStatusError, got %v", err)
+ }
+ })
+ }
+}
+
+// --- FindLatestConversation ------------------------------------------------
+
+func TestFindLatestConversation_ReturnsHighestIDRegardlessOfStatus(t *testing.T) {
+ // Unlike FindConversation, this returns the highest-id conversation in this
+ // inbox EVEN IF it is resolved — that is the conversation the reopen path
+ // resurrects. A higher-id conversation in a different inbox must be skipped
+ // so we never resurrect the wrong thread, and a lower-id open conversation
+ // in the right inbox must lose to the higher-id resolved one.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/accounts/1/contacts/7/conversations" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{
+ {"id": 10, "inbox_id": 2, "status": "open"}, // right inbox, lower id
+ {"id": 99, "inbox_id": 88, "status": "open"}, // higher id but wrong inbox -> skip
+ {"id": 20, "inbox_id": 2, "status": "resolved"}, // right inbox, highest -> winner
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindLatestConversation(7)
+ if err != nil {
+ t.Fatalf("FindLatestConversation: %v", err)
+ }
+ if conv == nil || conv.ID != 20 {
+ t.Fatalf("conv = %+v, want ID 20 (highest in inbox 2, even though resolved)", conv)
+ }
+ if conv.Status != "resolved" {
+ t.Errorf("Status = %q, want resolved (status is preserved, not filtered)", conv.Status)
+ }
+ if conv.ContactID != 7 {
+ t.Errorf("ContactID = %d, want 7 (set from the argument)", conv.ContactID)
+ }
+ if conv.InboxID != 2 {
+ t.Errorf("InboxID = %d, want 2", conv.InboxID)
+ }
+}
+
+func TestFindLatestConversation_SkipsOtherInboxesEntirely(t *testing.T) {
+ // When every conversation belongs to another inbox, there is no latest for
+ // THIS inbox -> (nil, nil), so the reopen path falls through to creating a
+ // fresh conversation in our inbox.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{
+ {"id": 50, "inbox_id": 88, "status": "open"},
+ {"id": 51, "inbox_id": 89, "status": "resolved"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindLatestConversation(7)
+ if err != nil {
+ t.Fatalf("FindLatestConversation: %v", err)
+ }
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil (no conversation in our inbox)", conv)
+ }
+}
+
+func TestFindLatestConversation_EmptyPayloadReturnsNil(t *testing.T) {
+ // No conversations at all -> (nil, nil).
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []map[string]any{}})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindLatestConversation(7)
+ if err != nil {
+ t.Fatalf("FindLatestConversation: %v", err)
+ }
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+}
+
+func TestFindLatestConversation_Non200(t *testing.T) {
+ // Shares listContactConversations with FindConversation, so the error Op is
+ // the same "list contact conversations".
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusBadGateway, map[string]any{"error": "down"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindLatestConversation(7)
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusBadGateway || httpErr.Op != "list contact conversations" {
+ t.Errorf("err = %+v, want 502 'list contact conversations'", httpErr)
+ }
+}
+
+// --- ToggleConversationStatus ----------------------------------------------
+
+func TestToggleConversationStatus_PostsStatus(t *testing.T) {
+ // POST to the toggle_status endpoint with a {"status":...} body. A 200 is
+ // success (nil error). We assert the path, method, and body for each of the
+ // statuses the reopen path actually sends.
+ tests := []struct {
+ name string
+ status string
+ }{
+ {"reopen to open", "open"},
+ {"reopen to pending", "pending"},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/conversations/55/toggle_status" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]string
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["status"] != tc.status {
+ t.Errorf("status = %q, want %q", body["status"], tc.status)
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := c.ToggleConversationStatus(55, tc.status); err != nil {
+ t.Fatalf("ToggleConversationStatus: %v", err)
+ }
+ })
+ }
+}
+
+func TestToggleConversationStatus_Non200(t *testing.T) {
+ // Non-200 -> HTTPStatusError with Op "toggle conversation status".
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusNotFound, map[string]any{"error": "no such conversation"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ err := c.ToggleConversationStatus(55, "open")
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusNotFound || httpErr.Op != "toggle conversation status" {
+ t.Errorf("err = %+v, want 404 'toggle conversation status'", httpErr)
+ }
+}
+
+// --- CreateConversation: pending status ------------------------------------
+
+func TestCreateConversation_PostsPendingWhenConfigured(t *testing.T) {
+ // With ChatwootConversationPending=true a freshly created conversation is
+ // opened as "pending" so it lands in the agent's unassigned queue. The
+ // default "open" case is covered in client_methods_test.go; here we only
+ // add the pending branch. Save/restore the global so sibling tests still
+ // observe the default false.
+ orig := config.ChatwootConversationPending
+ config.ChatwootConversationPending = true
+ defer func() { config.ChatwootConversationPending = orig }()
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/conversations" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["status"] != "pending" {
+ t.Errorf("status = %v, want pending", body["status"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 900}})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.CreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("CreateConversation: %v", err)
+ }
+ if conv.ID != 900 {
+ t.Fatalf("conv.ID = %d, want 900", conv.ID)
+ }
+}
+
+// --- CreateMessage with MessageOptions (JSON path) -------------------------
+
+func TestCreateMessage_OptionsJSONPath(t *testing.T) {
+ // On the no-attachment JSON path, opts populate source_id and
+ // content_attributes. source_id stamps the WAID anchor; content_attributes
+ // carries reply metadata. Both have ,omitempty, so the zero options must
+ // emit NEITHER key — that reproduces the pre-options behavior exactly.
+ tests := []struct {
+ name string
+ opts MessageOptions
+ wantSourceID any // nil means key must be absent
+ wantHasContentAtt bool // whether content_attributes must be present
+ wantPrivate bool
+ }{
+ {
+ name: "no options: neither key present",
+ opts: MessageOptions{},
+ wantSourceID: nil,
+ wantHasContentAtt: false,
+ wantPrivate: false,
+ },
+ {
+ name: "source_id only",
+ opts: MessageOptions{SourceID: "WAID:abc123"},
+ wantSourceID: "WAID:abc123",
+ wantHasContentAtt: false,
+ wantPrivate: false,
+ },
+ {
+ name: "content_attributes only",
+ opts: MessageOptions{ContentAttributes: map[string]any{
+ "in_reply_to_external_id": "WAID:x",
+ }},
+ wantSourceID: nil,
+ wantHasContentAtt: true,
+ wantPrivate: false,
+ },
+ {
+ name: "both source_id and content_attributes",
+ opts: MessageOptions{
+ SourceID: "WAID:abc123",
+ ContentAttributes: map[string]any{"in_reply_to_external_id": "WAID:x"},
+ },
+ wantSourceID: "WAID:abc123",
+ wantHasContentAtt: true,
+ wantPrivate: false,
+ },
+ {
+ name: "private note",
+ opts: MessageOptions{Private: true},
+ wantSourceID: nil,
+ wantHasContentAtt: false,
+ wantPrivate: true,
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if tc.wantSourceID == nil {
+ if _, ok := body["source_id"]; ok {
+ t.Errorf("source_id should be omitted, got %v", body["source_id"])
+ }
+ } else if body["source_id"] != tc.wantSourceID {
+ t.Errorf("source_id = %v, want %v", body["source_id"], tc.wantSourceID)
+ }
+ if tc.wantHasContentAtt {
+ ca, ok := body["content_attributes"].(map[string]any)
+ if !ok {
+ t.Fatalf("content_attributes missing or wrong type: %v", body["content_attributes"])
+ }
+ if ca["in_reply_to_external_id"] != "WAID:x" {
+ t.Errorf("content_attributes.in_reply_to_external_id = %v, want WAID:x", ca["in_reply_to_external_id"])
+ }
+ } else if _, ok := body["content_attributes"]; ok {
+ t.Errorf("content_attributes should be omitted, got %v", body["content_attributes"])
+ }
+ if body["private"] != tc.wantPrivate {
+ t.Errorf("private = %v, want %v", body["private"], tc.wantPrivate)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 1})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "hello", "incoming", nil, tc.opts)
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 1 {
+ t.Fatalf("id = %d, want 1", id)
+ }
+ })
+ }
+}
+
+// --- CreateMessage with MessageOptions (multipart path) --------------------
+
+func TestCreateMessage_OptionsMultipartPath(t *testing.T) {
+ // On the attachment path, source_id and content_attributes become form
+ // fields. content_attributes is written as a JSON string (not a nested
+ // object, since multipart fields are flat). When options are zero, both
+ // fields are absent (the WriteField calls are guarded by non-empty checks).
+ tmp := filepath.Join(t.TempDir(), "a.oga")
+ if err := os.WriteFile(tmp, []byte("X"), 0o600); err != nil {
+ t.Fatalf("write temp file: %v", err)
+ }
+
+ tests := []struct {
+ name string
+ opts MessageOptions
+ wantSourceID string // "" means field must be absent
+ wantContentAttrJS string // "" means field must be absent
+ wantPrivate string
+ }{
+ {
+ name: "no options: neither field present",
+ opts: MessageOptions{},
+ wantSourceID: "",
+ wantContentAttrJS: "",
+ wantPrivate: "false",
+ },
+ {
+ name: "source_id present",
+ opts: MessageOptions{SourceID: "WAID:abc123"},
+ wantSourceID: "WAID:abc123",
+ wantContentAttrJS: "",
+ wantPrivate: "false",
+ },
+ {
+ name: "content_attributes present as JSON string",
+ opts: MessageOptions{ContentAttributes: map[string]any{
+ "in_reply_to_external_id": "WAID:x",
+ }},
+ wantSourceID: "",
+ wantContentAttrJS: `{"in_reply_to_external_id":"WAID:x"}`,
+ wantPrivate: "false",
+ },
+ {
+ name: "private note",
+ opts: MessageOptions{Private: true},
+ wantSourceID: "",
+ wantContentAttrJS: "",
+ wantPrivate: "true",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ if err != nil {
+ t.Fatalf("ParseMediaType: %v", err)
+ }
+ mr := multipart.NewReader(r.Body, params["boundary"])
+ var gotSourceID, gotContentAttr string
+ var sawSourceID, sawContentAttr bool
+ var gotPrivate string
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatalf("NextPart: %v", err)
+ }
+ switch part.FormName() {
+ case "source_id":
+ data, _ := io.ReadAll(part)
+ gotSourceID = string(data)
+ sawSourceID = true
+ case "content_attributes":
+ data, _ := io.ReadAll(part)
+ gotContentAttr = string(data)
+ sawContentAttr = true
+ case "private":
+ data, _ := io.ReadAll(part)
+ gotPrivate = string(data)
+ }
+ }
+ if tc.wantSourceID == "" {
+ if sawSourceID {
+ t.Errorf("source_id field present (%q), want absent", gotSourceID)
+ }
+ } else {
+ if !sawSourceID || gotSourceID != tc.wantSourceID {
+ t.Errorf("source_id = %q (present=%v), want %q", gotSourceID, sawSourceID, tc.wantSourceID)
+ }
+ }
+ if tc.wantContentAttrJS == "" {
+ if sawContentAttr {
+ t.Errorf("content_attributes field present (%q), want absent", gotContentAttr)
+ }
+ } else {
+ if !sawContentAttr || gotContentAttr != tc.wantContentAttrJS {
+ t.Errorf("content_attributes = %q (present=%v), want %q", gotContentAttr, sawContentAttr, tc.wantContentAttrJS)
+ }
+ }
+ if gotPrivate != tc.wantPrivate {
+ t.Errorf("private = %q, want %q", gotPrivate, tc.wantPrivate)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 2})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "caption", "incoming", []string{tmp}, tc.opts)
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 2 {
+ t.Fatalf("id = %d, want 2", id)
+ }
+ })
+ }
+}
diff --git a/src/infrastructure/chatwoot/client_methods_test.go b/src/infrastructure/chatwoot/client_methods_test.go
new file mode 100644
index 00000000..38855e9a
--- /dev/null
+++ b/src/infrastructure/chatwoot/client_methods_test.go
@@ -0,0 +1,1246 @@
+package chatwoot
+
+import (
+ "encoding/json"
+ "errors"
+ "io"
+ "mime"
+ "mime/multipart"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// newTestClient builds a Client pointed at the given test server. Every
+// method under test reads BaseURL/APIToken/AccountID/InboxID, so this keeps
+// each table case terse and consistent with the existing client_test.go.
+func newTestClient(t *testing.T, serverURL string) *Client {
+ t.Helper()
+ return &Client{
+ BaseURL: serverURL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: http.DefaultClient,
+ }
+}
+
+// --- NewClient -------------------------------------------------------------
+
+func TestNewClient_TrimsTrailingSlashAndMapsConfig(t *testing.T) {
+ // NewClient reads package-level config globals. Mutating globals in a
+ // test is only safe if we restore them afterwards, otherwise a sibling
+ // test that constructs the default client would observe leaked state.
+ origURL := config.ChatwootURL
+ origToken := config.ChatwootAPIToken
+ origAccount := config.ChatwootAccountID
+ origInbox := config.ChatwootInboxID
+ defer func() {
+ config.ChatwootURL = origURL
+ config.ChatwootAPIToken = origToken
+ config.ChatwootAccountID = origAccount
+ config.ChatwootInboxID = origInbox
+ }()
+
+ tests := []struct {
+ name string
+ url string
+ wantURL string
+ }{
+ // The trailing slash matters: endpoints are built with
+ // fmt.Sprintf("%s/api/v1/...") so a stray slash would yield a
+ // double-slash path. TrimRight removes any run of trailing slashes.
+ {"single trailing slash", "https://chatwoot.example.com/", "https://chatwoot.example.com"},
+ {"multiple trailing slashes", "https://chatwoot.example.com///", "https://chatwoot.example.com"},
+ {"no trailing slash", "https://chatwoot.example.com", "https://chatwoot.example.com"},
+ {"empty url stays empty", "", ""},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ config.ChatwootURL = tc.url
+ config.ChatwootAPIToken = "tok-123"
+ config.ChatwootAccountID = 7
+ config.ChatwootInboxID = 9
+
+ c := NewClient()
+
+ if c.BaseURL != tc.wantURL {
+ t.Errorf("BaseURL = %q, want %q", c.BaseURL, tc.wantURL)
+ }
+ if c.APIToken != "tok-123" {
+ t.Errorf("APIToken = %q, want tok-123", c.APIToken)
+ }
+ if c.AccountID != 7 {
+ t.Errorf("AccountID = %d, want 7", c.AccountID)
+ }
+ if c.InboxID != 9 {
+ t.Errorf("InboxID = %d, want 9", c.InboxID)
+ }
+ if c.HTTPClient == nil {
+ t.Fatal("HTTPClient must not be nil")
+ }
+ })
+ }
+}
+
+// --- IsConfigured ----------------------------------------------------------
+
+func TestIsConfigured(t *testing.T) {
+ tests := []struct {
+ name string
+ c Client
+ want bool
+ }{
+ // Only the fully-populated client is configured. Each false case
+ // zeroes exactly one required field to prove every field is checked.
+ {"all set", Client{BaseURL: "u", APIToken: "t", AccountID: 1, InboxID: 2}, true},
+ {"missing BaseURL", Client{BaseURL: "", APIToken: "t", AccountID: 1, InboxID: 2}, false},
+ {"missing APIToken", Client{BaseURL: "u", APIToken: "", AccountID: 1, InboxID: 2}, false},
+ {"zero AccountID", Client{BaseURL: "u", APIToken: "t", AccountID: 0, InboxID: 2}, false},
+ {"zero InboxID", Client{BaseURL: "u", APIToken: "t", AccountID: 1, InboxID: 0}, false},
+ {"all empty", Client{}, false},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := tc.c.IsConfigured(); got != tc.want {
+ t.Errorf("IsConfigured() = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// --- FindContactByIdentifier ----------------------------------------------
+
+func TestFindContactByIdentifier_PhoneMatch(t *testing.T) {
+ // 1:1 path: the search query is the E.164-normalized phone, and the
+ // match is made on PhoneNumber equality. A contact whose phone differs
+ // must be ignored so we never bind to the wrong person.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/accounts/1/contacts/search" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ if got := r.URL.Query().Get("q"); got != "+6281234567890" {
+ t.Fatalf("search q = %q, want +6281234567890", got)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{
+ {ID: 1, PhoneNumber: "+6289999999999"}, // wrong phone, must be skipped
+ {ID: 2, PhoneNumber: "+6281234567890", Name: "Match"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier("6281234567890", false)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact == nil || contact.ID != 2 {
+ t.Fatalf("contact = %+v, want ID 2", contact)
+ }
+}
+
+func TestFindContactByIdentifier_PhoneNoMatch(t *testing.T) {
+ // When the search returns contacts but none match the normalized phone,
+ // the method returns (nil, nil) — not found is not an error.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{ID: 1, PhoneNumber: "+6280000000000"}},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier("6281234567890", false)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact != nil {
+ t.Fatalf("contact = %+v, want nil", contact)
+ }
+}
+
+func TestFindContactByIdentifier_GroupMatchByIdentifier(t *testing.T) {
+ // Group path: the raw JID is used as the search query (no phone
+ // normalization), and a match is made on the Identifier field.
+ const groupJID = "[email protected]"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.URL.Query().Get("q"); got != groupJID {
+ t.Fatalf("search q = %q, want %s", got, groupJID)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{ID: 55, Identifier: groupJID, Name: "Group"}},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier(groupJID, true)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact == nil || contact.ID != 55 {
+ t.Fatalf("contact = %+v, want ID 55", contact)
+ }
+}
+
+func TestFindContactByIdentifier_GroupMatchByCustomAttribute(t *testing.T) {
+ // Group path fallback: a contact whose Identifier field is blank can
+ // still match via custom_attributes.gowa_whatsapp_jid, which is the
+ // attribute CreateContact stamps on every contact it creates.
+ const groupJID = "[email protected]"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{
+ ID: 66,
+ Identifier: "", // not matched on this field
+ CustomAttributes: map[string]any{"gowa_whatsapp_jid": groupJID},
+ }},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier(groupJID, true)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact == nil || contact.ID != 66 {
+ t.Fatalf("contact = %+v, want ID 66", contact)
+ }
+}
+
+func TestFindContactByIdentifier_LidUsesIdentifierNotPhone(t *testing.T) {
+ // An @lid JID is a WhatsApp linked-device ID, not a phone number. The
+ // identifier-based branch must be taken: the raw @lid value is the
+ // search query and the match is on Identifier, never PhoneNumber.
+ const lidJID = "11223344556677@lid"
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.URL.Query().Get("q"); got != lidJID {
+ t.Fatalf("search q = %q, want %s (raw @lid, not normalized phone)", got, lidJID)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{
+ // A contact whose phone happens to equal the normalized lid
+ // must NOT match, proving the phone branch is not taken.
+ {ID: 1, PhoneNumber: "+11223344556677"},
+ {ID: 2, Identifier: lidJID, Name: "Lid"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier(lidJID, false)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact == nil || contact.ID != 2 {
+ t.Fatalf("contact = %+v, want ID 2", contact)
+ }
+}
+
+func TestFindContactByIdentifier_EmptyPayload(t *testing.T) {
+ // An empty payload yields (nil, nil): the loop never matches and the
+ // trailing return is reached.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []Contact{}})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier("6281234567890", false)
+ if err != nil {
+ t.Fatalf("FindContactByIdentifier: %v", err)
+ }
+ if contact != nil {
+ t.Fatalf("contact = %+v, want nil", contact)
+ }
+}
+
+func TestFindContactByIdentifier_Non200(t *testing.T) {
+ // A non-200 status is surfaced as an *HTTPStatusError carrying the code
+ // and Op so retrySyncOp can classify it as transient or fatal.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "boom"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindContactByIdentifier("6281234567890", false)
+ if contact != nil {
+ t.Fatalf("contact = %+v, want nil", contact)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusInternalServerError {
+ t.Errorf("StatusCode = %d, want 500", httpErr.StatusCode)
+ }
+ if httpErr.Op != "search contact" {
+ t.Errorf("Op = %q, want 'search contact'", httpErr.Op)
+ }
+}
+
+// --- CreateContact ---------------------------------------------------------
+
+func TestCreateContact_IndividualSendsPhone(t *testing.T) {
+ // 1:1 contacts are keyed on their E.164 phone. The request must set
+ // phone_number to the normalized value, leave identifier empty (omitted
+ // by ,omitempty), and stamp custom_attributes.gowa_whatsapp_jid with the
+ // raw identifier so later identifier-based lookups can still match.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/contacts" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["phone_number"] != "+6281234567890" {
+ t.Errorf("phone_number = %v, want +6281234567890", body["phone_number"])
+ }
+ if _, ok := body["identifier"]; ok {
+ t.Errorf("identifier should be omitted for 1:1, got %v", body["identifier"])
+ }
+ ca, _ := body["custom_attributes"].(map[string]any)
+ if ca["gowa_whatsapp_jid"] != "6281234567890" {
+ t.Errorf("gowa_whatsapp_jid = %v, want 6281234567890", ca["gowa_whatsapp_jid"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": map[string]any{"contact": map[string]any{"id": 100, "name": "Alice"}},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.CreateContact("Alice", "6281234567890", false)
+ if err != nil {
+ t.Fatalf("CreateContact: %v", err)
+ }
+ if contact.ID != 100 {
+ t.Fatalf("contact.ID = %d, want 100", contact.ID)
+ }
+}
+
+func TestCreateContact_GroupAndLidSendIdentifier(t *testing.T) {
+ // Both group JIDs and @lid JIDs use the identifier field and leave
+ // phone_number empty (it is non-phone data).
+ tests := []struct {
+ name string
+ identifier string
+ isGroup bool
+ }{
+ {"group jid", "[email protected]", true},
+ {"lid jid", "11223344556677@lid", false},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["identifier"] != tc.identifier {
+ t.Errorf("identifier = %v, want %s", body["identifier"], tc.identifier)
+ }
+ if _, ok := body["phone_number"]; ok {
+ t.Errorf("phone_number should be omitted, got %v", body["phone_number"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": map[string]any{"contact": map[string]any{"id": 200}},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.CreateContact("name", tc.identifier, tc.isGroup)
+ if err != nil {
+ t.Fatalf("CreateContact: %v", err)
+ }
+ if contact.ID != 200 {
+ t.Fatalf("contact.ID = %d, want 200", contact.ID)
+ }
+ })
+ }
+}
+
+func TestCreateContact_DecodesAllResponseShapes(t *testing.T) {
+ // Chatwoot's contact-create response shape has drifted across versions:
+ // nested {payload:{contact}}, flat {payload:Contact}, and bare Contact
+ // at the root. All three must decode, and both 200 and 201 are accepted.
+ tests := []struct {
+ name string
+ status int
+ body any
+ }{
+ {
+ name: "nested payload.contact, 200",
+ status: http.StatusOK,
+ body: map[string]any{"payload": map[string]any{"contact": map[string]any{"id": 1}}},
+ },
+ {
+ name: "flat payload contact, 201",
+ status: http.StatusCreated,
+ body: map[string]any{"payload": map[string]any{"id": 2}},
+ },
+ {
+ name: "root-level contact, 200",
+ status: http.StatusOK,
+ body: map[string]any{"id": 3},
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, tc.status, tc.body)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.CreateContact("name", "6281234567890", false)
+ if err != nil {
+ t.Fatalf("CreateContact: %v", err)
+ }
+ if contact == nil || contact.ID == 0 {
+ t.Fatalf("contact = %+v, want non-zero ID", contact)
+ }
+ })
+ }
+}
+
+func TestCreateContact_Non2xx(t *testing.T) {
+ // Any status outside {200,201} is an HTTPStatusError with Op "create contact".
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusUnprocessableEntity, map[string]any{"error": "taken"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.CreateContact("name", "6281234567890", false)
+ if contact != nil {
+ t.Fatalf("contact = %+v, want nil", contact)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusUnprocessableEntity || httpErr.Op != "create contact" {
+ t.Errorf("err = %+v, want 422 'create contact'", httpErr)
+ }
+}
+
+func TestCreateContact_ZeroIDOrUndecodable(t *testing.T) {
+ // A 2xx response whose body yields no valid (non-zero) ID is a hard
+ // failure — there is nothing usable to return. This covers both a body
+ // with id:0 and a body that does not unmarshal into any contact shape.
+ tests := []struct {
+ name string
+ body string
+ }{
+ {"all shapes give zero id", `{"payload":{"contact":{"id":0}}}`},
+ {"unrelated json", `{"unexpected":"field"}`},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, tc.body)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.CreateContact("name", "6281234567890", false)
+ if contact != nil {
+ t.Fatalf("contact = %+v, want nil", contact)
+ }
+ if err == nil {
+ t.Fatal("expected error for zero/undecodable id, got nil")
+ }
+ // This is a plain fmt.Errorf, not an HTTPStatusError.
+ var httpErr *HTTPStatusError
+ if errors.As(err, &httpErr) {
+ t.Fatalf("err should not be HTTPStatusError, got %v", err)
+ }
+ })
+ }
+}
+
+// --- UpdateContactName -----------------------------------------------------
+
+func TestUpdateContactName(t *testing.T) {
+ tests := []struct {
+ name string
+ status int
+ wantErr bool
+ }{
+ // PUT to the contact endpoint accepts both 200 and 204 (Chatwoot
+ // versions differ). Anything else is an error.
+ {"200 ok", http.StatusOK, false},
+ {"204 no content", http.StatusNoContent, false},
+ {"500 error", http.StatusInternalServerError, true},
+ {"422 error", http.StatusUnprocessableEntity, true},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPut || r.URL.Path != "/api/v1/accounts/1/contacts/42" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["name"] != "New Name" {
+ t.Errorf("name = %v, want New Name", body["name"])
+ }
+ w.WriteHeader(tc.status)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ err := c.UpdateContactName(42, "New Name")
+ if tc.wantErr {
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.Op != "update contact" {
+ t.Errorf("Op = %q, want 'update contact'", httpErr.Op)
+ }
+ } else if err != nil {
+ t.Fatalf("UpdateContactName: %v", err)
+ }
+ })
+ }
+}
+
+// --- FindConversation ------------------------------------------------------
+
+func TestFindConversation_ReturnsFirstOpenMatchingInbox(t *testing.T) {
+ // The first conversation that is both in this client's inbox AND not
+ // resolved wins. Earlier entries that fail either condition are skipped:
+ // a resolved conversation in the right inbox, and an open conversation
+ // in a different inbox, both come before the valid one.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/accounts/1/contacts/7/conversations" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{
+ {"id": 10, "inbox_id": 2, "status": "resolved"}, // right inbox, resolved -> skip
+ {"id": 11, "inbox_id": 99, "status": "open"}, // wrong inbox -> skip
+ {"id": 12, "inbox_id": 2, "status": "open"}, // match
+ {"id": 13, "inbox_id": 2, "status": "pending"}, // also valid but later
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindConversation(7)
+ if err != nil {
+ t.Fatalf("FindConversation: %v", err)
+ }
+ if conv == nil || conv.ID != 12 {
+ t.Fatalf("conv = %+v, want ID 12", conv)
+ }
+ if conv.ContactID != 7 {
+ t.Errorf("ContactID = %d, want 7 (set from the argument, not the payload)", conv.ContactID)
+ }
+ if conv.InboxID != 2 || conv.Status != "open" {
+ t.Errorf("conv = %+v, want inbox 2 status open", conv)
+ }
+}
+
+func TestFindConversation_NonResolvedNonResolvedStatuses(t *testing.T) {
+ // "resolved" is the only excluded status; any other status (here
+ // "pending") for the right inbox is considered an active conversation.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{
+ {"id": 20, "inbox_id": 2, "status": "pending"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindConversation(7)
+ if err != nil {
+ t.Fatalf("FindConversation: %v", err)
+ }
+ if conv == nil || conv.ID != 20 {
+ t.Fatalf("conv = %+v, want ID 20", conv)
+ }
+}
+
+func TestFindConversation_NoneMatch(t *testing.T) {
+ // All candidates are either resolved or in the wrong inbox -> nil, nil.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{
+ {"id": 30, "inbox_id": 2, "status": "resolved"},
+ {"id": 31, "inbox_id": 99, "status": "open"},
+ },
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindConversation(7)
+ if err != nil {
+ t.Fatalf("FindConversation: %v", err)
+ }
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+}
+
+func TestFindConversation_Non200(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusBadGateway, map[string]any{"error": "down"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindConversation(7)
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusBadGateway || httpErr.Op != "list contact conversations" {
+ t.Errorf("err = %+v, want 502 'list contact conversations'", httpErr)
+ }
+}
+
+// --- CreateConversation ----------------------------------------------------
+
+func TestCreateConversation_PostsOpenStatus(t *testing.T) {
+ // The create request must carry this client's inbox, the contact id, and
+ // status "open". The {payload:Conversation} shape decodes here.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/conversations" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["inbox_id"] != float64(2) {
+ t.Errorf("inbox_id = %v, want 2", body["inbox_id"])
+ }
+ if body["contact_id"] != float64(7) {
+ t.Errorf("contact_id = %v, want 7", body["contact_id"])
+ }
+ if body["status"] != "open" {
+ t.Errorf("status = %v, want open", body["status"])
+ }
+ if body["source_id"] != "[email protected]" {
+ t.Errorf("source_id = %v, want [email protected]", body["source_id"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": map[string]any{"id": 500},
+ })
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.CreateConversation(7, "[email protected]")
+ if err != nil {
+ t.Fatalf("CreateConversation: %v", err)
+ }
+ if conv.ID != 500 {
+ t.Fatalf("conv.ID = %d, want 500", conv.ID)
+ }
+}
+
+func TestCreateConversation_RootShape(t *testing.T) {
+ // Fallback decode path: the conversation lives at the JSON root.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 501})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.CreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("CreateConversation: %v", err)
+ }
+ if conv.ID != 501 {
+ t.Fatalf("conv.ID = %d, want 501", conv.ID)
+ }
+}
+
+func TestCreateConversation_Non200(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "x"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.CreateConversation(7, "")
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.Op != "create conversation" {
+ t.Errorf("Op = %q, want 'create conversation'", httpErr.Op)
+ }
+}
+
+func TestCreateConversation_ZeroID(t *testing.T) {
+ // A 200 with no usable ID in either shape is an error (not HTTPStatusError).
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, `{"payload":{"id":0}}`)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.CreateConversation(7, "")
+ if conv != nil {
+ t.Fatalf("conv = %+v, want nil", conv)
+ }
+ if err == nil {
+ t.Fatal("expected error for zero id, got nil")
+ }
+ var httpErr *HTTPStatusError
+ if errors.As(err, &httpErr) {
+ t.Fatalf("err should not be HTTPStatusError, got %v", err)
+ }
+}
+
+// --- FindOrCreateConversation ---------------------------------------------
+
+func TestFindOrCreateConversation_ReturnsFoundWithoutCreating(t *testing.T) {
+ // When FindConversation returns an existing conversation, no POST is made.
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/7/conversations":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{{"id": 600, "inbox_id": 2, "status": "open"}},
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/conversations":
+ createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 999}})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 600 {
+ t.Fatalf("conv.ID = %d, want 600 (found, not created)", conv.ID)
+ }
+ if createCalls != 0 {
+ t.Fatalf("create calls = %d, want 0", createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_CreatesWhenNotFound(t *testing.T) {
+ // FindConversation returns (nil, nil) -> the method falls through to
+ // CreateConversation.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet:
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []map[string]any{}})
+ case r.Method == http.MethodPost:
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 700}})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 700 {
+ t.Fatalf("conv.ID = %d, want 700 (created)", conv.ID)
+ }
+}
+
+func TestFindOrCreateConversation_SwallowsFindErrorThenCreates(t *testing.T) {
+ // FindConversation failing is logged but NOT propagated: the method still
+ // proceeds to create. This codifies the current swallow-and-create
+ // behavior — a find error must not block conversation creation.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet:
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "find failed"})
+ case r.Method == http.MethodPost:
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": 800}})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation should swallow find error, got: %v", err)
+ }
+ if conv.ID != 800 {
+ t.Fatalf("conv.ID = %d, want 800 (created after find error)", conv.ID)
+ }
+}
+
+// --- FindOrCreateContact 422 recovery -------------------------------------
+
+func TestFindOrCreateContact_RecoversFrom422ByRefinding(t *testing.T) {
+ // A concurrent creator wins the race between our find and create, so create
+ // returns 422 (identifier already taken). We re-find once and reuse the
+ // now-existing contact instead of dropping the message.
+ searchCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/search":
+ searchCalls++
+ if searchCalls == 1 {
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []map[string]any{}})
+ return
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []map[string]any{{"id": 42, "identifier": "[email protected]"}},
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/contacts":
+ writeJSON(t, w, http.StatusUnprocessableEntity, map[string]any{
+ "message": "Identifier has already been taken",
+ })
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ contact, err := c.FindOrCreateContact("Group", "[email protected]", true)
+ if err != nil {
+ t.Fatalf("FindOrCreateContact should recover from 422, got: %v", err)
+ }
+ if contact == nil || contact.ID != 42 {
+ t.Fatalf("contact = %+v, want id 42 (re-found after 422)", contact)
+ }
+ if searchCalls != 2 {
+ t.Fatalf("search calls = %d, want 2 (initial find + 422 recovery re-find)", searchCalls)
+ }
+}
+
+func TestFindOrCreateContact_PropagatesNon422CreateError(t *testing.T) {
+ // A non-422 create failure (e.g. 500) is NOT recovered: it surfaces so the
+ // caller treats it as transient and retries.
+ searchCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/search":
+ searchCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []map[string]any{}})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/contacts":
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "boom"})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ _, err := c.FindOrCreateContact("Group", "[email protected]", true)
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) || httpErr.StatusCode != http.StatusInternalServerError {
+ t.Fatalf("err = %v, want 500 HTTPStatusError", err)
+ }
+ if searchCalls != 1 {
+ t.Fatalf("search calls = %d, want 1 (no recovery re-find for non-422)", searchCalls)
+ }
+}
+
+// --- CreateMessage (no attachments) ---------------------------------------
+
+func TestCreateMessage_PlainPostsAndReturnsID(t *testing.T) {
+ // Plain text message: posts content/message_type with private=false, and
+ // returns the id from a 200 response.
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/api/v1/accounts/1/conversations/5/messages" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode body: %v", err)
+ }
+ if body["content"] != "hello" {
+ t.Errorf("content = %v, want hello", body["content"])
+ }
+ if body["message_type"] != "outgoing" {
+ t.Errorf("message_type = %v, want outgoing", body["message_type"])
+ }
+ if body["private"] != false {
+ t.Errorf("private = %v, want false", body["private"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 321})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "hello", "outgoing", nil, MessageOptions{})
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 321 {
+ t.Fatalf("id = %d, want 321", id)
+ }
+}
+
+func TestCreateMessage_Non200(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusTooManyRequests, map[string]any{"error": "slow down"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "hello", "outgoing", nil, MessageOptions{})
+ if id != 0 {
+ t.Fatalf("id = %d, want 0", id)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusTooManyRequests || httpErr.Op != "create message" {
+ t.Errorf("err = %+v, want 429 'create message'", httpErr)
+ }
+}
+
+func TestCreateMessage_MissingIDReturnsZeroNoError(t *testing.T) {
+ // A 200 whose body lacks an id (or has id:0) returns (0, nil): the send
+ // succeeded but no id is available to register for echo-dedup.
+ tests := []struct {
+ name string
+ body string
+ }{
+ {"empty object", `{}`},
+ {"explicit zero id", `{"id":0}`},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, tc.body)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "hello", "outgoing", nil, MessageOptions{})
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 0 {
+ t.Fatalf("id = %d, want 0", id)
+ }
+ })
+ }
+}
+
+func TestDeleteMessage_SendsDelete(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodDelete || r.URL.Path != "/api/v1/accounts/1/conversations/5/messages/9" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ if got := r.Header.Get("api_access_token"); got != "token" {
+ t.Fatalf("api token = %q, want token", got)
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := c.DeleteMessage(5, 9); err != nil {
+ t.Fatalf("DeleteMessage: %v", err)
+ }
+}
+
+func TestUpdateLastSeen_UsesInboxIdentifierAndContactSource(t *testing.T) {
+ var sawUpdate bool
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/v1/accounts/1/inboxes":
+ if r.Method != http.MethodGet {
+ t.Fatalf("list inboxes method = %s", r.Method)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{
+ {ID: 2, Name: "WhatsApp", InboxIdentifier: "api-inbox-token"},
+ },
+ })
+ case "/public/api/v1/inboxes/api-inbox-token/contacts/[email protected]/conversations/5/update_last_seen":
+ if r.Method != http.MethodPost {
+ t.Fatalf("update_last_seen method = %s", r.Method)
+ }
+ sawUpdate = true
+ w.WriteHeader(http.StatusOK)
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := c.UpdateLastSeen(5, "[email protected]"); err != nil {
+ t.Fatalf("UpdateLastSeen: %v", err)
+ }
+ if !sawUpdate {
+ t.Fatal("expected update_last_seen request")
+ }
+}
+
+// --- createMessageWithAttachments (via CreateMessage with attachments) -----
+
+func TestCreateMessage_WithAttachmentUploadsMultipart(t *testing.T) {
+ // With attachments, the request becomes multipart/form-data. We assert
+ // the text fields ride along, the file part carries the right filename
+ // and Content-Type, and the returned id is decoded from the response.
+ tmp := filepath.Join(t.TempDir(), "voice.oga")
+ if err := os.WriteFile(tmp, []byte("OGGDATA"), 0o600); err != nil {
+ t.Fatalf("write temp file: %v", err)
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ ct := r.Header.Get("Content-Type")
+ if !strings.HasPrefix(ct, "multipart/form-data") {
+ t.Fatalf("Content-Type = %q, want multipart/form-data", ct)
+ }
+ mediaType, params, err := mime.ParseMediaType(ct)
+ if err != nil || mediaType != "multipart/form-data" {
+ t.Fatalf("ParseMediaType(%q): %v", ct, err)
+ }
+ mr := multipart.NewReader(r.Body, params["boundary"])
+ sawContent, sawType, sawPrivate, sawFile := false, false, false, false
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatalf("NextPart: %v", err)
+ }
+ switch part.FormName() {
+ case "content":
+ data, _ := io.ReadAll(part)
+ if string(data) != "caption" {
+ t.Errorf("content = %q, want caption", data)
+ }
+ sawContent = true
+ case "message_type":
+ data, _ := io.ReadAll(part)
+ if string(data) != "incoming" {
+ t.Errorf("message_type = %q, want incoming", data)
+ }
+ sawType = true
+ case "private":
+ data, _ := io.ReadAll(part)
+ if string(data) != "false" {
+ t.Errorf("private = %q, want false", data)
+ }
+ sawPrivate = true
+ case "attachments[]":
+ if part.FileName() != "voice.oga" {
+ t.Errorf("filename = %q, want voice.oga", part.FileName())
+ }
+ // .oga must be tagged audio/ogg so Chatwoot renders the
+ // voice note inline rather than as a generic download.
+ if got := part.Header.Get("Content-Type"); got != "audio/ogg" {
+ t.Errorf("attachment Content-Type = %q, want audio/ogg", got)
+ }
+ data, _ := io.ReadAll(part)
+ if string(data) != "OGGDATA" {
+ t.Errorf("attachment body = %q, want OGGDATA", data)
+ }
+ sawFile = true
+ }
+ }
+ if !sawContent || !sawType || !sawPrivate || !sawFile {
+ t.Fatalf("missing parts: content=%v type=%v private=%v file=%v", sawContent, sawType, sawPrivate, sawFile)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 4242})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "caption", "incoming", []string{tmp}, MessageOptions{})
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 4242 {
+ t.Fatalf("id = %d, want 4242", id)
+ }
+}
+
+func TestCreateMessage_AttachmentUnknownExtensionUsesOctetStream(t *testing.T) {
+ // An extension with no known MIME mapping falls back to
+ // application/octet-stream.
+ tmp := filepath.Join(t.TempDir(), "blob.xyz123")
+ if err := os.WriteFile(tmp, []byte("RAW"), 0o600); err != nil {
+ t.Fatalf("write temp file: %v", err)
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ _, params, _ := mime.ParseMediaType(r.Header.Get("Content-Type"))
+ mr := multipart.NewReader(r.Body, params["boundary"])
+ found := false
+ for {
+ part, err := mr.NextPart()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatalf("NextPart: %v", err)
+ }
+ if part.FormName() == "attachments[]" {
+ if got := part.Header.Get("Content-Type"); got != "application/octet-stream" {
+ t.Errorf("Content-Type = %q, want application/octet-stream", got)
+ }
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal("attachment part not found")
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 1})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "x", "incoming", []string{tmp}, MessageOptions{})
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 1 {
+ t.Fatalf("id = %d, want 1", id)
+ }
+}
+
+func TestCreateMessage_AttachmentMissingFileFailsBeforeRequest(t *testing.T) {
+ // A missing local attachment must fail the send before Chatwoot receives a
+ // partial message without the file the operator expected to deliver.
+ missing := filepath.Join(t.TempDir(), "does-not-exist.png")
+
+ requests := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ t.Fatal("CreateMessage should not call Chatwoot when attachment open fails")
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ _, err := c.CreateMessage(5, "text only", "incoming", []string{missing}, MessageOptions{})
+ if err == nil {
+ t.Fatal("CreateMessage error = nil, want missing attachment error")
+ }
+ if requests != 0 {
+ t.Fatalf("requests = %d, want 0", requests)
+ }
+}
+
+func TestCreateMessage_AttachmentNon200(t *testing.T) {
+ tmp := filepath.Join(t.TempDir(), "a.oga")
+ if err := os.WriteFile(tmp, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write temp file: %v", err)
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(t, w, http.StatusServiceUnavailable, map[string]any{"error": "x"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "x", "incoming", []string{tmp}, MessageOptions{})
+ if id != 0 {
+ t.Fatalf("id = %d, want 0", id)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusServiceUnavailable || httpErr.Op != "create message with attachments" {
+ t.Errorf("err = %+v, want 503 'create message with attachments'", httpErr)
+ }
+}
+
+func TestCreateMessage_AttachmentMissingIDReturnsZero(t *testing.T) {
+ // As with the plain path, a 200 without a usable id yields (0, nil).
+ tmp := filepath.Join(t.TempDir(), "a.oga")
+ if err := os.WriteFile(tmp, []byte("x"), 0o600); err != nil {
+ t.Fatalf("write temp file: %v", err)
+ }
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(http.StatusOK)
+ _, _ = io.WriteString(w, `{}`)
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ id, err := c.CreateMessage(5, "x", "incoming", []string{tmp}, MessageOptions{})
+ if err != nil {
+ t.Fatalf("CreateMessage: %v", err)
+ }
+ if id != 0 {
+ t.Fatalf("id = %d, want 0", id)
+ }
+}
+
+// --- Echo dedup map (MarkMessageAsSent / IsMessageSentByUs) ----------------
+
+func TestEchoDedup_MapBehavior(t *testing.T) {
+ // MarkMessageAsSent(0) is a no-op and IsMessageSentByUs(0) is always
+ // false: id 0 is the "no id" sentinel returned by CreateMessage and must
+ // never be treated as a tracked message.
+ MarkMessageAsSent(0)
+ if IsMessageSentByUs(0) {
+ t.Error("IsMessageSentByUs(0) = true, want false")
+ }
+
+ // A real id, once marked, is recognized as ours. We use a large, fixed
+ // id unlikely to collide with anything (the map is package-global and
+ // shared, but this exact value is only touched here). IsMessageSentByUs
+ // does not delete on read, so it stays true on a second check — Chatwoot
+ // fires multiple webhook events for one message.
+ const id = 987654321
+ if IsMessageSentByUs(id) {
+ t.Fatalf("IsMessageSentByUs(%d) = true before marking, want false", id)
+ }
+ MarkMessageAsSent(id)
+ if !IsMessageSentByUs(id) {
+ t.Fatalf("IsMessageSentByUs(%d) = false after marking, want true", id)
+ }
+ if !IsMessageSentByUs(id) {
+ t.Fatalf("IsMessageSentByUs(%d) = false on second check, want true (no delete-on-read)", id)
+ }
+
+ // An id that was never marked is not ours.
+ if IsMessageSentByUs(123456789) {
+ t.Error("IsMessageSentByUs(unknown) = true, want false")
+ }
+}
diff --git a/src/infrastructure/chatwoot/client_reopen_test.go b/src/infrastructure/chatwoot/client_reopen_test.go
new file mode 100644
index 00000000..2a09ccac
--- /dev/null
+++ b/src/infrastructure/chatwoot/client_reopen_test.go
@@ -0,0 +1,249 @@
+package chatwoot
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// reopenCounters tallies the calls FindOrCreateConversation makes against the
+// fake Chatwoot server so each case can assert exactly which paths ran. Both
+// FindConversation and FindLatestConversation hit the same GET endpoint, so we
+// only distinguish create POSTs from toggle POSTs (the behaviorally meaningful
+// branches).
+type reopenCounters struct {
+ createCalls int
+ toggleCalls int
+ toggleBody string
+}
+
+// reopenServer builds an httptest server that serves the contact's
+// conversation list (for both Find and FindLatest), a toggle_status endpoint,
+// and a conversation-create endpoint, recording calls into the returned
+// counters. listPayload is the conversation list returned by the GET; toggleOK
+// controls whether toggle_status succeeds.
+func reopenServer(t *testing.T, listPayload []map[string]any, toggleOK bool, createID int) (*httptest.Server, *reopenCounters) {
+ t.Helper()
+ counters := &reopenCounters{}
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/7/conversations":
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": listPayload})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/conversations/20/toggle_status":
+ counters.toggleCalls++
+ var body map[string]string
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode toggle body: %v", err)
+ }
+ counters.toggleBody = body["status"]
+ if toggleOK {
+ w.WriteHeader(http.StatusOK)
+ } else {
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "toggle failed"})
+ }
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/conversations":
+ counters.createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": map[string]any{"id": createID}})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ return server, counters
+}
+
+func TestFindOrCreateConversation_ReopenReturnsOpenWithoutReopening(t *testing.T) {
+ // (a) When FindConversation finds an OPEN conversation, it is returned
+ // immediately: no FindLatest, no create, no toggle — even with reopen
+ // enabled. There is nothing to resurrect.
+ origReopen := config.ChatwootReopenConversation
+ config.ChatwootReopenConversation = true
+ defer func() { config.ChatwootReopenConversation = origReopen }()
+
+ server, counters := reopenServer(t, []map[string]any{
+ {"id": 12, "inbox_id": 2, "status": "open"},
+ }, true, 999)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 12 || conv.Status != "open" {
+ t.Fatalf("conv = %+v, want id 12 status open", conv)
+ }
+ if counters.toggleCalls != 0 {
+ t.Errorf("toggle calls = %d, want 0 (open conv needs no reopen)", counters.toggleCalls)
+ }
+ if counters.createCalls != 0 {
+ t.Errorf("create calls = %d, want 0 (found existing open conv)", counters.createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_ReopenResolvedTogglesOpen(t *testing.T) {
+ // (b) No OPEN conversation, but a RESOLVED one exists and reopen=true:
+ // FindLatestConversation returns the resolved conv, ToggleConversationStatus
+ // is called with "open", and the returned conv carries the UPDATED status.
+ // No new conversation is created.
+ origReopen := config.ChatwootReopenConversation
+ origPending := config.ChatwootConversationPending
+ config.ChatwootReopenConversation = true
+ config.ChatwootConversationPending = false
+ defer func() {
+ config.ChatwootReopenConversation = origReopen
+ config.ChatwootConversationPending = origPending
+ }()
+
+ server, counters := reopenServer(t, []map[string]any{
+ {"id": 20, "inbox_id": 2, "status": "resolved"},
+ }, true, 999)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 20 {
+ t.Fatalf("conv.ID = %d, want 20 (reopened, not newly created)", conv.ID)
+ }
+ if conv.Status != "open" {
+ t.Errorf("Status = %q, want open (updated after toggle)", conv.Status)
+ }
+ if counters.toggleCalls != 1 {
+ t.Errorf("toggle calls = %d, want 1", counters.toggleCalls)
+ }
+ if counters.toggleBody != "open" {
+ t.Errorf("toggle status = %q, want open", counters.toggleBody)
+ }
+ if counters.createCalls != 0 {
+ t.Errorf("create calls = %d, want 0", counters.createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_ReopenResolvedTogglesPendingWhenConfigured(t *testing.T) {
+ // (b') Same reopen path but with ConversationPending=true: the resolved
+ // conversation is toggled to "pending" instead of "open", routing the
+ // returning contact to the unassigned queue.
+ origReopen := config.ChatwootReopenConversation
+ origPending := config.ChatwootConversationPending
+ config.ChatwootReopenConversation = true
+ config.ChatwootConversationPending = true
+ defer func() {
+ config.ChatwootReopenConversation = origReopen
+ config.ChatwootConversationPending = origPending
+ }()
+
+ server, counters := reopenServer(t, []map[string]any{
+ {"id": 20, "inbox_id": 2, "status": "resolved"},
+ }, true, 999)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 20 || conv.Status != "pending" {
+ t.Fatalf("conv = %+v, want id 20 status pending", conv)
+ }
+ if counters.toggleBody != "pending" {
+ t.Errorf("toggle status = %q, want pending", counters.toggleBody)
+ }
+ if counters.createCalls != 0 {
+ t.Errorf("create calls = %d, want 0", counters.createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_ReopenNoConversationFallsThroughToCreate(t *testing.T) {
+ // (c) reopen=true but the contact has NO conversation at all in our inbox:
+ // FindLatestConversation returns nil, so the method falls through to
+ // CreateConversation. No toggle happens.
+ origReopen := config.ChatwootReopenConversation
+ config.ChatwootReopenConversation = true
+ defer func() { config.ChatwootReopenConversation = origReopen }()
+
+ server, counters := reopenServer(t, []map[string]any{}, true, 700)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 700 {
+ t.Fatalf("conv.ID = %d, want 700 (created)", conv.ID)
+ }
+ if counters.toggleCalls != 0 {
+ t.Errorf("toggle calls = %d, want 0", counters.toggleCalls)
+ }
+ if counters.createCalls != 1 {
+ t.Errorf("create calls = %d, want 1", counters.createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_ReopenDisabledSkipsLatestAndToggles(t *testing.T) {
+ // (d) reopen=false: even though a resolved conversation exists for the
+ // contact, the reopen branch is skipped entirely — FindLatest is never
+ // consulted and no toggle happens. With no OPEN conversation found, the
+ // method goes straight to creating a new one.
+ origReopen := config.ChatwootReopenConversation
+ config.ChatwootReopenConversation = false
+ defer func() { config.ChatwootReopenConversation = origReopen }()
+
+ server, counters := reopenServer(t, []map[string]any{
+ {"id": 20, "inbox_id": 2, "status": "resolved"},
+ }, true, 701)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation: %v", err)
+ }
+ if conv.ID != 701 {
+ t.Fatalf("conv.ID = %d, want 701 (created, reopen disabled)", conv.ID)
+ }
+ if counters.toggleCalls != 0 {
+ t.Errorf("toggle calls = %d, want 0 (reopen disabled)", counters.toggleCalls)
+ }
+ if counters.createCalls != 1 {
+ t.Errorf("create calls = %d, want 1", counters.createCalls)
+ }
+}
+
+func TestFindOrCreateConversation_ReopenToggleFailureStillReturnsLatest(t *testing.T) {
+ // (e) When ToggleConversationStatus fails, the error is logged but NOT
+ // propagated: the method still returns the latest conversation (no error),
+ // so a transient toggle failure never blocks message delivery. Because the
+ // toggle failed, the returned status keeps its original "resolved" value.
+ origReopen := config.ChatwootReopenConversation
+ config.ChatwootReopenConversation = true
+ defer func() { config.ChatwootReopenConversation = origReopen }()
+
+ server, counters := reopenServer(t, []map[string]any{
+ {"id": 20, "inbox_id": 2, "status": "resolved"},
+ }, false, 999)
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ conv, err := c.FindOrCreateConversation(7, "")
+ if err != nil {
+ t.Fatalf("FindOrCreateConversation should swallow toggle error, got: %v", err)
+ }
+ if conv.ID != 20 {
+ t.Fatalf("conv.ID = %d, want 20 (latest returned despite toggle failure)", conv.ID)
+ }
+ if conv.Status != "resolved" {
+ t.Errorf("Status = %q, want resolved (unchanged because toggle failed)", conv.Status)
+ }
+ if counters.toggleCalls != 1 {
+ t.Errorf("toggle calls = %d, want 1 (attempted once)", counters.toggleCalls)
+ }
+ if counters.createCalls != 0 {
+ t.Errorf("create calls = %d, want 0 (latest still returned, not created)", counters.createCalls)
+ }
+}
diff --git a/src/infrastructure/chatwoot/client_test.go b/src/infrastructure/chatwoot/client_test.go
new file mode 100644
index 00000000..22b90206
--- /dev/null
+++ b/src/infrastructure/chatwoot/client_test.go
@@ -0,0 +1,184 @@
+package chatwoot
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestFindOrCreateContact_PreservesExistingIndividualName(t *testing.T) {
+ tests := []struct {
+ name string
+ incomingName string
+ }{
+ {
+ name: "incoming WhatsApp name differs",
+ incomingName: "Alice WA",
+ },
+ {
+ name: "incoming name is phone fallback",
+ incomingName: "6281234567890",
+ },
+ {
+ name: "incoming name is empty",
+ incomingName: "",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ putCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/search":
+ if got := r.URL.Query().Get("q"); got != "+6281234567890" {
+ t.Fatalf("search q = %q, want +6281234567890", got)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{
+ ID: 123,
+ Name: "Manual Alice",
+ PhoneNumber: "+6281234567890",
+ }},
+ })
+ case r.Method == http.MethodPut && r.URL.Path == "/api/v1/accounts/1/contacts/123":
+ putCalls++
+ w.WriteHeader(http.StatusNoContent)
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }
+
+ contact, err := client.FindOrCreateContact(tc.incomingName, "6281234567890", false)
+ if err != nil {
+ t.Fatalf("FindOrCreateContact: %v", err)
+ }
+ if contact.Name != "Manual Alice" {
+ t.Fatalf("contact name = %q, want Manual Alice", contact.Name)
+ }
+ if putCalls != 0 {
+ t.Fatalf("PUT contact calls = %d, want 0", putCalls)
+ }
+ })
+ }
+}
+
+func TestFindOrCreateContact_FillsBlankExistingIndividualName(t *testing.T) {
+ putCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/search":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{
+ ID: 123,
+ Name: "",
+ PhoneNumber: "+6281234567890",
+ }},
+ })
+ case r.Method == http.MethodPut && r.URL.Path == "/api/v1/accounts/1/contacts/123":
+ putCalls++
+ var body map[string]string
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode PUT body: %v", err)
+ }
+ if body["name"] != "6281234567890" {
+ t.Fatalf("PUT name = %q, want 6281234567890", body["name"])
+ }
+ w.WriteHeader(http.StatusNoContent)
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }
+
+ contact, err := client.FindOrCreateContact("6281234567890", "6281234567890", false)
+ if err != nil {
+ t.Fatalf("FindOrCreateContact: %v", err)
+ }
+ if contact.Name != "6281234567890" {
+ t.Fatalf("contact name = %q, want 6281234567890", contact.Name)
+ }
+ if putCalls != 1 {
+ t.Fatalf("PUT contact calls = %d, want 1", putCalls)
+ }
+}
+
+func TestFindOrCreateContact_RefreshesExistingGroupName(t *testing.T) {
+ const groupJID = "[email protected]"
+ putCalls := 0
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/contacts/search":
+ if got := r.URL.Query().Get("q"); got != groupJID {
+ t.Fatalf("search q = %q, want %s", got, groupJID)
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Contact{{
+ ID: 456,
+ Name: "Old Group",
+ Identifier: groupJID,
+ }},
+ })
+ case r.Method == http.MethodPut && r.URL.Path == "/api/v1/accounts/1/contacts/456":
+ putCalls++
+ var body map[string]string
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode PUT body: %v", err)
+ }
+ if body["name"] != "New Group" {
+ t.Fatalf("PUT name = %q, want New Group", body["name"])
+ }
+ w.WriteHeader(http.StatusNoContent)
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ client := &Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }
+
+ contact, err := client.FindOrCreateContact("New Group", groupJID, true)
+ if err != nil {
+ t.Fatalf("FindOrCreateContact: %v", err)
+ }
+ if contact.Name != "New Group" {
+ t.Fatalf("contact name = %q, want New Group", contact.Name)
+ }
+ if putCalls != 1 {
+ t.Fatalf("PUT contact calls = %d, want 1", putCalls)
+ }
+}
+
+func writeJSON(t *testing.T, w http.ResponseWriter, status int, body any) {
+ t.Helper()
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ if err := json.NewEncoder(w).Encode(body); err != nil {
+ t.Fatalf("write JSON: %v", err)
+ }
+}
diff --git a/src/infrastructure/chatwoot/pgimport/AGENTS.md b/src/infrastructure/chatwoot/pgimport/AGENTS.md
new file mode 100644
index 00000000..95a64c17
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/AGENTS.md
@@ -0,0 +1,50 @@
+# CHATWOOT PGIMPORT
+
+Generated: 2026-06-06
+
+## OVERVIEW
+
+`pgimport` writes historical WhatsApp messages directly into Chatwoot's Postgres schema. It is not the live REST forwarding path.
+
+## STRUCTURE
+
+```text
+pgimport/
+|-- conn.go # DB connection, schema/account/inbox verification, importer lifecycle
+|-- identity.go # Chat/contact identity helpers and message type/content rules
+`-- writer.go # ImportChat transaction, contact/conversation/message writes, links
+```
+
+## WHERE TO LOOK
+
+| Task | Location | Notes |
+|------|----------|-------|
+| Open importer | `conn.go` | Verifies required Chatwoot tables plus configured account/inbox. |
+| Import a chat | `writer.go` `ImportChat` | Transaction with contact, contact_inbox, conversation, message loop, links. |
+| Contact identity | `identity.go`, `writer.go` `upsertContact` | Private chats use phone fallback; groups and `@lid` JIDs use identifiers. |
+| Conversation behavior | `writer.go` `findOrCreateConversation` | Reuses latest conversation and mirrors pending/reopen config. |
+| Message idempotency | `writer.go` `insertMessage` | Probe by `inbox_id` and `source_id` before insert. |
+| Content mapping | `identity.go`, `writer.go` `buildContent` | Group incoming messages get sender prefix; media placeholder behavior is configurable. |
+| Tests | `*_test.go` | sqlmock-heavy unit and flow coverage; update expected SQL with schema changes. |
+
+## CONVENTIONS
+
+- Use `source_id = WAID:<whatsapp_message_id>` for imported Chatwoot messages.
+- Preserve WhatsApp timestamps in message rows and anchor new conversations to the first valid message time.
+- Existing individual contact names are preserved; group names may refresh from the latest subject.
+- Per-message failures use savepoints so one bad row can be counted without rolling back the whole import.
+- Direct DB import inserts metadata/content only; REST attachment upload is orchestrated from parent `sync.go` when enabled.
+- `Importer.Close()` is idempotent and is reached through `SyncService.Close()` on REST shutdown.
+
+## ANTI-PATTERNS
+
+- Do not use this package for live Chatwoot forwarding.
+- Do not key idempotency only by conversation; resolved/reopened conversations can move rows.
+- Do not overwrite existing one-to-one contact names when attaching a WhatsApp JID.
+- Do not insert blank Chatwoot messages when both content and media placeholder are empty.
+- Do not bypass account/inbox verification when opening a direct database connection.
+
+## TESTING
+
+- Keep sqlmock expectations close to the SQL shape; broad regexes hide schema regressions.
+- Add focused unit tests for identity/content helpers before changing import flow tests.
diff --git a/src/infrastructure/chatwoot/pgimport/conn.go b/src/infrastructure/chatwoot/pgimport/conn.go
new file mode 100644
index 00000000..cdd47fc1
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/conn.go
@@ -0,0 +1,238 @@
+// Package pgimport implements the direct-Postgres history importer for
+// Chatwoot. Instead of relaying historical WhatsApp messages through
+// Chatwoot's public REST API (which stamps server time on every message),
+// it INSERTs directly into Chatwoot's Rails schema so that `created_at`,
+// sender identity, and group metadata are preserved faithfully.
+//
+// Only the historical-sync path uses this package. Live message forwarding
+// and the Chatwoot → WhatsApp reply path continue to use the REST client
+// in the parent package, so Chatwoot's normal event pipeline (assignment
+// rules, automations, webhooks, agent UI sockets) keeps firing on inbound
+// traffic exactly as before.
+//
+// The package is opt-in via config.ChatwootImportDBURI. When unset, the
+// parent SyncService uses the REST importer and behavior is identical to
+// earlier releases. When set, a broken DB connection is treated as a sync
+// failure instead of falling back silently.
+package pgimport
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ _ "github.com/lib/pq"
+ "github.com/sirupsen/logrus"
+)
+
+// Importer owns a pooled Postgres connection to the Chatwoot database and
+// the account/inbox identifiers that every INSERT is scoped to.
+//
+// An Importer is safe for concurrent use. The underlying *sql.DB has its
+// own connection pool; callers should re-use a single Importer per process.
+type Importer struct {
+ db *sql.DB
+ accountID int
+ inboxID int
+
+ // schemaVersion is the latest Chatwoot Rails migration version observed
+ // on startup. Stored for diagnostics only; writes do not gate on it.
+ schemaVersion string
+
+ // agentUserType / agentUserID identify the Chatwoot user that owns the
+ // configured API token. Used to stamp outgoing imported messages so they
+ // render with the agent's name and avatar in the agent UI instead of as
+ // "Unknown sender". Resolved best-effort from access_tokens at startup;
+ // when unset (token absent or table unreachable), outgoing messages fall
+ // back to NULL sender — the row still imports, just without attribution.
+ agentUserType string
+ agentUserID int64
+
+ once sync.Once
+ closed atomic.Bool
+}
+
+// Config is the minimal input required to open an Importer.
+type Config struct {
+ // DSN is a libpq connection string, e.g.
+ // postgresql://postgres:secret@chatwoot-db:5432/chatwoot_production?sslmode=disable
+ DSN string
+
+ // AccountID and InboxID must match the Chatwoot account and inbox that
+ // the parent REST client (client.go) is configured against. The
+ // importer refuses to open if either is zero.
+ AccountID int
+ InboxID int
+
+ // APIToken is the Chatwoot REST API token (same one the parent REST
+ // client uses). Optional — when present, the importer resolves the
+ // owning Chatwoot user from `access_tokens` so outgoing imported
+ // messages can be stamped with that agent (sender_type='User',
+ // sender_id=<user_id>). Without it, outgoing rows are written with NULL
+ // sender, which Chatwoot displays as "Unknown sender".
+ APIToken string
+}
+
+// New opens a Postgres pool to the Chatwoot database and verifies that the
+// tables the importer writes to actually exist. It does *not* check the
+// migration version range: the same write pattern has held across
+// Chatwoot 2.x → 4.x, and additive schema changes should keep
+// working. If the schema has diverged in a way we can't write against, the
+// error surfaces on the first INSERT.
+func New(ctx context.Context, cfg Config) (*Importer, error) {
+ if cfg.DSN == "" {
+ return nil, fmt.Errorf("pgimport: empty DSN")
+ }
+ if cfg.AccountID == 0 || cfg.InboxID == 0 {
+ return nil, fmt.Errorf("pgimport: AccountID and InboxID must be non-zero")
+ }
+
+ db, err := sql.Open("postgres", cfg.DSN)
+ if err != nil {
+ return nil, fmt.Errorf("pgimport: open: %w", err)
+ }
+
+ db.SetMaxOpenConns(8)
+ db.SetConnMaxLifetime(30 * time.Minute)
+
+ pingCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ if err := db.PingContext(pingCtx); err != nil {
+ _ = db.Close()
+ return nil, fmt.Errorf("pgimport: ping: %w", err)
+ }
+
+ imp := &Importer{
+ db: db,
+ accountID: cfg.AccountID,
+ inboxID: cfg.InboxID,
+ }
+
+ if err := imp.verifyTables(ctx); err != nil {
+ _ = db.Close()
+ return nil, err
+ }
+ imp.schemaVersion = imp.readSchemaVersion(ctx)
+ if err := imp.verifyAccountInbox(ctx); err != nil {
+ _ = db.Close()
+ return nil, err
+ }
+ imp.resolveAgent(ctx, cfg.APIToken)
+
+ logrus.Infof("Chatwoot pgimport: connected (account=%d inbox=%d schema_version=%s agent=%s/%d)",
+ imp.accountID, imp.inboxID, imp.schemaVersion, imp.agentUserType, imp.agentUserID)
+ return imp, nil
+}
+
+// Close releases the underlying pool. Safe to call more than once.
+func (i *Importer) Close() error {
+ var err error
+ i.once.Do(func() {
+ i.closed.Store(true)
+ err = i.db.Close()
+ })
+ return err
+}
+
+// verifyTables confirms that every table the writer touches exists and is
+// reachable. We fail fast here rather than halfway through an import.
+func (i *Importer) verifyTables(ctx context.Context) error {
+ required := []string{
+ "accounts",
+ "inboxes",
+ "contacts",
+ "contact_inboxes",
+ "conversations",
+ "messages",
+ }
+ for _, name := range required {
+ var exists bool
+ err := i.db.QueryRowContext(ctx, `
+ SELECT EXISTS (
+ SELECT 1 FROM information_schema.tables
+ WHERE table_schema = current_schema()
+ AND table_name = $1
+ )`, name).Scan(&exists)
+ if err != nil {
+ return fmt.Errorf("pgimport: verify table %q: %w", name, err)
+ }
+ if !exists {
+ return fmt.Errorf("pgimport: required Chatwoot table %q not found; is CHATWOOT_IMPORT_DB_URI pointing at the right database?", name)
+ }
+ }
+ return nil
+}
+
+// verifyAccountInbox confirms the configured (account, inbox) pair exists
+// before any import writes start. The direct importer writes every row with
+// these IDs, so a mismatch is configuration failure and should not degrade
+// into later per-row insert errors.
+func (i *Importer) verifyAccountInbox(ctx context.Context) error {
+ var ok bool
+ err := i.db.QueryRowContext(ctx, `
+ SELECT EXISTS (
+ SELECT 1 FROM inboxes
+ WHERE id = $1 AND account_id = $2
+ )`, i.inboxID, i.accountID).Scan(&ok)
+ if err != nil {
+ return fmt.Errorf("pgimport: verify inbox=%d account=%d: %w", i.inboxID, i.accountID, err)
+ }
+ if !ok {
+ return fmt.Errorf("pgimport: inbox=%d not found under account=%d", i.inboxID, i.accountID)
+ }
+ return nil
+}
+
+// resolveAgent looks up the Chatwoot user that owns the given API token in
+// the access_tokens table. The result is cached on the Importer and used
+// to stamp outgoing imported messages (sender_type='User', sender_id=<id>)
+// so they render with the agent's name and avatar in Chatwoot's UI.
+//
+// Best-effort: if the token is empty, the row is missing, or the query
+// fails, the importer leaves agentUserType/agentUserID zero-valued and
+// outgoing messages fall back to NULL sender.
+func (i *Importer) resolveAgent(ctx context.Context, apiToken string) {
+ if apiToken == "" {
+ logrus.Warnf("Chatwoot pgimport: no API token configured; outgoing imported messages will have NULL sender")
+ return
+ }
+ var ownerType sql.NullString
+ var ownerID sql.NullInt64
+ err := i.db.QueryRowContext(ctx, `
+ SELECT owner_type, owner_id
+ FROM access_tokens
+ WHERE token = $1
+ LIMIT 1
+ `, apiToken).Scan(&ownerType, &ownerID)
+ if err != nil {
+ // sql.ErrNoRows or any other error — non-fatal, just degrade attribution.
+ logrus.Warnf("Chatwoot pgimport: agent lookup from access_tokens failed (outgoing messages will have NULL sender): %v", err)
+ return
+ }
+ if !ownerType.Valid || !ownerID.Valid || ownerID.Int64 == 0 {
+ logrus.Warnf("Chatwoot pgimport: access_tokens row has empty owner; outgoing messages will have NULL sender")
+ return
+ }
+ i.agentUserType = ownerType.String
+ i.agentUserID = ownerID.Int64
+}
+
+// readSchemaVersion returns the latest row from schema_migrations. It is
+// purely informational — if the table is unreachable we return an empty
+// string and continue.
+func (i *Importer) readSchemaVersion(ctx context.Context) string {
+ var v sql.NullString
+ err := i.db.QueryRowContext(ctx, `
+ SELECT version
+ FROM schema_migrations
+ ORDER BY version DESC
+ LIMIT 1
+ `).Scan(&v)
+ if err != nil {
+ return ""
+ }
+ return v.String
+}
diff --git a/src/infrastructure/chatwoot/pgimport/conn_test.go b/src/infrastructure/chatwoot/pgimport/conn_test.go
new file mode 100644
index 00000000..9d767902
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/conn_test.go
@@ -0,0 +1,192 @@
+package pgimport
+
+import (
+ "context"
+ "database/sql"
+ "errors"
+ "testing"
+
+ "github.com/DATA-DOG/go-sqlmock"
+)
+
+// newTestImporter wires a freshly-mocked *sql.DB into a bare Importer so the
+// caller can drive both arrange/assert sides of a sqlmock conversation
+// against unit-level methods (resolveAgent, insertMessage, ...) without
+// going through the New() startup checks.
+func newTestImporter(t *testing.T) (*Importer, sqlmock.Sqlmock, func()) {
+ t.Helper()
+ db, mock, err := sqlmock.New(sqlmock.QueryMatcherOption(sqlmock.QueryMatcherEqual))
+ if err != nil {
+ t.Fatalf("sqlmock.New: %v", err)
+ }
+ imp := &Importer{
+ db: db,
+ accountID: 1,
+ inboxID: 2,
+ }
+ return imp, mock, func() { _ = db.Close() }
+}
+
+// resolveAgentSQL is the single source of truth for what we expect
+// resolveAgent to send to Postgres. Keeping it separate from the test bodies
+// makes it obvious if an unrelated edit perturbs the query — the tests will
+// fail on QueryMatcherEqual rather than silently exercising the wrong SQL.
+const resolveAgentSQL = `
+ SELECT owner_type, owner_id
+ FROM access_tokens
+ WHERE token = $1
+ LIMIT 1
+ `
+
+const verifyAccountInboxSQL = `
+ SELECT EXISTS (
+ SELECT 1 FROM inboxes
+ WHERE id = $1 AND account_id = $2
+ )`
+
+func TestVerifyAccountInbox_Found(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ rows := sqlmock.NewRows([]string{"exists"}).AddRow(true)
+ mock.ExpectQuery(verifyAccountInboxSQL).WithArgs(imp.inboxID, imp.accountID).WillReturnRows(rows)
+
+ if err := imp.verifyAccountInbox(context.Background()); err != nil {
+ t.Fatalf("verifyAccountInbox: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestVerifyAccountInbox_MissingFails(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ rows := sqlmock.NewRows([]string{"exists"}).AddRow(false)
+ mock.ExpectQuery(verifyAccountInboxSQL).WithArgs(imp.inboxID, imp.accountID).WillReturnRows(rows)
+
+ err := imp.verifyAccountInbox(context.Background())
+ if err == nil {
+ t.Fatal("verifyAccountInbox error = nil, want missing inbox error")
+ }
+ if got, want := err.Error(), "pgimport: inbox=2 not found under account=1"; got != want {
+ t.Errorf("error = %q, want %q", got, want)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestVerifyAccountInbox_QueryErrorFails(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ queryErr := errors.New("permission denied")
+ mock.ExpectQuery(verifyAccountInboxSQL).WithArgs(imp.inboxID, imp.accountID).WillReturnError(queryErr)
+
+ err := imp.verifyAccountInbox(context.Background())
+ if !errors.Is(err, queryErr) {
+ t.Fatalf("verifyAccountInbox error = %v, want wrapping permission denied", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestResolveAgent_FoundUserSetsFields(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ rows := sqlmock.NewRows([]string{"owner_type", "owner_id"}).AddRow("User", int64(42))
+ mock.ExpectQuery(resolveAgentSQL).WithArgs("token-123").WillReturnRows(rows)
+
+ imp.resolveAgent(context.Background(), "token-123")
+
+ if got := imp.agentUserType; got != "User" {
+ t.Errorf("agentUserType = %q, want %q", got, "User")
+ }
+ if got := imp.agentUserID; got != 42 {
+ t.Errorf("agentUserID = %d, want %d", got, 42)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestResolveAgent_FoundAgentBotSetsFields(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ rows := sqlmock.NewRows([]string{"owner_type", "owner_id"}).AddRow("AgentBot", int64(7))
+ mock.ExpectQuery(resolveAgentSQL).WithArgs("bot-token").WillReturnRows(rows)
+
+ imp.resolveAgent(context.Background(), "bot-token")
+
+ if got := imp.agentUserType; got != "AgentBot" {
+ t.Errorf("agentUserType = %q, want AgentBot", got)
+ }
+ if got := imp.agentUserID; got != 7 {
+ t.Errorf("agentUserID = %d, want 7", got)
+ }
+}
+
+func TestResolveAgent_EmptyTokenSkipsQuery(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ // No expectations registered: any DB query would fail the test, proving
+ // resolveAgent returns early and never reaches the connection.
+ imp.resolveAgent(context.Background(), "")
+
+ if imp.agentUserType != "" || imp.agentUserID != 0 {
+ t.Errorf("expected agent fields zero, got type=%q id=%d", imp.agentUserType, imp.agentUserID)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestResolveAgent_NotFoundLeavesFieldsZero(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectQuery(resolveAgentSQL).WithArgs("missing").WillReturnError(sql.ErrNoRows)
+
+ imp.resolveAgent(context.Background(), "missing")
+
+ if imp.agentUserType != "" || imp.agentUserID != 0 {
+ t.Errorf("expected zero fields on missing agent, got type=%q id=%d", imp.agentUserType, imp.agentUserID)
+ }
+}
+
+func TestResolveAgent_QueryErrorLeavesFieldsZero(t *testing.T) {
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectQuery(resolveAgentSQL).WithArgs("any").WillReturnError(errors.New("boom"))
+
+ imp.resolveAgent(context.Background(), "any")
+
+ if imp.agentUserType != "" || imp.agentUserID != 0 {
+ t.Errorf("expected zero fields on query error, got type=%q id=%d", imp.agentUserType, imp.agentUserID)
+ }
+}
+
+func TestResolveAgent_NullOwnerLeavesFieldsZero(t *testing.T) {
+ // Defensive against a malformed access_tokens row: NULL owner_type or
+ // owner_id must NOT silently pass through as agentUserType="" and
+ // agentUserID=0 while passing the !ownerID.Valid check, otherwise we'd
+ // stamp NULL on outgoing messages anyway and waste a DB round-trip.
+ imp, mock, cleanup := newTestImporter(t)
+ defer cleanup()
+
+ rows := sqlmock.NewRows([]string{"owner_type", "owner_id"}).AddRow(nil, nil)
+ mock.ExpectQuery(resolveAgentSQL).WithArgs("nullrow").WillReturnRows(rows)
+
+ imp.resolveAgent(context.Background(), "nullrow")
+
+ if imp.agentUserType != "" || imp.agentUserID != 0 {
+ t.Errorf("expected zero fields on NULL owner row, got type=%q id=%d", imp.agentUserType, imp.agentUserID)
+ }
+}
diff --git a/src/infrastructure/chatwoot/pgimport/identity.go b/src/infrastructure/chatwoot/pgimport/identity.go
new file mode 100644
index 00000000..f6f521fa
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/identity.go
@@ -0,0 +1,81 @@
+package pgimport
+
+import (
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+)
+
+// Chatwoot enum values. These have been stable across Chatwoot 2.x → 4.x;
+// they come from the Rails models `Message.message_types`, `Message.statuses`,
+// `Message.content_types`, and `Conversation.statuses`.
+//
+// If a future Chatwoot release renumbers these, only this file needs to
+// change — every writer function reads the constants from here.
+const (
+ // message_type enum
+ messageTypeIncoming = 0
+ messageTypeOutgoing = 1
+ // (activity = 2, template = 3 — unused by the importer)
+
+ // message status enum (sent = 0, read = 2, failed = 3 — unused: incoming WA
+ // history carries no read receipts, so every imported row is "delivered")
+ messageStatusDelivered = 1
+
+ // content_type enum — we only ever write plain text
+ contentTypeText = 0
+
+ // conversation status enum
+ conversationStatusOpen = 0
+ conversationStatusResolved = 1
+ conversationStatusPending = 2
+ // snoozed = 3 (unused by the importer)
+
+ // Rails single-table-inheritance values on messages.sender_type
+ senderTypeContact = "Contact"
+)
+
+// isGroupJID returns true if the WhatsApp JID represents a group chat.
+// Mirrors the check used throughout sync.go so the two paths agree.
+func isGroupJID(jid string) bool {
+ return strings.HasSuffix(jid, "@g.us")
+}
+
+// isLidJID returns true for the privacy-preserving @lid identifiers that
+// WhatsApp now uses for some groups and channels. These are not phone
+// numbers and must not be normalized to E.164.
+func isLidJID(jid string) bool {
+ return strings.HasSuffix(jid, "@lid")
+}
+
+// contactIdentity computes the (phone_number, identifier, display_name)
+// triple that the importer writes to Chatwoot's `contacts` table.
+//
+// This matches the behavior of the REST client in the parent package
+// (client.go:CreateContact) so that contacts created by the live path and
+// contacts created by the importer resolve to the same row on lookup by
+// `custom_attributes.gowa_whatsapp_jid`.
+func contactIdentity(jid, fallbackName string) (phoneNumber, identifier, name string) {
+ name = strings.TrimSpace(fallbackName)
+ if name == "" {
+ name = utils.ExtractPhoneFromJID(jid)
+ }
+
+ // Groups and @lid JIDs have no phone number — store JID as identifier.
+ if isGroupJID(jid) || isLidJID(jid) {
+ return "", jid, name
+ }
+
+ // 1:1 chat: phone number in E.164, no Rails identifier.
+ return utils.NormalizePhoneE164(jid), "", name
+}
+
+// messageTypeForWA returns the Chatwoot message_type enum for a WhatsApp
+// message based on its direction. IsFromMe ⇒ outgoing (agent side in
+// Chatwoot), otherwise incoming (customer side).
+func messageTypeForWA(isFromMe bool) int {
+ if isFromMe {
+ return messageTypeOutgoing
+ }
+ return messageTypeIncoming
+}
diff --git a/src/infrastructure/chatwoot/pgimport/identity_test.go b/src/infrastructure/chatwoot/pgimport/identity_test.go
new file mode 100644
index 00000000..3ce5b642
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/identity_test.go
@@ -0,0 +1,134 @@
+package pgimport
+
+import (
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+func TestIsGroupJID(t *testing.T) {
+ tests := []struct {
+ jid string
+ want bool
+ }{
+ {"[email protected]", false},
+ {"[email protected]", true},
+ {"foo@lid", false},
+ {"status@broadcast", false},
+ }
+ for _, tt := range tests {
+ if got := isGroupJID(tt.jid); got != tt.want {
+ t.Errorf("isGroupJID(%q) = %v, want %v", tt.jid, got, tt.want)
+ }
+ }
+}
+
+func TestIsLidJID(t *testing.T) {
+ if !isLidJID("abc@lid") {
+ t.Error("expected @lid to be true")
+ }
+ if isLidJID("[email protected]") {
+ t.Error("expected s.whatsapp.net to be false")
+ }
+}
+
+func TestContactIdentity_IndividualChat(t *testing.T) {
+ phone, identifier, name := contactIdentity("[email protected]", "Alice")
+ if phone == "" {
+ t.Errorf("expected phone to be normalized, got empty")
+ }
+ if identifier != "" {
+ t.Errorf("expected empty identifier for 1:1 chat, got %q", identifier)
+ }
+ if name != "Alice" {
+ t.Errorf("expected name 'Alice', got %q", name)
+ }
+}
+
+func TestContactIdentity_Group(t *testing.T) {
+ phone, identifier, name := contactIdentity(jid, "Project Team")
+ if phone != "" {
+ t.Errorf("expected empty phone for group, got %q", phone)
+ }
+ if identifier != jid {
+ t.Errorf("expected identifier == jid for group, got %q", identifier)
+ }
+ if name != "Project Team" {
+ t.Errorf("expected name 'Project Team', got %q", name)
+ }
+}
+
+func TestContactIdentity_Lid(t *testing.T) {
+ jid := "987654321@lid"
+ phone, identifier, _ := contactIdentity(jid, "Masked User")
+ if phone != "" {
+ t.Errorf("expected empty phone for @lid, got %q", phone)
+ }
+ if identifier != jid {
+ t.Errorf("expected identifier == jid for @lid, got %q", identifier)
+ }
+}
+
+func TestContactIdentity_FallbackName(t *testing.T) {
+ _, _, name := contactIdentity("[email protected]", "")
+ if name == "" {
+ t.Error("expected fallback name derived from JID, got empty")
+ }
+}
+
+func TestMessageTypeForWA(t *testing.T) {
+ if messageTypeForWA(true) != messageTypeOutgoing {
+ t.Errorf("expected outgoing for IsFromMe=true")
+ }
+ if messageTypeForWA(false) != messageTypeIncoming {
+ t.Errorf("expected incoming for IsFromMe=false")
+ }
+}
+
+func TestBuildContent_PlainText(t *testing.T) {
+ msg := &domainChatStorage.Message{Content: "hello world"}
+ got := buildContent(msg, false)
+ if got != "hello world" {
+ t.Errorf("expected 'hello world', got %q", got)
+ }
+}
+
+func TestBuildContent_NoDateStampingInBody(t *testing.T) {
+ // Regression guard for issue #580: unlike the REST path, the direct-DB
+ // importer must NOT prepend a "[YYYY-MM-DD HH:MM]" marker to the body,
+ // because Chatwoot's own created_at column now holds the real timestamp.
+ msg := &domainChatStorage.Message{Content: "hello"}
+ got := buildContent(msg, false)
+ if got != "hello" {
+ t.Errorf("expected raw body 'hello', got %q", got)
+ }
+}
+
+func TestBuildContent_GroupPrefix(t *testing.T) {
+ msg := &domainChatStorage.Message{
+ Content: "morning!",
+ Sender: "[email protected]",
+ }
+ got := buildContent(msg, true)
+ if got != "6281234567890: morning!" {
+ t.Errorf("unexpected group body: %q", got)
+ }
+}
+
+func TestBuildContent_MediaPlaceholder(t *testing.T) {
+ prev := config.ChatwootImportPlaceholderMediaMessage
+ defer func() { config.ChatwootImportPlaceholderMediaMessage = prev }()
+
+ config.ChatwootImportPlaceholderMediaMessage = true
+ msg := &domainChatStorage.Message{MediaType: "image"}
+ if got := buildContent(msg, false); got != "[image]" {
+ t.Errorf("expected '[image]' placeholder, got %q", got)
+ }
+
+ config.ChatwootImportPlaceholderMediaMessage = false
+ if got := buildContent(msg, false); got != "" {
+ t.Errorf("expected empty body when placeholder disabled, got %q", got)
+ }
+}
diff --git a/src/infrastructure/chatwoot/pgimport/upsert_contact_test.go b/src/infrastructure/chatwoot/pgimport/upsert_contact_test.go
new file mode 100644
index 00000000..a15dad99
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/upsert_contact_test.go
@@ -0,0 +1,100 @@
+package pgimport
+
+import (
+ "context"
+ "regexp"
+ "testing"
+
+ "github.com/DATA-DOG/go-sqlmock"
+)
+
+func TestUpsertContact_PreservesExistingIndividualName(t *testing.T) {
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ mock.ExpectRollback()
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContact(context.Background(), tx, jid, "Alice WA", false)
+ if err != nil {
+ t.Fatalf("upsertContact: %v", err)
+ }
+ if id != 200 {
+ t.Fatalf("contact id = %d, want 200", id)
+ }
+ if err := tx.Rollback(); err != nil {
+ t.Fatalf("Rollback: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatalf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContact_RefreshesExistingGroupName(t *testing.T) {
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const groupJID = "[email protected]"
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, groupJID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(300))
+ mock.ExpectExec(regexp.QuoteMeta(refreshContactNameSQL)).
+ WithArgs("New Group", 300, imp.accountID).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+ mock.ExpectRollback()
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContact(context.Background(), tx, groupJID, "New Group", true)
+ if err != nil {
+ t.Fatalf("upsertContact: %v", err)
+ }
+ if id != 300 {
+ t.Fatalf("contact id = %d, want 300", id)
+ }
+ if err := tx.Rollback(); err != nil {
+ t.Fatalf("Rollback: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Fatalf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func newUpsertContactTestImporter(t *testing.T) (*Importer, sqlmock.Sqlmock, func()) {
+ t.Helper()
+ db, mock, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("sqlmock.New: %v", err)
+ }
+ imp := &Importer{
+ db: db,
+ accountID: 1,
+ inboxID: 2,
+ }
+ return imp, mock, func() { _ = db.Close() }
+}
+
+const upsertContactByJIDSQL = `
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1
+ AND (custom_attributes->>'gowa_whatsapp_jid') = $2
+ LIMIT 1
+ `
+
+const refreshContactNameSQL = `
+ UPDATE contacts
+ SET name = $1, updated_at = now()
+ WHERE id = $2 AND account_id = $3 AND (name IS DISTINCT FROM $1)
+ `
diff --git a/src/infrastructure/chatwoot/pgimport/writer.go b/src/infrastructure/chatwoot/pgimport/writer.go
new file mode 100644
index 00000000..ee65ca23
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/writer.go
@@ -0,0 +1,606 @@
+package pgimport
+
+import (
+ "context"
+ "database/sql"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/sirupsen/logrus"
+)
+
+// txFatalError signals that the database transaction is in an unrecoverable
+// state (e.g. connection lost, SAVEPOINT creation failed). The message loop
+// in ImportChat checks for this to abort early instead of churning through
+// remaining messages that will all fail.
+type txFatalError struct{ cause error }
+
+func (e txFatalError) Error() string { return e.cause.Error() }
+func (e txFatalError) Unwrap() error { return e.cause }
+
+// ImportChatRequest carries everything the importer needs to write one
+// WhatsApp chat's worth of history into Chatwoot. The caller is
+// responsible for:
+//
+// - resolving `ChatName` to a real display name (group subject, push
+// name, or fallback phone) BEFORE calling; the importer will not
+// look names up. This is deliberate — the SyncService already has a
+// whatsmeow client handy, and routing GetGroupInfo through the
+// importer would duplicate logic from webhook_forward.go.
+// - sorting `Messages` in chronological order (oldest first), matching
+// how the REST path orders them.
+type ImportChatRequest struct {
+ ChatJID string
+ ChatName string
+ Messages []*domainChatStorage.Message
+}
+
+// ImportResult reports per-chat counts back to the SyncService so it can
+// update its progress tracker in the same shape as the REST path.
+type ImportResult struct {
+ ContactID int
+ ConversationID int
+ MessagesWrote int
+ MessagesSkipped int // already present (idempotent replay)
+ MessagesFailed int
+ Links []domainChatStorage.ChatwootMessageLink
+}
+
+// ImportChat is the single public entry point for writing historical
+// messages into Chatwoot. Everything happens inside one transaction per
+// chat so that a mid-import failure rolls back cleanly and the chat can
+// be retried without producing duplicates.
+//
+// Per-message errors (unexpected NULLs, schema drift, etc.) do NOT abort
+// the whole transaction — each message row is wrapped in a SAVEPOINT so
+// one bad message only loses itself. This is critical when importing
+// tens of thousands of rows.
+func (i *Importer) ImportChat(ctx context.Context, req ImportChatRequest) (*ImportResult, error) {
+ if i.closed.Load() {
+ return nil, fmt.Errorf("pgimport: importer is closed")
+ }
+ if req.ChatJID == "" {
+ return nil, fmt.Errorf("pgimport: empty ChatJID")
+ }
+
+ res := &ImportResult{}
+
+ tx, err := i.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
+ if err != nil {
+ return nil, fmt.Errorf("pgimport: begin tx: %w", err)
+ }
+ defer func() {
+ if p := recover(); p != nil {
+ _ = tx.Rollback()
+ panic(p)
+ }
+ }()
+
+ isGroup := isGroupJID(req.ChatJID)
+
+ contactID, err := i.upsertContact(ctx, tx, req.ChatJID, req.ChatName, isGroup)
+ if err != nil {
+ _ = tx.Rollback()
+ return nil, fmt.Errorf("pgimport: upsert contact: %w", err)
+ }
+ res.ContactID = contactID
+
+ contactInboxID, err := i.upsertContactInbox(ctx, tx, contactID, req.ChatJID)
+ if err != nil {
+ _ = tx.Rollback()
+ return nil, fmt.Errorf("pgimport: upsert contact_inbox: %w", err)
+ }
+
+ convID, err := i.findOrCreateConversation(ctx, tx, contactID, contactInboxID, req.Messages)
+ if err != nil {
+ _ = tx.Rollback()
+ return nil, fmt.Errorf("pgimport: conversation: %w", err)
+ }
+ res.ConversationID = convID
+
+ var lastActivity time.Time
+ for _, msg := range req.Messages {
+ if err := ctx.Err(); err != nil {
+ _ = tx.Rollback()
+ return res, err
+ }
+
+ link, wrote, err := i.insertMessageSavepoint(ctx, tx, convID, contactID, msg, isGroup)
+ switch {
+ case errors.As(err, &txFatalError{}):
+ // Transaction is broken — abort the loop. The caller (syncChatPG)
+ // counts every message as failed when ImportChat returns an error,
+ // so we deliberately do NOT increment res.MessagesFailed here to
+ // avoid double-counting.
+ _ = tx.Rollback()
+ return res, fmt.Errorf("pgimport: transaction-fatal error on message %s: %w", msg.ID, err)
+ case err != nil:
+ res.MessagesFailed++
+ logrus.Warnf("Chatwoot pgimport: message %s failed: %v", msg.ID, err)
+ case !wrote:
+ res.MessagesSkipped++
+ default:
+ res.MessagesWrote++
+ if msg.Timestamp.After(lastActivity) {
+ lastActivity = msg.Timestamp
+ }
+ }
+ if link != nil {
+ res.Links = append(res.Links, *link)
+ }
+ }
+
+ if res.MessagesWrote > 0 {
+ // Fall back to now() if every written message carried a zero
+ // timestamp (shouldn't happen in practice, but prevents the
+ // conversation landing at year 0001 in Chatwoot's agent UI).
+ if lastActivity.IsZero() {
+ lastActivity = time.Now()
+ }
+ if err := i.touchConversation(ctx, tx, convID, lastActivity); err != nil {
+ _ = tx.Rollback()
+ return res, fmt.Errorf("pgimport: touch conversation %d: %w", convID, err)
+ }
+ }
+
+ if err := tx.Commit(); err != nil {
+ return res, fmt.Errorf("pgimport: commit: %w", err)
+ }
+ return res, nil
+}
+
+// upsertContact finds a Chatwoot contact whose custom_attributes.gowa_whatsapp_jid
+// matches the chat JID, or creates one if absent. The matching key is the
+// same one the REST client writes at client.go:231, so a contact created by
+// the live path and a contact looked up by the importer resolve to the
+// same row.
+func (i *Importer) upsertContact(ctx context.Context, tx *sql.Tx, jid, name string, isGroup bool) (int, error) {
+ // Fast path: look up by our custom attribute.
+ var id int
+ err := tx.QueryRowContext(ctx, `
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1
+ AND (custom_attributes->>'gowa_whatsapp_jid') = $2
+ LIMIT 1
+ `, i.accountID, jid).Scan(&id)
+ if err == nil {
+ // Preserve manually edited 1:1 contact names; group subjects can
+ // legitimately change and should keep following WhatsApp.
+ if isGroup && name != "" {
+ if _, err := tx.ExecContext(ctx, `
+ UPDATE contacts
+ SET name = $1, updated_at = now()
+ WHERE id = $2 AND account_id = $3 AND (name IS DISTINCT FROM $1)
+ `, name, id, i.accountID); err != nil {
+ return 0, fmt.Errorf("refresh contact name: %w", err)
+ }
+ }
+ return id, nil
+ }
+ if err != sql.ErrNoRows {
+ return 0, err
+ }
+
+ // Fallback lookup by phone number for 1:1 chats — matches the REST
+ // client's FindContactByIdentifier path and avoids creating duplicate
+ // contacts when the live REST sync already landed one without the
+ // gowa_whatsapp_jid attribute.
+ phone, identifier, displayName := contactIdentity(jid, name)
+ if phone != "" {
+ var existing int
+ err := tx.QueryRowContext(ctx, `
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1 AND phone_number = $2
+ LIMIT 1
+ `, i.accountID, phone).Scan(&existing)
+ if err == nil {
+ // Attach our JID attribute so future lookups find it on the fast path.
+ if _, err := tx.ExecContext(ctx, `
+ UPDATE contacts
+ SET custom_attributes = COALESCE(custom_attributes, '{}'::jsonb)
+ || jsonb_build_object('gowa_whatsapp_jid', $1::text),
+ updated_at = now()
+ WHERE id = $2
+ `, jid, existing); err != nil {
+ return 0, fmt.Errorf("attach contact JID attribute: %w", err)
+ }
+ return existing, nil
+ }
+ if err != sql.ErrNoRows {
+ return 0, err
+ }
+ }
+
+ // Brand new contact.
+ customAttrs, _ := json.Marshal(map[string]any{
+ "gowa_whatsapp_jid": jid,
+ })
+
+ var newID int
+ err = tx.QueryRowContext(ctx, `
+ INSERT INTO contacts
+ (account_id, name, phone_number, identifier,
+ custom_attributes, additional_attributes, created_at, updated_at)
+ VALUES
+ ($1, $2, NULLIF($3, ''), NULLIF($4, ''),
+ $5::jsonb, '{}'::jsonb, now(), now())
+ RETURNING id
+ `, i.accountID, displayName, phone, identifier, string(customAttrs)).Scan(&newID)
+ if err != nil {
+ return 0, fmt.Errorf("insert contact: %w", err)
+ }
+ logrus.Debugf("Chatwoot pgimport: created contact id=%d jid=%s isGroup=%v", newID, jid, isGroup)
+ return newID, nil
+}
+
+// upsertContactInbox links a contact to the configured inbox. Chatwoot
+// requires this row before a conversation can be opened — the inbox-side
+// `source_id` uniquely identifies the customer within an API channel.
+// Uses ON CONFLICT on the (inbox_id, source_id) UNIQUE index so a race
+// with the live REST path (which may create the same row concurrently)
+// resolves to a single winning row instead of a 23505 violation.
+func (i *Importer) upsertContactInbox(ctx context.Context, tx *sql.Tx, contactID int, jid string) (int, error) {
+ var id int
+ err := tx.QueryRowContext(ctx, `
+ SELECT id
+ FROM contact_inboxes
+ WHERE contact_id = $1 AND inbox_id = $2
+ LIMIT 1
+ `, contactID, i.inboxID).Scan(&id)
+ if err == nil {
+ return id, nil
+ }
+ if err != sql.ErrNoRows {
+ return 0, err
+ }
+
+ // Chatwoot's Rails model generates pubsub_token via a callback. In raw
+ // SQL we produce our own — gen_random_uuid() is guaranteed present:
+ // Chatwoot's schema.rb calls `enable_extension "pgcrypto"` at the top.
+ var newID int
+ err = tx.QueryRowContext(ctx, `
+ INSERT INTO contact_inboxes
+ (contact_id, inbox_id, source_id, hmac_verified,
+ pubsub_token, created_at, updated_at)
+ VALUES
+ ($1, $2, $3, false,
+ replace(gen_random_uuid()::text, '-', ''), now(), now())
+ ON CONFLICT (inbox_id, source_id) DO UPDATE
+ SET updated_at = EXCLUDED.updated_at
+ RETURNING id
+ `, contactID, i.inboxID, jid).Scan(&newID)
+ if err != nil {
+ return 0, fmt.Errorf("insert contact_inbox: %w", err)
+ }
+ return newID, nil
+}
+
+// conversationStatusForNew returns the Chatwoot conversation status enum a
+// newly created (or reopened) conversation should land in. It mirrors the REST
+// client's conversationStatusForNew() (client.go) so both paths honor the
+// CHATWOOT_CONVERSATION_PENDING setting consistently: `pending` (the unassigned
+// queue) when enabled, otherwise `open` (the agent's active queue).
+func conversationStatusForNew() int {
+ if config.ChatwootConversationPending {
+ return conversationStatusPending
+ }
+ return conversationStatusOpen
+}
+
+// findOrCreateConversation returns the id of the most recent conversation
+// for (account, inbox, contact), opening a fresh one if none exists. We
+// match regardless of `status` so that a conversation resolved by an agent
+// and then re-imported from WhatsApp reuses the same row instead of
+// creating a duplicate (the live REST path hits the same row for new
+// inbound messages, so the two paths agree). When CHATWOOT_REOPEN_CONVERSATION
+// is enabled (the default), a reused *resolved* conversation is flipped back to
+// the configured new-status so a returning customer's history resurfaces in the
+// agent queue — matching the REST path's reopen behavior. (When reopen is
+// disabled the REST path opens a brand-new conversation instead; the importer
+// still reuses the row here to avoid duplicate threads, leaving its status
+// untouched. This is a deliberate, narrow asymmetry: the live REST path opens
+// a fresh thread when reopen is off, while this importer reuses any existing
+// conversation regardless of status and never spawns a second one — keeping a
+// backfilled history in a single thread.)
+//
+// We deliberately do NOT supply `display_id`. Chatwoot installs a
+// BEFORE INSERT trigger `conversations_before_insert_row_tr` that
+// unconditionally assigns `NEW.display_id := nextval('conv_dpid_seq_' || account_id)`,
+// so any value we pass would be thrown away. Letting the trigger fill it
+// avoids racing the per-account sequence with the live Rails path.
+//
+// `gen_random_uuid()` is guaranteed present: Chatwoot's schema.rb calls
+// `enable_extension "pgcrypto"` at the top.
+func (i *Importer) findOrCreateConversation(
+ ctx context.Context,
+ tx *sql.Tx,
+ contactID, contactInboxID int,
+ msgs []*domainChatStorage.Message,
+) (int, error) {
+ var id, status int
+ err := tx.QueryRowContext(ctx, `
+ SELECT id, status
+ FROM conversations
+ WHERE account_id = $1
+ AND inbox_id = $2
+ AND contact_id = $3
+ ORDER BY id DESC
+ LIMIT 1
+ `, i.accountID, i.inboxID, contactID).Scan(&id, &status)
+ if err == nil {
+ // Reopen a reused resolved thread when configured. Only `resolved`
+ // is touched (pending/snoozed reused rows are left as the agent set
+ // them), matching the REST path. The UPDATE is idempotent via its
+ // WHERE status guard.
+ if config.ChatwootReopenConversation && status == conversationStatusResolved {
+ if _, uerr := tx.ExecContext(ctx, `
+ UPDATE conversations
+ SET status = $1, updated_at = now()
+ WHERE id = $2 AND account_id = $3 AND status = $4
+ `, conversationStatusForNew(), id, i.accountID, conversationStatusResolved); uerr != nil {
+ return 0, fmt.Errorf("reopen conversation %d: %w", id, uerr)
+ }
+ }
+ return id, nil
+ }
+ if err != sql.ErrNoRows {
+ return 0, err
+ }
+
+ // Anchor the new conversation's created_at at the first message's
+ // timestamp when available, so Chatwoot's UI sorts it correctly. Fall
+ // back to now() for empty or zero-time message slices.
+ var createdAt time.Time
+ if len(msgs) > 0 && !msgs[0].Timestamp.IsZero() {
+ createdAt = msgs[0].Timestamp
+ } else {
+ createdAt = time.Now()
+ }
+
+ // `waiting_since = created_at` matches Rails' before_create callback
+ // (`ensure_waiting_since`). Without it, every imported conversation
+ // is perpetually flagged as "unattended" in Chatwoot's dashboard scope.
+ var newID int
+ err = tx.QueryRowContext(ctx, `
+ INSERT INTO conversations
+ (account_id, inbox_id, status, contact_id, contact_inbox_id,
+ uuid, additional_attributes, custom_attributes,
+ last_activity_at, waiting_since, created_at, updated_at)
+ VALUES
+ ($1, $2, $3, $4, $5,
+ gen_random_uuid()::text,
+ '{}'::jsonb, '{}'::jsonb,
+ $6, $6, $6, now())
+ RETURNING id
+ `, i.accountID, i.inboxID, conversationStatusForNew(), contactID, contactInboxID, createdAt).Scan(&newID)
+ if err != nil {
+ return 0, fmt.Errorf("insert conversation: %w", err)
+ }
+ logrus.Debugf("Chatwoot pgimport: created conversation id=%d contact=%d", newID, contactID)
+ return newID, nil
+}
+
+// insertMessageSavepoint wraps one INSERT in a SAVEPOINT so a single bad
+// row doesn't abort the surrounding chat transaction. Returns (wrote,
+// err) — wrote=false, err=nil means the row was already present and was
+// skipped idempotently.
+func (i *Importer) insertMessageSavepoint(
+ ctx context.Context,
+ tx *sql.Tx,
+ convID, contactID int,
+ msg *domainChatStorage.Message,
+ isGroup bool,
+) (*domainChatStorage.ChatwootMessageLink, bool, error) {
+ const savepoint = "cw_msg"
+
+ if _, err := tx.ExecContext(ctx, "SAVEPOINT "+savepoint); err != nil {
+ // SAVEPOINT failure means the transaction itself is broken (connection
+ // lost, aborted state). Wrap as txFatalError so the caller aborts the loop.
+ return nil, false, txFatalError{err}
+ }
+
+ link, wrote, err := i.insertMessage(ctx, tx, convID, contactID, msg, isGroup)
+ if err != nil {
+ if _, rbErr := tx.ExecContext(ctx, "ROLLBACK TO SAVEPOINT "+savepoint); rbErr != nil {
+ return nil, false, txFatalError{fmt.Errorf("%v (rollback failed: %v)", err, rbErr)}
+ }
+ return nil, false, err
+ }
+ if _, err := tx.ExecContext(ctx, "RELEASE SAVEPOINT "+savepoint); err != nil {
+ // RELEASE almost never fails on a healthy connection; when it does
+ // the connection is wedged and every subsequent SAVEPOINT will fail.
+ // Propagate as txFatalError so the caller aborts the loop cleanly.
+ return link, wrote, txFatalError{err}
+ }
+ return link, wrote, nil
+}
+
+// insertMessage does the actual write. It skips rows that already exist
+// (matched by source_id within the inbox) so re-runs are safe even when
+// the previous conversation was resolved and re-opened as a new row.
+func (i *Importer) insertMessage(
+ ctx context.Context,
+ tx *sql.Tx,
+ convID, contactID int,
+ msg *domainChatStorage.Message,
+ isGroup bool,
+) (*domainChatStorage.ChatwootMessageLink, bool, error) {
+ if msg.ID == "" {
+ return nil, false, fmt.Errorf("empty message ID")
+ }
+
+ // WAID: prefix matches the source_id convention Chatwoot's WhatsApp channel
+ // integrations use for WhatsApp message IDs. Using the same format means a
+ // Chatwoot instance that already imported these messages through another
+ // integration recognizes already-imported rows on re-sync instead of
+ // double-inserting.
+ sourceID := "WAID:" + msg.ID
+
+ // Idempotency probe keyed to the inbox: Chatwoot's `index_messages_on_source_id`
+ // is plain (non-unique), but messages imported under the same inbox
+ // share a source_id iff they're the same WhatsApp message — whether
+ // they landed in a different conversation after a resolve/reopen cycle
+ // or not. Inbox-scoped lookup makes replays correctly skip duplicates.
+ var existingID, existingConvID int
+ err := tx.QueryRowContext(ctx, `
+ SELECT id, conversation_id FROM messages
+ WHERE inbox_id = $1 AND source_id = $2
+ LIMIT 1
+ `, i.inboxID, sourceID).Scan(&existingID, &existingConvID)
+ if err == nil {
+ return i.buildMessageLink(msg, existingConvID, existingID, sourceID, messageTypeForWA(msg.IsFromMe)), false, nil
+ }
+ if err != sql.ErrNoRows {
+ return nil, false, err
+ }
+
+ content := buildContent(msg, isGroup)
+ // Skip entirely when there is nothing meaningful to show — no body, no
+ // media placeholder. Writing blank rows pollutes Chatwoot's UI.
+ if content == "" {
+ return nil, false, nil
+ }
+ mType := messageTypeForWA(msg.IsFromMe)
+ // Historical messages were all successfully delivered by definition (we're
+ // pulling them from our local chat store), so "delivered" is the honest default.
+ status := messageStatusDelivered
+
+ // additional_attributes carries metadata useful for debugging and for
+ // agents who want to see the original WhatsApp identifiers. We populate
+ // this column because the cost is zero and the extra traceability helps
+ // when correlating Chatwoot rows back to chat-storage entries.
+ addl, _ := json.Marshal(map[string]any{
+ "wa_message_id": msg.ID,
+ "wa_chat_jid": msg.ChatJID,
+ "wa_sender": msg.Sender,
+ "wa_media_type": msg.MediaType,
+ })
+
+ // senderType/senderID: for incoming messages the sender is the Contact
+ // row we already upserted. For outgoing messages Chatwoot expects a
+ // User (or AgentBot) — the row is rendered as "Unknown sender" if these
+ // stay NULL. We resolve the API-token's owner from `access_tokens` once
+ // at startup
+ // (see Importer.resolveAgent) and stamp every outgoing imported row
+ // with that user. When the lookup failed (no token, missing row,
+ // table unreachable) i.agentUserID is 0 and we deliberately leave the
+ // columns NULL — the message still imports, just without attribution.
+ var senderType sql.NullString
+ var senderID sql.NullInt64
+ if msg.IsFromMe {
+ if i.agentUserID != 0 && i.agentUserType != "" {
+ senderType = sql.NullString{String: i.agentUserType, Valid: true}
+ senderID = sql.NullInt64{Int64: i.agentUserID, Valid: true}
+ }
+ } else {
+ senderType = sql.NullString{String: senderTypeContact, Valid: true}
+ senderID = sql.NullInt64{Int64: int64(contactID), Valid: true}
+ }
+
+ // processed_message_content mirrors `content` so Chatwoot's full-text
+ // search over conversations returns hits for imported messages. Rails
+ // fills this via a before_save callback; direct SQL must do it manually.
+ var chatwootMessageID int
+ err = tx.QueryRowContext(ctx, `
+ INSERT INTO messages
+ (content, processed_message_content,
+ account_id, inbox_id, conversation_id,
+ message_type, created_at, updated_at, private, status,
+ source_id, content_type, content_attributes,
+ sender_type, sender_id, additional_attributes)
+ VALUES
+ ($1, $1,
+ $2, $3, $4,
+ $5, $6, $6, false, $7,
+ $8, $9, '{}'::jsonb,
+ $10, $11, $12::jsonb)
+ RETURNING id
+ `,
+ content,
+ i.accountID, i.inboxID, convID,
+ mType, msg.Timestamp, status,
+ sourceID, contentTypeText,
+ senderType, senderID, string(addl),
+ ).Scan(&chatwootMessageID)
+ if err != nil {
+ return nil, false, err
+ }
+ return i.buildMessageLink(msg, convID, chatwootMessageID, sourceID, mType), true, nil
+}
+
+func (i *Importer) buildMessageLink(msg *domainChatStorage.Message, convID, chatwootMessageID int, sourceID string, messageType int) *domainChatStorage.ChatwootMessageLink {
+ if msg == nil || msg.ID == "" || msg.DeviceID == "" || chatwootMessageID == 0 {
+ return nil
+ }
+
+ direction := "incoming"
+ if messageType == messageTypeOutgoing {
+ direction = "outgoing"
+ }
+
+ return &domainChatStorage.ChatwootMessageLink{
+ DeviceID: msg.DeviceID,
+ WhatsAppMessageID: msg.ID,
+ WhatsAppChatJID: msg.ChatJID,
+ ChatwootMessageID: chatwootMessageID,
+ ChatwootConversationID: convID,
+ ChatwootInboxID: i.inboxID,
+ ChatwootContactInboxSourceID: msg.ChatJID,
+ SourceID: sourceID,
+ Direction: direction,
+ IsRead: false,
+ }
+}
+
+// touchConversation advances last_activity_at on the conversation row so
+// that Chatwoot's agent UI orders it correctly in the conversation list.
+// Not strictly required, but matches how the Rails callbacks behave.
+func (i *Importer) touchConversation(ctx context.Context, tx *sql.Tx, convID int, at time.Time) error {
+ _, err := tx.ExecContext(ctx, `
+ UPDATE conversations
+ SET last_activity_at = GREATEST(COALESCE(last_activity_at, $2), $2),
+ updated_at = now()
+ WHERE id = $1
+ `, convID, at)
+ return err
+}
+
+// buildContent computes the message body text for the Chatwoot messages
+// table. Unlike the REST path in sync.go, this deliberately does NOT
+// prepend "[YYYY-MM-DD HH:MM]" — the whole point of the direct-DB
+// importer is that we can preserve real timestamps on the row itself, so
+// polluting the body with a string copy is unnecessary.
+//
+// For group messages, we still prefix the sender so agents can tell
+// participants apart in Chatwoot's single conversation thread. That is a
+// semantic prefix, not a timestamp workaround, and it's consistent with
+// how the Chatwoot agent UI renders group chats everywhere else.
+func buildContent(msg *domainChatStorage.Message, isGroup bool) string {
+ body := strings.TrimSpace(msg.Content)
+
+ if body == "" && msg.MediaType != "" {
+ if config.ChatwootImportPlaceholderMediaMessage {
+ body = fmt.Sprintf("[%s]", msg.MediaType)
+ }
+ }
+
+ if isGroup && !msg.IsFromMe && msg.Sender != "" {
+ // The sender label is the JID user portion — a phone number for normal
+ // users, an @lid identifier for privacy-masked senders. This matches the
+ // REST path (sync.go:syncMessage), which labels group senders the same way.
+ senderName := utils.ExtractPhoneFromJID(msg.Sender)
+ if body == "" {
+ return senderName + ":"
+ }
+ return senderName + ": " + body
+ }
+ return body
+}
diff --git a/src/infrastructure/chatwoot/pgimport/writer_flow_test.go b/src/infrastructure/chatwoot/pgimport/writer_flow_test.go
new file mode 100644
index 00000000..a0c10f02
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/writer_flow_test.go
@@ -0,0 +1,523 @@
+package pgimport
+
+import (
+ "context"
+ "errors"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/DATA-DOG/go-sqlmock"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+// SQL fragments for the upsertContact create-path, kept as literals so
+// regexp.QuoteMeta pins the exact query the writer emits (matching the
+// discipline of upsert_contact_test.go's consts).
+
+const contactPhoneLookupSQL = `
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1 AND phone_number = $2
+ LIMIT 1
+ `
+
+const insertContactSQL = `
+ INSERT INTO contacts
+ (account_id, name, phone_number, identifier,
+ custom_attributes, additional_attributes, created_at, updated_at)
+ VALUES
+ ($1, $2, NULLIF($3, ''), NULLIF($4, ''),
+ $5::jsonb, '{}'::jsonb, now(), now())
+ RETURNING id
+ `
+
+// expectContactCreatePath registers the three queries upsertContact issues for
+// a brand-new 1:1 contact: JID miss, phone miss, INSERT RETURNING id. It
+// returns nothing; callers chain it between ExpectBegin and the next stage.
+func expectContactCreatePath(t *testing.T, mock sqlmock.Sqlmock, imp *Importer, jid, phone string, newID int) {
+ t.Helper()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(regexp.QuoteMeta(contactPhoneLookupSQL)).
+ WithArgs(imp.accountID, phone).
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(regexp.QuoteMeta(insertContactSQL)).
+ WithArgs(imp.accountID, sqlmock.AnyArg(), phone, sqlmock.AnyArg(), sqlmock.AnyArg()).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(newID))
+}
+
+func TestImportChat_HappyPath(t *testing.T) {
+ // End-to-end happy path for a 1:1 chat with two messages, both new:
+ // Begin
+ // upsertContact (JID miss -> phone miss -> INSERT id=100)
+ // upsertContactInbox (SELECT miss -> INSERT id=200)
+ // findOrCreateConversation (SELECT miss -> INSERT id=300)
+ // msg1: probe miss -> INSERT
+ // msg2: probe miss -> INSERT
+ // touchConversation UPDATE
+ // Commit
+ // The result counts must report 2 written, 0 skipped, 0 failed.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ const phone = "+6281234567890" // E.164 normalization of the above JID
+ t1 := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ t2 := t1.Add(time.Minute)
+ msgs := []*domainChatStorage.Message{
+ {ID: "wa-1", Content: "hello", Timestamp: t1},
+ {ID: "wa-2", Content: "world", Timestamp: t2},
+ }
+
+ mock.ExpectBegin()
+ expectContactCreatePath(t, mock, imp, jid, phone, 100)
+
+ // contact_inbox: SELECT miss -> INSERT ... ON CONFLICT RETURNING id.
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(regexp.QuoteMeta(insertContactInboxSQL)).
+ WithArgs(100, imp.inboxID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+
+ // conversation: SELECT miss -> INSERT RETURNING id, created_at pinned to t1.
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusOpen, 100, 200, t1).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(300))
+
+ // msg1 — savepoint, probe miss, insert, release.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-1").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ // msg2 — same shape.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-2").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ // touchConversation advances last_activity_at to the latest written ts (t2).
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(300, t2).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+
+ mock.ExpectCommit()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ ChatName: "Alice",
+ Messages: msgs,
+ })
+ if err != nil {
+ t.Fatalf("ImportChat: %v", err)
+ }
+ if res.ContactID != 100 {
+ t.Errorf("ContactID = %d, want 100", res.ContactID)
+ }
+ if res.ConversationID != 300 {
+ t.Errorf("ConversationID = %d, want 300", res.ConversationID)
+ }
+ if res.MessagesWrote != 2 {
+ t.Errorf("MessagesWrote = %d, want 2", res.MessagesWrote)
+ }
+ if res.MessagesSkipped != 0 || res.MessagesFailed != 0 {
+ t.Errorf("Skipped/Failed = %d/%d, want 0/0", res.MessagesSkipped, res.MessagesFailed)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_HappyPathExistingContactFastPath(t *testing.T) {
+ // Variant where the contact already exists (JID fast-path hit) and the
+ // contact_inbox + conversation also already exist. This exercises the
+ // no-insert branches of all three upsert helpers in a single flow, with a
+ // single new message written.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ ts := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ msgs := []*domainChatStorage.Message{{ID: "wa-1", Content: "hi", Timestamp: ts}}
+
+ mock.ExpectBegin()
+ // Contact fast path hits (1:1, isGroup=false => no name refresh UPDATE).
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(100))
+ // contact_inbox exists.
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ // conversation exists.
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(300, conversationStatusOpen))
+ // single message written.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-1").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(300, ts).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+ mock.ExpectCommit()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ ChatName: "Alice",
+ Messages: msgs,
+ })
+ if err != nil {
+ t.Fatalf("ImportChat: %v", err)
+ }
+ if res.ContactID != 100 || res.ConversationID != 300 || res.MessagesWrote != 1 {
+ t.Errorf("res = %+v, want contact=100 conv=300 wrote=1", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_IdempotentSkip(t *testing.T) {
+ // A message whose idempotency probe finds an existing row is skipped:
+ // MessagesSkipped++ and NO INSERT for it. The savepoint still wraps the
+ // (no-op) probe, and because nothing was written, touchConversation is NOT
+ // issued (res.MessagesWrote stays 0).
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ ts := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ msgs := []*domainChatStorage.Message{{ID: "wa-dup", Content: "hi", Timestamp: ts}}
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(100))
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(300, conversationStatusOpen))
+
+ // Savepoint + probe HIT -> RELEASE, but no INSERT and no touchConversation.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-dup").
+ WillReturnRows(sqlmock.NewRows([]string{"id", "conversation_id"}).AddRow(1, 300))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ mock.ExpectCommit()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ ChatName: "Alice",
+ Messages: msgs,
+ })
+ if err != nil {
+ t.Fatalf("ImportChat: %v", err)
+ }
+ if res.MessagesWrote != 0 {
+ t.Errorf("MessagesWrote = %d, want 0", res.MessagesWrote)
+ }
+ if res.MessagesSkipped != 1 {
+ t.Errorf("MessagesSkipped = %d, want 1", res.MessagesSkipped)
+ }
+ if res.MessagesFailed != 0 {
+ t.Errorf("MessagesFailed = %d, want 0", res.MessagesFailed)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_PerMessageFailureCountedNotFatal(t *testing.T) {
+ // A single message INSERT failure rolls back only that row's savepoint and
+ // is counted as MessagesFailed; the loop continues. Here msg1 fails and
+ // msg2 succeeds, so the chat still commits with 1 written / 1 failed.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ t1 := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ t2 := t1.Add(time.Minute)
+ msgs := []*domainChatStorage.Message{
+ {ID: "wa-bad", Content: "boom", Timestamp: t1},
+ {ID: "wa-good", Content: "ok", Timestamp: t2},
+ }
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(100))
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(300, conversationStatusOpen))
+
+ // msg1 fails the INSERT -> ROLLBACK TO SAVEPOINT, not fatal.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-bad").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnError(errors.New("constraint boom"))
+ mock.ExpectExec(regexp.QuoteMeta("ROLLBACK TO SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ // msg2 succeeds.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-good").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ // touchConversation uses t2 (only written msg).
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(300, t2).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+ mock.ExpectCommit()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ ChatName: "Alice",
+ Messages: msgs,
+ })
+ if err != nil {
+ t.Fatalf("ImportChat: %v", err)
+ }
+ if res.MessagesWrote != 1 || res.MessagesFailed != 1 || res.MessagesSkipped != 0 {
+ t.Errorf("res = %+v, want wrote=1 failed=1 skipped=0", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_ClosedReturnsErrorNoDB(t *testing.T) {
+ // A closed importer rejects the call up front. No transaction is opened, so
+ // registering zero expectations proves the DB is never touched.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+ imp.closed.Store(true)
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: "[email protected]",
+ Messages: []*domainChatStorage.Message{{ID: "x"}},
+ })
+ if err == nil {
+ t.Fatalf("expected error on closed importer, got nil")
+ }
+ if res != nil {
+ t.Errorf("res = %+v, want nil", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_EmptyChatJIDReturnsErrorNoDB(t *testing.T) {
+ // An empty ChatJID is rejected before BeginTx — no DB calls.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: "",
+ Messages: []*domainChatStorage.Message{{ID: "x"}},
+ })
+ if err == nil {
+ t.Fatalf("expected error on empty ChatJID, got nil")
+ }
+ if res != nil {
+ t.Errorf("res = %+v, want nil", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_UpsertContactErrorRollsBack(t *testing.T) {
+ // A non-ErrNoRows error from the very first contact lookup aborts the whole
+ // import: tx is rolled back and ImportChat returns a wrapped error. No
+ // further stage runs.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(errors.New("db down"))
+ mock.ExpectRollback()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ Messages: []*domainChatStorage.Message{{ID: "wa-1", Content: "hi"}},
+ })
+ if err == nil {
+ t.Fatalf("expected error on upsertContact failure, got nil")
+ }
+ if res != nil {
+ t.Errorf("res = %+v, want nil", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_FatalSavepointErrorAbortsLoopAndRollsBack(t *testing.T) {
+ // A txFatalError from the message loop (here a failed SAVEPOINT) aborts the
+ // whole import: ImportChat rolls back and returns a wrapped error. The
+ // deliberately-NOT-incremented MessagesFailed counter is asserted via the
+ // returned res being non-nil but carrying zero failed (the caller counts
+ // every message as failed when ImportChat errors, so double-counting is
+ // avoided).
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ msgs := []*domainChatStorage.Message{
+ {ID: "wa-1", Content: "hi", Timestamp: time.Now()},
+ {ID: "wa-2", Content: "ho", Timestamp: time.Now()},
+ }
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(100))
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(300, conversationStatusOpen))
+
+ // First message's SAVEPOINT fails => txFatalError => loop aborts before
+ // touching msg2. Only one SAVEPOINT is expected; a second would be unmet.
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnError(errors.New("connection reset"))
+ mock.ExpectRollback()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: jid,
+ ChatName: "Alice",
+ Messages: msgs,
+ })
+ if err == nil {
+ t.Fatalf("expected fatal error, got nil")
+ }
+ // res is returned (non-nil) so the caller can read partial progress, but the
+ // failed counter is intentionally left at 0 to avoid double-counting.
+ if res == nil {
+ t.Fatalf("res = nil, want non-nil partial result")
+ }
+ if res.MessagesFailed != 0 || res.MessagesWrote != 0 {
+ t.Errorf("res = %+v, want wrote=0 failed=0 on fatal abort", res)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_CanceledContextFailsAtBeginTx(t *testing.T) {
+ // An already-canceled context fails at BeginTx — database/sql checks ctx
+ // before reaching the driver — so ImportChat returns the wrapped "begin tx"
+ // error with res == nil and never registers any mocked query. This codifies
+ // that cancellation before the transaction opens is a hard failure, not a
+ // partial import.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+
+ res, err := imp.ImportChat(ctx, ImportChatRequest{
+ ChatJID: "[email protected]",
+ Messages: []*domainChatStorage.Message{{ID: "wa-1", Content: "hi", Timestamp: time.Now()}},
+ })
+ if err == nil {
+ t.Fatalf("expected error on canceled context, got nil")
+ }
+ if res != nil {
+ t.Errorf("res = %+v, want nil when BeginTx fails", res)
+ }
+ // No mocked expectations were registered, proving no query ran past begin.
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestImportChat_GroupSkipsTouchWhenAllZeroTimestampsFallBackToNow(t *testing.T) {
+ // A group chat where the only written message carries a zero Timestamp:
+ // lastActivity stays zero through the loop, so ImportChat falls back to
+ // time.Now() for the touchConversation argument (guarding against the
+ // thread landing at year 0001 in Chatwoot). We assert the touch arg is
+ // now-ish rather than the zero time.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const groupJID = "[email protected]"
+ // Zero timestamp on the single message; group incoming so it gets a sender
+ // prefix and is therefore non-empty content.
+ msgs := []*domainChatStorage.Message{
+ {ID: "wa-1", Content: "hey", Sender: "[email protected]"},
+ }
+
+ mock.ExpectBegin()
+ // Group contact fast-path hit; name non-empty triggers the refresh UPDATE.
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, groupJID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(100))
+ mock.ExpectExec(regexp.QuoteMeta(refreshContactNameSQL)).
+ WithArgs("Team", 100, imp.accountID).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(100, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(200))
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 100).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(300, conversationStatusOpen))
+
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-1").
+ WillReturnError(noRowsError())
+ mock.ExpectQuery(`INSERT INTO messages`).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).WillReturnResult(sqlmock.NewResult(0, 0))
+
+ before := time.Now()
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(300, nowishArg{notBefore: before}).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+ mock.ExpectCommit()
+
+ res, err := imp.ImportChat(context.Background(), ImportChatRequest{
+ ChatJID: groupJID,
+ ChatName: "Team",
+ Messages: msgs,
+ })
+ if err != nil {
+ t.Fatalf("ImportChat: %v", err)
+ }
+ if res.MessagesWrote != 1 {
+ t.Errorf("MessagesWrote = %d, want 1", res.MessagesWrote)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
diff --git a/src/infrastructure/chatwoot/pgimport/writer_test.go b/src/infrastructure/chatwoot/pgimport/writer_test.go
new file mode 100644
index 00000000..499956b5
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/writer_test.go
@@ -0,0 +1,157 @@
+package pgimport
+
+import (
+ "context"
+ "database/sql"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/DATA-DOG/go-sqlmock"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+// insertMessageTestCase exercises insertMessage end-to-end against sqlmock,
+// asserting on the sender_type/sender_id arguments passed to INSERT. The
+// regex matchers are intentionally lenient on whitespace but pinned on the
+// table and column structure so a meaningful schema change in the writer
+// would surface as a test failure rather than silently breaking attribution.
+type insertMessageTestCase struct {
+ name string
+ agentUserType string
+ agentUserID int64
+ msg *domainChatStorage.Message
+ wantSenderType any // string or nil — nil means SQL NULL
+ wantSenderID any // int64 or nil — nil means SQL NULL
+}
+
+func TestInsertMessage_SenderResolution(t *testing.T) {
+ const (
+ convID = 100
+ contactID = 200
+ )
+
+ now := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+
+ cases := []insertMessageTestCase{
+ {
+ name: "incoming message stamps Contact / contactID regardless of agent state",
+ agentUserType: "User",
+ agentUserID: 42,
+ msg: &domainChatStorage.Message{ID: "wa-1", Content: "hi", Timestamp: now, IsFromMe: false, Sender: "[email protected]"},
+ wantSenderType: "Contact",
+ wantSenderID: int64(contactID),
+ },
+ {
+ name: "outgoing message with resolved User agent stamps that agent",
+ agentUserType: "User",
+ agentUserID: 42,
+ msg: &domainChatStorage.Message{ID: "wa-2", Content: "reply", Timestamp: now, IsFromMe: true},
+ wantSenderType: "User",
+ wantSenderID: int64(42),
+ },
+ {
+ name: "outgoing message with resolved AgentBot stamps that bot",
+ agentUserType: "AgentBot",
+ agentUserID: 7,
+ msg: &domainChatStorage.Message{ID: "wa-3", Content: "automated", Timestamp: now, IsFromMe: true},
+ wantSenderType: "AgentBot",
+ wantSenderID: int64(7),
+ },
+ {
+ name: "outgoing message without agent leaves sender NULL",
+ agentUserType: "",
+ agentUserID: 0,
+ msg: &domainChatStorage.Message{ID: "wa-4", Content: "lonely", Timestamp: now, IsFromMe: true},
+ wantSenderType: nil,
+ wantSenderID: nil,
+ },
+ }
+
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ db, mock, err := sqlmock.New()
+ if err != nil {
+ t.Fatalf("sqlmock.New: %v", err)
+ }
+ defer db.Close()
+
+ imp := &Importer{
+ db: db,
+ accountID: 1,
+ inboxID: 2,
+ agentUserType: tc.agentUserType,
+ agentUserID: tc.agentUserID,
+ }
+
+ // Idempotency probe must hit messages with (inbox_id, source_id).
+ // Returning ErrNoRows forces the writer to attempt the INSERT.
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(`SELECT id, conversation_id FROM messages
+ WHERE inbox_id = $1 AND source_id = $2
+ LIMIT 1`)).
+ WithArgs(2, "WAID:"+tc.msg.ID).
+ WillReturnError(noRowsError())
+
+ // The INSERT carries 12 args. Pin the WhatsApp timestamp because
+ // issue #580 regressed when Chatwoot stamped history rows with
+ // import time instead of the original message time. Keep unrelated
+ // formatting arguments loose so this test remains focused.
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WithArgs(
+ sqlmock.AnyArg(), // content
+ 1, // account_id
+ 2, // inbox_id
+ convID, // conversation_id
+ sqlmock.AnyArg(), // message_type
+ tc.msg.Timestamp, // created_at and updated_at both use this placeholder
+ sqlmock.AnyArg(), // status
+ "WAID:"+tc.msg.ID,
+ 0, // content_type (text)
+ nullableArg(tc.wantSenderType), // sender_type
+ nullableArg(tc.wantSenderID), // sender_id
+ sqlmock.AnyArg(), // additional_attributes
+ ).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectCommit()
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessage(context.Background(), tx, convID, contactID, tc.msg, false)
+ if err != nil {
+ t.Fatalf("insertMessage: %v", err)
+ }
+ if !wrote {
+ t.Errorf("insertMessage wrote=false; want true (idempotency probe should miss)")
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatalf("Commit: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+ })
+ }
+}
+
+// nullableArg returns a sqlmock argument matcher for either a concrete
+// expected value or a SQL-level NULL, since lib/pq passes sql.Null{String,Int64}
+// through as their underlying value or nil. database/sql turns
+// sql.NullString{Valid:false} into the empty string and sql.NullInt64{Valid:false}
+// into 0 from the driver's perspective; sqlmock unfortunately compares the
+// rendered driver value, so a NULL-expecting case has to match nil.
+func nullableArg(want any) any {
+ if want == nil {
+ return nil
+ }
+ return want
+}
+
+// noRowsError returns sql.ErrNoRows. The wrapper exists so call sites read
+// as "expect the idempotency probe to miss" rather than referencing the
+// generic package-level constant inline.
+func noRowsError() error {
+ return sql.ErrNoRows
+}
diff --git a/src/infrastructure/chatwoot/pgimport/writer_units_test.go b/src/infrastructure/chatwoot/pgimport/writer_units_test.go
new file mode 100644
index 00000000..0af34f3f
--- /dev/null
+++ b/src/infrastructure/chatwoot/pgimport/writer_units_test.go
@@ -0,0 +1,1317 @@
+package pgimport
+
+import (
+ "context"
+ "database/sql"
+ "database/sql/driver"
+ "errors"
+ "regexp"
+ "testing"
+ "time"
+
+ "github.com/DATA-DOG/go-sqlmock"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+// SQL fragments below mirror the exact text the writer sends so that
+// regexp.QuoteMeta turns each into a literal matcher. Pinning the literal
+// (rather than a loose substring) means a meaningful query edit surfaces as
+// a test failure instead of silently passing — the same discipline the
+// existing upsert_contact_test.go applies.
+
+const insertContactInboxSQL = `
+ INSERT INTO contact_inboxes
+ (contact_id, inbox_id, source_id, hmac_verified,
+ pubsub_token, created_at, updated_at)
+ VALUES
+ ($1, $2, $3, false,
+ replace(gen_random_uuid()::text, '-', ''), now(), now())
+ ON CONFLICT (inbox_id, source_id) DO UPDATE
+ SET updated_at = EXCLUDED.updated_at
+ RETURNING id
+ `
+
+const selectContactInboxSQL = `
+ SELECT id
+ FROM contact_inboxes
+ WHERE contact_id = $1 AND inbox_id = $2
+ LIMIT 1
+ `
+
+const selectConversationSQL = `
+ SELECT id, status
+ FROM conversations
+ WHERE account_id = $1
+ AND inbox_id = $2
+ AND contact_id = $3
+ ORDER BY id DESC
+ LIMIT 1
+ `
+
+const insertConversationSQL = `
+ INSERT INTO conversations
+ (account_id, inbox_id, status, contact_id, contact_inbox_id,
+ uuid, additional_attributes, custom_attributes,
+ last_activity_at, waiting_since, created_at, updated_at)
+ VALUES
+ ($1, $2, $3, $4, $5,
+ gen_random_uuid()::text,
+ '{}'::jsonb, '{}'::jsonb,
+ $6, $6, $6, now())
+ RETURNING id
+ `
+
+const idempotencyProbeSQL = `
+ SELECT id, conversation_id FROM messages
+ WHERE inbox_id = $1 AND source_id = $2
+ LIMIT 1
+ `
+
+const touchConversationSQL = `
+ UPDATE conversations
+ SET last_activity_at = GREATEST(COALESCE(last_activity_at, $2), $2),
+ updated_at = now()
+ WHERE id = $1
+ `
+
+// ---------------------------------------------------------------------------
+// buildContent — cases not already covered by identity_test.go
+// ---------------------------------------------------------------------------
+
+func TestBuildContent_OutgoingMediaPlaceholder(t *testing.T) {
+ // Outgoing (IsFromMe) media with an empty body falls through to the media
+ // placeholder when the feature flag is on. The group-prefix branch is
+ // skipped because IsFromMe is true, so no sender label is prepended.
+ prev := config.ChatwootImportPlaceholderMediaMessage
+ defer func() { config.ChatwootImportPlaceholderMediaMessage = prev }()
+ config.ChatwootImportPlaceholderMediaMessage = true
+
+ msg := &domainChatStorage.Message{MediaType: "video", IsFromMe: true, Sender: "[email protected]"}
+ if got := buildContent(msg, true); got != "[video]" {
+ t.Errorf("buildContent outgoing media = %q, want %q", got, "[video]")
+ }
+}
+
+func TestBuildContent_GroupOutgoingNoPrefix(t *testing.T) {
+ // In a group, our own outgoing messages (IsFromMe) must NOT be prefixed
+ // with a sender label — the prefix is only for distinguishing *other*
+ // participants. The body is returned verbatim.
+ msg := &domainChatStorage.Message{Content: "my reply", IsFromMe: true, Sender: "[email protected]"}
+ if got := buildContent(msg, true); got != "my reply" {
+ t.Errorf("buildContent group outgoing = %q, want %q", got, "my reply")
+ }
+}
+
+func TestBuildContent_WhitespaceTrimmedThenMediaPlaceholder(t *testing.T) {
+ // A body that is only whitespace trims to "" so the media-placeholder
+ // branch takes over. This guards the TrimSpace step feeding the empty
+ // check that gates the placeholder.
+ prev := config.ChatwootImportPlaceholderMediaMessage
+ defer func() { config.ChatwootImportPlaceholderMediaMessage = prev }()
+ config.ChatwootImportPlaceholderMediaMessage = true
+
+ msg := &domainChatStorage.Message{Content: " \t ", MediaType: "audio"}
+ if got := buildContent(msg, false); got != "[audio]" {
+ t.Errorf("buildContent whitespace+media = %q, want %q", got, "[audio]")
+ }
+}
+
+func TestBuildContent_GroupEmptyBodyPlaceholderOffYieldsLabelOnly(t *testing.T) {
+ // Group incoming message, no body, media placeholder disabled: body stays
+ // empty after trimming so the group branch returns "<label>:" (the colon
+ // form), proving the label-only path is reachable.
+ prev := config.ChatwootImportPlaceholderMediaMessage
+ defer func() { config.ChatwootImportPlaceholderMediaMessage = prev }()
+ config.ChatwootImportPlaceholderMediaMessage = false
+
+ msg := &domainChatStorage.Message{MediaType: "image", Sender: "[email protected]"}
+ if got := buildContent(msg, true); got != "628111:" {
+ t.Errorf("buildContent group empty body = %q, want %q", got, "628111:")
+ }
+}
+
+// ---------------------------------------------------------------------------
+// insertMessage — error / empty-content / idempotency branches.
+// Sender resolution itself is covered in writer_test.go; these exercise the
+// early-return paths that the sender-resolution table does not.
+// ---------------------------------------------------------------------------
+
+func TestInsertMessage_EmptyIDReturnsErrorNoSQL(t *testing.T) {
+ // An empty message ID is rejected before any SQL is issued — registering
+ // no expectations proves the function never touches the connection.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectBegin()
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+
+ _, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20,
+ &domainChatStorage.Message{ID: ""}, false)
+ if wrote {
+ t.Errorf("wrote = true, want false on empty ID")
+ }
+ if err == nil || err.Error() != "empty message ID" {
+ t.Errorf("err = %v, want \"empty message ID\"", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessage_IdempotencyHitReturnsFalseNoInsert(t *testing.T) {
+ // When the idempotency probe finds an existing row, insertMessage returns
+ // (false, nil) and must NOT issue an INSERT — the row already exists.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-dup").
+ WillReturnRows(sqlmock.NewRows([]string{"id", "conversation_id"}).AddRow(1, 300))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20,
+ &domainChatStorage.Message{ID: "wa-dup", Content: "hi"}, false)
+ if err != nil {
+ t.Fatalf("insertMessage: %v", err)
+ }
+ if wrote {
+ t.Errorf("wrote = true, want false on idempotency hit")
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessage_EmptyContentSkipsAfterProbeMiss(t *testing.T) {
+ // Probe misses (ErrNoRows) but the computed content is empty (no body, no
+ // media placeholder): insertMessage returns (false, nil) WITHOUT an INSERT
+ // so blank rows never pollute Chatwoot's UI.
+ prev := config.ChatwootImportPlaceholderMediaMessage
+ defer func() { config.ChatwootImportPlaceholderMediaMessage = prev }()
+ config.ChatwootImportPlaceholderMediaMessage = false
+
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-empty").
+ WillReturnError(sql.ErrNoRows)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ // Content empty and MediaType set but placeholder OFF => content == "".
+ _, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20,
+ &domainChatStorage.Message{ID: "wa-empty", MediaType: "image"}, false)
+ if err != nil {
+ t.Fatalf("insertMessage: %v", err)
+ }
+ if wrote {
+ t.Errorf("wrote = true, want false on empty content")
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessage_ProbeQueryErrorPropagates(t *testing.T) {
+ // A non-ErrNoRows probe error is surfaced to the caller verbatim (not
+ // swallowed as a skip), so the savepoint wrapper can roll back the row.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ probeErr := errors.New("probe boom")
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-err").
+ WillReturnError(probeErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20,
+ &domainChatStorage.Message{ID: "wa-err", Content: "hi"}, false)
+ if wrote {
+ t.Errorf("wrote = true, want false on probe error")
+ }
+ if !errors.Is(err, probeErr) {
+ t.Errorf("err = %v, want probe boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessage_ReturnsChatwootLinkForInsertedMessage(t *testing.T) {
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ now := time.Date(2026, time.June, 6, 11, 0, 0, 0, time.UTC)
+ msg := &domainChatStorage.Message{
+ ID: "wa-linked",
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ Content: "linked message",
+ Timestamp: now,
+ }
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-linked").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WithArgs(
+ "linked message",
+ imp.accountID,
+ imp.inboxID,
+ 10,
+ messageTypeIncoming,
+ now,
+ messageStatusDelivered,
+ "WAID:wa-linked",
+ contentTypeText,
+ "Contact",
+ int64(20),
+ sqlmock.AnyArg(),
+ ).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(303))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ link, wrote, err := imp.insertMessage(context.Background(), tx, 10, 20, msg, false)
+ if err != nil {
+ t.Fatalf("insertMessage: %v", err)
+ }
+ if !wrote {
+ t.Fatal("wrote = false, want true")
+ }
+ if link == nil {
+ t.Fatal("expected chatwoot message link")
+ }
+ if link.ChatwootMessageID != 303 || link.ChatwootConversationID != 10 || link.SourceID != "WAID:wa-linked" {
+ t.Fatalf("unexpected link: %+v", link)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessage_GroupIncomingContentGetsSenderPrefix(t *testing.T) {
+ // Group incoming message: the INSERT's content arg carries the
+ // "<label>: <body>" prefix produced by buildContent. Pinning the content
+ // arg proves the group-prefix branch feeds the persisted row, not just the
+ // unit-tested buildContent helper.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ ts := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ msg := &domainChatStorage.Message{
+ ID: "wa-grp",
+ Content: "morning",
+ Timestamp: ts,
+ Sender: "[email protected]",
+ }
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:wa-grp").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WithArgs(
+ "628999: morning", // content carries the group sender prefix
+ imp.accountID,
+ imp.inboxID,
+ 55, // conversation_id
+ 0, // message_type (incoming)
+ ts, // created_at/updated_at
+ 1, // status (delivered)
+ "WAID:wa-grp", // source_id
+ 0, // content_type
+ "Contact", // sender_type (incoming -> Contact)
+ int64(77), // sender_id (contactID)
+ sqlmock.AnyArg(), // additional_attributes
+ ).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessage(context.Background(), tx, 55, 77, msg, true)
+ if err != nil {
+ t.Fatalf("insertMessage: %v", err)
+ }
+ if !wrote {
+ t.Errorf("wrote = false, want true")
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// insertMessageSavepoint — SAVEPOINT / RELEASE / ROLLBACK orchestration.
+// ---------------------------------------------------------------------------
+
+func TestInsertMessageSavepoint_Success(t *testing.T) {
+ // Happy path: SAVEPOINT -> probe miss -> INSERT -> RELEASE SAVEPOINT.
+ // wrote=true and no error.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ ts := time.Date(2026, 5, 9, 10, 0, 0, 0, time.UTC)
+ msg := &domainChatStorage.Message{ID: "sp-ok", Content: "hi", Timestamp: ts}
+
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:sp-ok").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessageSavepoint(context.Background(), tx, 10, 20, msg, false)
+ if err != nil {
+ t.Fatalf("insertMessageSavepoint: %v", err)
+ }
+ if !wrote {
+ t.Errorf("wrote = false, want true")
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessageSavepoint_InsertErrorRollsBackToSavepoint(t *testing.T) {
+ // A per-row INSERT error is NOT fatal: the function rolls back to the
+ // savepoint and returns the underlying error (un-wrapped, not txFatalError)
+ // so the caller counts a single failed message and keeps going.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ insertErr := errors.New("insert boom")
+ msg := &domainChatStorage.Message{ID: "sp-fail", Content: "hi"}
+
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:sp-fail").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WillReturnError(insertErr)
+ mock.ExpectExec(regexp.QuoteMeta("ROLLBACK TO SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessageSavepoint(context.Background(), tx, 10, 20, msg, false)
+ if wrote {
+ t.Errorf("wrote = true, want false on insert error")
+ }
+ if !errors.Is(err, insertErr) {
+ t.Errorf("err = %v, want insert boom", err)
+ }
+ // Must NOT be a txFatalError — a single bad row is recoverable.
+ var fatal txFatalError
+ if errors.As(err, &fatal) {
+ t.Errorf("err classified as txFatalError; want recoverable error")
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessageSavepoint_SavepointExecErrorIsFatal(t *testing.T) {
+ // If creating the SAVEPOINT itself fails, the whole tx is broken: the
+ // function returns a txFatalError so ImportChat aborts the message loop
+ // instead of churning every remaining row.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ spErr := errors.New("savepoint boom")
+ msg := &domainChatStorage.Message{ID: "sp-conn", Content: "hi"}
+
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnError(spErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessageSavepoint(context.Background(), tx, 10, 20, msg, false)
+ if wrote {
+ t.Errorf("wrote = true, want false on savepoint error")
+ }
+ var fatal txFatalError
+ if !errors.As(err, &fatal) {
+ t.Fatalf("err = %v, want txFatalError", err)
+ }
+ if !errors.Is(err, spErr) {
+ t.Errorf("txFatalError did not wrap underlying savepoint error: %v", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessageSavepoint_ReleaseErrorIsFatal(t *testing.T) {
+ // RELEASE failing on an otherwise-successful write means the connection is
+ // wedged. The function returns txFatalError but preserves wrote=true (the
+ // row did land) so callers can distinguish "written then connection died".
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ relErr := errors.New("release boom")
+ msg := &domainChatStorage.Message{ID: "sp-rel", Content: "hi"}
+
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:sp-rel").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
+ mock.ExpectExec(regexp.QuoteMeta("RELEASE SAVEPOINT cw_msg")).
+ WillReturnError(relErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessageSavepoint(context.Background(), tx, 10, 20, msg, false)
+ if !wrote {
+ t.Errorf("wrote = false, want true (the row was written before RELEASE failed)")
+ }
+ var fatal txFatalError
+ if !errors.As(err, &fatal) {
+ t.Fatalf("err = %v, want txFatalError", err)
+ }
+ if !errors.Is(err, relErr) {
+ t.Errorf("txFatalError did not wrap underlying release error: %v", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestInsertMessageSavepoint_RollbackErrorBecomesFatal(t *testing.T) {
+ // When the per-row INSERT fails AND the ROLLBACK TO SAVEPOINT also fails,
+ // the connection is unrecoverable: the recoverable insert error is
+ // upgraded to txFatalError so the loop aborts rather than spinning.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ insertErr := errors.New("insert boom")
+ rbErr := errors.New("rollback boom")
+ msg := &domainChatStorage.Message{ID: "sp-rb", Content: "hi"}
+
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta("SAVEPOINT cw_msg")).
+ WillReturnResult(sqlmock.NewResult(0, 0))
+ mock.ExpectQuery(regexp.QuoteMeta(idempotencyProbeSQL)).
+ WithArgs(imp.inboxID, "WAID:sp-rb").
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(`INSERT INTO messages`).
+ WillReturnError(insertErr)
+ mock.ExpectExec(regexp.QuoteMeta("ROLLBACK TO SAVEPOINT cw_msg")).
+ WillReturnError(rbErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, wrote, err := imp.insertMessageSavepoint(context.Background(), tx, 10, 20, msg, false)
+ if wrote {
+ t.Errorf("wrote = true, want false")
+ }
+ var fatal txFatalError
+ if !errors.As(err, &fatal) {
+ t.Fatalf("err = %v, want txFatalError when rollback fails", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// upsertContact — phone fallback branch (JID miss -> phone hit -> attach attr)
+// ---------------------------------------------------------------------------
+
+const attachJIDAttributeSQL = `
+ UPDATE contacts
+ SET custom_attributes = COALESCE(custom_attributes, '{}'::jsonb)
+ || jsonb_build_object('gowa_whatsapp_jid', $1::text),
+ updated_at = now()
+ WHERE id = $2
+ `
+
+func TestUpsertContact_PhoneFallbackFoundAttachesJID(t *testing.T) {
+ // 1:1 chat where the JID lookup misses but a contact with the same phone
+ // number already exists (e.g. created by the live REST path without our
+ // custom attribute). We reuse that row and attach gowa_whatsapp_jid so the
+ // next import resolves it on the fast path — no duplicate contact created.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ const phone = "+6281234567890"
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(`
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1 AND phone_number = $2
+ LIMIT 1
+ `)).
+ WithArgs(imp.accountID, phone).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(555))
+ mock.ExpectExec(regexp.QuoteMeta(attachJIDAttributeSQL)).
+ WithArgs(jid, 555).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContact(context.Background(), tx, jid, "Alice", false)
+ if err != nil {
+ t.Fatalf("upsertContact: %v", err)
+ }
+ if id != 555 {
+ t.Errorf("id = %d, want 555 (reused phone-matched contact)", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContact_PhoneLookupErrorPropagates(t *testing.T) {
+ // A non-ErrNoRows error from the phone fallback lookup is surfaced to the
+ // caller (which rolls back the whole chat tx) — it must not silently fall
+ // through to an INSERT and risk a duplicate.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ const phone = "+6281234567890"
+ lookupErr := errors.New("phone lookup boom")
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(`
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1 AND phone_number = $2
+ LIMIT 1
+ `)).
+ WithArgs(imp.accountID, phone).
+ WillReturnError(lookupErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.upsertContact(context.Background(), tx, jid, "Alice", false)
+ if !errors.Is(err, lookupErr) {
+ t.Errorf("err = %v, want phone lookup boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContact_InsertContactErrorPropagates(t *testing.T) {
+ // Brand-new contact path where the INSERT ... RETURNING id fails: the error
+ // is wrapped ("insert contact: ...") and returned so the chat tx rolls back.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ const phone = "+6281234567890"
+ insErr := errors.New("insert contact boom")
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(`
+ SELECT id
+ FROM contacts
+ WHERE account_id = $1 AND phone_number = $2
+ LIMIT 1
+ `)).
+ WithArgs(imp.accountID, phone).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(`
+ INSERT INTO contacts
+ (account_id, name, phone_number, identifier,
+ custom_attributes, additional_attributes, created_at, updated_at)
+ VALUES
+ ($1, $2, NULLIF($3, ''), NULLIF($4, ''),
+ $5::jsonb, '{}'::jsonb, now(), now())
+ RETURNING id
+ `)).
+ WithArgs(imp.accountID, sqlmock.AnyArg(), phone, sqlmock.AnyArg(), sqlmock.AnyArg()).
+ WillReturnError(insErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.upsertContact(context.Background(), tx, jid, "Alice", false)
+ if !errors.Is(err, insErr) {
+ t.Errorf("err = %v, want wrapped insert contact boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContact_GroupCreatesNewWithJIDIdentifier(t *testing.T) {
+ // A brand-new group contact has no phone number, so the phone fallback is
+ // skipped entirely (phone == "") and the INSERT runs with the JID as
+ // identifier. Asserts the create path for groups bypasses the phone branch.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const groupJID = "[email protected]"
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, groupJID).
+ WillReturnError(sql.ErrNoRows)
+ // No phone lookup expected for a group (phone == ""). INSERT runs with an
+ // empty phone_number arg (NULLIF turns "" into NULL) and the JID identifier.
+ mock.ExpectQuery(regexp.QuoteMeta(`
+ INSERT INTO contacts
+ (account_id, name, phone_number, identifier,
+ custom_attributes, additional_attributes, created_at, updated_at)
+ VALUES
+ ($1, $2, NULLIF($3, ''), NULLIF($4, ''),
+ $5::jsonb, '{}'::jsonb, now(), now())
+ `)).
+ WithArgs(imp.accountID, "Team", "", groupJID, sqlmock.AnyArg()).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(666))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContact(context.Background(), tx, groupJID, "Team", true)
+ if err != nil {
+ t.Fatalf("upsertContact: %v", err)
+ }
+ if id != 666 {
+ t.Errorf("id = %d, want 666", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContact_JIDLookupErrorPropagates(t *testing.T) {
+ // A non-ErrNoRows error from the very first JID lookup short-circuits with
+ // the raw error (no phone fallback, no INSERT attempted).
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ jidErr := errors.New("jid lookup boom")
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(upsertContactByJIDSQL)).
+ WithArgs(imp.accountID, jid).
+ WillReturnError(jidErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.upsertContact(context.Background(), tx, jid, "Alice", false)
+ if !errors.Is(err, jidErr) {
+ t.Errorf("err = %v, want jid lookup boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// upsertContactInbox
+// ---------------------------------------------------------------------------
+
+func TestUpsertContactInbox_ExistingReturnsIDNoInsert(t *testing.T) {
+ // The SELECT finds an existing contact_inbox row, so the function returns
+ // its id WITHOUT issuing the INSERT ... ON CONFLICT.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(500, imp.inboxID).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(900))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContactInbox(context.Background(), tx, 500, "[email protected]")
+ if err != nil {
+ t.Fatalf("upsertContactInbox: %v", err)
+ }
+ if id != 900 {
+ t.Errorf("id = %d, want 900", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContactInbox_MissingInsertsReturnsID(t *testing.T) {
+ // SELECT misses (ErrNoRows) => INSERT ... ON CONFLICT (inbox_id, source_id)
+ // runs with the contact id, inbox id, and JID as source_id, returning the
+ // new id.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(500, imp.inboxID).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertContactInboxSQL)).
+ WithArgs(500, imp.inboxID, jid).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(901))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.upsertContactInbox(context.Background(), tx, 500, jid)
+ if err != nil {
+ t.Fatalf("upsertContactInbox: %v", err)
+ }
+ if id != 901 {
+ t.Errorf("id = %d, want 901", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContactInbox_SelectErrorPropagates(t *testing.T) {
+ // A non-ErrNoRows SELECT error short-circuits before the INSERT, surfacing
+ // the underlying error to the caller (which rolls back the whole chat tx).
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ selErr := errors.New("select boom")
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(500, imp.inboxID).
+ WillReturnError(selErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.upsertContactInbox(context.Background(), tx, 500, "[email protected]")
+ if !errors.Is(err, selErr) {
+ t.Errorf("err = %v, want select boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestUpsertContactInbox_InsertErrorPropagates(t *testing.T) {
+ // SELECT misses, then the INSERT ... ON CONFLICT RETURNING id fails: the
+ // error is wrapped ("insert contact_inbox: ...") and returned.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ const jid = "[email protected]"
+ insErr := errors.New("inbox insert boom")
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectContactInboxSQL)).
+ WithArgs(500, imp.inboxID).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertContactInboxSQL)).
+ WithArgs(500, imp.inboxID, jid).
+ WillReturnError(insErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.upsertContactInbox(context.Background(), tx, 500, jid)
+ if !errors.Is(err, insErr) {
+ t.Errorf("err = %v, want wrapped inbox insert boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// findOrCreateConversation
+// ---------------------------------------------------------------------------
+
+func TestFindOrCreateConversation_ExistingReturnsIDNoInsert(t *testing.T) {
+ // An existing conversation is reused (matched regardless of status) so a
+ // resolved-then-reimported chat does not spawn a duplicate row.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(42, conversationStatusOpen))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, nil)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 42 {
+ t.Errorf("id = %d, want 42", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_CreatesWithFirstMessageTimestamp(t *testing.T) {
+ // On a miss, the new conversation's created_at (and waiting_since /
+ // last_activity_at, all the same $6 placeholder) is pinned to msgs[0]'s
+ // timestamp so Chatwoot's UI sorts the thread at the real first-message
+ // time, not import time.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ first := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
+ msgs := []*domainChatStorage.Message{
+ {ID: "m1", Timestamp: first},
+ {ID: "m2", Timestamp: first.Add(time.Hour)},
+ }
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusOpen, 500, 600, first).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(43))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, msgs)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 43 {
+ t.Errorf("id = %d, want 43", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_EmptyMsgsUsesNowish(t *testing.T) {
+ // With no messages (and likewise a zero-time first message), created_at
+ // falls back to time.Now(). We can't pin an exact value, so we assert the
+ // arg is a non-zero time close to now via a custom matcher.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ before := time.Now()
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusOpen, 500, 600,
+ nowishArg{notBefore: before}).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(44))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, nil)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 44 {
+ t.Errorf("id = %d, want 44", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_ZeroTimeFirstMsgUsesNowish(t *testing.T) {
+ // A first message carrying a zero Timestamp also triggers the now() branch
+ // (the guard is `!msgs[0].Timestamp.IsZero()`), so created_at is now-ish
+ // rather than year 0001.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ before := time.Now()
+ msgs := []*domainChatStorage.Message{{ID: "m1"}} // zero Timestamp
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusOpen, 500, 600,
+ nowishArg{notBefore: before}).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(45))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, msgs)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 45 {
+ t.Errorf("id = %d, want 45", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_SelectErrorPropagates(t *testing.T) {
+ // Non-ErrNoRows SELECT error short-circuits before the INSERT.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ selErr := errors.New("conv select boom")
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(selErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.findOrCreateConversation(context.Background(), tx, 500, 600, nil)
+ if !errors.Is(err, selErr) {
+ t.Errorf("err = %v, want conv select boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_InsertErrorPropagates(t *testing.T) {
+ // SELECT misses, then the INSERT ... RETURNING id fails: the error is
+ // wrapped ("insert conversation: ...") and returned to abort the chat tx.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ first := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
+ msgs := []*domainChatStorage.Message{{ID: "m1", Timestamp: first}}
+ insErr := errors.New("conv insert boom")
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusOpen, 500, 600, first).
+ WillReturnError(insErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ _, err = imp.findOrCreateConversation(context.Background(), tx, 500, 600, msgs)
+ if !errors.Is(err, insErr) {
+ t.Errorf("err = %v, want wrapped conv insert boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_CreatesPendingWhenConfigured(t *testing.T) {
+ // With CHATWOOT_CONVERSATION_PENDING=true, a newly created conversation must
+ // land in `pending` (status 2), mirroring the REST path, instead of `open`.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ prevPending := config.ChatwootConversationPending
+ defer func() { config.ChatwootConversationPending = prevPending }()
+ config.ChatwootConversationPending = true
+
+ first := time.Date(2025, 1, 2, 3, 4, 5, 0, time.UTC)
+ msgs := []*domainChatStorage.Message{{ID: "m1", Timestamp: first}}
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnError(sql.ErrNoRows)
+ mock.ExpectQuery(regexp.QuoteMeta(insertConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, conversationStatusPending, 500, 600, first).
+ WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(43))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, msgs)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 43 {
+ t.Errorf("id = %d, want 43", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_ReopensResolvedReusedConversation(t *testing.T) {
+ // With CHATWOOT_REOPEN_CONVERSATION=true (default), reusing a *resolved*
+ // conversation flips it back to the new-status via an UPDATE so the returning
+ // customer's thread resurfaces in the agent queue — matching the REST path.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ prevReopen := config.ChatwootReopenConversation
+ prevPending := config.ChatwootConversationPending
+ defer func() {
+ config.ChatwootReopenConversation = prevReopen
+ config.ChatwootConversationPending = prevPending
+ }()
+ config.ChatwootReopenConversation = true
+ config.ChatwootConversationPending = false
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(42, conversationStatusResolved))
+ mock.ExpectExec("UPDATE conversations").
+ WithArgs(conversationStatusOpen, 42, imp.accountID, conversationStatusResolved).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, nil)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 42 {
+ t.Errorf("id = %d, want 42", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestFindOrCreateConversation_NoReopenWhenDisabled(t *testing.T) {
+ // With CHATWOOT_REOPEN_CONVERSATION=false, a reused resolved conversation is
+ // returned as-is with no status UPDATE (no extra query is expected).
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ prevReopen := config.ChatwootReopenConversation
+ defer func() { config.ChatwootReopenConversation = prevReopen }()
+ config.ChatwootReopenConversation = false
+
+ mock.ExpectBegin()
+ mock.ExpectQuery(regexp.QuoteMeta(selectConversationSQL)).
+ WithArgs(imp.accountID, imp.inboxID, 500).
+ WillReturnRows(sqlmock.NewRows([]string{"id", "status"}).AddRow(42, conversationStatusResolved))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ id, err := imp.findOrCreateConversation(context.Background(), tx, 500, 600, nil)
+ if err != nil {
+ t.Fatalf("findOrCreateConversation: %v", err)
+ }
+ if id != 42 {
+ t.Errorf("id = %d, want 42", id)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// nowishArg matches a driver time.Time argument that is at or after notBefore
+// and no further than a few seconds into the future — i.e. a value produced by
+// a time.Now() call during the test. It lets us assert the now() fallback
+// branch without pinning an exact instant.
+type nowishArg struct {
+ notBefore time.Time
+}
+
+func (n nowishArg) Match(v driver.Value) bool {
+ got, ok := v.(time.Time)
+ if !ok {
+ return false
+ }
+ if got.IsZero() {
+ return false
+ }
+ return !got.Before(n.notBefore) && got.Before(n.notBefore.Add(10*time.Second))
+}
+
+// ---------------------------------------------------------------------------
+// touchConversation
+// ---------------------------------------------------------------------------
+
+func TestTouchConversation_IssuesGreatestUpdate(t *testing.T) {
+ // touchConversation runs the GREATEST(...) UPDATE with the conversation id
+ // ($1) and the supplied activity time ($2). GREATEST keeps last_activity_at
+ // monotonic so a later import never moves the thread backwards.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ at := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(777, at).
+ WillReturnResult(sqlmock.NewResult(0, 1))
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ if err := imp.touchConversation(context.Background(), tx, 777, at); err != nil {
+ t.Fatalf("touchConversation: %v", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+func TestTouchConversation_ErrorPropagates(t *testing.T) {
+ // touchConversation surfaces the UPDATE error to its caller; ImportChat
+ // treats it as a transaction failure and rolls back the chat import.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ updErr := errors.New("touch boom")
+ at := time.Date(2026, 6, 1, 12, 0, 0, 0, time.UTC)
+ mock.ExpectBegin()
+ mock.ExpectExec(regexp.QuoteMeta(touchConversationSQL)).
+ WithArgs(777, at).
+ WillReturnError(updErr)
+
+ tx, err := imp.db.BeginTx(context.Background(), nil)
+ if err != nil {
+ t.Fatalf("BeginTx: %v", err)
+ }
+ if err := imp.touchConversation(context.Background(), tx, 777, at); !errors.Is(err, updErr) {
+ t.Errorf("err = %v, want touch boom", err)
+ }
+ _ = tx.Rollback()
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Close
+// ---------------------------------------------------------------------------
+
+func TestClose_IdempotentSetsClosed(t *testing.T) {
+ // Close uses sync.Once: the first call closes the pool and flips the closed
+ // flag; the second is a no-op (ExpectClose is registered once, so a second
+ // db.Close would trip an unexpected-call failure). The flag must read true
+ // after the first call.
+ imp, mock, cleanup := newUpsertContactTestImporter(t)
+ defer cleanup()
+
+ mock.ExpectClose()
+
+ if err := imp.Close(); err != nil {
+ t.Fatalf("first Close: %v", err)
+ }
+ if !imp.closed.Load() {
+ t.Errorf("closed flag = false after Close, want true")
+ }
+ // Second call must not touch the DB again (sync.Once guards it).
+ if err := imp.Close(); err != nil {
+ t.Fatalf("second Close: %v", err)
+ }
+ if err := mock.ExpectationsWereMet(); err != nil {
+ t.Errorf("unmet sqlmock expectations: %v", err)
+ }
+}
diff --git a/src/infrastructure/chatwoot/provision.go b/src/infrastructure/chatwoot/provision.go
new file mode 100644
index 00000000..0129b976
--- /dev/null
+++ b/src/infrastructure/chatwoot/provision.go
@@ -0,0 +1,84 @@
+package chatwoot
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/sirupsen/logrus"
+)
+
+// EnsureInbox provisions the Chatwoot inbox at startup when auto-create is
+// enabled. It reuses an existing inbox whose name matches
+// config.ChatwootInboxName — so restarts never pile up duplicates — and
+// otherwise creates a fresh API-channel inbox wired to config.ChatwootWebhookURL.
+// On success it sets config.ChatwootInboxID (and the passed client's InboxID)
+// so both the REST client and the direct-DB importer target the resolved inbox.
+//
+// It is a no-op when auto-create is disabled, when the client is not minimally
+// configured (URL + token + account id), or when an explicit CHATWOOT_INBOX_ID
+// is already set — that value is treated as the operator's override.
+func EnsureInbox(client *Client) error {
+ if !config.ChatwootAutoCreate {
+ return nil
+ }
+ if client == nil || client.BaseURL == "" || client.APIToken == "" || client.AccountID == 0 {
+ logrus.Warn("Chatwoot auto-create: skipped — CHATWOOT_URL, CHATWOOT_API_TOKEN, and CHATWOOT_ACCOUNT_ID must all be set")
+ return nil
+ }
+ if config.ChatwootInboxID != 0 {
+ logrus.Infof("Chatwoot auto-create: CHATWOOT_INBOX_ID=%d already set; skipping provisioning", config.ChatwootInboxID)
+ return nil
+ }
+
+ name := strings.TrimSpace(config.ChatwootInboxName)
+ if name == "" {
+ name = "WhatsApp"
+ }
+
+ inboxes, err := client.ListInboxes()
+ if err != nil {
+ return fmt.Errorf("chatwoot auto-create: list inboxes: %w", err)
+ }
+ // Reuse only an API-channel inbox of the configured name. A same-name inbox
+ // of another (non-API) channel type, often also called "WhatsApp",
+ // cannot receive our agent-reply webhook, so binding
+ // to it would silently break outbound — skip it and create a dedicated API
+ // inbox instead.
+ for _, inbox := range inboxes {
+ if !strings.EqualFold(inbox.Name, name) {
+ continue
+ }
+ if !strings.EqualFold(inbox.ChannelType, "Channel::Api") {
+ logrus.Warnf("Chatwoot auto-create: existing inbox %q (id=%d) is channel %q, not an API channel; creating a separate API inbox (set CHATWOOT_INBOX_ID to use a specific inbox)", inbox.Name, inbox.ID, inbox.ChannelType)
+ continue
+ }
+ applyResolvedInbox(client, inbox)
+ logrus.Infof("Chatwoot auto-create: reusing existing API inbox %q (id=%d)", inbox.Name, inbox.ID)
+ return nil
+ }
+
+ created, err := client.CreateInbox(name, config.ChatwootWebhookURL)
+ if err != nil {
+ return fmt.Errorf("chatwoot auto-create: create inbox: %w", err)
+ }
+ applyResolvedInbox(client, *created)
+ if config.ChatwootWebhookURL == "" {
+ logrus.Warnf("Chatwoot auto-create: created inbox %q (id=%d) WITHOUT a webhook URL — set CHATWOOT_WEBHOOK_URL so Chatwoot agent replies reach WhatsApp", created.Name, created.ID)
+ } else {
+ logrus.Infof("Chatwoot auto-create: created inbox %q (id=%d) with webhook %s", created.Name, created.ID, config.ChatwootWebhookURL)
+ }
+ return nil
+}
+
+// applyResolvedInbox records the resolved inbox id on both the global config
+// (read by the direct-DB importer and freshly-constructed clients) and the
+// live client instance (whose InboxID was 0 before provisioning). The inbox
+// identifier is cached too so read sync never needs a lookup GET to find it.
+func applyResolvedInbox(client *Client, inbox Inbox) {
+ config.ChatwootInboxID = inbox.ID
+ client.InboxID = inbox.ID
+ if inbox.InboxIdentifier != "" {
+ client.InboxIdentifier = inbox.InboxIdentifier
+ }
+}
diff --git a/src/infrastructure/chatwoot/provision_test.go b/src/infrastructure/chatwoot/provision_test.go
new file mode 100644
index 00000000..3dd92874
--- /dev/null
+++ b/src/infrastructure/chatwoot/provision_test.go
@@ -0,0 +1,385 @@
+package chatwoot
+
+import (
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// saveProvisionConfig snapshots every config global EnsureInbox reads or writes
+// and returns a restore func. Provisioning mutates package globals (notably
+// ChatwootInboxID), so without this a leaked value would make sibling tests —
+// and even later cases in the same test — observe the wrong state.
+func saveProvisionConfig(t *testing.T) func() {
+ t.Helper()
+ origAuto := config.ChatwootAutoCreate
+ origInboxID := config.ChatwootInboxID
+ origInboxName := config.ChatwootInboxName
+ origWebhook := config.ChatwootWebhookURL
+ return func() {
+ config.ChatwootAutoCreate = origAuto
+ config.ChatwootInboxID = origInboxID
+ config.ChatwootInboxName = origInboxName
+ config.ChatwootWebhookURL = origWebhook
+ }
+}
+
+func TestEnsureInbox_NoopWhenAutoCreateDisabled(t *testing.T) {
+ // Auto-create off is a hard no-op: EnsureInbox must return nil without ever
+ // touching the network. A server that fails the test on any request proves
+ // no HTTP call is made.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = false
+ config.ChatwootInboxID = 0
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatalf("unexpected HTTP request when auto-create disabled: %s %s", r.Method, r.URL.String())
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+}
+
+func TestEnsureInbox_NoopWhenNotMinimallyConfigured(t *testing.T) {
+ // Even with auto-create on, a client missing URL/token/account id can't
+ // provision anything, so EnsureInbox returns nil without any HTTP. Each
+ // case zeroes exactly one required field to prove all three are checked,
+ // plus a nil client.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatalf("unexpected HTTP request for unconfigured client: %s %s", r.Method, r.URL.String())
+ }))
+ defer server.Close()
+
+ tests := []struct {
+ name string
+ client *Client
+ }{
+ {"nil client", nil},
+ {"empty BaseURL", &Client{APIToken: "t", AccountID: 1, HTTPClient: server.Client()}},
+ {"empty APIToken", &Client{BaseURL: server.URL, AccountID: 1, HTTPClient: server.Client()}},
+ {"zero AccountID", &Client{BaseURL: server.URL, APIToken: "t", HTTPClient: server.Client()}},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if err := EnsureInbox(tc.client); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ })
+ }
+}
+
+func TestEnsureInbox_SkipsWhenInboxIDAlreadySet(t *testing.T) {
+ // An explicit CHATWOOT_INBOX_ID is treated as the operator's override:
+ // EnsureInbox skips provisioning entirely (no HTTP) and leaves the id as-is.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 42
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ t.Fatalf("unexpected HTTP request when inbox id already set: %s %s", r.Method, r.URL.String())
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if config.ChatwootInboxID != 42 {
+ t.Errorf("ChatwootInboxID = %d, want 42 (unchanged)", config.ChatwootInboxID)
+ }
+}
+
+func TestEnsureInbox_ReusesExistingInboxByName(t *testing.T) {
+ // When an inbox already exists whose name matches ChatwootInboxName
+ // case-insensitively, EnsureInbox reuses it: it sets both config and the
+ // live client's InboxID to that inbox and makes NO CreateInbox POST. The
+ // case-insensitive match (config "whatsapp" vs server "WhatsApp") guards
+ // against restarts piling up near-duplicate inboxes.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "whatsapp"
+
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{
+ {ID: 5, Name: "Email"},
+ {ID: 9, Name: "WhatsApp", ChannelType: "Channel::Api"}, // differs only in case -> must match
+ },
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 100})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if createCalls != 0 {
+ t.Errorf("create calls = %d, want 0 (reused existing inbox)", createCalls)
+ }
+ if config.ChatwootInboxID != 9 {
+ t.Errorf("config.ChatwootInboxID = %d, want 9", config.ChatwootInboxID)
+ }
+ if c.InboxID != 9 {
+ t.Errorf("client.InboxID = %d, want 9", c.InboxID)
+ }
+}
+
+func TestEnsureInbox_SkipsSameNameNonAPIInbox(t *testing.T) {
+ // A same-name inbox that is NOT an API channel (e.g. a native WhatsApp
+ // channel also called "WhatsApp") must NOT be reused — binding to it would
+ // silently break agent-reply delivery. EnsureInbox skips it and creates a
+ // dedicated API inbox instead.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "WhatsApp"
+
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{
+ {ID: 9, Name: "WhatsApp", ChannelType: "Channel::Whatsapp"}, // native WA -> must NOT reuse
+ },
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 100, "name": "WhatsApp"})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if createCalls != 1 {
+ t.Errorf("create calls = %d, want 1 (non-API same-name inbox skipped)", createCalls)
+ }
+ if config.ChatwootInboxID != 100 || c.InboxID != 100 {
+ t.Errorf("inbox id config=%d client=%d, want 100 (newly created API inbox)", config.ChatwootInboxID, c.InboxID)
+ }
+}
+
+func TestEnsureInbox_ReusesAPIInboxOverSameNameNonAPI(t *testing.T) {
+ // When both a non-API and an API inbox share the configured name, the API
+ // one is reused and no inbox is created.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "WhatsApp"
+
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{
+ {ID: 7, Name: "WhatsApp", ChannelType: "Channel::Whatsapp"}, // skipped
+ {ID: 9, Name: "WhatsApp", ChannelType: "Channel::Api"}, // reused
+ },
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 100})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if createCalls != 0 {
+ t.Errorf("create calls = %d, want 0 (reused same-name API inbox)", createCalls)
+ }
+ if config.ChatwootInboxID != 9 || c.InboxID != 9 {
+ t.Errorf("inbox id config=%d client=%d, want 9 (API inbox)", config.ChatwootInboxID, c.InboxID)
+ }
+}
+
+func TestEnsureInbox_CreatesWhenNoNameMatch(t *testing.T) {
+ // No existing inbox matches the configured name, so EnsureInbox creates a
+ // fresh one and adopts the created id into both config and the client. We
+ // also confirm the name and webhook from config flow into the POST body.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "Support"
+ config.ChatwootWebhookURL = "https://hook.example/webhook"
+
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{{ID: 5, Name: "Email"}}, // no "Support" -> create
+ })
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ createCalls++
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatalf("decode create body: %v", err)
+ }
+ if body["name"] != "Support" {
+ t.Errorf("create name = %v, want Support", body["name"])
+ }
+ ch, _ := body["channel"].(map[string]any)
+ if ch["webhook_url"] != "https://hook.example/webhook" {
+ t.Errorf("webhook_url = %v, want config value", ch["webhook_url"])
+ }
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 123, "name": "Support"})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if createCalls != 1 {
+ t.Errorf("create calls = %d, want 1", createCalls)
+ }
+ if config.ChatwootInboxID != 123 {
+ t.Errorf("config.ChatwootInboxID = %d, want 123", config.ChatwootInboxID)
+ }
+ if c.InboxID != 123 {
+ t.Errorf("client.InboxID = %d, want 123", c.InboxID)
+ }
+}
+
+func TestEnsureInbox_DefaultsNameToWhatsAppWhenBlank(t *testing.T) {
+ // A blank/whitespace ChatwootInboxName falls back to "WhatsApp" before the
+ // name match runs, so an existing "WhatsApp" inbox is still reused without
+ // creating a duplicate.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = " "
+
+ createCalls := 0
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{
+ "payload": []Inbox{{ID: 8, Name: "WhatsApp", ChannelType: "Channel::Api"}},
+ })
+ case r.Method == http.MethodPost:
+ createCalls++
+ writeJSON(t, w, http.StatusOK, map[string]any{"id": 100})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ if err := EnsureInbox(c); err != nil {
+ t.Fatalf("EnsureInbox: %v", err)
+ }
+ if createCalls != 0 {
+ t.Errorf("create calls = %d, want 0 (matched default WhatsApp name)", createCalls)
+ }
+ if config.ChatwootInboxID != 8 || c.InboxID != 8 {
+ t.Errorf("inbox id config=%d client=%d, want 8", config.ChatwootInboxID, c.InboxID)
+ }
+}
+
+func TestEnsureInbox_WrapsListInboxesError(t *testing.T) {
+ // A ListInboxes failure aborts provisioning with a wrapped error so startup
+ // surfaces the cause. The wrapped HTTPStatusError must still be unwrappable.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "WhatsApp"
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet || r.URL.Path != "/api/v1/accounts/1/inboxes" {
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ writeJSON(t, w, http.StatusInternalServerError, map[string]any{"error": "boom"})
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ err := EnsureInbox(c)
+ if err == nil {
+ t.Fatal("expected error from ListInboxes failure, got nil")
+ }
+ if !strings.Contains(err.Error(), "list inboxes") {
+ t.Errorf("err = %v, want it to mention 'list inboxes'", err)
+ }
+ var httpErr *HTTPStatusError
+ if !errors.As(err, &httpErr) {
+ t.Fatalf("err = %v, want wrapped *HTTPStatusError", err)
+ }
+ if httpErr.StatusCode != http.StatusInternalServerError {
+ t.Errorf("StatusCode = %d, want 500", httpErr.StatusCode)
+ }
+ // Provisioning failed, so the inbox id must remain unset.
+ if config.ChatwootInboxID != 0 {
+ t.Errorf("config.ChatwootInboxID = %d, want 0 (unchanged on error)", config.ChatwootInboxID)
+ }
+}
+
+func TestEnsureInbox_WrapsCreateInboxError(t *testing.T) {
+ // When no inbox matches and CreateInbox fails, EnsureInbox returns a wrapped
+ // "create inbox" error and leaves the inbox id unset.
+ defer saveProvisionConfig(t)()
+ config.ChatwootAutoCreate = true
+ config.ChatwootInboxID = 0
+ config.ChatwootInboxName = "Support"
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch {
+ case r.Method == http.MethodGet && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusOK, map[string]any{"payload": []Inbox{}})
+ case r.Method == http.MethodPost && r.URL.Path == "/api/v1/accounts/1/inboxes":
+ writeJSON(t, w, http.StatusUnprocessableEntity, map[string]any{"error": "taken"})
+ default:
+ t.Fatalf("unexpected request: %s %s", r.Method, r.URL.String())
+ }
+ }))
+ defer server.Close()
+
+ c := newTestClient(t, server.URL)
+ err := EnsureInbox(c)
+ if err == nil {
+ t.Fatal("expected error from CreateInbox failure, got nil")
+ }
+ if !strings.Contains(err.Error(), "create inbox") {
+ t.Errorf("err = %v, want it to mention 'create inbox'", err)
+ }
+ if config.ChatwootInboxID != 0 {
+ t.Errorf("config.ChatwootInboxID = %d, want 0 (unchanged on error)", config.ChatwootInboxID)
+ }
+}
diff --git a/src/infrastructure/chatwoot/sync.go b/src/infrastructure/chatwoot/sync.go
index 053693fb..71c0ae3c 100644
--- a/src/infrastructure/chatwoot/sync.go
+++ b/src/infrastructure/chatwoot/sync.go
@@ -10,11 +10,14 @@ import (
"sync"
"time"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot/pgimport"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
"go.mau.fi/whatsmeow/proto/waE2E"
+ "go.mau.fi/whatsmeow/types"
"google.golang.org/protobuf/proto"
)
@@ -26,6 +29,14 @@ type SyncService struct {
// Track sync progress per device
progressMap map[string]*SyncProgress
progressMu sync.RWMutex
+
+ // pgImporter is the optional direct-Postgres history importer. When
+ // non-nil (i.e. when config.ChatwootImportDBURI is set), SyncHistory
+ // writes rows into Chatwoot's schema directly instead of replaying
+ // every message through the REST API. Live message forwarding and
+ // inbound handling always use the REST client, regardless of this.
+ pgImporter *pgimport.Importer
+ pgInitMu sync.Mutex
}
// NewSyncService creates a new sync service instance
@@ -40,6 +51,80 @@ func NewSyncService(
}
}
+// groupNameResolver memoizes GetGroupInfo lookups for the duration of a
+// single sync run. Scoping the cache per-run (rather than per-SyncService)
+// avoids cross-device pollution when two devices sync concurrently and may
+// see different subjects for the same group.
+type groupNameResolver struct {
+ mu sync.Mutex
+ cache map[string]string
+}
+
+func newGroupNameResolver() *groupNameResolver {
+ return &groupNameResolver{cache: make(map[string]string)}
+}
+
+// resolve looks up a group's real subject via whatsmeow, caching the
+// result. Returns "" on parse/RPC failure so the caller can fall back to
+// the stored chat name.
+func (g *groupNameResolver) resolve(ctx context.Context, waClient *whatsmeow.Client, chatJID string) string {
+ if waClient == nil {
+ return ""
+ }
+ g.mu.Lock()
+ if cached, ok := g.cache[chatJID]; ok {
+ g.mu.Unlock()
+ return cached
+ }
+ g.mu.Unlock()
+
+ jid, err := types.ParseJID(chatJID)
+ if err != nil {
+ return ""
+ }
+ lookupCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
+ defer cancel()
+ info, err := waClient.GetGroupInfo(lookupCtx, jid)
+ if err != nil || info == nil || info.Name == "" {
+ return ""
+ }
+
+ g.mu.Lock()
+ g.cache[chatJID] = info.Name
+ g.mu.Unlock()
+ return info.Name
+}
+
+// pgImporterForSync returns the shared direct-Postgres importer, opening it
+// lazily the first time it's requested. A blank import DB URI means the REST
+// path is selected. A configured-but-broken URI is a sync error, not a REST
+// fallback, because operators explicitly opted into direct DB import.
+func (s *SyncService) pgImporterForSync(ctx context.Context) (*pgimport.Importer, error) {
+ if strings.TrimSpace(config.ChatwootImportDBURI) == "" {
+ return nil, nil
+ }
+ s.pgInitMu.Lock()
+ defer s.pgInitMu.Unlock()
+ if s.pgImporter != nil {
+ return s.pgImporter, nil
+ }
+ imp, err := pgimport.New(ctx, pgimport.Config{
+ DSN: config.ChatwootImportDBURI,
+ AccountID: config.ChatwootAccountID,
+ InboxID: config.ChatwootInboxID,
+ // APIToken is forwarded so the importer can resolve the Chatwoot
+ // agent that owns this token from the access_tokens table.
+ // Outgoing imported messages get stamped with that agent so they
+ // render with a name/avatar instead of as "Unknown sender".
+ APIToken: config.ChatwootAPIToken,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("chatwoot pgimport: %w", err)
+ }
+ s.pgImporter = imp
+ return s.pgImporter, nil
+}
+
// GetProgress returns the current sync progress for a device
func (s *SyncService) GetProgress(deviceID string) *SyncProgress {
s.progressMu.RLock()
@@ -78,8 +163,25 @@ func (s *SyncService) SyncHistory(ctx context.Context, deviceID string, waClient
progress.SetRunning()
- logrus.Infof("Chatwoot Sync: Starting history sync for device %s (days: %d, media: %v, groups: %v)",
- deviceID, opts.DaysLimit, opts.IncludeMedia, opts.IncludeGroups)
+ // Per-run group-name cache — local so concurrent SyncHistory calls
+ // for different devices don't share and invalidate each other's
+ // entries.
+ groupResolver := newGroupNameResolver()
+
+ // Decide up front whether this run uses the direct-Postgres importer
+ // or the REST path. The decision is logged
+ // so operators can tell from the logs which path ran.
+ importer, err := s.pgImporterForSync(ctx)
+ if err != nil {
+ progress.SetFailed(err)
+ return progress, err
+ }
+ backend := "REST"
+ if importer != nil {
+ backend = "pgimport"
+ }
+ logrus.Infof("Chatwoot Sync: Starting history sync for device %s (backend=%s days=%d media=%v groups=%v)",
+ deviceID, backend, opts.DaysLimit, opts.IncludeMedia, opts.IncludeGroups)
// 1. Get all chats for this device
chats, err := s.chatStorageRepo.GetChats(&domainChatStorage.ChatFilter{
@@ -103,9 +205,35 @@ func (s *SyncService) SyncHistory(ctx context.Context, deviceID string, waClient
return progress, err // Context cancelled
}
+ // status@broadcast and [email protected] carry no actionable
+ // conversation for an agent, and operators can ignore additional JIDs
+ // (or whole address spaces) via CHATWOOT_IGNORE_JIDS. Skipping at the
+ // chat level (rather than per-message) keeps the totals honest in the
+ // progress tracker — the chat is excluded entirely instead of counted
+ // as "synced 0".
+ if utils.IsSystemBroadcastJID(chat.JID) || utils.MatchesIgnoredJID(chat.JID, config.ChatwootIgnoreJids) {
+ logrus.Debugf("Chatwoot Sync: Skipping ignored chat %s", chat.JID)
+ continue
+ }
+
progress.UpdateChat(chat.JID)
- err := s.syncChat(ctx, deviceID, chat, sinceTime, waClient, opts, progress)
+ // Resolve the real group subject before dispatching so both paths
+ // write a meaningful name instead of the "Group 120363…@g.us"
+ // fallback from sqlite_repository.go. Individual chats don't need
+ // this — their stored name comes from the push-name pipeline.
+ if strings.HasSuffix(chat.JID, "@g.us") {
+ if resolved := groupResolver.resolve(ctx, waClient, chat.JID); resolved != "" {
+ chat.Name = resolved
+ }
+ }
+
+ var err error
+ if importer != nil {
+ err = s.syncChatPG(ctx, importer, deviceID, chat, sinceTime, waClient, opts, progress)
+ } else {
+ err = s.syncChat(ctx, deviceID, chat, sinceTime, waClient, opts, progress)
+ }
if err != nil {
logrus.Errorf("Chatwoot Sync: Failed to sync chat %s: %v", chat.JID, err)
progress.IncrementFailedChats()
@@ -148,14 +276,24 @@ func (s *SyncService) syncChat(
contactName = utils.ExtractPhoneFromJID(chat.JID)
}
- contact, err := s.client.FindOrCreateContact(contactName, chat.JID, isGroup)
+ var contact *Contact
+ err := retrySyncOp(ctx, 3, func() error {
+ var createErr error
+ contact, createErr = s.client.FindOrCreateContact(contactName, chat.JID, isGroup)
+ return createErr
+ })
if err != nil {
return fmt.Errorf("failed to create contact: %w", err)
}
logrus.Debugf("Chatwoot Sync: Contact ID: %d", contact.ID)
// 2. Find or create conversation
- conversation, err := s.client.FindOrCreateConversation(contact.ID)
+ var conversation *Conversation
+ err = retrySyncOp(ctx, 3, func() error {
+ var createErr error
+ conversation, createErr = s.client.FindOrCreateConversation(contact.ID, chat.JID)
+ return createErr
+ })
if err != nil {
return fmt.Errorf("failed to create conversation: %w", err)
}
@@ -209,6 +347,174 @@ func (s *SyncService) syncChat(
return nil
}
+// syncChatPG syncs a chat's history to Chatwoot via the direct-Postgres
+// importer. It mirrors syncChat's preprocessing (filtering groups, time
+// window, sort order) but delegates the actual writes to pgimport, which
+// uses a single transaction per chat and preserves original timestamps.
+//
+// Media is normally represented by text placeholders because direct-DB import
+// does not touch Chatwoot's ActiveStorage layer. When
+// ChatwootImportMediaWithREST is enabled, downloadable media rows are first
+// uploaded through Chatwoot REST with the same source_id; the following DB
+// import then skips those REST-created rows idempotently.
+func (s *SyncService) syncChatPG(
+ ctx context.Context,
+ importer *pgimport.Importer,
+ deviceID string,
+ chat *domainChatStorage.Chat,
+ sinceTime time.Time,
+ waClient *whatsmeow.Client,
+ opts SyncOptions,
+ progress *SyncProgress,
+) error {
+ isGroup := strings.HasSuffix(chat.JID, "@g.us")
+ if isGroup && !opts.IncludeGroups {
+ logrus.Debugf("Chatwoot Sync: Skipping group %s (groups disabled)", chat.JID)
+ return nil
+ }
+
+ logrus.Infof("Chatwoot pgimport: Processing chat %s (%s)", chat.Name, chat.JID)
+
+ messages, err := s.chatStorageRepo.GetMessages(&domainChatStorage.MessageFilter{
+ DeviceID: deviceID,
+ ChatJID: chat.JID,
+ StartTime: &sinceTime,
+ Limit: opts.MaxMessagesPerChat,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to get messages: %w", err)
+ }
+ if len(messages) == 0 {
+ logrus.Debugf("Chatwoot pgimport: No messages to sync for %s", chat.JID)
+ return nil
+ }
+
+ sort.Slice(messages, func(i, j int) bool {
+ return messages[i].Timestamp.Before(messages[j].Timestamp)
+ })
+
+ progress.AddMessages(len(messages))
+ logrus.Infof("Chatwoot pgimport: Found %d messages for %s", len(messages), chat.JID)
+
+ // Use a display name that is never the "Group <jid>" fallback from
+ // sqlite_repository.go. If the stored name still starts with "Group "
+ // followed by the JID user portion, treat it as unset and let the
+ // importer use the phone number / JID as last resort.
+ chatName := chat.Name
+ if isGroup && strings.HasPrefix(chatName, "Group ") {
+ chatName = ""
+ }
+
+ if mediaMessages := chatwootRESTMediaCandidates(messages, opts); len(mediaMessages) > 0 {
+ conversation, err := s.findOrCreateHistoryConversation(ctx, chat, isGroup)
+ if err != nil {
+ logrus.Warnf("Chatwoot pgimport: REST media pre-pass skipped for %s: %v", chat.JID, err)
+ } else {
+ s.syncHybridMediaMessagesREST(ctx, conversation.ID, mediaMessages, waClient, opts, isGroup)
+ }
+ }
+
+ result, err := importer.ImportChat(ctx, pgimport.ImportChatRequest{
+ ChatJID: chat.JID,
+ ChatName: chatName,
+ Messages: messages,
+ })
+ if err != nil {
+ // On a fatal tx-level error, count every message as failed so the
+ // progress totals stay honest.
+ progress.AddFailedMessages(len(messages))
+ return err
+ }
+ if err := s.storeChatwootImportLinks(result); err != nil {
+ return err
+ }
+
+ // Idempotent skips are recorded as "synced" for UI purposes — the row
+ // is present in Chatwoot, which is what the operator cares about.
+ progress.AddSyncedMessages(result.MessagesWrote + result.MessagesSkipped)
+ progress.AddFailedMessages(result.MessagesFailed)
+
+ logrus.Infof("Chatwoot pgimport: %s wrote=%d skipped=%d failed=%d",
+ chat.JID, result.MessagesWrote, result.MessagesSkipped, result.MessagesFailed)
+ return nil
+}
+
+func hasDownloadableChatwootMedia(msg *domainChatStorage.Message) bool {
+ return msg != nil && msg.MediaType != "" && msg.URL != "" && len(msg.MediaKey) > 0
+}
+
+func chatwootRESTMediaCandidates(messages []*domainChatStorage.Message, opts SyncOptions) []*domainChatStorage.Message {
+ if !config.ChatwootImportMediaWithREST || !opts.IncludeMedia {
+ return nil
+ }
+ candidates := make([]*domainChatStorage.Message, 0)
+ for _, msg := range messages {
+ if hasDownloadableChatwootMedia(msg) {
+ candidates = append(candidates, msg)
+ }
+ }
+ return candidates
+}
+
+func (s *SyncService) findOrCreateHistoryConversation(ctx context.Context, chat *domainChatStorage.Chat, isGroup bool) (*Conversation, error) {
+ contactName := chat.Name
+ if contactName == "" {
+ contactName = utils.ExtractPhoneFromJID(chat.JID)
+ }
+
+ var contact *Contact
+ err := retrySyncOp(ctx, 3, func() error {
+ var createErr error
+ contact, createErr = s.client.FindOrCreateContact(contactName, chat.JID, isGroup)
+ return createErr
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create contact for REST media import: %w", err)
+ }
+
+ var conversation *Conversation
+ err = retrySyncOp(ctx, 3, func() error {
+ var createErr error
+ conversation, createErr = s.client.FindOrCreateConversation(contact.ID, chat.JID)
+ return createErr
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create conversation for REST media import: %w", err)
+ }
+ return conversation, nil
+}
+
+func (s *SyncService) syncHybridMediaMessagesREST(
+ ctx context.Context,
+ conversationID int,
+ messages []*domainChatStorage.Message,
+ waClient *whatsmeow.Client,
+ opts SyncOptions,
+ isGroup bool,
+) {
+ for _, msg := range messages {
+ if err := ctx.Err(); err != nil {
+ return
+ }
+ if err := s.syncMessageWithOptions(ctx, conversationID, msg, waClient, opts, isGroup, true); err != nil {
+ logrus.Warnf("Chatwoot pgimport: REST media pre-pass failed for message %s: %v", msg.ID, err)
+ }
+ }
+}
+
+func (s *SyncService) storeChatwootImportLinks(result *pgimport.ImportResult) error {
+ if s.chatStorageRepo == nil || result == nil {
+ return nil
+ }
+ for i := range result.Links {
+ link := result.Links[i]
+ if err := s.chatStorageRepo.UpsertChatwootMessageLink(&link); err != nil {
+ return fmt.Errorf("failed to store chatwoot import link for %s: %w", link.WhatsAppMessageID, err)
+ }
+ }
+ return nil
+}
+
// syncMessage syncs a single message to Chatwoot
func (s *SyncService) syncMessage(
ctx context.Context,
@@ -218,6 +524,29 @@ func (s *SyncService) syncMessage(
opts SyncOptions,
isGroup bool,
) error {
+ return s.syncMessageWithOptions(ctx, conversationID, msg, waClient, opts, isGroup, false)
+}
+
+func (s *SyncService) syncMessageWithOptions(
+ ctx context.Context,
+ conversationID int,
+ msg *domainChatStorage.Message,
+ waClient *whatsmeow.Client,
+ opts SyncOptions,
+ isGroup bool,
+ requireMediaAttachment bool,
+) error {
+ if msg.ID != "" && msg.DeviceID != "" && s.chatStorageRepo != nil {
+ existing, err := s.chatStorageRepo.GetChatwootMessageLinkByWhatsAppID(msg.DeviceID, msg.ID)
+ if err != nil {
+ return fmt.Errorf("failed to lookup chatwoot message link: %w", err)
+ }
+ if existing != nil && existing.ChatwootMessageID != 0 {
+ logrus.Debugf("Chatwoot Sync: Skipping already-linked message %s -> %d", msg.ID, existing.ChatwootMessageID)
+ return nil
+ }
+ }
+
// Determine message type: "incoming" or "outgoing"
messageType := "incoming"
if msg.IsFromMe {
@@ -230,15 +559,10 @@ func (s *SyncService) syncMessage(
content = fmt.Sprintf("[%s]", msg.MediaType) // Placeholder for media-only
}
- // Add timestamp prefix for historical context
- timePrefix := msg.Timestamp.Format("2006-01-02 15:04")
-
- // For group messages, add sender info
+ // For group messages, add sender info so agents can tell participants apart
if isGroup && !msg.IsFromMe && msg.Sender != "" {
senderName := utils.ExtractPhoneFromJID(msg.Sender)
- content = fmt.Sprintf("[%s] %s: %s", timePrefix, senderName, content)
- } else {
- content = fmt.Sprintf("[%s] %s", timePrefix, content)
+ content = fmt.Sprintf("%s: %s", senderName, content)
}
var attachments []string
@@ -247,6 +571,9 @@ func (s *SyncService) syncMessage(
if opts.IncludeMedia && msg.MediaType != "" && msg.URL != "" && len(msg.MediaKey) > 0 {
filePath, err := s.downloadMedia(ctx, msg, waClient)
if err != nil {
+ if requireMediaAttachment {
+ return fmt.Errorf("failed to download required media: %w", err)
+ }
logrus.Debugf("Chatwoot Sync: Failed to download media for message %s: %v", msg.ID, err)
// Continue without media - it might be expired
content += " [media unavailable]"
@@ -254,10 +581,26 @@ func (s *SyncService) syncMessage(
attachments = append(attachments, filePath)
}
}
+ if requireMediaAttachment && len(attachments) == 0 {
+ return fmt.Errorf("required media attachment is unavailable")
+ }
+
+ // Send to Chatwoot with retry on transient errors (429, 5xx). Register
+ // the returned ID in the dedup cache so the resulting webhook event is
+ // recognized as "ours" and not forwarded back to WhatsApp.
+ // Stamp source_id = WAID:<id> so the REST-imported row shares the importer's
+ // dedup key and gives later replies a stable thread anchor.
+ var msgOpts MessageOptions
+ if msg.ID != "" {
+ msgOpts.SourceID = "WAID:" + msg.ID
+ }
- // Send to Chatwoot and register the returned ID in the dedup cache so the
- // resulting webhook event is recognized as "ours" and not forwarded back to WhatsApp.
- msgID, err := s.client.CreateMessage(conversationID, content, messageType, attachments)
+ var msgID int
+ err := retrySyncOp(ctx, 3, func() error {
+ var createErr error
+ msgID, createErr = s.client.CreateMessage(conversationID, content, messageType, attachments, msgOpts)
+ return createErr
+ })
for _, fp := range attachments {
if err := os.Remove(fp); err != nil {
@@ -270,6 +613,22 @@ func (s *SyncService) syncMessage(
}
MarkMessageAsSent(msgID)
+ if msgID != 0 && msg.ID != "" && msg.DeviceID != "" && s.chatStorageRepo != nil {
+ if err := s.chatStorageRepo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{
+ DeviceID: msg.DeviceID,
+ WhatsAppMessageID: msg.ID,
+ WhatsAppChatJID: msg.ChatJID,
+ ChatwootMessageID: msgID,
+ ChatwootConversationID: conversationID,
+ ChatwootInboxID: s.client.InboxID,
+ ChatwootContactInboxSourceID: msg.ChatJID,
+ SourceID: msgOpts.SourceID,
+ Direction: messageType,
+ IsRead: false,
+ }); err != nil {
+ return fmt.Errorf("failed to store chatwoot message link: %w", err)
+ }
+ }
return nil
}
@@ -377,6 +736,36 @@ func getExtensionForMediaType(mediaType, filename string) string {
}
}
+// retrySyncOp retries fn up to maxAttempts times with exponential backoff
+// (1s, 2s, 4s). Retries only transient errors — Retryable() returns true
+// for network/IO failures and for HTTP 429 / 5xx responses, and false for
+// 4xx validation errors so we don't hammer Chatwoot on misconfiguration.
+func retrySyncOp(ctx context.Context, maxAttempts int, fn func() error) error {
+ var lastErr error
+ for attempt := 0; attempt < maxAttempts; attempt++ {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ lastErr = fn()
+ if lastErr == nil {
+ return nil
+ }
+ if !Retryable(lastErr) {
+ return lastErr
+ }
+ if attempt < maxAttempts-1 {
+ backoff := time.Duration(1<<uint(attempt)) * time.Second
+ logrus.Debugf("Chatwoot Sync: retry attempt %d/%d after %v: %v", attempt+1, maxAttempts, backoff, lastErr)
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(backoff):
+ }
+ }
+ }
+ return lastErr
+}
+
// Global sync service instance for REST endpoints
var (
globalSyncService *SyncService
@@ -398,3 +787,67 @@ func GetSyncService(
func GetDefaultSyncService() *SyncService {
return globalSyncService
}
+
+// Close releases resources held by the sync service, including the optional
+// direct-Postgres importer pool. Safe to call even when pgImporter is nil.
+func (s *SyncService) Close() error {
+ if s.pgImporter != nil {
+ return s.pgImporter.Close()
+ }
+ return nil
+}
+
+// autoSyncTriggered latches per storage-JID so history auto-sync runs at most
+// once per device per process. events.Connected fires on every reconnect, and
+// SyncHistory's in-flight guard only blocks *concurrent* runs — without this
+// latch a reconnect after a completed sync would re-import history (harmless for
+// the idempotent pgimport path, but the REST path would duplicate messages).
+var autoSyncTriggered sync.Map
+
+// TriggerAutoSync starts a one-time history sync for a freshly connected device
+// when CHATWOOT_IMPORT_MESSAGES is enabled. It is safe to call on every connect
+// event: it self-guards on configuration, requires a logged-in client (so the
+// storage JID is available), and latches per device so it runs only once per
+// process. The sync runs in the background and never blocks the caller.
+func TriggerAutoSync(chatStorageRepo domainChatStorage.IChatStorageRepository, waClient *whatsmeow.Client) {
+ if !config.ChatwootEnabled || !config.ChatwootImportMessages {
+ return
+ }
+
+ // Chats are stored under the full WhatsApp JID, so a logged-in client is
+ // required to resolve the storage device ID. Before login there is nothing
+ // to sync; a later connect (post-login) retries.
+ if waClient == nil || waClient.Store == nil || waClient.Store.ID == nil {
+ return
+ }
+ storageDeviceID := waClient.Store.ID.ToNonAD().String()
+ if storageDeviceID == "" {
+ return
+ }
+
+ client := GetDefaultClient()
+ if !client.IsConfigured() {
+ // Provisioning may not have resolved the inbox yet; don't consume the
+ // latch so a later connect can retry once configuration completes.
+ logrus.Warn("Chatwoot Sync: Auto-sync skipped - Chatwoot not configured")
+ return
+ }
+
+ if _, loaded := autoSyncTriggered.LoadOrStore(storageDeviceID, struct{}{}); loaded {
+ return // already triggered this process for this device
+ }
+
+ syncService := GetSyncService(client, chatStorageRepo)
+
+ go func() {
+ opts := DefaultSyncOptions()
+ opts.DaysLimit = config.ChatwootDaysLimitImportMessages
+
+ logrus.Infof("Chatwoot Sync: Auto-sync triggered for device %s", storageDeviceID)
+
+ _, err := syncService.SyncHistory(context.Background(), storageDeviceID, waClient, opts)
+ if err != nil {
+ logrus.Errorf("Chatwoot Sync: Auto-sync failed for device %s: %v", storageDeviceID, err)
+ }
+ }()
+}
diff --git a/src/infrastructure/chatwoot/sync_links_test.go b/src/infrastructure/chatwoot/sync_links_test.go
new file mode 100644
index 00000000..4d6713a4
--- /dev/null
+++ b/src/infrastructure/chatwoot/sync_links_test.go
@@ -0,0 +1,196 @@
+package chatwoot
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot/pgimport"
+)
+
+type chatwootSyncLinkRepo struct {
+ domainChatStorage.IChatStorageRepository
+ links map[string]*domainChatStorage.ChatwootMessageLink
+}
+
+func newChatwootSyncLinkTestRepo() *chatwootSyncLinkRepo {
+ return &chatwootSyncLinkRepo{links: make(map[string]*domainChatStorage.ChatwootMessageLink)}
+}
+
+func chatwootSyncLinkKey(deviceID, waMessageID string) string {
+ return deviceID + "\x00" + waMessageID
+}
+
+func (r *chatwootSyncLinkRepo) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
+ cloned := *link
+ r.links[chatwootSyncLinkKey(link.DeviceID, link.WhatsAppMessageID)] = &cloned
+ return nil
+}
+
+func (r *chatwootSyncLinkRepo) GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*domainChatStorage.ChatwootMessageLink, error) {
+ link := r.links[chatwootSyncLinkKey(deviceID, waMessageID)]
+ if link == nil {
+ return nil, nil
+ }
+ cloned := *link
+ return &cloned, nil
+}
+
+func TestSyncMessageSkipsExistingChatwootLink(t *testing.T) {
+ repo := newChatwootSyncLinkTestRepo()
+ msg := &domainChatStorage.Message{
+ ID: "wa-existing",
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ Content: "already synced",
+ Timestamp: time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC),
+ }
+ if err := repo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{
+ DeviceID: msg.DeviceID,
+ WhatsAppMessageID: msg.ID,
+ WhatsAppChatJID: msg.ChatJID,
+ ChatwootMessageID: 777,
+ SourceID: "WAID:" + msg.ID,
+ Direction: "incoming",
+ }); err != nil {
+ t.Fatalf("seed link: %v", err)
+ }
+
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ w.WriteHeader(http.StatusInternalServerError)
+ }))
+ defer server.Close()
+
+ svc := NewSyncService(&Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }, repo)
+
+ if err := svc.syncMessage(context.Background(), 42, msg, nil, SyncOptions{}, false); err != nil {
+ t.Fatalf("syncMessage: %v", err)
+ }
+ if got := requests.Load(); got != 0 {
+ t.Fatalf("Chatwoot received %d requests, want 0 for existing link", got)
+ }
+}
+
+func TestSyncMessageStoresChatwootLinkAfterCreate(t *testing.T) {
+ repo := newChatwootSyncLinkTestRepo()
+ msg := &domainChatStorage.Message{
+ ID: "wa-new",
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ Content: "new sync",
+ Timestamp: time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC),
+ }
+
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/v1/accounts/1/conversations/42/messages" {
+ t.Fatalf("path = %s", r.URL.Path)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"id":888}`))
+ }))
+ defer server.Close()
+
+ svc := NewSyncService(&Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }, repo)
+
+ if err := svc.syncMessage(context.Background(), 42, msg, nil, SyncOptions{}, false); err != nil {
+ t.Fatalf("syncMessage: %v", err)
+ }
+
+ link, err := repo.GetChatwootMessageLinkByWhatsAppID(msg.DeviceID, msg.ID)
+ if err != nil {
+ t.Fatalf("lookup link: %v", err)
+ }
+ if link == nil {
+ t.Fatal("expected stored chatwoot message link")
+ }
+ if link.ChatwootMessageID != 888 || link.ChatwootConversationID != 42 || link.SourceID != "WAID:wa-new" {
+ t.Fatalf("unexpected link: %+v", link)
+ }
+}
+
+func TestSyncMessageWithRequiredMediaDoesNotCreatePlaceholderWhenDownloadFails(t *testing.T) {
+ repo := newChatwootSyncLinkTestRepo()
+ msg := &domainChatStorage.Message{
+ ID: "wa-media",
+ DeviceID: "[email protected]",
+ ChatJID: "[email protected]",
+ MediaType: "image",
+ URL: "https://mmg.whatsapp.net/file",
+ MediaKey: []byte("key"),
+ Timestamp: time.Date(2026, time.June, 6, 10, 0, 0, 0, time.UTC),
+ }
+
+ var requests atomic.Int32
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests.Add(1)
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write([]byte(`{"id":888}`))
+ }))
+ defer server.Close()
+
+ svc := NewSyncService(&Client{
+ BaseURL: server.URL,
+ APIToken: "token",
+ AccountID: 1,
+ InboxID: 2,
+ HTTPClient: server.Client(),
+ }, repo)
+
+ err := svc.syncMessageWithOptions(context.Background(), 42, msg, nil, SyncOptions{IncludeMedia: true}, false, true)
+ if err == nil {
+ t.Fatal("syncMessageWithOptions error = nil, want media download failure")
+ }
+ if got := requests.Load(); got != 0 {
+ t.Fatalf("Chatwoot received %d requests, want 0 when required media cannot be attached", got)
+ }
+}
+
+func TestStoreChatwootImportLinksPersistsReturnedLinks(t *testing.T) {
+ repo := newChatwootSyncLinkTestRepo()
+ svc := NewSyncService(nil, repo)
+
+ result := &pgimport.ImportResult{
+ Links: []domainChatStorage.ChatwootMessageLink{
+ {
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "wa-imported",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootMessageID: 909,
+ ChatwootConversationID: 808,
+ ChatwootInboxID: 707,
+ SourceID: "WAID:wa-imported",
+ Direction: "incoming",
+ },
+ },
+ }
+
+ if err := svc.storeChatwootImportLinks(result); err != nil {
+ t.Fatalf("storeChatwootImportLinks: %v", err)
+ }
+
+ link, err := repo.GetChatwootMessageLinkByWhatsAppID("[email protected]", "wa-imported")
+ if err != nil {
+ t.Fatalf("lookup link: %v", err)
+ }
+ if link == nil || link.ChatwootMessageID != 909 {
+ t.Fatalf("expected imported link to be stored, got %+v", link)
+ }
+}
diff --git a/src/infrastructure/chatwoot/sync_rest_test.go b/src/infrastructure/chatwoot/sync_rest_test.go
new file mode 100644
index 00000000..9cda1ecb
--- /dev/null
+++ b/src/infrastructure/chatwoot/sync_rest_test.go
@@ -0,0 +1,148 @@
+package chatwoot
+
+import (
+ "context"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+)
+
+func TestGroupNameResolver_NilClientReturnsEmpty(t *testing.T) {
+ // resolve must short-circuit to "" when there is no WhatsApp client,
+ // because the caller (SyncHistory) falls back to the stored chat name in
+ // that case. Crucially this also lets the resolver be exercised without a
+ // live *whatsmeow.Client — the nil guard is the first statement.
+ r := newGroupNameResolver()
+ if got := r.resolve(context.Background(), nil, "[email protected]"); got != "" {
+ t.Errorf("resolve(nil client) = %q, want empty string", got)
+ }
+}
+
+func TestPgImporterForSync_EmptyURIReturnsNil(t *testing.T) {
+ // pgImporterForSync returns nil when the direct-Postgres import feature is
+ // not configured (blank or whitespace-only URI), which is what makes
+ // SyncHistory use the REST path. We mutate the package config global and
+ // restore it so other tests/packages see no leak.
+ orig := config.ChatwootImportDBURI
+ defer func() { config.ChatwootImportDBURI = orig }()
+
+ s := NewSyncService(nil, nil)
+
+ tests := []struct {
+ name string
+ uri string
+ }{
+ {"empty string", ""},
+ {"whitespace only", " "},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ config.ChatwootImportDBURI = tc.uri
+ imp, err := s.pgImporterForSync(context.Background())
+ if err != nil {
+ t.Fatalf("pgImporterForSync() error = %v, want nil", err)
+ }
+ if imp != nil {
+ t.Errorf("pgImporterForSync() = %v, want nil for URI %q", imp, tc.uri)
+ }
+ // The cached importer must stay nil so a later configured run can
+ // still initialize it.
+ if s.pgImporter != nil {
+ t.Errorf("s.pgImporter = %v, want nil (must not be cached)", s.pgImporter)
+ }
+ })
+ }
+}
+
+func TestPgImporterForSync_ConfiguredURIRequiresAccountAndInbox(t *testing.T) {
+ origURI := config.ChatwootImportDBURI
+ origAccountID := config.ChatwootAccountID
+ origInboxID := config.ChatwootInboxID
+ defer func() {
+ config.ChatwootImportDBURI = origURI
+ config.ChatwootAccountID = origAccountID
+ config.ChatwootInboxID = origInboxID
+ }()
+
+ config.ChatwootImportDBURI = "postgres://chatwoot:secret@localhost/chatwoot"
+ config.ChatwootAccountID = 0
+ config.ChatwootInboxID = 99
+
+ s := NewSyncService(nil, nil)
+ imp, err := s.pgImporterForSync(context.Background())
+ if err == nil {
+ t.Fatal("pgImporterForSync() error = nil, want configured import failure")
+ }
+ if imp != nil {
+ t.Errorf("pgImporterForSync() importer = %v, want nil on failure", imp)
+ }
+ if s.pgImporter != nil {
+ t.Errorf("s.pgImporter = %v, want nil (must not cache failed importer)", s.pgImporter)
+ }
+}
+
+func TestHasDownloadableChatwootMedia(t *testing.T) {
+ tests := []struct {
+ name string
+ msg *domainChatStorage.Message
+ want bool
+ }{
+ {
+ name: "media with url and key",
+ msg: &domainChatStorage.Message{MediaType: "image", URL: "https://mmg.whatsapp.net/file", MediaKey: []byte("key")},
+ want: true,
+ },
+ {
+ name: "text message",
+ msg: &domainChatStorage.Message{Content: "hello"},
+ want: false,
+ },
+ {
+ name: "media without url",
+ msg: &domainChatStorage.Message{MediaType: "image", MediaKey: []byte("key")},
+ want: false,
+ },
+ {
+ name: "media without key",
+ msg: &domainChatStorage.Message{MediaType: "image", URL: "https://mmg.whatsapp.net/file"},
+ want: false,
+ },
+ {
+ name: "nil",
+ msg: nil,
+ want: false,
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := hasDownloadableChatwootMedia(tt.msg); got != tt.want {
+ t.Fatalf("hasDownloadableChatwootMedia() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootRESTMediaCandidates(t *testing.T) {
+ prev := config.ChatwootImportMediaWithREST
+ defer func() { config.ChatwootImportMediaWithREST = prev }()
+
+ messages := []*domainChatStorage.Message{
+ {ID: "text", Content: "hello"},
+ {ID: "media", MediaType: "image", URL: "https://mmg.whatsapp.net/file", MediaKey: []byte("key")},
+ }
+
+ config.ChatwootImportMediaWithREST = false
+ if got := chatwootRESTMediaCandidates(messages, SyncOptions{IncludeMedia: true}); len(got) != 0 {
+ t.Fatalf("candidates with config disabled = %d, want 0", len(got))
+ }
+
+ config.ChatwootImportMediaWithREST = true
+ if got := chatwootRESTMediaCandidates(messages, SyncOptions{IncludeMedia: false}); len(got) != 0 {
+ t.Fatalf("candidates with media disabled = %d, want 0", len(got))
+ }
+ got := chatwootRESTMediaCandidates(messages, SyncOptions{IncludeMedia: true})
+ if len(got) != 1 || got[0].ID != "media" {
+ t.Fatalf("candidates = %+v, want only media", got)
+ }
+}
diff --git a/src/infrastructure/chatwoot/sync_test.go b/src/infrastructure/chatwoot/sync_test.go
index 33d883bd..4ee363d8 100644
--- a/src/infrastructure/chatwoot/sync_test.go
+++ b/src/infrastructure/chatwoot/sync_test.go
@@ -1,10 +1,42 @@
package chatwoot
import (
+ "context"
+ "fmt"
"testing"
"time"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
)
+// TestTriggerAutoSync_NoopWhenGated verifies the connect-path entrypoint is a
+// safe no-op under the documented gates and with a not-logged-in (nil) client.
+// The call site fires on every WhatsApp connect event, so these guards must
+// never panic or start work when they shouldn't.
+func TestTriggerAutoSync_NoopWhenGated(t *testing.T) {
+ prevEnabled := config.ChatwootEnabled
+ prevImport := config.ChatwootImportMessages
+ defer func() {
+ config.ChatwootEnabled = prevEnabled
+ config.ChatwootImportMessages = prevImport
+ }()
+
+ // Disabled integration: no-op regardless of the import flag.
+ config.ChatwootEnabled = false
+ config.ChatwootImportMessages = true
+ TriggerAutoSync(nil, nil)
+
+ // Enabled but import off: no-op.
+ config.ChatwootEnabled = true
+ config.ChatwootImportMessages = false
+ TriggerAutoSync(nil, nil)
+
+ // Enabled + import on, but no logged-in client (nil) means no storage JID
+ // is available yet — must return without panicking or launching a sync.
+ config.ChatwootImportMessages = true
+ TriggerAutoSync(nil, nil)
+}
+
func TestSyncProgress_SetRunning(t *testing.T) {
p := NewSyncProgress("test-device")
@@ -188,3 +220,80 @@ type testError struct {
func (e *testError) Error() string {
return e.msg
}
+
+func TestRetryable(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ retryable bool
+ }{
+ {"nil error", nil, false},
+ {"4xx", &HTTPStatusError{StatusCode: 400}, false},
+ {"401", &HTTPStatusError{StatusCode: 401}, false},
+ {"422", &HTTPStatusError{StatusCode: 422}, false},
+ {"429", &HTTPStatusError{StatusCode: 429}, true},
+ {"500", &HTTPStatusError{StatusCode: 500}, true},
+ {"502", &HTTPStatusError{StatusCode: 502}, true},
+ {"503", &HTTPStatusError{StatusCode: 503}, true},
+ {"non-HTTP error", &testError{msg: "network"}, true},
+ }
+ for _, tt := range tests {
+ if got := Retryable(tt.err); got != tt.retryable {
+ t.Errorf("%s: Retryable(%v) = %v, want %v", tt.name, tt.err, got, tt.retryable)
+ }
+ }
+}
+
+func TestRetrySyncOp_DoesNotRetry4xx(t *testing.T) {
+ // 4xx is a validation/auth error — hitting it 3 times would waste
+ // backoff time and spam Chatwoot.
+ attempts := 0
+ err := retrySyncOp(context.Background(), 3, func() error {
+ attempts++
+ return &HTTPStatusError{StatusCode: 400, Op: "test", Body: "bad"}
+ })
+ if err == nil {
+ t.Fatal("expected error, got nil")
+ }
+ if attempts != 1 {
+ t.Errorf("expected 1 attempt on 4xx, got %d", attempts)
+ }
+}
+
+func TestRetrySyncOp_Retries5xxUntilSuccess(t *testing.T) {
+ attempts := 0
+ err := retrySyncOp(context.Background(), 3, func() error {
+ attempts++
+ if attempts < 2 {
+ return &HTTPStatusError{StatusCode: 503, Op: "test", Body: "unavailable"}
+ }
+ return nil
+ })
+ if err != nil {
+ t.Fatalf("expected success after retry, got %v", err)
+ }
+ if attempts != 2 {
+ t.Errorf("expected 2 attempts, got %d", attempts)
+ }
+}
+
+func TestRetrySyncOp_RetriesUnknownErrors(t *testing.T) {
+ // Non-HTTP errors (network, timeout) should retry.
+ attempts := 0
+ _ = retrySyncOp(context.Background(), 3, func() error {
+ attempts++
+ return fmt.Errorf("connection refused")
+ })
+ if attempts != 3 {
+ t.Errorf("expected 3 attempts on generic error, got %d", attempts)
+ }
+}
+
+func TestHTTPStatusError_Message(t *testing.T) {
+ err := &HTTPStatusError{StatusCode: 429, Op: "create message", Body: "rate limited"}
+ got := err.Error()
+ want := "chatwoot create message: status 429 body rate limited"
+ if got != want {
+ t.Errorf("got %q, want %q", got, want)
+ }
+}
diff --git a/src/infrastructure/chatwoot/sync_types.go b/src/infrastructure/chatwoot/sync_types.go
index 4d346d2b..3c644b07 100644
--- a/src/infrastructure/chatwoot/sync_types.go
+++ b/src/infrastructure/chatwoot/sync_types.go
@@ -49,8 +49,8 @@ type SyncOptions struct {
type SyncRequest struct {
DeviceID string `json:"device_id,omitempty"`
DaysLimit int `json:"days_limit,omitempty"`
- IncludeMedia bool `json:"include_media"`
- IncludeGroups bool `json:"include_groups"`
+ IncludeMedia *bool `json:"include_media,omitempty"`
+ IncludeGroups *bool `json:"include_groups,omitempty"`
}
// SyncResponse is the API response for sync operations
@@ -160,6 +160,23 @@ func (p *SyncProgress) AddMessages(count int) {
p.TotalMessages += count
}
+// AddSyncedMessages adds count to the synced messages counter in a single
+// locked update — cheaper than calling IncrementSyncedMessages in a loop when
+// a per-chat batch result is known up front.
+func (p *SyncProgress) AddSyncedMessages(count int) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.SyncedMessages += count
+}
+
+// AddFailedMessages adds count to the failed messages counter in a single
+// locked update.
+func (p *SyncProgress) AddFailedMessages(count int) {
+ p.mu.Lock()
+ defer p.mu.Unlock()
+ p.FailedMessages += count
+}
+
// Clone returns a thread-safe copy of the progress
func (p *SyncProgress) Clone() SyncProgress {
p.mu.RLock()
diff --git a/src/infrastructure/chatwoot/types.go b/src/infrastructure/chatwoot/types.go
index b37e2464..fcb548a4 100644
--- a/src/infrastructure/chatwoot/types.go
+++ b/src/infrastructure/chatwoot/types.go
@@ -36,24 +36,53 @@ type CreateConversationRequest struct {
InboxID int `json:"inbox_id"`
ContactID int `json:"contact_id"`
Status string `json:"status"`
+ // SourceID is the WhatsApp chat JID. Sending it keys the conversation's
+ // contact_inbox by that JID so the contact public endpoints can resolve the
+ // conversation; empty is omitted so Chatwoot generates one.
+ SourceID string `json:"source_id,omitempty"`
}
type CreateMessageRequest struct {
- Content string `json:"content"`
- MessageType string `json:"message_type"`
- Private bool `json:"private"`
+ Content string `json:"content"`
+ MessageType string `json:"message_type"`
+ Private bool `json:"private"`
+ SourceID string `json:"source_id,omitempty"`
+ ContentAttributes map[string]any `json:"content_attributes,omitempty"`
+}
+
+// Inbox is the subset of a Chatwoot inbox we read during auto-provisioning.
+type Inbox struct {
+ ID int `json:"id"`
+ Name string `json:"name"`
+ ChannelType string `json:"channel_type"`
+ InboxIdentifier string `json:"inbox_identifier"`
+}
+
+// CreateInboxRequest provisions an API-channel inbox. Chatwoot nests the
+// channel descriptor under "channel"; type "api" with a webhook_url makes
+// Chatwoot POST agent replies to that URL.
+type CreateInboxRequest struct {
+ Name string `json:"name"`
+ Channel CreateInboxChannel `json:"channel"`
+}
+
+type CreateInboxChannel struct {
+ Type string `json:"type"`
+ WebhookURL string `json:"webhook_url,omitempty"`
}
type WebhookPayload struct {
- ID int `json:"id"`
- Event string `json:"event"`
- MessageType string `json:"message_type"`
- Content string `json:"content"`
- Private bool `json:"private"`
- Account Account `json:"account"`
- Conversation ConversationWebhook `json:"conversation"`
- Sender Contact `json:"sender"`
- Attachments []Attachment `json:"attachments"`
+ ID int `json:"id"`
+ Event string `json:"event"`
+ MessageType string `json:"message_type"`
+ Content string `json:"content"`
+ Private bool `json:"private"`
+ SourceID string `json:"source_id"`
+ ContentAttributes map[string]any `json:"content_attributes"`
+ Account Account `json:"account"`
+ Conversation ConversationWebhook `json:"conversation"`
+ Sender Contact `json:"sender"`
+ Attachments []Attachment `json:"attachments"`
}
type Attachment struct {
diff --git a/src/infrastructure/whatsapp/AGENTS.md b/src/infrastructure/whatsapp/AGENTS.md
index 2336c34b..1e349fc6 100644
--- a/src/infrastructure/whatsapp/AGENTS.md
+++ b/src/infrastructure/whatsapp/AGENTS.md
@@ -1,6 +1,6 @@
# WHATSAPP INFRASTRUCTURE
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
@@ -14,6 +14,7 @@ presence pulse scheduling, webhook forwarding, and the event-side chatstorage wr
| Device lifecycle | `device_manager.go`, `device_instance.go`, `client_lifecycle.go` | Create/load/purge/reconnect and persisted registry behavior. |
| Event routing | `event_handler.go`, `event_*.go` | Add new event types to the central switch. |
| Message webhooks | `event_message.go`, `webhook_forward.go` | Payload construction, media fields, signatures, event filters. |
+| Chatwoot forward retry | `webhook_forward.go` | Queue-backed retries for WhatsApp-to-Chatwoot forward failures. |
| Send retry / 463 | `send_retry.go`, `key_cache.go` | Reachout timelock retry and privacy-token store wiring. |
| Presence behavior | `event_handler.go`, `event_chat_presence.go`, `presence_pulse.go` | Connect-time presence, chat presence webhooks, scheduled daily pulses. |
| History import | `history_sync.go` | Stores chats/messages for history sync batches. |
@@ -29,6 +30,7 @@ presence pulse scheduling, webhook forwarding, and the event-side chatstorage wr
- Normalize `@lid` JIDs with `NormalizeJIDFromLID(ctx, jid, client)` before DB lookup/storage when a phone JID is needed.
- Use `ToNonAD()` when persisting or emitting stable non-device JIDs.
- Webhook forwarding uses goroutines and bounded contexts in selected handlers; keep failures logged without blocking the event loop.
+- `StartChatwootForwardRetryWorker` persists retry jobs in chat storage; queued events need stable `device_id`, event name, and WhatsApp message ID.
- `chatstorage_wrapper.go` should provide device defaults for scoped repository methods, including message edit and device-scoped ID lookups.
## ANTI-PATTERNS
@@ -40,6 +42,7 @@ presence pulse scheduling, webhook forwarding, and the event-side chatstorage wr
- Do not start a second presence pulse loop; `cmd/helpers.go` uses `sync.Once` for process-wide startup.
- Do not move privacy tokens to a volatile keys DB; long-lived sessions need them in durable primary WhatsApp storage.
- Do not assume `client`, `client.Store`, or `client.Store.LIDs` is non-nil during LID resolution.
+- Do not replay Chatwoot forward events without device scoping; the retry queue uniqueness depends on it.
## TESTING
diff --git a/src/infrastructure/whatsapp/chatstorage_wrapper.go b/src/infrastructure/whatsapp/chatstorage_wrapper.go
index 10f77d6c..b2f32507 100644
--- a/src/infrastructure/whatsapp/chatstorage_wrapper.go
+++ b/src/infrastructure/whatsapp/chatstorage_wrapper.go
@@ -134,6 +134,60 @@ func (r *deviceChatStorage) DeleteMessageByDevice(deviceID, id, chatJID string)
return r.base.DeleteMessageByDevice(deviceID, id, chatJID)
}
+func (r *deviceChatStorage) UpsertChatwootMessageLink(link *domainChatStorage.ChatwootMessageLink) error {
+ if link != nil && link.DeviceID == "" {
+ link.DeviceID = r.deviceID
+ }
+ return r.base.UpsertChatwootMessageLink(link)
+}
+
+func (r *deviceChatStorage) GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID string) (*domainChatStorage.ChatwootMessageLink, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetChatwootMessageLinkByWhatsAppID(targetDeviceID, waMessageID)
+}
+
+func (r *deviceChatStorage) GetChatwootMessageLinkByChatwootID(deviceID string, chatwootMessageID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetChatwootMessageLinkByChatwootID(targetDeviceID, chatwootMessageID)
+}
+
+func (r *deviceChatStorage) GetLatestChatwootMessageLinkByConversation(conversationID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ return r.base.GetLatestChatwootMessageLinkByConversation(conversationID)
+}
+
+func (r *deviceChatStorage) GetLatestUnreadChatwootMessageLinkByChat(deviceID, waChatJID string) (*domainChatStorage.ChatwootMessageLink, error) {
+ targetDeviceID := deviceID
+ if targetDeviceID == "" {
+ targetDeviceID = r.deviceID
+ }
+ return r.base.GetLatestUnreadChatwootMessageLinkByChat(targetDeviceID, waChatJID)
+}
+
+func (r *deviceChatStorage) EnqueueChatwootForwardEvent(event *domainChatStorage.ChatwootForwardEvent) error {
+ if event != nil && event.DeviceID == "" {
+ event.DeviceID = r.deviceID
+ }
+ return r.base.EnqueueChatwootForwardEvent(event)
+}
+
+func (r *deviceChatStorage) ListDueChatwootForwardEvents(now time.Time, limit int) ([]*domainChatStorage.ChatwootForwardEvent, error) {
+ return r.base.ListDueChatwootForwardEvents(now, limit)
+}
+
+func (r *deviceChatStorage) MarkChatwootForwardEventFailed(id int64, lastError string, nextAttemptAt time.Time) error {
+ return r.base.MarkChatwootForwardEventFailed(id, lastError, nextAttemptAt)
+}
+
+func (r *deviceChatStorage) MarkChatwootForwardEventDone(id int64) error {
+ return r.base.MarkChatwootForwardEventDone(id)
+}
+
func (r *deviceChatStorage) StoreSentMessageWithContext(ctx context.Context, messageID string, senderJID string, recipientJID string, content string, timestamp time.Time, msg *waE2E.Message) error {
if _, ok := DeviceFromContext(ctx); !ok && r.deviceID != "" {
ctx = ContextWithDevice(ctx, NewDeviceInstance(r.deviceID, nil, nil))
diff --git a/src/infrastructure/whatsapp/chatwoot_content_test.go b/src/infrastructure/whatsapp/chatwoot_content_test.go
new file mode 100644
index 00000000..071095c9
--- /dev/null
+++ b/src/infrastructure/whatsapp/chatwoot_content_test.go
@@ -0,0 +1,882 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// --- Fakes implementing the structural interfaces extractStructuredMessageContent
+// matches against. The production code asserts payload values against anonymous
+// interfaces (interface{ GetDegreesLatitude()... }), so a test type only needs the
+// matching method set — it does NOT need to be the real protobuf type. Each fake is
+// given a unique name (ccTest* prefix) to avoid colliding with helpers in sibling
+// test files in this package.
+
+// ccTestLocation satisfies the location interface (lat/long/name) used by the
+// data["location"] branch.
+type ccTestLocation struct {
+ lat float64
+ long float64
+ name string
+}
+
+func (l ccTestLocation) GetDegreesLatitude() float64 { return l.lat }
+func (l ccTestLocation) GetDegreesLongitude() float64 { return l.long }
+func (l ccTestLocation) GetName() string { return l.name }
+
+// ccTestLiveLocation satisfies the live_location interface, which deliberately
+// lacks GetName — exercising the separate live-location branch.
+type ccTestLiveLocation struct {
+ lat float64
+ long float64
+}
+
+func (l ccTestLiveLocation) GetDegreesLatitude() float64 { return l.lat }
+func (l ccTestLiveLocation) GetDegreesLongitude() float64 { return l.long }
+
+// ccTestList satisfies the list interface (GetTitle).
+type ccTestList struct{ title string }
+
+func (l ccTestList) GetTitle() string { return l.title }
+
+// ccTestOrder satisfies the order interface (GetOrderTitle).
+type ccTestOrder struct{ title string }
+
+func (o ccTestOrder) GetOrderTitle() string { return o.title }
+
+// ccTestContactIface satisfies the GetDisplayName/GetVcard interface branch in
+// extractContactDetails — the path the real waE2E.ContactMessage takes.
+type ccTestContactIface struct {
+ name string
+ vcard string
+}
+
+func (c ccTestContactIface) GetDisplayName() string { return c.name }
+func (c ccTestContactIface) GetVcard() string { return c.vcard }
+
+// vcardWithTel builds a minimal vCard whose TEL field carries the supplied number,
+// so tests can drive ExtractPhoneFromVCard without hand-writing the format inline.
+func vcardWithTel(t *testing.T, phone string) string {
+ t.Helper()
+ return "BEGIN:VCARD\nVERSION:3.0\nFN:Someone\nTEL;type=CELL:" + phone + "\nEND:VCARD"
+}
+
+// TestExtractChatwootContactInfo pins the contact-derivation logic that decides
+// which Chatwoot contact a WhatsApp message maps to. The branch selection here is
+// security/UX sensitive: a wrong identifier silently merges or splits conversations
+// in the agent inbox, and a missed system-JID guard floods Chatwoot with status
+// noise. Every case calls with context.Background(), where getGroupName has no
+// WhatsApp client and therefore returns "" — exercising the group-name fallback.
+func TestExtractChatwootContactInfo(t *testing.T) {
+ ctx := context.Background()
+
+ t.Run("empty from is rejected", func(t *testing.T) {
+ // Without a sender we cannot identify a contact at all; the producer must
+ // never reach Chatwoot, so this is an error rather than a placeholder.
+ info, err := extractChatwootContactInfo(ctx, map[string]any{"from": ""})
+ if err == nil {
+ t.Fatalf("expected error for empty 'from', got info=%+v", info)
+ }
+ if info != nil {
+ t.Fatalf("expected nil info on error, got %+v", info)
+ }
+ })
+
+ t.Run("missing from field is rejected", func(t *testing.T) {
+ // A payload with no 'from' key at all takes the same path as empty string
+ // (the type assertion yields "").
+ if _, err := extractChatwootContactInfo(ctx, map[string]any{}); err == nil {
+ t.Fatal("expected error when 'from' field is absent")
+ }
+ })
+
+ t.Run("status broadcast chat_id is skipped", func(t *testing.T) {
+ // status@broadcast in chat_id must short-circuit even though 'from' is a
+ // real user — relaying status posts would spawn a noise "Status" contact.
+ _, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "status@broadcast",
+ })
+ if err == nil {
+ t.Fatal("expected status@broadcast chat_id to be skipped")
+ }
+ })
+
+ t.Run("system service account from is skipped", func(t *testing.T) {
+ // [email protected] is WhatsApp's official service account; guarding on
+ // 'from' (not just chat_id) blocks its TOS/notice messages.
+ _, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected [email protected] 'from' to be skipped")
+ }
+ })
+
+ t.Run("group uses chat_id identifier and Group: phone fallback name", func(t *testing.T) {
+ // For a group, the identifier is the raw @g.us JID (so every member's
+ // messages collapse into one conversation). With no client in context
+ // getGroupName returns "", so Name falls back to "Group: <extracted phone>".
+ groupJID := "[email protected]"
+ // Seed the cache with an empty name so the fallback is deterministic even
+ // if another test in this package has set a global WhatsApp client. A
+ // cached "" still flows to the "Group: <phone>" fallback. This is a fresh
+ // entry (TTL in the future), so no timing dependency is introduced.
+ setCachedGroupName(groupJID, "")
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": groupJID,
+ "from_name": "Alice",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !info.IsGroup {
+ t.Fatal("expected IsGroup=true for @g.us chat_id")
+ }
+ if info.Identifier != groupJID {
+ t.Fatalf("expected identifier %q, got %q", groupJID, info.Identifier)
+ }
+ // ExtractPhoneFromJID splits on '@', so the fallback embeds the JID's local part.
+ wantName := "Group: 120363999000111"
+ if info.Name != wantName {
+ t.Fatalf("expected fallback name %q, got %q", wantName, info.Name)
+ }
+ // FromName is carried through verbatim for later sender-prefixing.
+ if info.FromName != "Alice" {
+ t.Fatalf("expected FromName=Alice, got %q", info.FromName)
+ }
+ })
+
+ t.Run("group fallback prefix even when from_name empty", func(t *testing.T) {
+ groupJID := "[email protected]"
+ setCachedGroupName(groupJID, "")
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": groupJID,
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !strings.HasPrefix(info.Name, "Group: ") {
+ t.Fatalf("expected name to start with 'Group: ', got %q", info.Name)
+ }
+ })
+
+ t.Run("outgoing 1:1 uses chat_id identifier and identifier as name", func(t *testing.T) {
+ // is_from_me=true means WE sent it; the contact is the recipient encoded in
+ // chat_id, and there is no pushname for ourselves, so Name == Identifier.
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ "is_from_me": true,
+ "from_name": "Me",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if info.IsGroup {
+ t.Fatal("expected IsGroup=false for s.whatsapp.net chat")
+ }
+ // chatwootIdentifierForJID strips the suffix for ordinary phone JIDs.
+ if info.Identifier != "628999" {
+ t.Fatalf("expected identifier 628999 (from chat_id), got %q", info.Identifier)
+ }
+ if info.Name != info.Identifier {
+ t.Fatalf("expected Name==Identifier for outgoing, got Name=%q Identifier=%q", info.Name, info.Identifier)
+ }
+ })
+
+ t.Run("inbound 1:1 uses from identifier and from_name as name", func(t *testing.T) {
+ // Incoming 1:1: identifier derives from 'from', and the human-readable
+ // pushname (from_name) becomes the contact Name when present.
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ "from_name": "Charlie",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if info.Identifier != "628123456789" {
+ t.Fatalf("expected identifier 628123456789, got %q", info.Identifier)
+ }
+ if info.Name != "Charlie" {
+ t.Fatalf("expected Name=Charlie, got %q", info.Name)
+ }
+ })
+
+ t.Run("inbound 1:1 falls back to identifier when from_name empty", func(t *testing.T) {
+ // No pushname → Name defaults to the identifier so the inbox isn't blank.
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if info.Name != "628123456789" {
+ t.Fatalf("expected Name to fall back to identifier, got %q", info.Name)
+ }
+ })
+
+ t.Run("lid sender keeps @lid suffix in identifier", func(t *testing.T) {
+ // @lid (privacy-masked) JIDs must retain the suffix so the Chatwoot client
+ // takes its identifier-search branch instead of phone-normalizing garbage.
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "1234567890abcd@lid",
+ "chat_id": "1234567890abcd@lid",
+ "from_name": "Masked",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if info.Identifier != "1234567890abcd@lid" {
+ t.Fatalf("expected @lid identifier preserved, got %q", info.Identifier)
+ }
+ if info.Name != "Masked" {
+ t.Fatalf("expected Name=Masked, got %q", info.Name)
+ }
+ })
+}
+
+// TestBuildChatwootMessageContent pins how a message payload is rendered into the
+// (content, attachments) pair Chatwoot receives. The media handling and group
+// sender-prefixing are the regression-prone parts: a dropped attachment or a
+// missing sender prefix degrades the agent experience silently.
+func TestBuildChatwootMessageContent(t *testing.T) {
+ t.Run("plain body passthrough", func(t *testing.T) {
+ content, atts := buildChatwootMessageContent(map[string]any{"body": "hello world"}, false, "")
+ if content != "hello world" {
+ t.Fatalf("expected body passthrough, got %q", content)
+ }
+ if len(atts) != 0 {
+ t.Fatalf("expected no attachments, got %v", atts)
+ }
+ })
+
+ t.Run("empty body falls back to structured content", func(t *testing.T) {
+ // An empty body but a structured location → the structured extractor fills
+ // the content instead of leaving it blank.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "",
+ "location": ccTestLocation{lat: 1.5, long: 2.5, name: "Office"},
+ }, false, "")
+ if content != "Location: Office (1.500000, 2.500000)" {
+ t.Fatalf("expected structured location content, got %q", content)
+ }
+ })
+
+ t.Run("group prefixes sender name onto text content", func(t *testing.T) {
+ // In a group, every text message is prefixed "<sender>: " so agents can tell
+ // who spoke without opening each message.
+ content, _ := buildChatwootMessageContent(map[string]any{"body": "morning"}, true, "Alice")
+ if content != "Alice: morning" {
+ t.Fatalf("expected 'Alice: morning', got %q", content)
+ }
+ })
+
+ t.Run("group falls back to participant phone when fromName empty", func(t *testing.T) {
+ // With no pushname but a participant JID present, the sender is labeled by
+ // phone so group attribution survives, matching the reaction path.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "hi",
+ "from": "[email protected]",
+ }, true, "")
+ if content != "628111: hi" {
+ t.Fatalf("expected '628111: hi', got %q", content)
+ }
+ })
+
+ t.Run("group with empty fromName and no from does not prefix", func(t *testing.T) {
+ // Guard: nothing to attribute → no stray ": " prefix.
+ content, _ := buildChatwootMessageContent(map[string]any{"body": "hi"}, true, "")
+ if content != "hi" {
+ t.Fatalf("expected unprefixed 'hi', got %q", content)
+ }
+ })
+
+ t.Run("outgoing group message is not prefixed with operator name", func(t *testing.T) {
+ // is_from_me messages are our own replies; prefixing them with the
+ // operator's pushname would mislabel the outgoing bubble.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "on it",
+ "is_from_me": true,
+ }, true, "Operator")
+ if content != "on it" {
+ t.Fatalf("expected unprefixed 'on it' for outgoing, got %q", content)
+ }
+ })
+
+ // Each media field is verified for both shapes the producer can emit:
+ // a bare string path, and a {path, caption} map. Both must yield exactly one
+ // attachment. A url-only map (auto-download disabled) must yield none.
+ mediaFields := []string{"image", "audio", "video", "document", "sticker", "video_note"}
+ for _, field := range mediaFields {
+ field := field
+ t.Run("media field string path -> attachment: "+field, func(t *testing.T) {
+ content, atts := buildChatwootMessageContent(map[string]any{
+ field: "/tmp/wa/" + field + ".bin",
+ }, false, "")
+ if len(atts) != 1 || atts[0] != "/tmp/wa/"+field+".bin" {
+ t.Fatalf("expected single attachment for %s string, got %v", field, atts)
+ }
+ // With an attachment present, the placeholder is NOT applied (that only
+ // fires when there is neither content nor any attachment). For a
+ // non-group media-only message the content stays empty — Chatwoot shows
+ // just the file.
+ if content != "" {
+ t.Fatalf("expected empty content for media-only %s, got %q", field, content)
+ }
+ })
+
+ t.Run("media field {path,caption} map -> attachment + caption: "+field, func(t *testing.T) {
+ content, atts := buildChatwootMessageContent(map[string]any{
+ "body": "see this",
+ field: map[string]any{"path": "/tmp/wa/" + field + ".bin", "caption": "see this"},
+ }, false, "")
+ if len(atts) != 1 || atts[0] != "/tmp/wa/"+field+".bin" {
+ t.Fatalf("expected single attachment for %s map, got %v", field, atts)
+ }
+ if content != "see this" {
+ t.Fatalf("expected caption body for %s, got %q", field, content)
+ }
+ })
+
+ t.Run("media field url-only map -> no attachment: "+field, func(t *testing.T) {
+ // auto-download disabled: only a remote URL is present, which Chatwoot
+ // can't fetch, so it must not be added as an attachment.
+ content, atts := buildChatwootMessageContent(map[string]any{
+ field: map[string]any{"url": "https://wa.example/" + field, "caption": "x"},
+ }, false, "")
+ if len(atts) != 0 {
+ t.Fatalf("expected no attachment for url-only %s, got %v", field, atts)
+ }
+ if content != "(Unsupported message type)" {
+ t.Fatalf("expected placeholder when only url present for %s, got %q", field, content)
+ }
+ })
+ }
+
+ t.Run("nil media value is skipped", func(t *testing.T) {
+ // A present-but-nil field must be ignored, not panic or add a blank attachment.
+ _, atts := buildChatwootMessageContent(map[string]any{"image": nil}, false, "")
+ if len(atts) != 0 {
+ t.Fatalf("expected no attachment for nil image, got %v", atts)
+ }
+ })
+
+ t.Run("no body and no attachments yields placeholder", func(t *testing.T) {
+ content, atts := buildChatwootMessageContent(map[string]any{}, false, "")
+ if content != "(Unsupported message type)" {
+ t.Fatalf("expected placeholder, got %q", content)
+ }
+ if len(atts) != 0 {
+ t.Fatalf("expected no attachments, got %v", atts)
+ }
+ })
+
+ t.Run("group with attachment but empty content prepends sender (media)", func(t *testing.T) {
+ // A group media message with no text still credits the sender via the
+ // "<sender>: (media)" form so the inbox shows attribution.
+ content, atts := buildChatwootMessageContent(map[string]any{
+ "image": "/tmp/wa/photo.jpg",
+ }, true, "Alice")
+ if len(atts) != 1 {
+ t.Fatalf("expected one attachment, got %v", atts)
+ }
+ if content != "Alice: (media)" {
+ t.Fatalf("expected 'Alice: (media)', got %q", content)
+ }
+ })
+
+ t.Run("group with attachment and text prefixes sender onto text", func(t *testing.T) {
+ // When both a caption and media exist in a group, the caption is prefixed
+ // with the sender and the file is still attached.
+ content, atts := buildChatwootMessageContent(map[string]any{
+ "body": "nice pic",
+ "image": map[string]any{"path": "/tmp/wa/photo.jpg", "caption": "nice pic"},
+ }, true, "Alice")
+ if len(atts) != 1 {
+ t.Fatalf("expected one attachment, got %v", atts)
+ }
+ if content != "Alice: nice pic" {
+ t.Fatalf("expected 'Alice: nice pic', got %q", content)
+ }
+ })
+
+ t.Run("multiple media fields all attach", func(t *testing.T) {
+ // The loop walks every media field, so a payload carrying several produces
+ // one attachment each, in field order.
+ _, atts := buildChatwootMessageContent(map[string]any{
+ "image": "/tmp/wa/a.jpg",
+ "audio": "/tmp/wa/b.oga",
+ "document": "/tmp/wa/c.pdf",
+ }, false, "")
+ if len(atts) != 3 {
+ t.Fatalf("expected 3 attachments, got %v", atts)
+ }
+ })
+}
+
+// TestExtractStructuredMessageContentVariants drives every non-text branch of the
+// structured extractor. The function is what renders non-body messages (contacts,
+// locations, lists, orders) into a human-readable line, so each branch's exact
+// output is part of the agent-facing contract. Note: the contact and contacts-array
+// happy paths via webhookContactPayload are already covered in webhook_forward_test.go
+// — here we focus on the map/interface/empty/default permutations and the
+// location/list/order branches.
+func TestExtractStructuredMessageContentVariants(t *testing.T) {
+ t.Run("contact map with displayName and phone", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "contact": map[string]any{
+ "displayName": "Dana",
+ "phone_number": "+62 800 1",
+ },
+ })
+ if got != "Contact: Dana (+62 800 1)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contact map with only vcard extracts phone", func(t *testing.T) {
+ // No phone_number key → fall back to parsing the vCard's TEL field.
+ got := extractStructuredMessageContent(map[string]any{
+ "contact": map[string]any{
+ "displayName": "Eve",
+ "vcard": vcardWithTel(t, "+628999"),
+ },
+ })
+ if got != "Contact: Eve (+628999)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contact map with no usable fields yields Contact shared", func(t *testing.T) {
+ // extractContactDetails returns ok=false (no name, no phone), so the
+ // extractor uses the generic "Contact shared" sentinel.
+ got := extractStructuredMessageContent(map[string]any{
+ "contact": map[string]any{"unrelated": "x"},
+ })
+ if got != "Contact shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contact via GetDisplayName/GetVcard interface", func(t *testing.T) {
+ // The real protobuf ContactMessage takes this branch; the phone comes from
+ // the vCard TEL field.
+ got := extractStructuredMessageContent(map[string]any{
+ "contact": ccTestContactIface{name: "Frank", vcard: vcardWithTel(t, "+628111")},
+ })
+ if got != "Contact: Frank (+628111)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array []any non-empty uses first with plural prefix", func(t *testing.T) {
+ // JSON-decoded payloads arrive as []any; the first element drives the
+ // summary and the plural "Contacts" prefix is used.
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": []any{
+ map[string]any{"displayName": "Gina", "phone_number": "+62 1"},
+ map[string]any{"displayName": "Hank", "phone_number": "+62 2"},
+ },
+ })
+ if got != "Contacts: Gina (+62 1)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array []any empty yields Contacts shared", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": []any{},
+ })
+ if got != "Contacts shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array []any first element unusable yields Contacts shared", func(t *testing.T) {
+ // First element has no extractable name/phone → fall back to sentinel.
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": []any{map[string]any{"unrelated": "x"}},
+ })
+ if got != "Contacts shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array pointer slice normalizes and skips nil", func(t *testing.T) {
+ // []*webhookContactPayload is normalized to values; a nil pointer is dropped
+ // so the first non-nil entry drives the summary.
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": []*webhookContactPayload{
+ nil,
+ {DisplayName: "Ivy", PhoneNumber: "+62 9"},
+ },
+ })
+ if got != "Contacts: Ivy (+62 9)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array pointer slice all nil yields Contacts shared", func(t *testing.T) {
+ // Every pointer nil → normalized slice empty → sentinel.
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": []*webhookContactPayload{nil, nil},
+ })
+ if got != "Contacts shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("contacts_array unknown type yields Contacts shared", func(t *testing.T) {
+ // The default switch arm guards against an unexpected concrete type.
+ got := extractStructuredMessageContent(map[string]any{
+ "contacts_array": "just a string",
+ })
+ if got != "Contacts shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("location with name", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "location": ccTestLocation{lat: -6.2, long: 106.8, name: "HQ"},
+ })
+ if got != "Location: HQ (-6.200000, 106.800000)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("location without name omits the label", func(t *testing.T) {
+ // Empty name → the coordinates-only form (no "Name (" wrapper).
+ got := extractStructuredMessageContent(map[string]any{
+ "location": ccTestLocation{lat: -6.2, long: 106.8},
+ })
+ if got != "Location: -6.200000, 106.800000" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("location value not implementing interface yields generic", func(t *testing.T) {
+ // A non-nil location that does not satisfy the interface still produces a
+ // readable sentinel rather than crashing.
+ got := extractStructuredMessageContent(map[string]any{
+ "location": "raw string location",
+ })
+ if got != "Location shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("live_location", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "live_location": ccTestLiveLocation{lat: 1.1, long: 2.2},
+ })
+ if got != "Live Location: 1.100000, 2.200000" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("live_location not implementing interface yields generic", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "live_location": 123,
+ })
+ if got != "Live location shared" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("list with title", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "list": ccTestList{title: "Menu"},
+ })
+ if got != "List: Menu" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("list with empty title yields generic", func(t *testing.T) {
+ // Implements the interface but title is empty → generic "List message".
+ got := extractStructuredMessageContent(map[string]any{
+ "list": ccTestList{title: ""},
+ })
+ if got != "List message" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("list not implementing interface yields generic", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "list": "raw",
+ })
+ if got != "List message" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("order with title", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "order": ccTestOrder{title: "Pizza"},
+ })
+ if got != "Order: Pizza" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("order with empty title yields generic", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "order": ccTestOrder{title: ""},
+ })
+ if got != "Order message" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("order not implementing interface yields generic", func(t *testing.T) {
+ got := extractStructuredMessageContent(map[string]any{
+ "order": 42,
+ })
+ if got != "Order message" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("nil contact value falls through to next branch", func(t *testing.T) {
+ // A present "contact" key holding nil must be treated as absent (the
+ // `&& contact != nil` guard), so a sibling location branch still wins.
+ got := extractStructuredMessageContent(map[string]any{
+ "contact": nil,
+ "location": ccTestLocation{lat: 1, long: 2, name: "X"},
+ })
+ if got != "Location: X (1.000000, 2.000000)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+
+ t.Run("empty payload yields empty string", func(t *testing.T) {
+ // No recognized structured key → "" so the caller falls back to its own
+ // placeholder logic.
+ if got := extractStructuredMessageContent(map[string]any{}); got != "" {
+ t.Fatalf("expected empty string, got %q", got)
+ }
+ })
+}
+
+// TestExtractContactDetails pins the per-shape contact parsing used by the
+// structured extractor. Each concrete type the payload can carry maps to a
+// (name, phone, ok) triple; the ok flag gates whether the caller renders a
+// formatted summary or a generic sentinel.
+func TestExtractContactDetails(t *testing.T) {
+ t.Run("webhookContactPayload value", func(t *testing.T) {
+ name, phone, ok := extractContactDetails(webhookContactPayload{
+ DisplayName: "Alice", PhoneNumber: "+62 1",
+ })
+ if !ok || name != "Alice" || phone != "+62 1" {
+ t.Fatalf("got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("webhookContactPayload pointer", func(t *testing.T) {
+ name, phone, ok := extractContactDetails(&webhookContactPayload{
+ DisplayName: "Bob", PhoneNumber: "+62 2",
+ })
+ if !ok || name != "Bob" || phone != "+62 2" {
+ t.Fatalf("got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("nil webhookContactPayload pointer is not ok", func(t *testing.T) {
+ // A typed-nil pointer must report ok=false rather than dereferencing.
+ var p *webhookContactPayload
+ name, phone, ok := extractContactDetails(p)
+ if ok || name != "" || phone != "" {
+ t.Fatalf("expected empty/false, got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("map with displayName key", func(t *testing.T) {
+ name, phone, ok := extractContactDetails(map[string]any{
+ "displayName": "Cara", "phone_number": "+62 3",
+ })
+ if !ok || name != "Cara" || phone != "+62 3" {
+ t.Fatalf("got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("map with display_name fallback key", func(t *testing.T) {
+ // When camelCase displayName is absent, snake_case display_name is read.
+ name, _, ok := extractContactDetails(map[string]any{
+ "display_name": "Dee",
+ })
+ if !ok || name != "Dee" {
+ t.Fatalf("got name=%q ok=%v", name, ok)
+ }
+ })
+
+ t.Run("map displayName takes precedence over display_name", func(t *testing.T) {
+ // The else-if order means displayName wins when both are present.
+ name, _, _ := extractContactDetails(map[string]any{
+ "displayName": "Primary",
+ "display_name": "Secondary",
+ })
+ if name != "Primary" {
+ t.Fatalf("expected displayName precedence, got %q", name)
+ }
+ })
+
+ t.Run("map falls back to vcard when phone_number absent", func(t *testing.T) {
+ name, phone, ok := extractContactDetails(map[string]any{
+ "displayName": "Erin",
+ "vcard": vcardWithTel(t, "+628222"),
+ })
+ if !ok || name != "Erin" || phone != "+628222" {
+ t.Fatalf("got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("map phone_number wins over vcard", func(t *testing.T) {
+ // vcard is only consulted when phone_number resolves to empty.
+ _, phone, _ := extractContactDetails(map[string]any{
+ "phone_number": "+62 explicit",
+ "vcard": vcardWithTel(t, "+62 fromcard"),
+ })
+ if phone != "+62 explicit" {
+ t.Fatalf("expected explicit phone, got %q", phone)
+ }
+ })
+
+ t.Run("empty map is not ok", func(t *testing.T) {
+ // Neither name nor phone → ok=false.
+ _, _, ok := extractContactDetails(map[string]any{})
+ if ok {
+ t.Fatal("expected ok=false for empty map")
+ }
+ })
+
+ t.Run("GetDisplayName/GetVcard interface", func(t *testing.T) {
+ name, phone, ok := extractContactDetails(ccTestContactIface{
+ name: "Fay", vcard: vcardWithTel(t, "+628333"),
+ })
+ if !ok || name != "Fay" || phone != "+628333" {
+ t.Fatalf("got name=%q phone=%q ok=%v", name, phone, ok)
+ }
+ })
+
+ t.Run("unrelated type is not ok", func(t *testing.T) {
+ // The default switch arm rejects anything that doesn't match a known shape.
+ _, _, ok := extractContactDetails(12345)
+ if ok {
+ t.Fatal("expected ok=false for unrelated type")
+ }
+ })
+}
+
+// TestStructuredContactsArraySummary pins the small helper that summarizes a typed
+// contacts slice — empty slices must not index out of bounds.
+func TestStructuredContactsArraySummary(t *testing.T) {
+ t.Run("empty slice yields Contacts shared", func(t *testing.T) {
+ if got := structuredContactsArraySummary(nil); got != "Contacts shared" {
+ t.Fatalf("got %q", got)
+ }
+ if got := structuredContactsArraySummary([]webhookContactPayload{}); got != "Contacts shared" {
+ t.Fatalf("got %q for empty slice", got)
+ }
+ })
+
+ t.Run("non-empty uses first contact with plural prefix", func(t *testing.T) {
+ got := structuredContactsArraySummary([]webhookContactPayload{
+ {DisplayName: "Gail", PhoneNumber: "+62 7"},
+ {DisplayName: "Hugo", PhoneNumber: "+62 8"},
+ })
+ if got != "Contacts: Gail (+62 7)" {
+ t.Fatalf("got %q", got)
+ }
+ })
+}
+
+// TestIsEventWhitelisted pins the case-insensitive, space-trimming whitelist match.
+// It mutates the global config slice, so it saves and restores the original value.
+func TestIsEventWhitelisted(t *testing.T) {
+ original := config.WhatsappWebhookEvents
+ defer func() { config.WhatsappWebhookEvents = original }()
+
+ t.Run("exact match", func(t *testing.T) {
+ config.WhatsappWebhookEvents = []string{"message"}
+ if !isEventWhitelisted("message") {
+ t.Fatal("expected exact match to be whitelisted")
+ }
+ })
+
+ t.Run("case-insensitive match", func(t *testing.T) {
+ config.WhatsappWebhookEvents = []string{"MESSAGE"}
+ if !isEventWhitelisted("message") {
+ t.Fatal("expected case-insensitive match")
+ }
+ })
+
+ t.Run("surrounding whitespace is trimmed", func(t *testing.T) {
+ // Operators often paste comma-separated lists with stray spaces; the match
+ // trims each configured entry before comparing.
+ config.WhatsappWebhookEvents = []string{" message.ack "}
+ if !isEventWhitelisted("message.ack") {
+ t.Fatal("expected whitespace-trimmed match")
+ }
+ })
+
+ t.Run("absent event is not whitelisted", func(t *testing.T) {
+ config.WhatsappWebhookEvents = []string{"message"}
+ if isEventWhitelisted("message.reaction") {
+ t.Fatal("expected unlisted event to be rejected")
+ }
+ })
+
+ t.Run("empty whitelist matches nothing here", func(t *testing.T) {
+ // isEventWhitelisted itself does NOT treat an empty list as allow-all — that
+ // allow-all behavior lives in the callers. With no entries the loop never
+ // matches.
+ config.WhatsappWebhookEvents = nil
+ if isEventWhitelisted("message") {
+ t.Fatal("expected empty whitelist to match nothing in isEventWhitelisted")
+ }
+ })
+}
+
+// TestGroupNameCache pins the TTL cache's store/load contract without depending on
+// expiry timing. setCachedGroupName stores with a future TTL, so a subsequent load
+// returns (name, true); an unknown key returns ("", false).
+func TestGroupNameCache(t *testing.T) {
+ t.Run("store then load returns cached name", func(t *testing.T) {
+ // Use a JID unlikely to collide with other tests so a leftover entry from a
+ // prior run can't mask a regression.
+ setCachedGroupName(jid, "My Group")
+ name, ok := getCachedGroupName(jid)
+ if !ok || name != "My Group" {
+ t.Fatalf("expected ('My Group', true), got (%q, %v)", name, ok)
+ }
+ })
+
+ t.Run("unknown key returns empty and false", func(t *testing.T) {
+ name, ok := getCachedGroupName("[email protected]")
+ if ok || name != "" {
+ t.Fatalf("expected ('', false) for unknown key, got (%q, %v)", name, ok)
+ }
+ })
+
+ t.Run("empty cached name still reports present", func(t *testing.T) {
+ // Storing an empty name is meaningful (it records "we tried and got nothing")
+ // — load must still return ok=true so callers don't re-fetch.
+ setCachedGroupName(jid, "")
+ name, ok := getCachedGroupName(jid)
+ if !ok || name != "" {
+ t.Fatalf("expected ('', true) for empty cached name, got (%q, %v)", name, ok)
+ }
+ })
+}
diff --git a/src/infrastructure/whatsapp/chatwoot_events_test.go b/src/infrastructure/whatsapp/chatwoot_events_test.go
new file mode 100644
index 00000000..7947a707
--- /dev/null
+++ b/src/infrastructure/whatsapp/chatwoot_events_test.go
@@ -0,0 +1,482 @@
+package whatsapp
+
+import (
+ "context"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+)
+
+// TestBuildEditDeleteChatwootContent pins how WhatsApp edit/revoke/delete events
+// render into the Chatwoot note text and the WhatsApp message id used for
+// threading. The exact emoji-prefixed strings are agent-facing contract, and the
+// threadID is what anchors the note onto the message it refers to — a wrong key
+// here detaches the note in the inbox. The edited body is run through the WA->CW
+// markdown translator, so emphasis added in the original edit survives the hop.
+func TestBuildEditDeleteChatwootContent(t *testing.T) {
+ t.Run("edited with plain body", func(t *testing.T) {
+ // Happy path: a non-empty edit body is wrapped in the "Edited:" prefix and
+ // the original message id is returned for threading.
+ content, threadID := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "new text",
+ "original_message_id": "wamid-edit-1",
+ }, false, "")
+ if content != "✏️ **Edited:** new text" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "wamid-edit-1" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("edited body is markdown-translated", func(t *testing.T) {
+ // WhatsApp markup in the edited body must be translated to Chatwoot/GFM so
+ // "*hi*" renders as bold rather than literal asterisks. This is the whole
+ // reason WhatsAppToChatwootMarkdown is called in the edit branch.
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "*hi*",
+ "original_message_id": "wamid-edit-md",
+ }, false, "")
+ if content != "✏️ **Edited:** **hi**" {
+ t.Fatalf("content = %q", content)
+ }
+ // Defensive: the translated markdown must appear inside the rendered note.
+ if !strings.Contains(content, "**hi**") {
+ t.Fatalf("expected translated bold in content, got %q", content)
+ }
+ })
+
+ t.Run("edited body mixed markup translated", func(t *testing.T) {
+ // Bold + italic together exercise the sentinel ordering in the translator:
+ // "*bold* _it_" -> "**bold** *it*".
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "*bold* _it_",
+ "original_message_id": "wamid-edit-mix",
+ }, false, "")
+ if content != "✏️ **Edited:** **bold** *it*" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("edited group prepends sender after translation", func(t *testing.T) {
+ // In a group the sender name is prefixed onto the (already translated) body
+ // before the "Edited:" wrapper, so the prefix sits inside the note body.
+ content, threadID := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "*hi*",
+ "original_message_id": "wamid-edit-grp",
+ }, true, "Alice")
+ if content != "✏️ **Edited:** Alice: **hi**" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "wamid-edit-grp" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("edited group with empty fromName does not prefix", func(t *testing.T) {
+ // Guard: empty sender name in a group must not produce a stray ": " prefix.
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "hello",
+ "original_message_id": "wamid-edit-noname",
+ }, true, "")
+ if content != "✏️ **Edited:** hello" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("edited non-group ignores fromName", func(t *testing.T) {
+ // The sender prefix is group-only; a 1:1 edit must never be prefixed even
+ // when a fromName is present.
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "solo",
+ "original_message_id": "wamid-edit-1to1",
+ }, false, "Bob")
+ if content != "✏️ **Edited:** solo" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("edited with empty body yields placeholder", func(t *testing.T) {
+ // An edit event with no body (e.g. the new content couldn't be extracted)
+ // still produces a renderable "message edited" note rather than dropping.
+ content, threadID := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "",
+ "original_message_id": "wamid-edit-empty",
+ }, false, "")
+ if content != "✏️ _(message edited)_" {
+ t.Fatalf("content = %q", content)
+ }
+ // threadID is still threaded onto the original message even with no body.
+ if threadID != "wamid-edit-empty" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("edited with whitespace-only body yields placeholder", func(t *testing.T) {
+ // The body is TrimSpace'd before the empty check, so a whitespace-only edit
+ // collapses to the same placeholder as an empty one.
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": " \t ",
+ "original_message_id": "wamid-edit-ws",
+ }, false, "")
+ if content != "✏️ _(message edited)_" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("edited group with whitespace-only body uses placeholder not prefix", func(t *testing.T) {
+ // After trim the body is empty, so the group prefix branch (guarded on
+ // body != "") is skipped and the placeholder is returned unprefixed.
+ content, _ := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": " ",
+ "original_message_id": "wamid-edit-ws-grp",
+ }, true, "Alice")
+ if content != "✏️ _(message edited)_" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("edited with missing body key yields placeholder", func(t *testing.T) {
+ // No "body" key at all takes the same path as empty string (assertion -> "").
+ content, threadID := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "original_message_id": "wamid-edit-nobody",
+ }, false, "")
+ if content != "✏️ _(message edited)_" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "wamid-edit-nobody" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("edited with missing original_message_id yields empty threadID", func(t *testing.T) {
+ // Without the original id the note still renders, but threading is impossible
+ // so threadID is empty and the caller skips the in_reply_to wiring.
+ content, threadID := buildEditDeleteChatwootContent("message.edited", map[string]any{
+ "body": "text",
+ }, false, "")
+ if content != "✏️ **Edited:** text" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "" {
+ t.Fatalf("expected empty threadID, got %q", threadID)
+ }
+ })
+
+ t.Run("revoked yields delete note and revoked id", func(t *testing.T) {
+ // A revoke (sender deleted for everyone) renders the fixed delete note and
+ // threads on revoked_message_id.
+ content, threadID := buildEditDeleteChatwootContent("message.revoked", map[string]any{
+ "revoked_message_id": "wamid-rev-1",
+ }, false, "")
+ if content != "🗑️ _This message was deleted._" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "wamid-rev-1" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("revoked ignores group/fromName", func(t *testing.T) {
+ // The delete note is fixed text; group flag and sender name never alter it.
+ content, _ := buildEditDeleteChatwootContent("message.revoked", map[string]any{
+ "revoked_message_id": "wamid-rev-grp",
+ }, true, "Alice")
+ if content != "🗑️ _This message was deleted._" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("revoked with missing id yields empty threadID", func(t *testing.T) {
+ content, threadID := buildEditDeleteChatwootContent("message.revoked", map[string]any{}, false, "")
+ if content != "🗑️ _This message was deleted._" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "" {
+ t.Fatalf("expected empty threadID, got %q", threadID)
+ }
+ })
+
+ t.Run("deleted yields same delete note and deleted id", func(t *testing.T) {
+ // message.deleted (deleted-for-me) shares the revoke note text but reads its
+ // id from deleted_message_id, a distinct key.
+ content, threadID := buildEditDeleteChatwootContent("message.deleted", map[string]any{
+ "deleted_message_id": "wamid-del-1",
+ }, false, "")
+ if content != "🗑️ _This message was deleted._" {
+ t.Fatalf("content = %q", content)
+ }
+ if threadID != "wamid-del-1" {
+ t.Fatalf("threadID = %q", threadID)
+ }
+ })
+
+ t.Run("deleted reads deleted_message_id not revoked_message_id", func(t *testing.T) {
+ // Pin the key separation: a deleted event must NOT pick up revoked_message_id
+ // even when it is present in the payload.
+ _, threadID := buildEditDeleteChatwootContent("message.deleted", map[string]any{
+ "deleted_message_id": "wamid-del-2",
+ "revoked_message_id": "wamid-should-be-ignored",
+ }, false, "")
+ if threadID != "wamid-del-2" {
+ t.Fatalf("expected deleted_message_id to win, got %q", threadID)
+ }
+ })
+
+ t.Run("unknown event yields empty content and threadID", func(t *testing.T) {
+ // Any event the function doesn't handle returns ("","") so the caller skips
+ // it rather than emitting a blank note.
+ content, threadID := buildEditDeleteChatwootContent("message.reaction", map[string]any{
+ "body": "ignored",
+ }, false, "")
+ if content != "" || threadID != "" {
+ t.Fatalf("expected empty pair for unknown event, got (%q, %q)", content, threadID)
+ }
+ })
+
+ t.Run("plain message event is not handled here", func(t *testing.T) {
+ // The base "message" event is rendered by buildChatwootMessageContent, not
+ // this function, so it falls through to the empty default.
+ content, threadID := buildEditDeleteChatwootContent("message", map[string]any{
+ "body": "hi",
+ }, false, "")
+ if content != "" || threadID != "" {
+ t.Fatalf("expected empty pair for 'message', got (%q, %q)", content, threadID)
+ }
+ })
+}
+
+// TestExtractChatwootContactInfoIgnoreJids pins the CHATWOOT_IGNORE_JIDS branch of
+// extractChatwootContactInfo. This is operator-facing access control: a JID in the
+// ignore list must be rejected (error, nil info) before any contact is created, so
+// muted groups/numbers never spawn a Chatwoot conversation. The global slice is
+// saved and restored on every case so sibling tests see the default (empty) list.
+// All cases use context.Background(), where getGroupName has no WA client.
+func TestExtractChatwootContactInfoIgnoreJids(t *testing.T) {
+ ctx := context.Background()
+ original := config.ChatwootIgnoreJids
+ defer func() { config.ChatwootIgnoreJids = original }()
+
+ t.Run("@g.us wildcard rejects a group chat", func(t *testing.T) {
+ // The "@g.us" address-space wildcard matches the group chat_id suffix, so a
+ // group message is skipped with an error and no info is returned.
+ config.ChatwootIgnoreJids = []string{"@g.us"}
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err == nil {
+ t.Fatalf("expected ignored-JID error, got info=%+v", info)
+ }
+ if info != nil {
+ t.Fatalf("expected nil info on ignore, got %+v", info)
+ }
+ })
+
+ t.Run("@g.us wildcard does not reject a 1:1 chat", func(t *testing.T) {
+ // Same wildcard must leave ordinary @s.whatsapp.net chats untouched — the
+ // suffix doesn't match, so normal processing proceeds.
+ config.ChatwootIgnoreJids = []string{"@g.us"}
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error for non-group under @g.us ignore: %v", err)
+ }
+ if info == nil || info.Identifier != "628123456789" {
+ t.Fatalf("expected normal processing, got %+v", info)
+ }
+ })
+
+ t.Run("exact JID rejects matching from/chat_id", func(t *testing.T) {
+ // An exact (non-wildcard) entry rejects precisely that JID. Here it matches
+ // both 'from' and 'chat_id'.
+ config.ChatwootIgnoreJids = []string{"[email protected]"}
+ _, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected exact-JID ignore to reject")
+ }
+ })
+
+ t.Run("exact JID rejects when only chat_id matches", func(t *testing.T) {
+ // The ignore check ORs 'chat_id' and 'from'; a match on chat_id alone is
+ // enough to skip, even with a different (allowed) sender.
+ config.ChatwootIgnoreJids = []string{"[email protected]"}
+ _, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected ignore to trigger on chat_id match alone")
+ }
+ })
+
+ t.Run("exact JID rejects when only from matches", func(t *testing.T) {
+ // Symmetric to the above: a match on 'from' alone also skips.
+ config.ChatwootIgnoreJids = []string{"[email protected]"}
+ _, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ })
+ if err == nil {
+ t.Fatal("expected ignore to trigger on from match alone")
+ }
+ })
+
+ t.Run("exact JID does not reject a different JID", func(t *testing.T) {
+ // A specific ignore entry must NOT over-match: an unrelated 1:1 chat is
+ // processed normally.
+ config.ChatwootIgnoreJids = []string{"[email protected]"}
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ "from_name": "Other",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error for non-ignored JID: %v", err)
+ }
+ if info == nil || info.Name != "Other" {
+ t.Fatalf("expected normal processing, got %+v", info)
+ }
+ })
+
+ t.Run("empty ignore list processes normally", func(t *testing.T) {
+ // With no ignore patterns, the branch is a no-op and a normal 1:1 message is
+ // processed (no rejection).
+ config.ChatwootIgnoreJids = nil
+ info, err := extractChatwootContactInfo(ctx, map[string]any{
+ "from": "[email protected]",
+ "chat_id": "[email protected]",
+ "from_name": "Charlie",
+ })
+ if err != nil {
+ t.Fatalf("unexpected error with empty ignore list: %v", err)
+ }
+ if info == nil || info.Identifier != "628123456789" || info.Name != "Charlie" {
+ t.Fatalf("expected normal processing, got %+v", info)
+ }
+ })
+}
+
+// TestBuildChatwootMessageContentMarkdown pins the WA->CW markdown translation in
+// the main message-content path. WhatsApp emphasis must be rewritten to GFM so it
+// renders in the Chatwoot inbox, and (for groups) the sender prefix must be applied
+// AFTER translation so the prefix itself is never mangled by the translator.
+func TestBuildChatwootMessageContentMarkdown(t *testing.T) {
+ t.Run("bold and italic body translated to GFM", func(t *testing.T) {
+ // "*bold* _it_" is WhatsApp markup; the Chatwoot rendering is "**bold** *it*".
+ content, atts := buildChatwootMessageContent(map[string]any{
+ "body": "*bold* _it_",
+ }, false, "")
+ if content != "**bold** *it*" {
+ t.Fatalf("content = %q", content)
+ }
+ if len(atts) != 0 {
+ t.Fatalf("expected no attachments, got %v", atts)
+ }
+ })
+
+ t.Run("strikethrough body translated to GFM", func(t *testing.T) {
+ // "~del~" -> "~~del~~"; pins the strike pass too.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "~del~",
+ }, false, "")
+ if content != "~~del~~" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("plain body without markup is unchanged", func(t *testing.T) {
+ // A body with no formatting delimiters short-circuits the translator and is
+ // passed through verbatim.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "plain text only",
+ }, false, "")
+ if content != "plain text only" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("group sender prefix applied after translation", func(t *testing.T) {
+ // The body is translated first ("*hi*" -> "**hi**"), then the sender prefix is
+ // prepended — so the prefix sits outside the translated emphasis.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "*hi*",
+ }, true, "Alice")
+ if content != "Alice: **hi**" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+
+ t.Run("group sender prefix with mixed markup", func(t *testing.T) {
+ // End-to-end: mixed markup translated, then prefixed with the sender name.
+ content, _ := buildChatwootMessageContent(map[string]any{
+ "body": "*bold* _it_",
+ }, true, "Bob")
+ if content != "Bob: **bold** *it*" {
+ t.Fatalf("content = %q", content)
+ }
+ })
+}
+
+// TestIsEventWhitelistedForChatwootEditsDeletes pins the ride-along whitelist rule
+// for edit/revoke/delete sub-events: when the base "message" event is whitelisted,
+// these derived events are mirrored to Chatwoot without operators having to list
+// each one. An empty whitelist allows everything; an unrelated whitelist blocks
+// them. The global slice is saved/restored so siblings see the default.
+func TestIsEventWhitelistedForChatwootEditsDeletes(t *testing.T) {
+ original := config.WhatsappWebhookEvents
+ defer func() { config.WhatsappWebhookEvents = original }()
+
+ editDeleteEvents := []string{"message.edited", "message.revoked", "message.deleted"}
+
+ t.Run("message whitelist allows edits and deletes to ride along", func(t *testing.T) {
+ // "message" in the whitelist must pull in the derived edit/delete events even
+ // though they are not themselves listed.
+ config.WhatsappWebhookEvents = []string{"message"}
+ for _, e := range editDeleteEvents {
+ if !isEventWhitelistedForChatwoot(e) {
+ t.Errorf("%q should ride along when 'message' is whitelisted", e)
+ }
+ }
+ })
+
+ t.Run("unrelated whitelist blocks edits and deletes", func(t *testing.T) {
+ // A whitelist that doesn't cover "message" (and lists none of the sub-events)
+ // must block all of them for Chatwoot.
+ config.WhatsappWebhookEvents = []string{"call.offer"}
+ for _, e := range editDeleteEvents {
+ if isEventWhitelistedForChatwoot(e) {
+ t.Errorf("%q should be blocked when whitelist is unrelated", e)
+ }
+ }
+ })
+
+ t.Run("empty whitelist allows edits and deletes", func(t *testing.T) {
+ // Empty whitelist is allow-all at the Chatwoot gate.
+ config.WhatsappWebhookEvents = nil
+ for _, e := range editDeleteEvents {
+ if !isEventWhitelistedForChatwoot(e) {
+ t.Errorf("%q should be allowed when whitelist is empty", e)
+ }
+ }
+ })
+
+ t.Run("explicitly whitelisted sub-event is allowed", func(t *testing.T) {
+ // Listing a sub-event by name (without "message") still allows it via the
+ // direct isEventWhitelisted match, independent of the ride-along path.
+ config.WhatsappWebhookEvents = []string{"message.edited"}
+ if !isEventWhitelistedForChatwoot("message.edited") {
+ t.Fatal("expected explicitly whitelisted message.edited to be allowed")
+ }
+ // A sibling sub-event not listed (and no "message") is still blocked.
+ if isEventWhitelistedForChatwoot("message.deleted") {
+ t.Fatal("expected message.deleted to be blocked when only message.edited is listed")
+ }
+ })
+}
diff --git a/src/infrastructure/whatsapp/chatwoot_forward_test.go b/src/infrastructure/whatsapp/chatwoot_forward_test.go
index fcf8e091..72de9491 100644
--- a/src/infrastructure/whatsapp/chatwoot_forward_test.go
+++ b/src/infrastructure/whatsapp/chatwoot_forward_test.go
@@ -4,6 +4,7 @@ import (
"testing"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
)
func TestChatwootMessageTypeFromPayload(t *testing.T) {
@@ -48,27 +49,176 @@ func TestChatwootMessageTypeFromPayload(t *testing.T) {
}
}
-func TestShouldForwardEventToChatwoot(t *testing.T) {
+func TestBuildChatwootForwardMessageLink(t *testing.T) {
+ data := map[string]any{
+ "id": "wa-live-1",
+ "chat_id": "[email protected]",
+ "is_from_me": false,
+ }
+
+ link := buildChatwootForwardMessageLink(
+ data,
+ chatwoot.MessageOptions{SourceID: "WAID:wa-live-1"},
+ &chatwootSyncResult{MessageID: 123, ConversationID: 456, InboxID: 789},
+ )
+
+ if link == nil {
+ t.Fatal("expected chatwoot message link")
+ }
+ if link.DeviceID != "[email protected]" {
+ t.Fatalf("DeviceID = %q", link.DeviceID)
+ }
+ if link.WhatsAppMessageID != "wa-live-1" || link.SourceID != "WAID:wa-live-1" {
+ t.Fatalf("unexpected source mapping: %+v", link)
+ }
+ if link.ChatwootMessageID != 123 || link.ChatwootConversationID != 456 || link.ChatwootInboxID != 789 {
+ t.Fatalf("unexpected chatwoot ids: %+v", link)
+ }
+ if link.Direction != "incoming" {
+ t.Fatalf("Direction = %q, want incoming", link.Direction)
+ }
+}
+
+func TestExtractReceiptMessageIDs(t *testing.T) {
tests := []struct {
- name string
- eventName string
- expected bool
+ name string
+ in any
+ want []string
}{
- {name: "message supported", eventName: "message", expected: true},
- {name: "message reaction supported", eventName: "message.reaction", expected: true},
- {name: "message edited unsupported", eventName: "message.edited", expected: false},
- {name: "message revoked unsupported", eventName: "message.revoked", expected: false},
+ {name: "string slice", in: []string{"a", "b"}, want: []string{"a", "b"}},
+ {name: "any slice", in: []any{"a", "b", 3}, want: []string{"a", "b"}},
+ {name: "single string", in: "a", want: []string{"a"}},
+ {name: "empty", in: nil, want: nil},
}
-
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
- if got := shouldForwardEventToChatwoot(tc.eventName); got != tc.expected {
- t.Fatalf("expected %v, got %v", tc.expected, got)
+ got := extractReceiptMessageIDs(map[string]any{"ids": tc.in})
+ if len(got) != len(tc.want) {
+ t.Fatalf("len = %d, want %d (%v)", len(got), len(tc.want), got)
+ }
+ for i := range got {
+ if got[i] != tc.want[i] {
+ t.Fatalf("ids = %v, want %v", got, tc.want)
+ }
+ }
+ })
+ }
+}
+
+func TestDeleteTargetMessageID(t *testing.T) {
+ cases := []struct {
+ event string
+ data map[string]any
+ want string
+ }{
+ {"message.revoked", map[string]any{"revoked_message_id": "wa-1"}, "wa-1"},
+ {"message.deleted", map[string]any{"deleted_message_id": "wa-2"}, "wa-2"},
+ {"message.deleted", map[string]any{"id": "wa-current"}, "wa-current"},
+ {"message", map[string]any{"id": "wa-current"}, ""},
+ }
+ for _, tc := range cases {
+ t.Run(tc.event, func(t *testing.T) {
+ if got := deleteTargetMessageID(tc.event, tc.data); got != tc.want {
+ t.Fatalf("deleteTargetMessageID = %q, want %q", got, tc.want)
}
})
}
}
+func TestShouldForwardEventToChatwoot(t *testing.T) {
+ // message and message.reaction are always forwarded; edits and deletes are
+ // gated by their config toggles. Save/restore the globals so other tests in
+ // the package see the defaults.
+ origEdits := config.ChatwootForwardEdits
+ origDeletes := config.ChatwootForwardDeletes
+ origRead := config.ChatwootMessageRead
+ origMsgDelete := config.ChatwootMessageDelete
+ defer func() {
+ config.ChatwootForwardEdits = origEdits
+ config.ChatwootForwardDeletes = origDeletes
+ config.ChatwootMessageRead = origRead
+ config.ChatwootMessageDelete = origMsgDelete
+ }()
+
+ t.Run("always-on and unrelated events", func(t *testing.T) {
+ config.ChatwootMessageRead = false
+ cases := map[string]bool{
+ "message": true,
+ "message.reaction": true,
+ "message.ack": false,
+ "chat_presence": false,
+ }
+ for event, want := range cases {
+ if got := shouldForwardEventToChatwoot(event); got != want {
+ t.Errorf("shouldForwardEventToChatwoot(%q) = %v, want %v", event, got, want)
+ }
+ }
+ })
+
+ t.Run("read receipts follow toggle", func(t *testing.T) {
+ config.ChatwootMessageRead = true
+ if !shouldForwardEventToChatwoot("message.ack") {
+ t.Fatal("message.ack should forward when ChatwootMessageRead is enabled")
+ }
+ config.ChatwootMessageRead = false
+ if shouldForwardEventToChatwoot("message.ack") {
+ t.Fatal("message.ack should not forward when ChatwootMessageRead is disabled")
+ }
+ })
+
+ t.Run("edits and deletes follow their toggles", func(t *testing.T) {
+ config.ChatwootMessageDelete = false
+ config.ChatwootForwardEdits = true
+ config.ChatwootForwardDeletes = true
+ for _, e := range []string{"message.edited", "message.revoked", "message.deleted"} {
+ if !shouldForwardEventToChatwoot(e) {
+ t.Errorf("%q should forward when toggles enabled", e)
+ }
+ }
+
+ config.ChatwootForwardEdits = false
+ config.ChatwootForwardDeletes = false
+ for _, e := range []string{"message.edited", "message.revoked", "message.deleted"} {
+ if shouldForwardEventToChatwoot(e) {
+ t.Errorf("%q should NOT forward when toggles disabled", e)
+ }
+ }
+ })
+
+ t.Run("deletes forward when only ChatwootMessageDelete is enabled", func(t *testing.T) {
+ // The hard-delete feature must reach the forwarder even when tombstone-note
+ // forwarding (ChatwootForwardDeletes) is off, so the two are independent.
+ // Edits remain gated solely on ChatwootForwardEdits.
+ config.ChatwootForwardEdits = false
+ config.ChatwootForwardDeletes = false
+ config.ChatwootMessageDelete = true
+ for _, e := range []string{"message.revoked", "message.deleted"} {
+ if !shouldForwardEventToChatwoot(e) {
+ t.Errorf("%q should forward when ChatwootMessageDelete is enabled", e)
+ }
+ }
+ if shouldForwardEventToChatwoot("message.edited") {
+ t.Error("message.edited should NOT forward on ChatwootMessageDelete alone")
+ }
+ })
+}
+
+func TestIsRetryableChatwootForwardEvent(t *testing.T) {
+ // Base messages and their sub-events carry a unique WhatsApp id and are
+ // retry-eligible; read receipts are best-effort and must not be queued.
+ for _, e := range []string{"message", "message.edited", "message.revoked", "message.deleted", "message.reaction"} {
+ if !isRetryableChatwootForwardEvent(e) {
+ t.Errorf("%q should be retry-eligible", e)
+ }
+ }
+ for _, e := range []string{"message.ack", "chat_presence", ""} {
+ if isRetryableChatwootForwardEvent(e) {
+ t.Errorf("%q should NOT be retry-eligible", e)
+ }
+ }
+}
+
func TestIsEventWhitelistedForChatwoot(t *testing.T) {
originalEvents := config.WhatsappWebhookEvents
defer func() { config.WhatsappWebhookEvents = originalEvents }()
@@ -102,32 +252,128 @@ func TestIsEventWhitelistedForChatwoot(t *testing.T) {
})
}
+func TestExtractMediaPath(t *testing.T) {
+ // extractMediaPath handles the two shapes buildAutoDownloadPayload emits
+ // for image/video/document fields. The map branch is the regression-prone
+ // one: prior to its introduction, captioned images silently dropped their
+ // attachment because the string assertion failed and the loop moved on.
+ tests := []struct {
+ name string
+ in any
+ want string
+ }{
+ {
+ name: "plain string path (audio/sticker shape)",
+ in: "/tmp/whatsapp/audio-123.oga",
+ want: "/tmp/whatsapp/audio-123.oga",
+ },
+ {
+ name: "map with path key (captioned image/video/document shape)",
+ in: map[string]any{"path": "/tmp/whatsapp/img-1.jpg", "caption": "look at this"},
+ want: "/tmp/whatsapp/img-1.jpg",
+ },
+ {
+ name: "map with only url (auto-download disabled) yields empty",
+ in: map[string]any{"url": "https://wa.example/blob.jpg", "caption": "x"},
+ want: "",
+ },
+ {
+ name: "nil yields empty",
+ in: nil,
+ want: "",
+ },
+ {
+ name: "unrelated type yields empty",
+ in: 42,
+ want: "",
+ },
+ {
+ name: "empty string returns empty (caller treats as no-op)",
+ in: "",
+ want: "",
+ },
+ {
+ name: "map with non-string path yields empty",
+ in: map[string]any{"path": 12345},
+ want: "",
+ },
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := extractMediaPath(tc.in); got != tc.want {
+ t.Fatalf("extractMediaPath(%#v) = %q, want %q", tc.in, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestChatwootIdentifierForJID(t *testing.T) {
+ // chatwootIdentifierForJID guards the boundary into the Chatwoot REST
+ // client. The client picks its identifier-vs-phone search path by
+ // checking HasSuffix(identifier, "@lid"); stripping that suffix here
+ // would silently downgrade @lid contacts to phone-normalized garbage.
+ // Each case below pins a specific JID server / suffix so a regression
+ // (e.g. someone reintroducing ExtractPhoneFromJID at the call site)
+ // surfaces as a focused test failure rather than a downstream search miss.
+ tests := []struct {
+ name string
+ jid string
+ want string
+ }{
+ {
+ name: "ordinary phone JID is stripped to digits",
+ want: "628123456789",
+ },
+ {
+ name: "lid JID is preserved end-to-end so chatwoot client takes identifier path",
+ jid: "1234567890abcd@lid",
+ want: "1234567890abcd@lid",
+ },
+ {
+ name: "raw digits without @ pass through untouched",
+ jid: "628123456789",
+ want: "628123456789",
+ },
+ {
+ name: "empty string yields empty",
+ jid: "",
+ want: "",
+ },
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := chatwootIdentifierForJID(tc.jid); got != tc.want {
+ t.Fatalf("chatwootIdentifierForJID(%q) = %q, want %q", tc.jid, got, tc.want)
+ }
+ })
+ }
+}
+
func TestBuildReactionChatwootContent(t *testing.T) {
tests := []struct {
name string
payload map[string]any
- isGroup bool
fromName string
expected string
}{
{
- name: "group reaction with sender name and target id",
+ name: "reaction with sender name and target id",
payload: map[string]any{
"reaction": "👍",
"reacted_message_id": "wamid-123",
},
- isGroup: true,
fromName: "Alice",
expected: "Alice reacted 👍 to message wamid-123",
},
{
- name: "direct reaction falls back to phone",
+ name: "reaction falls back to phone",
payload: map[string]any{
"reaction": "🔥",
"reacted_message_id": "wamid-456",
"from": "[email protected]",
},
- isGroup: false,
fromName: "",
expected: "628123456789 reacted 🔥 to message wamid-456",
},
@@ -137,18 +383,16 @@ func TestBuildReactionChatwootContent(t *testing.T) {
"reaction": "",
"reacted_message_id": "wamid-789",
},
- isGroup: true,
fromName: "Bob",
expected: "Bob removed a reaction from message wamid-789",
},
{
- name: "group reaction falls back to sender jid when pushname missing",
+ name: "reaction falls back to sender jid when pushname missing",
payload: map[string]any{
"reaction": "😂",
"reacted_message_id": "wamid-999",
"from": "[email protected]",
},
- isGroup: true,
fromName: "",
expected: "628777000111 reacted 😂 to message wamid-999",
},
@@ -157,7 +401,6 @@ func TestBuildReactionChatwootContent(t *testing.T) {
payload: map[string]any{
"reaction": "❤️",
},
- isGroup: true,
fromName: "Carol",
expected: "Carol reacted ❤️",
},
@@ -165,7 +408,7 @@ func TestBuildReactionChatwootContent(t *testing.T) {
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
- if got := buildReactionChatwootContent(tc.payload, tc.isGroup, tc.fromName); got != tc.expected {
+ if got := buildReactionChatwootContent(tc.payload, tc.fromName); got != tc.expected {
t.Fatalf("expected %q, got %q", tc.expected, got)
}
})
diff --git a/src/infrastructure/whatsapp/device_manager.go b/src/infrastructure/whatsapp/device_manager.go
index 82b9c83b..77f7e110 100644
--- a/src/infrastructure/whatsapp/device_manager.go
+++ b/src/infrastructure/whatsapp/device_manager.go
@@ -69,6 +69,17 @@ func (m *DeviceManager) GetDevice(id string) (*DeviceInstance, bool) {
return instance, ok
}
+func (m *DeviceManager) getDeviceByJID(jid string) (*DeviceInstance, bool) {
+ m.mu.RLock()
+ defer m.mu.RUnlock()
+ for _, inst := range m.devices {
+ if inst != nil && inst.JID() == jid {
+ return inst, true
+ }
+ }
+ return nil, false
+}
+
// IsHealthy returns true if the device manager is initialized and has a valid store connection.
// Note: This is a service initialization check, not a live connectivity check.
// Returning true indicates the internal store is ready, but does not guarantee
@@ -114,6 +125,9 @@ func (m *DeviceManager) ResolveDevice(deviceID string) (*DeviceInstance, string,
if inst, ok := m.GetDevice(trimmedID); ok && inst != nil {
return inst, trimmedID, nil
}
+ if inst, ok := m.getDeviceByJID(trimmedID); ok && inst != nil {
+ return inst, inst.ID(), nil
+ }
return nil, trimmedID, fmt.Errorf("device %s not found", trimmedID)
}
diff --git a/src/infrastructure/whatsapp/device_manager_test.go b/src/infrastructure/whatsapp/device_manager_test.go
index 1b5dc06b..2e89b280 100644
--- a/src/infrastructure/whatsapp/device_manager_test.go
+++ b/src/infrastructure/whatsapp/device_manager_test.go
@@ -110,6 +110,29 @@ func TestListDevices_SingleDevice(t *testing.T) {
}
}
+func TestResolveDeviceFindsManualDeviceByJID(t *testing.T) {
+ manager := &DeviceManager{
+ devices: make(map[string]*DeviceInstance),
+ }
+ instance := &DeviceInstance{
+ id: "support-phone",
+ createdAt: time.Now(),
+ }
+ manager.devices[instance.id] = instance
+
+ resolved, resolvedID, err := manager.ResolveDevice("[email protected]")
+ if err != nil {
+ t.Fatalf("ResolveDevice by JID returned error: %v", err)
+ }
+ if resolved != instance {
+ t.Fatal("ResolveDevice by JID returned the wrong instance")
+ }
+ if resolvedID != "support-phone" {
+ t.Fatalf("resolvedID = %q, want support-phone", resolvedID)
+ }
+}
+
func TestListDevices_SameCreatedAt(t *testing.T) {
manager := &DeviceManager{
devices: make(map[string]*DeviceInstance),
diff --git a/src/infrastructure/whatsapp/event_handler.go b/src/infrastructure/whatsapp/event_handler.go
index 67aa1a45..4982004e 100644
--- a/src/infrastructure/whatsapp/event_handler.go
+++ b/src/infrastructure/whatsapp/event_handler.go
@@ -10,6 +10,7 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
domainDevice "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/device"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/ui/websocket"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow"
@@ -201,6 +202,17 @@ func handleConnectionEvents(_ context.Context, client *whatsmeow.Client, instanc
}
}
}
+ // Start Chatwoot history auto-sync on first connect for this device when
+ // CHATWOOT_IMPORT_MESSAGES is enabled. TriggerAutoSync self-guards on config,
+ // login state, and a once-per-device latch, so it is safe to call on every
+ // connect — placed before the pushname early-return because a freshly paired
+ // device may connect before its pushname is known.
+ if instance != nil {
+ if repo := instance.GetChatStorage(); repo != nil {
+ chatwoot.TriggerAutoSync(repo, client)
+ }
+ }
+
if len(client.Store.PushName) == 0 {
return
}
@@ -225,9 +237,9 @@ func handleReceipt(ctx context.Context, evt *events.Receipt, deviceID string, cl
log.Infof("%s was delivered to %s at %s: %+v", evt.MessageIDs[0], evt.SourceString(), evt.Timestamp, evt)
}
- // Forward receipt (ack) event to webhook if configured
+ // Forward receipt (ack) event to webhook or Chatwoot if configured
// Note: Receipt events are not rate limited as they are critical for message delivery status
- if len(config.WhatsappWebhook) > 0 && sendReceipt {
+ if (len(config.WhatsappWebhook) > 0 || (config.ChatwootEnabled && config.ChatwootMessageRead)) && sendReceipt {
go func(e *events.Receipt, c *whatsmeow.Client) {
webhookCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
diff --git a/src/infrastructure/whatsapp/event_message.go b/src/infrastructure/whatsapp/event_message.go
index f28009b5..cda101a1 100644
--- a/src/infrastructure/whatsapp/event_message.go
+++ b/src/infrastructure/whatsapp/event_message.go
@@ -12,7 +12,6 @@ import (
"go.mau.fi/whatsmeow/types"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
- pkgError "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/error"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow/types/events"
@@ -266,10 +265,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, audioMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download audio: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download audio: %v", err))
+ } else {
+ payload["audio"] = extracted.MediaPath
}
- payload["audio"] = extracted.MediaPath
} else {
payload["audio"] = map[string]any{
"url": audioMedia.GetURL(),
@@ -281,10 +283,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, documentMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download document: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download document: %v", err))
+ } else {
+ payload["document"] = buildAutoDownloadPayload(extracted)
}
- payload["document"] = buildAutoDownloadPayload(extracted)
} else {
payload["document"] = map[string]any{
"url": documentMedia.GetURL(),
@@ -297,10 +302,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, imageMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download image: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download image: %v", err))
+ } else {
+ payload["image"] = buildAutoDownloadPayload(extracted)
}
- payload["image"] = buildAutoDownloadPayload(extracted)
} else {
payload["image"] = map[string]any{
"url": imageMedia.GetURL(),
@@ -313,10 +321,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, stickerMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download sticker: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download sticker: %v", err))
+ } else {
+ payload["sticker"] = extracted.MediaPath
}
- payload["sticker"] = extracted.MediaPath
} else {
payload["sticker"] = map[string]any{
"url": stickerMedia.GetURL(),
@@ -328,10 +339,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, videoMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download video: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download video: %v", err))
+ } else {
+ payload["video"] = buildAutoDownloadPayload(extracted)
}
- payload["video"] = buildAutoDownloadPayload(extracted)
} else {
payload["video"] = map[string]any{
"url": videoMedia.GetURL(),
@@ -344,10 +358,13 @@ func buildMediaFields(ctx context.Context, client *whatsmeow.Client, msg *waE2E.
if config.WhatsappAutoDownloadMedia {
extracted, err := utils.ExtractMedia(ctx, client, config.PathMedia, ptvMedia)
if err != nil {
+ // Media expired/unavailable: skip the attachment but keep
+ // forwarding the message so its body/caption still reaches
+ // downstream consumers, instead of dropping the whole event.
logrus.Errorf("Failed to download video note: %v", err)
- return pkgError.WebhookError(fmt.Sprintf("Failed to download video note: %v", err))
+ } else {
+ payload["video_note"] = buildAutoDownloadPayload(extracted)
}
- payload["video_note"] = buildAutoDownloadPayload(extracted)
} else {
payload["video_note"] = map[string]any{
"url": ptvMedia.GetURL(),
diff --git a/src/infrastructure/whatsapp/webhook_forward.go b/src/infrastructure/whatsapp/webhook_forward.go
index 418ab53e..62176c65 100644
--- a/src/infrastructure/whatsapp/webhook_forward.go
+++ b/src/infrastructure/whatsapp/webhook_forward.go
@@ -2,6 +2,7 @@ package whatsapp
import (
"context"
+ "encoding/json"
"fmt"
"hash/fnv"
"strings"
@@ -9,13 +10,17 @@ import (
"time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
"github.com/sirupsen/logrus"
"go.mau.fi/whatsmeow/types"
)
-var submitWebhookFn = submitWebhook
+var (
+ submitWebhookFn = submitWebhook
+ getChatwootClientFn = chatwoot.GetDefaultClient
+)
// mutexShardCount is the number of mutex shards for contact synchronization.
// Using a fixed array avoids memory growth from sync.Map while still providing
@@ -135,6 +140,16 @@ type chatwootContactInfo struct {
IsGroup bool
FromName string
IsFromMe bool
+ // ChatJID is the full WhatsApp chat JID. It is used as the conversation's
+ // contact_inbox source_id so Chatwoot's contact endpoints (read receipts)
+ // can resolve the conversation, matching the value stored on message links.
+ ChatJID string
+}
+
+type chatwootSyncResult struct {
+ MessageID int
+ ConversationID int
+ InboxID int
}
// extractChatwootContactInfo extracts contact identifier and name from message payload.
@@ -152,10 +167,27 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]any) (*chat
return nil, fmt.Errorf("empty 'from' field")
}
+ // System JIDs (status broadcasts and the WhatsApp service account) carry
+ // no useful conversation context for an agent inbox — relaying them would
+ // create a "Status" contact and a flood of status-update messages in
+ // Chatwoot for every contact who posts a status. We filter these out
+ // here for both incoming and outgoing flows.
+ if utils.IsSystemBroadcastJID(chatID) || utils.IsSystemBroadcastJID(from) {
+ return nil, fmt.Errorf("skipping system/broadcast JID chat=%s from=%s", chatID, from)
+ }
+
+ // Operator-configured ignore list (CHATWOOT_IGNORE_JIDS) on top of the
+ // always-ignored system JIDs — supports exact JIDs and the "@g.us" /
+ // "@s.whatsapp.net" / "@lid" address-space wildcards.
+ if utils.MatchesIgnoredJID(chatID, config.ChatwootIgnoreJids) || utils.MatchesIgnoredJID(from, config.ChatwootIgnoreJids) {
+ return nil, fmt.Errorf("skipping ignored JID chat=%s from=%s", chatID, from)
+ }
+
isGroup := utils.IsGroupJID(chatID)
info := &chatwootContactInfo{
IsGroup: isGroup,
FromName: fromName,
+ ChatJID: chatID,
}
if isGroup {
@@ -166,10 +198,10 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]any) (*chat
}
logrus.Infof("Chatwoot: Detected group message, using group contact: %s", info.Name)
} else if isFromMe {
- info.Identifier = utils.ExtractPhoneFromJID(chatID)
+ info.Identifier = chatwootIdentifierForJID(chatID)
info.Name = info.Identifier
} else {
- info.Identifier = utils.ExtractPhoneFromJID(from)
+ info.Identifier = chatwootIdentifierForJID(from)
info.Name = fromName
if info.Name == "" {
info.Name = info.Identifier
@@ -179,11 +211,63 @@ func extractChatwootContactInfo(ctx context.Context, data map[string]any) (*chat
return info, nil
}
+// chatwootIdentifierForJID returns the value to pass as the Chatwoot contact
+// identifier for a 1:1 chat. For @lid (privacy-masked) JIDs the full JID is
+// preserved so the Chatwoot client at client.go:FindContactByIdentifier
+// takes its identifier-based branch (HasSuffix "@lid"); for ordinary
+// @s.whatsapp.net JIDs the suffix is stripped so the client takes its
+// phone-normalization branch. Without this distinction, an @lid sender
+// whose LID->phone resolution fails earlier in the pipeline would arrive
+// here as e.g. "1234abcde@lid", get its suffix stripped to "1234abcde",
+// and then be misclassified as a phone number — creating a Chatwoot
+// contact with a garbage phone_number that subsequent messages from the
+// same @lid sender cannot find.
+func chatwootIdentifierForJID(jid string) string {
+ if strings.HasSuffix(jid, "@lid") {
+ return jid
+ }
+ return utils.ExtractPhoneFromJID(jid)
+}
+
+// extractMediaPath returns the on-disk path for a media field in the
+// webhook payload, handling both shapes that buildAutoDownloadPayload can
+// emit: a bare string (no caption) or a map with a "path" key (when a
+// caption rode along). Returns "" when neither shape applies — including
+// when WhatsappAutoDownloadMedia is disabled and the field carries only
+// {"url", ...} (Chatwoot can't render a remote URL as an attachment, so
+// we skip rather than POST a URL it can't fetch).
+func extractMediaPath(mediaData any) string {
+ switch v := mediaData.(type) {
+ case string:
+ return v
+ case map[string]any:
+ if path, ok := v["path"].(string); ok {
+ return path
+ }
+ }
+ return ""
+}
+
// buildChatwootMessageContent extracts message body and attachments from the payload.
// For group messages, prepends the sender name to the content.
func buildChatwootMessageContent(data map[string]any, isGroup bool, fromName string) (content string, attachments []string) {
+ // Group sender attribution: label inbound participant messages so agents can
+ // tell who spoke. Skip our own outgoing messages (the label would be the
+ // operator's own pushname) and fall back to the participant's phone when no
+ // pushname is available, matching the reaction path.
+ fromMe := chatwootMessageTypeFromPayload(data) == "outgoing"
+ senderLabel := fromName
+ if senderLabel == "" {
+ if from, ok := data["from"].(string); ok {
+ senderLabel = utils.ExtractPhoneFromJID(from)
+ }
+ }
+ prefixGroupSender := isGroup && !fromMe && senderLabel != ""
+
if body, ok := data["body"].(string); ok && body != "" {
- content = body
+ // Translate WhatsApp formatting (*bold*, _italic_, ~strike~) into the
+ // GitHub-flavored markdown Chatwoot renders so emphasis survives the hop.
+ content = utils.WhatsAppToChatwootMarkdown(body)
}
if content == "" {
@@ -191,19 +275,30 @@ func buildChatwootMessageContent(data map[string]any, isGroup bool, fromName str
}
// For group messages, prepend sender name to content
- if isGroup && fromName != "" && content != "" {
- content = fromName + ": " + content
+ if prefixGroupSender && content != "" {
+ content = senderLabel + ": " + content
}
- // Extract media attachments
+ // Extract media attachments. The producer side (buildAutoDownloadPayload
+ // in event_message.go) emits a string path when the media has no caption
+ // and a {"path", "caption"} map when it does — the latter case applies
+ // to image, video, and document fields, where WhatsApp lets the user
+ // attach a body alongside the media. Without the map branch, captioned
+ // images/videos/documents land in Chatwoot as a text caption with NO
+ // attached file, since the string assertion silently fails. audio and
+ // sticker are always plain strings, so the original branch covers them.
mediaFields := []string{"image", "audio", "video", "document", "sticker", "video_note"}
for _, field := range mediaFields {
- if mediaData, ok := data[field]; ok {
- if path, ok := mediaData.(string); ok && path != "" {
- attachments = append(attachments, path)
- logrus.Infof("Chatwoot: Found %s attachment at %s", field, path)
- }
+ mediaData, ok := data[field]
+ if !ok || mediaData == nil {
+ continue
+ }
+ path := extractMediaPath(mediaData)
+ if path == "" {
+ continue
}
+ attachments = append(attachments, path)
+ logrus.Infof("Chatwoot: Found %s attachment at %s", field, path)
}
// Handle empty content
@@ -213,8 +308,8 @@ func buildChatwootMessageContent(data map[string]any, isGroup bool, fromName str
}
// For group messages with attachments but no text, still prepend sender name
- if isGroup && fromName != "" && content == "" && len(attachments) > 0 {
- content = fromName + ": (media)"
+ if prefixGroupSender && content == "" && len(attachments) > 0 {
+ content = senderLabel + ": (media)"
}
return content, attachments
@@ -224,6 +319,15 @@ func shouldForwardEventToChatwoot(eventName string) bool {
switch eventName {
case "message", "message.reaction":
return true
+ case "message.ack":
+ return config.ChatwootMessageRead
+ case "message.edited":
+ return config.ChatwootForwardEdits
+ case "message.revoked", "message.deleted":
+ // Either feature needs the event: ChatwootForwardDeletes posts a
+ // tombstone note, ChatwootMessageDelete hard-deletes the linked Chatwoot
+ // message. They are independent and gated separately downstream.
+ return config.ChatwootForwardDeletes || config.ChatwootMessageDelete
default:
return false
}
@@ -236,10 +340,17 @@ func isEventWhitelistedForChatwoot(eventName string) bool {
if isEventWhitelisted(eventName) {
return true
}
- return eventName == "message.reaction" && isEventWhitelisted("message")
+ // Derived message sub-events (reactions, edits, deletes) ride along when the
+ // base "message" event is whitelisted, so operators don't have to enumerate
+ // every sub-event to get them mirrored to Chatwoot.
+ switch eventName {
+ case "message.reaction", "message.ack", "message.edited", "message.revoked", "message.deleted":
+ return isEventWhitelisted("message")
+ }
+ return false
}
-func buildReactionChatwootContent(data map[string]any, isGroup bool, fromName string) string {
+func buildReactionChatwootContent(data map[string]any, fromName string) string {
reaction, _ := data["reaction"].(string)
reactedMessageID, _ := data["reacted_message_id"].(string)
@@ -396,7 +507,7 @@ func structuredContactsArraySummary(contacts []webhookContactPayload) string {
}
// syncMessageToChatwoot creates or finds contact/conversation and sends the message.
-func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, content string, attachments []string) error {
+func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, content string, attachments []string, opts chatwoot.MessageOptions) (*chatwootSyncResult, error) {
// Lock per-identifier mutex to prevent duplicate contact/conversation creation
mu := getContactMutex(info.Identifier)
mu.Lock()
@@ -404,14 +515,14 @@ func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, conte
contact, err := cw.FindOrCreateContact(info.Name, info.Identifier, info.IsGroup)
if err != nil {
mu.Unlock()
- return fmt.Errorf("failed to find/create contact for %s: %w", info.Identifier, err)
+ return nil, fmt.Errorf("failed to find/create contact for %s: %w", info.Identifier, err)
}
logrus.Infof("Chatwoot: Contact ID: %d", contact.ID)
- conversation, err := cw.FindOrCreateConversation(contact.ID)
+ conversation, err := cw.FindOrCreateConversation(contact.ID, info.ChatJID)
mu.Unlock()
if err != nil {
- return fmt.Errorf("failed to find/create conversation for contact %d: %w", contact.ID, err)
+ return nil, fmt.Errorf("failed to find/create conversation for contact %d: %w", contact.ID, err)
}
logrus.Infof("Chatwoot: Conversation ID: %d", conversation.ID)
@@ -420,54 +531,445 @@ func syncMessageToChatwoot(cw *chatwoot.Client, info *chatwootContactInfo, conte
if info.IsFromMe {
messageType = "outgoing"
}
- msgID, err := cw.CreateMessage(conversation.ID, content, messageType, attachments)
+ msgID, err := cw.CreateMessage(conversation.ID, content, messageType, attachments, opts)
if err != nil {
- return fmt.Errorf("failed to create message: %w", err)
+ return nil, fmt.Errorf("failed to create message: %w", err)
}
chatwoot.MarkMessageAsSent(msgID)
logrus.Infof("Chatwoot: Message synced successfully for %s", info.Identifier)
- return nil
+ return &chatwootSyncResult{
+ MessageID: msgID,
+ ConversationID: conversation.ID,
+ InboxID: cw.InboxID,
+ }, nil
}
-func forwardToChatwoot(ctx context.Context, payload map[string]any, eventName string) {
- logrus.Infof("Chatwoot: Attempting to forward %s...", eventName)
- cw := chatwoot.GetDefaultClient()
+func chatwootLinkStorageFromContext(ctx context.Context) (string, domainChatStorage.IChatStorageRepository) {
+ instance, ok := DeviceFromContext(ctx)
+ if !ok || instance == nil {
+ return "", nil
+ }
+
+ deviceID := instance.JID()
+ if deviceID == "" {
+ if client := instance.GetClient(); client != nil && client.Store != nil && client.Store.ID != nil {
+ deviceID = client.Store.ID.ToNonAD().String()
+ }
+ }
+ if deviceID == "" {
+ deviceID = instance.ID()
+ }
+ return deviceID, instance.GetChatStorage()
+}
+
+func buildChatwootForwardMessageLink(deviceID string, data map[string]any, opts chatwoot.MessageOptions, result *chatwootSyncResult) *domainChatStorage.ChatwootMessageLink {
+ if result == nil || deviceID == "" || result.MessageID == 0 {
+ return nil
+ }
+ waMessageID, _ := data["id"].(string)
+ if waMessageID == "" {
+ return nil
+ }
+ chatJID, _ := data["chat_id"].(string)
+
+ return &domainChatStorage.ChatwootMessageLink{
+ DeviceID: deviceID,
+ WhatsAppMessageID: waMessageID,
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: result.MessageID,
+ ChatwootConversationID: result.ConversationID,
+ ChatwootInboxID: result.InboxID,
+ ChatwootContactInboxSourceID: chatJID,
+ SourceID: opts.SourceID,
+ Direction: chatwootMessageTypeFromPayload(data),
+ IsRead: false,
+ }
+}
+
+func extractReceiptMessageIDs(data map[string]any) []string {
+ rawIDs, ok := data["ids"]
+ if !ok {
+ return nil
+ }
+
+ switch ids := rawIDs.(type) {
+ case []string:
+ return ids
+ case []any:
+ result := make([]string, 0, len(ids))
+ for _, raw := range ids {
+ if id, ok := raw.(string); ok && id != "" {
+ result = append(result, id)
+ }
+ }
+ return result
+ case string:
+ if ids == "" {
+ return nil
+ }
+ return []string{ids}
+ default:
+ return nil
+ }
+}
+
+func deleteTargetMessageID(eventName string, data map[string]any) string {
+ switch eventName {
+ case "message.revoked":
+ if id, _ := data["revoked_message_id"].(string); id != "" {
+ return id
+ }
+ case "message.deleted":
+ if id, _ := data["deleted_message_id"].(string); id != "" {
+ return id
+ }
+ if id, _ := data["id"].(string); id != "" {
+ return id
+ }
+ }
+ return ""
+}
+
+func syncReadReceiptsToChatwoot(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, data map[string]any) {
+ receiptType, _ := data["receipt_type"].(string)
+ if receiptType != string(types.ReceiptTypeRead) && receiptType != string(types.ReceiptTypeReadSelf) {
+ return
+ }
+ if deviceID == "" || linkRepo == nil {
+ logrus.Warn("Chatwoot: Cannot sync read receipt without message-link storage")
+ return
+ }
+
+ for _, messageID := range extractReceiptMessageIDs(data) {
+ link, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, messageID)
+ if err != nil {
+ logrus.Errorf("Chatwoot: Failed to lookup read receipt link for %s: %v", messageID, err)
+ continue
+ }
+ if link == nil || link.ChatwootConversationID == 0 {
+ continue
+ }
+
+ sourceID := link.ChatwootContactInboxSourceID
+ if sourceID == "" {
+ sourceID = link.WhatsAppChatJID
+ }
+ if sourceID == "" {
+ logrus.Debugf("Chatwoot: Skipping read receipt %s without contact inbox source", messageID)
+ continue
+ }
+ if err := cw.UpdateLastSeen(link.ChatwootConversationID, sourceID); err != nil {
+ logrus.Errorf("Chatwoot: Failed to update last seen for message %s: %v", messageID, err)
+ continue
+ }
+ link.IsRead = true
+ if err := linkRepo.UpsertChatwootMessageLink(link); err != nil {
+ logrus.Errorf("Chatwoot: Failed to mark link read for %s: %v", messageID, err)
+ }
+ }
+}
+
+func deleteLinkedChatwootMessage(cw *chatwoot.Client, deviceID string, linkRepo domainChatStorage.IChatStorageRepository, eventName string, data map[string]any) bool {
+ if !config.ChatwootMessageDelete || deviceID == "" || linkRepo == nil {
+ return false
+ }
+
+ targetID := deleteTargetMessageID(eventName, data)
+ if targetID == "" {
+ return false
+ }
+
+ link, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, targetID)
+ if err != nil {
+ logrus.Errorf("Chatwoot: Failed to lookup delete link for %s: %v", targetID, err)
+ return false
+ }
+ if link == nil || link.ChatwootConversationID == 0 || link.ChatwootMessageID == 0 {
+ return false
+ }
+
+ if err := cw.DeleteMessage(link.ChatwootConversationID, link.ChatwootMessageID); err != nil {
+ logrus.Errorf("Chatwoot: Failed to delete Chatwoot message %d for WhatsApp %s: %v", link.ChatwootMessageID, targetID, err)
+ return false
+ }
+ return true
+}
+
+func chatwootForwardMessageID(payload map[string]any) string {
+ data, ok := payload["payload"].(map[string]any)
+ if !ok {
+ return ""
+ }
+ messageID, _ := data["id"].(string)
+ return strings.TrimSpace(messageID)
+}
+
+func chatwootForwardRetryDelay(attempts int) time.Duration {
+ if attempts < 0 {
+ attempts = 0
+ }
+ delay := time.Minute
+ for i := 0; i < attempts; i++ {
+ delay *= 2
+ if delay >= time.Hour {
+ return time.Hour
+ }
+ }
+ return delay
+}
+
+func truncateChatwootForwardError(err error) string {
+ if err == nil {
+ return ""
+ }
+ msg := err.Error()
+ if len(msg) > 2000 {
+ return msg[:2000]
+ }
+ return msg
+}
+
+// isRetryableChatwootForwardEvent reports whether a forward event is durable
+// enough to enqueue for retry on a transient failure. Base messages and their
+// edit/delete/reaction sub-events all carry a unique WhatsApp message id, so the
+// retry queue can replay them and dedup correctly. Read receipts (message.ack)
+// are intentionally excluded — they are best-effort and self-heal on the next
+// receipt.
+func isRetryableChatwootForwardEvent(eventName string) bool {
+ switch eventName {
+ case "message", "message.edited", "message.revoked", "message.deleted", "message.reaction":
+ return true
+ default:
+ return false
+ }
+}
+
+func enqueueChatwootForwardRetry(linkRepo domainChatStorage.IChatStorageRepository, deviceID, eventName string, payload map[string]any, syncErr error) bool {
+ if !isRetryableChatwootForwardEvent(eventName) || linkRepo == nil || strings.TrimSpace(deviceID) == "" || !chatwoot.Retryable(syncErr) {
+ return false
+ }
+
+ messageID := chatwootForwardMessageID(payload)
+ if messageID == "" {
+ return false
+ }
+
+ payloadJSON, err := json.Marshal(payload)
+ if err != nil {
+ logrus.Errorf("Chatwoot: Failed to serialize retry payload for %s: %v", messageID, err)
+ return false
+ }
+
+ event := &domainChatStorage.ChatwootForwardEvent{
+ DeviceID: deviceID,
+ EventName: eventName,
+ WhatsAppMessageID: messageID,
+ PayloadJSON: string(payloadJSON),
+ LastError: truncateChatwootForwardError(syncErr),
+ NextAttemptAt: time.Now().Add(chatwootForwardRetryDelay(0)),
+ }
+ if err := linkRepo.EnqueueChatwootForwardEvent(event); err != nil {
+ logrus.Errorf("Chatwoot: Failed to enqueue retry for %s: %v", messageID, err)
+ return false
+ }
+ logrus.Warnf("Chatwoot: Queued retry for WhatsApp message %s after transient failure", messageID)
+ return true
+}
+
+func syncPayloadToChatwoot(ctx context.Context, payload map[string]any, eventName, deviceID string, linkRepo domainChatStorage.IChatStorageRepository) error {
+ cw := getChatwootClientFn()
+ if cw == nil {
+ logrus.Warn("Chatwoot: Client is not initialized")
+ return nil
+ }
if !cw.IsConfigured() {
logrus.Warn("Chatwoot: Client is not configured (check CHATWOOT_* env vars)")
- return
+ return nil
}
data, ok := payload["payload"].(map[string]any)
if !ok {
logrus.Error("Chatwoot: Invalid payload format (missing 'payload' object)")
- return
+ return nil
+ }
+
+ switch eventName {
+ case "message.ack":
+ syncReadReceiptsToChatwoot(cw, deviceID, linkRepo, data)
+ return nil
+ case "message.revoked", "message.deleted":
+ if deleteLinkedChatwootMessage(cw, deviceID, linkRepo, eventName, data) {
+ return nil
+ }
+ // The hard delete was attempted (or there was no link to delete). The
+ // tombstone note that follows is a separate feature; only fall through to
+ // it when note forwarding is enabled, so ChatwootMessageDelete alone never
+ // posts a note the operator disabled.
+ if !config.ChatwootForwardDeletes {
+ return nil
+ }
}
// Extract contact information
info, err := extractChatwootContactInfo(ctx, data)
if err != nil {
logrus.Warnf("Chatwoot: Skipping message: %v", err)
- return
+ return nil
}
- // Build message content
+ // Build message content. msgOpts threads WhatsApp identifiers into Chatwoot:
+ // SourceID stamps the live message with WAID:<id> (unifying dedup with the
+ // importer and anchoring future replies); ContentAttributes.in_reply_to_external_id
+ // threads reactions/edits/deletes/replies onto the message they reference.
var (
content string
attachments []string
+ msgOpts chatwoot.MessageOptions
)
switch eventName {
case "message.reaction":
- content = buildReactionChatwootContent(data, info.IsGroup, info.FromName)
+ content = buildReactionChatwootContent(data, info.FromName)
+ if rid, _ := data["reacted_message_id"].(string); rid != "" {
+ msgOpts.ContentAttributes = map[string]any{"in_reply_to_external_id": "WAID:" + rid}
+ }
+ case "message.edited", "message.revoked", "message.deleted":
+ var threadID string
+ content, threadID = buildEditDeleteChatwootContent(eventName, data, info.IsGroup, info.FromName)
+ if content == "" {
+ logrus.Debugf("Chatwoot: Skipping %s with no renderable content", eventName)
+ return nil
+ }
+ if threadID != "" {
+ msgOpts.ContentAttributes = map[string]any{"in_reply_to_external_id": "WAID:" + threadID}
+ }
default:
content, attachments = buildChatwootMessageContent(data, info.IsGroup, info.FromName)
+ if id, _ := data["id"].(string); id != "" {
+ msgOpts.SourceID = "WAID:" + id
+ }
+ if rid, _ := data["replied_to_id"].(string); rid != "" {
+ msgOpts.ContentAttributes = map[string]any{"in_reply_to_external_id": "WAID:" + rid}
+ }
}
info.IsFromMe = chatwootMessageTypeFromPayload(data) == "outgoing"
// Sync to Chatwoot
- if err := syncMessageToChatwoot(cw, info, content, attachments); err != nil {
+ if eventName == "message" && deviceID != "" && linkRepo != nil {
+ if waMessageID, _ := data["id"].(string); waMessageID != "" {
+ existing, err := linkRepo.GetChatwootMessageLinkByWhatsAppID(deviceID, waMessageID)
+ if err != nil {
+ logrus.Errorf("Chatwoot: Failed to lookup message link for %s: %v", waMessageID, err)
+ return err
+ }
+ if existing != nil && existing.ChatwootMessageID != 0 {
+ logrus.Debugf("Chatwoot: Skipping already-linked message %s -> %d", waMessageID, existing.ChatwootMessageID)
+ return nil
+ }
+ }
+ }
+
+ result, err := syncMessageToChatwoot(cw, info, content, attachments, msgOpts)
+ if err != nil {
+ return err
+ }
+ if eventName == "message" && linkRepo != nil {
+ if link := buildChatwootForwardMessageLink(deviceID, data, msgOpts, result); link != nil {
+ if err := linkRepo.UpsertChatwootMessageLink(link); err != nil {
+ logrus.Errorf("Chatwoot: Failed to store message link for %s: %v", link.WhatsAppMessageID, err)
+ }
+ }
+ }
+ return nil
+}
+
+func forwardToChatwoot(ctx context.Context, payload map[string]any, eventName string) {
+ logrus.Infof("Chatwoot: Attempting to forward %s...", eventName)
+ deviceID, linkRepo := chatwootLinkStorageFromContext(ctx)
+ if err := syncPayloadToChatwoot(ctx, payload, eventName, deviceID, linkRepo); err != nil {
logrus.Errorf("Chatwoot: %v", err)
+ enqueueChatwootForwardRetry(linkRepo, deviceID, eventName, payload, err)
+ }
+}
+
+func processChatwootForwardRetryEvent(repo domainChatStorage.IChatStorageRepository, event *domainChatStorage.ChatwootForwardEvent) error {
+ if event == nil {
+ return nil
+ }
+ var payload map[string]any
+ if err := json.Unmarshal([]byte(event.PayloadJSON), &payload); err != nil {
+ return fmt.Errorf("decode retry payload %d: %w", event.ID, err)
+ }
+ return syncPayloadToChatwoot(context.Background(), payload, event.EventName, event.DeviceID, repo)
+}
+
+func processDueChatwootForwardRetries(repo domainChatStorage.IChatStorageRepository) {
+ if repo == nil {
+ return
+ }
+ events, err := repo.ListDueChatwootForwardEvents(time.Now(), 20)
+ if err != nil {
+ logrus.Errorf("Chatwoot: Failed to list retry queue: %v", err)
+ return
+ }
+ for _, event := range events {
+ if err := processChatwootForwardRetryEvent(repo, event); err != nil {
+ nextAttempt := time.Now().Add(chatwootForwardRetryDelay(event.Attempts + 1))
+ if markErr := repo.MarkChatwootForwardEventFailed(event.ID, truncateChatwootForwardError(err), nextAttempt); markErr != nil {
+ logrus.Errorf("Chatwoot: Failed to reschedule retry job %d: %v", event.ID, markErr)
+ }
+ logrus.Warnf("Chatwoot: Retry job %d failed, next attempt at %s: %v", event.ID, nextAttempt.Format(time.RFC3339), err)
+ continue
+ }
+ if err := repo.MarkChatwootForwardEventDone(event.ID); err != nil {
+ logrus.Errorf("Chatwoot: Failed to delete completed retry job %d: %v", event.ID, err)
+ }
+ }
+}
+
+var chatwootForwardRetryWorkerOnce sync.Once
+
+func StartChatwootForwardRetryWorker(repo domainChatStorage.IChatStorageRepository) {
+ if repo == nil || !config.ChatwootEnabled {
+ return
+ }
+ chatwootForwardRetryWorkerOnce.Do(func() {
+ go func() {
+ ticker := time.NewTicker(30 * time.Second)
+ defer ticker.Stop()
+ for {
+ processDueChatwootForwardRetries(repo)
+ <-ticker.C
+ }
+ }()
+ })
+}
+
+// buildEditDeleteChatwootContent renders a WhatsApp edit or delete event into a
+// Chatwoot note and the WhatsApp id of the message it refers to (for threading).
+// Edits carry the new text in "body"; deletes/revokes carry only the original
+// message id. Returns ("", "") when there is nothing to render.
+func buildEditDeleteChatwootContent(eventName string, data map[string]any, isGroup bool, fromName string) (content, threadID string) {
+ switch eventName {
+ case "message.edited":
+ threadID, _ = data["original_message_id"].(string)
+ body, _ := data["body"].(string)
+ body = utils.WhatsAppToChatwootMarkdown(strings.TrimSpace(body))
+ if isGroup && fromName != "" && body != "" {
+ body = fromName + ": " + body
+ }
+ if body == "" {
+ return "✏️ _(message edited)_", threadID
+ }
+ return "✏️ **Edited:** " + body, threadID
+ case "message.revoked":
+ threadID, _ = data["revoked_message_id"].(string)
+ return "🗑️ _This message was deleted._", threadID
+ case "message.deleted":
+ threadID, _ = data["deleted_message_id"].(string)
+ return "🗑️ _This message was deleted._", threadID
}
+ return "", ""
}
// isEventWhitelisted checks if the given event name is in the configured whitelist
diff --git a/src/infrastructure/whatsapp/webhook_forward_test.go b/src/infrastructure/whatsapp/webhook_forward_test.go
index 8d907993..e468a05c 100644
--- a/src/infrastructure/whatsapp/webhook_forward_test.go
+++ b/src/infrastructure/whatsapp/webhook_forward_test.go
@@ -3,12 +3,26 @@ package whatsapp
import (
"context"
"errors"
+ "net/http"
"strings"
"testing"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
)
+type chatwootForwardQueueTestRepo struct {
+ domainChatStorage.IChatStorageRepository
+ events []*domainChatStorage.ChatwootForwardEvent
+}
+
+func (r *chatwootForwardQueueTestRepo) EnqueueChatwootForwardEvent(event *domainChatStorage.ChatwootForwardEvent) error {
+ cloned := *event
+ r.events = append(r.events, &cloned)
+ return nil
+}
+
func TestForwardPayloadToConfiguredWebhooks_NoWebhooksConfigured(t *testing.T) {
ctx := context.Background()
payload := map[string]any{"foo": "bar"}
@@ -195,6 +209,54 @@ func TestForwardPayloadToConfiguredWebhooks_WhitelistCaseInsensitive(t *testing.
}
}
+func TestEnqueueChatwootForwardRetryStoresTransientMessageFailure(t *testing.T) {
+ repo := &chatwootForwardQueueTestRepo{}
+ payload := map[string]any{
+ "payload": map[string]any{
+ "id": "wa-queue-1",
+ "chat_id": "[email protected]",
+ },
+ }
+
+ queued := enqueueChatwootForwardRetry(repo, "[email protected]", "message", payload, &chatwoot.HTTPStatusError{
+ StatusCode: http.StatusInternalServerError,
+ Op: "create message",
+ Body: "unavailable",
+ })
+ if !queued {
+ t.Fatal("expected transient Chatwoot failure to be queued")
+ }
+ if len(repo.events) != 1 {
+ t.Fatalf("queued events = %d, want 1", len(repo.events))
+ }
+ event := repo.events[0]
+ if event.DeviceID != "[email protected]" || event.EventName != "message" || event.WhatsAppMessageID != "wa-queue-1" {
+ t.Fatalf("unexpected queued event: %+v", event)
+ }
+ if !strings.Contains(event.PayloadJSON, "wa-queue-1") || event.NextAttemptAt.IsZero() {
+ t.Fatalf("queued event missing payload/next attempt: %+v", event)
+ }
+}
+
+func TestEnqueueChatwootForwardRetrySkipsPermanentFailure(t *testing.T) {
+ repo := &chatwootForwardQueueTestRepo{}
+ payload := map[string]any{
+ "payload": map[string]any{"id": "wa-permanent"},
+ }
+
+ queued := enqueueChatwootForwardRetry(repo, "[email protected]", "message", payload, &chatwoot.HTTPStatusError{
+ StatusCode: http.StatusBadRequest,
+ Op: "create message",
+ Body: "bad payload",
+ })
+ if queued {
+ t.Fatal("permanent Chatwoot failure should not be queued")
+ }
+ if len(repo.events) != 0 {
+ t.Fatalf("queued events = %d, want 0", len(repo.events))
+ }
+}
+
func TestExtractStructuredMessageContentWithContactPayload(t *testing.T) {
payload := map[string]any{
"contact": webhookContactPayload{
diff --git a/src/pkg/utils/chatwoot.go b/src/pkg/utils/chatwoot.go
new file mode 100644
index 00000000..55dfdcc9
--- /dev/null
+++ b/src/pkg/utils/chatwoot.go
@@ -0,0 +1,118 @@
+package utils
+
+import (
+ "regexp"
+ "strings"
+)
+
+// MatchesIgnoredJID reports whether jid matches any pattern in the ignore
+// list. A pattern is either a suffix wildcard ("@g.us", "@s.whatsapp.net",
+// "@lid") that matches an entire address space, or an exact JID. This powers
+// config.ChatwootIgnoreJids on both the live-forward and history-import paths.
+func MatchesIgnoredJID(jid string, ignore []string) bool {
+ if jid == "" {
+ return false
+ }
+ for _, pattern := range ignore {
+ pattern = strings.TrimSpace(pattern)
+ if pattern == "" {
+ continue
+ }
+ if strings.HasPrefix(pattern, "@") {
+ if strings.HasSuffix(jid, pattern) {
+ return true
+ }
+ } else if jid == pattern {
+ return true
+ }
+ }
+ return false
+}
+
+// IsSystemBroadcastJID reports the WhatsApp system JIDs that must never reach
+// Chatwoot: status@broadcast (the per-account status feed) and [email protected]
+// (WhatsApp's official service account). Forwarding either creates noise
+// contacts that pollute the agent inbox without giving an agent anything to
+// act on. The match is by exact string — not by suffix — so legitimate JIDs
+// like "[email protected]" or "[email protected]" are not caught.
+// Both the live-forward path (webhook_forward.go) and the history importer
+// (chatwoot/sync.go) share this single definition.
+func IsSystemBroadcastJID(jid string) bool {
+ return jid == "status@broadcast" || jid == "[email protected]"
+}
+
+// Markdown translation between WhatsApp and Chatwoot.
+//
+// WhatsApp renders *bold*, _italic_, ~strikethrough~. Chatwoot renders the
+// GitHub-flavored markdown **bold**, *italic*, ~~strikethrough~~. Translating
+// in both directions keeps formatting intact as messages cross the bridge.
+// Monospace/code spans are intentionally
+// left untouched — they are rare in support chats and translating them
+// reliably (single vs. triple backtick, nesting) is error-prone.
+//
+// The transforms use paired, non-greedy delimiters, so a lone unmatched
+// delimiter (e.g. "2 * 3") is left alone — exactly the inputs WhatsApp and
+// Chatwoot themselves decline to format. Sentinel runes guard the bold pass
+// from being re-matched by the italic pass.
+
+const (
+ mdBoldSentinel = "\x01"
+ mdStrikeSentinel = "\x02"
+)
+
+var (
+ reCwBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
+ reCwStrike = regexp.MustCompile(`~~(.+?)~~`)
+ reCwItalic = regexp.MustCompile(`\*(.+?)\*`)
+ reWaBold = regexp.MustCompile(`\*(.+?)\*`)
+ reWaItalic = regexp.MustCompile(`_(.+?)_`)
+ reWaStrike = regexp.MustCompile(`~(.+?)~`)
+)
+
+// stripMarkdownSentinels removes any pre-existing guard runes from input so
+// they can never be mistaken for the internal bold/strike markers and restored
+// into markdown. Real WhatsApp/Chatwoot message text never contains these
+// control runes, so this is purely defensive.
+func stripMarkdownSentinels(s string) string {
+ if !strings.ContainsAny(s, mdBoldSentinel+mdStrikeSentinel) {
+ return s
+ }
+ return strings.NewReplacer(mdBoldSentinel, "", mdStrikeSentinel, "").Replace(s)
+}
+
+// ChatwootToWhatsAppMarkdown rewrites Chatwoot/GFM markdown to WhatsApp's
+// formatting syntax: **bold**->*bold*, *italic*->_italic_, ~~strike~~->~strike~.
+func ChatwootToWhatsAppMarkdown(s string) string {
+ if s == "" || !strings.ContainsAny(s, "*~") {
+ return s
+ }
+ s = stripMarkdownSentinels(s)
+ // Bold first so its asterisks are hidden from the italic pass.
+ s = reCwBold.ReplaceAllString(s, mdBoldSentinel+"$1"+mdBoldSentinel)
+ s = reCwStrike.ReplaceAllString(s, mdStrikeSentinel+"$1"+mdStrikeSentinel)
+ // "${1}" (braced) is required: a bare "$1_" parses as the named group "1_"
+ // (underscore is a legal $name char), which would drop the capture and
+ // collapse *italic* to a lone "_".
+ s = reCwItalic.ReplaceAllString(s, "_${1}_")
+ s = strings.ReplaceAll(s, mdBoldSentinel, "*")
+ s = strings.ReplaceAll(s, mdStrikeSentinel, "~")
+ return s
+}
+
+// WhatsAppToChatwootMarkdown rewrites WhatsApp formatting to Chatwoot/GFM
+// markdown: *bold*->**bold**, _italic_->*italic*, ~strike~->~~strike~~.
+func WhatsAppToChatwootMarkdown(s string) string {
+ if s == "" || !strings.ContainsAny(s, "*_~") {
+ return s
+ }
+ s = stripMarkdownSentinels(s)
+ // Hide bold asterisks behind a sentinel, convert italic underscores to
+ // asterisks, then expand the sentinel to a double asterisk. Doing it in
+ // this order keeps the freshly-created italic asterisks from being seen
+ // as bold.
+ s = reWaBold.ReplaceAllString(s, mdBoldSentinel+"$1"+mdBoldSentinel)
+ s = reWaItalic.ReplaceAllString(s, "*$1*")
+ s = reWaStrike.ReplaceAllString(s, "~~$1~~")
+ s = strings.ReplaceAll(s, mdBoldSentinel, "**")
+ return s
+}
diff --git a/src/pkg/utils/chatwoot_test.go b/src/pkg/utils/chatwoot_test.go
new file mode 100644
index 00000000..ae737c10
--- /dev/null
+++ b/src/pkg/utils/chatwoot_test.go
@@ -0,0 +1,385 @@
+package utils
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestMatchesIgnoredJID(t *testing.T) {
+ tests := []struct {
+ name string
+ jid string
+ ignore []string
+ want bool
+ }{
+ {
+ // Empty jid is never ignored, even when patterns exist — guards the
+ // early return that protects the live-forward path from blank JIDs.
+ name: "EmptyJIDWithNonEmptyIgnore",
+ jid: "",
+ ignore: []string{"@g.us"},
+ want: false,
+ },
+ {
+ // No patterns means nothing to match against.
+ name: "EmptyIgnoreList",
+ ignore: nil,
+ want: false,
+ },
+ {
+ // Blank/whitespace patterns are skipped, so an otherwise-empty list
+ // cannot accidentally match every JID.
+ name: "WhitespaceOnlyPatternsSkipped",
+ ignore: []string{"", " ", "\t"},
+ want: false,
+ },
+ {
+ // Suffix wildcard for the group space matches any group JID.
+ name: "GroupWildcardMatchesGroup",
+ ignore: []string{"@g.us"},
+ want: true,
+ },
+ {
+ // The group wildcard must NOT match a DM in a different address space.
+ name: "GroupWildcardDoesNotMatchDM",
+ ignore: []string{"@g.us"},
+ want: false,
+ },
+ {
+ // DM wildcard matches any direct-message JID.
+ name: "DMWildcardMatchesDM",
+ ignore: []string{"@s.whatsapp.net"},
+ want: true,
+ },
+ {
+ // DM wildcard must NOT match a group JID.
+ name: "DMWildcardDoesNotMatchGroup",
+ ignore: []string{"@s.whatsapp.net"},
+ want: false,
+ },
+ {
+ // lid wildcard matches lid-space JIDs.
+ name: "LidWildcardMatchesLid",
+ jid: "12345@lid",
+ ignore: []string{"@lid"},
+ want: true,
+ },
+ {
+ // lid wildcard must NOT bleed into the DM space.
+ name: "LidWildcardDoesNotMatchDM",
+ ignore: []string{"@lid"},
+ want: false,
+ },
+ {
+ // An exact JID pattern matches that exact JID.
+ name: "ExactJIDMatch",
+ ignore: []string{"[email protected]"},
+ want: true,
+ },
+ {
+ // Critical: an exact (non-wildcard) pattern must NOT match by suffix.
+ // "[email protected]" must not ignore "[email protected]",
+ // otherwise one blocked number would shadow many unrelated numbers.
+ name: "ExactPatternDoesNotMatchBySuffix",
+ ignore: []string{"[email protected]"},
+ want: false,
+ },
+ {
+ // Exact pattern that differs from the JID does not match.
+ name: "ExactPatternMismatch",
+ ignore: []string{"[email protected]"},
+ want: false,
+ },
+ {
+ // Surrounding spaces on a wildcard pattern are trimmed before
+ // matching — config values are often whitespace-padded.
+ name: "WildcardPatternTrimmed",
+ ignore: []string{" @g.us "},
+ want: true,
+ },
+ {
+ // Surrounding spaces on an exact pattern are trimmed too.
+ name: "ExactPatternTrimmed",
+ ignore: []string{" [email protected] "},
+ want: true,
+ },
+ {
+ // First pattern misses, a later pattern matches — the loop must scan
+ // the whole list, not stop at the first non-match.
+ name: "LaterPatternMatches",
+ ignore: []string{"[email protected]", "", "@g.us"},
+ want: true,
+ },
+ {
+ // Multiple patterns, none match.
+ name: "MultiplePatternsNoMatch",
+ jid: "12345@lid",
+ ignore: []string{"@g.us", "@s.whatsapp.net", "999@lid"},
+ want: false,
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := MatchesIgnoredJID(tt.jid, tt.ignore); got != tt.want {
+ t.Fatalf("MatchesIgnoredJID(%q, %v) = %v, want %v", tt.jid, tt.ignore, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestIsSystemBroadcastJID(t *testing.T) {
+ // Pinning the exact strings prevents a future "match by suffix" rewrite
+ // from letting real-status-bearing JIDs (e.g. "[email protected]")
+ // through, or blocking legitimate user JIDs that happen to start with "0".
+ // Single source of truth for both the live-forward and history-import paths.
+ tests := []struct {
+ name string
+ jid string
+ want bool
+ }{
+ {name: "status broadcast", jid: "status@broadcast", want: true},
+ {name: "wa service account", jid: "[email protected]", want: true},
+ {name: "ordinary user JID", jid: "[email protected]", want: false},
+ {name: "group JID", jid: "[email protected]", want: false},
+ {name: "lid JID", jid: "abc123@lid", want: false},
+ {name: "user starting with 0 is NOT system", jid: "[email protected]", want: false},
+ {name: "empty string", jid: "", want: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := IsSystemBroadcastJID(tt.jid); got != tt.want {
+ t.Fatalf("IsSystemBroadcastJID(%q) = %v, want %v", tt.jid, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootToWhatsAppMarkdown(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {
+ // Empty string short-circuits the fast path.
+ name: "Empty",
+ in: "",
+ want: "",
+ },
+ {
+ // Plain text with no * or ~ takes the ContainsAny fast path and is
+ // returned byte-for-byte unchanged.
+ name: "PlainTextNoMarkersFastPath",
+ in: "hello world",
+ want: "hello world",
+ },
+ {
+ // Underscores alone are not a Chatwoot marker here, so the fast path
+ // returns them untouched (no * or ~ present).
+ name: "UnderscoresUntouchedFastPath",
+ in: "a_b_c",
+ want: "a_b_c",
+ },
+ {
+ // **bold** -> *bold*.
+ name: "BoldAlone",
+ in: "**bold**",
+ want: "*bold*",
+ },
+ {
+ // Guard the documented invariant: bold must become a single
+ // asterisk, never get re-italicized into _x_.
+ name: "BoldNotReItalicized",
+ in: "**x**",
+ want: "*x*",
+ },
+ {
+ // *italic* -> _italic_. The braced "${1}" template terminates the
+ // group reference before the trailing underscore, so the capture is
+ // preserved (a bare "$1_" would parse "1_" as a named group and drop it).
+ name: "ItalicAlone",
+ in: "*italic*",
+ want: "_italic_",
+ },
+ {
+ // ~~strike~~ -> ~strike~. The strike template "~$1~" is safe because
+ // "~" is not a valid $name character, so $1 expands normally.
+ name: "StrikeAlone",
+ in: "~~strike~~",
+ want: "~strike~",
+ },
+ {
+ // Combined input: bold, italic, and strike all convert independently.
+ name: "Combined",
+ in: "**b** and *i* and ~~s~~",
+ want: "*b* and _i_ and ~s~",
+ },
+ {
+ // A lone unmatched asterisk has no closing pair, so it is left alone.
+ name: "LoneAsteriskUnchanged",
+ in: "2 * 3",
+ want: "2 * 3",
+ },
+ {
+ // Single closing-less asterisk in a sentence stays put.
+ name: "SingleTrailingAsterisk",
+ in: "value*",
+ want: "value*",
+ },
+ {
+ // A lone tilde without a pair is left unchanged.
+ name: "LoneTildeUnchanged",
+ in: "approx ~ 5",
+ want: "approx ~ 5",
+ },
+ {
+ // A pre-existing sentinel control rune in the input must be stripped
+ // up front, never restored into stray markdown — defends the bold/
+ // strike placeholder mechanism against crafted input.
+ name: "PreExistingSentinelStripped",
+ in: "\x01**bold**\x02",
+ want: "*bold*",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := ChatwootToWhatsAppMarkdown(tt.in)
+ if got != tt.want {
+ t.Fatalf("ChatwootToWhatsAppMarkdown(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ // No sentinel runes may ever leak into output.
+ assertNoMarkdownSentinels(t, got)
+ })
+ }
+}
+
+func TestWhatsAppToChatwootMarkdown(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {
+ // Empty string short-circuits the fast path.
+ name: "Empty",
+ in: "",
+ want: "",
+ },
+ {
+ // Plain text without *, _ or ~ is returned unchanged via fast path.
+ name: "PlainTextNoMarkersFastPath",
+ in: "hello world",
+ want: "hello world",
+ },
+ {
+ // *bold* -> **bold**.
+ name: "BoldAlone",
+ in: "*bold*",
+ want: "**bold**",
+ },
+ {
+ // _italic_ -> *italic*.
+ name: "ItalicAlone",
+ in: "_italic_",
+ want: "*italic*",
+ },
+ {
+ // ~strike~ -> ~~strike~~.
+ name: "StrikeAlone",
+ in: "~strike~",
+ want: "~~strike~~",
+ },
+ {
+ // All three convert independently; the freshly-created italic
+ // asterisks must not be re-read as bold.
+ name: "Combined",
+ in: "*b* and _i_ and ~s~",
+ want: "**b** and *i* and ~~s~~",
+ },
+ {
+ // A lone unmatched asterisk is left alone (no closing pair).
+ name: "LoneAsteriskUnchanged",
+ in: "2 * 3",
+ want: "2 * 3",
+ },
+ {
+ // A lone underscore without a pair is left unchanged.
+ name: "LoneUnderscoreUnchanged",
+ in: "a_b",
+ want: "a_b",
+ },
+ {
+ // A lone tilde without a pair is left unchanged.
+ name: "LoneTildeUnchanged",
+ in: "approx ~ 5",
+ want: "approx ~ 5",
+ },
+ {
+ // A pre-existing sentinel control rune in the input must be stripped
+ // up front, never restored into stray markdown.
+ name: "PreExistingSentinelStripped",
+ in: "\x01*bold*\x02",
+ want: "**bold**",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := WhatsAppToChatwootMarkdown(tt.in)
+ if got != tt.want {
+ t.Fatalf("WhatsAppToChatwootMarkdown(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ // The defensive sentinel-stripping pass must keep \x01/\x02 out of
+ // every output, even for inputs that never created a sentinel.
+ assertNoMarkdownSentinels(t, got)
+ })
+ }
+}
+
+// TestChatwootMarkdownRoundTrip is a sanity check that simple WhatsApp-flavored
+// strings survive a WhatsApp -> Chatwoot -> WhatsApp round trip intact.
+func TestChatwootMarkdownRoundTrip(t *testing.T) {
+ tests := []struct {
+ name string
+ wa string
+ }{
+ {name: "Bold", wa: "*bold*"},
+ {name: "Italic", wa: "_italic_"},
+ {name: "Strike", wa: "~strike~"},
+ {name: "Combined", wa: "*b* and _i_ and ~s~"},
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ cw := WhatsAppToChatwootMarkdown(tt.wa)
+ back := ChatwootToWhatsAppMarkdown(cw)
+ if back != tt.wa {
+ t.Fatalf("round trip %q -> %q -> %q, want original", tt.wa, cw, back)
+ }
+ })
+ }
+}
+
+// assertNoMarkdownSentinels fails if the markdown bridge leaked either of the
+// internal guard runes (\x01 bold, \x02 strike) into a user-visible string.
+func assertNoMarkdownSentinels(t *testing.T, out string) {
+ t.Helper()
+ if strings.ContainsAny(out, "\x01\x02") {
+ t.Fatalf("output leaked a markdown sentinel rune: %q", out)
+ }
+}
diff --git a/src/ui/AGENTS.md b/src/ui/AGENTS.md
index 82773a4b..1714388d 100644
--- a/src/ui/AGENTS.md
+++ b/src/ui/AGENTS.md
@@ -1,6 +1,6 @@
# UI ADAPTERS
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
@@ -24,6 +24,7 @@ ui/
| Add MCP tool | `mcp/<domain>.go` | Define `tool*`, `handle*`, and register in `Add*Tools`. |
| Device context | `rest/middleware/device.go`, `mcp/helpers/context.go` | REST uses header/query; MCP uses default/only device. |
| Send transport fields | `rest/send.go`, `mcp/send.go` | REST receives full send DTOs; MCP send is a smaller tool subset with manual args. |
+| Chatwoot webhook | `rest/chatwoot.go` | Public route, optional shared secret, echo suppression, read/delete sync. |
| Websocket changes | `websocket/websocket.go`, `../views/index.html` | Browser connects with `?device_id=`. |
## CONVENTIONS
@@ -32,6 +33,7 @@ ui/
- REST success payloads use `utils.ResponseData{Status: 200, Code: "SUCCESS", Message: ..., Results: ...}`.
- Device management routes are registered outside `DeviceMiddleware`; most operational routes are wrapped by it.
- Chatwoot webhook is registered before basic auth so Chatwoot can POST without the app's Basic Auth header.
+- If `CHATWOOT_WEBHOOK_SECRET` is set, the public Chatwoot webhook must pass the shared-secret check before sending to WhatsApp.
- MCP handlers validate argument types manually and return `mcp.NewToolResultText(...)`.
- MCP handlers must call `ContextWithDefaultDevice` before device-bound usecase calls.
- MCP coverage is intentionally selective: send has 6 tools, query 5, app 5, and group 13.
@@ -42,3 +44,4 @@ ui/
- Do not assume MCP receives a device header or device ID argument; use `ContextWithDefaultDevice`.
- Do not register device-scoped REST operations outside `DeviceMiddleware`.
- Do not expose new unauthenticated REST paths unless they are health checks or explicitly public webhooks.
+- Do not remove Chatwoot `source_id` and sent-message cache echo guards without a replacement loop breaker.
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index 35cbda7c..cb6b4134 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -2,11 +2,15 @@ package rest
import (
"context"
+ "crypto/subtle"
"fmt"
+ "strings"
+ "time"
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
@@ -17,6 +21,7 @@ import (
type ChatwootHandler struct {
AppUsecase domainApp.IAppUsecase
+ MessageUsecase domainMessage.IMessageUsecase
SendUsecase domainSend.ISendUsecase
DeviceManager *whatsapp.DeviceManager
ChatStorageRepo domainChatStorage.IChatStorageRepository
@@ -25,34 +30,198 @@ type ChatwootHandler struct {
func NewChatwootHandler(
appUsecase domainApp.IAppUsecase,
sendUsecase domainSend.ISendUsecase,
+ messageUsecase domainMessage.IMessageUsecase,
dm *whatsapp.DeviceManager,
chatStorageRepo domainChatStorage.IChatStorageRepository,
) *ChatwootHandler {
return &ChatwootHandler{
AppUsecase: appUsecase,
+ MessageUsecase: messageUsecase,
SendUsecase: sendUsecase,
DeviceManager: dm,
ChatStorageRepo: chatStorageRepo,
}
}
-func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
- logrus.Debugf("Chatwoot Webhook raw body: %s", string(c.Body()))
+// composeOutgoingText prepares a Chatwoot agent reply for WhatsApp delivery:
+// it translates Chatwoot/GFM markdown (**bold**, *italic*, ~~strike~~) into
+// WhatsApp's syntax, and — when CHATWOOT_SIGN_MSG is enabled — prefixes the
+// agent's name (joined by CHATWOOT_SIGN_DELIMITER, with literal "\n" escapes
+// expanded). Returns "" when the reply has no text body.
+func composeOutgoingText(payload chatwoot.WebhookPayload) string {
+ text := utils.ChatwootToWhatsAppMarkdown(payload.Content)
+ if config.ChatwootSignMsg && text != "" {
+ if agent := strings.TrimSpace(payload.Sender.Name); agent != "" {
+ delimiter := strings.ReplaceAll(config.ChatwootSignDelimiter, "\\n", "\n")
+ text = "*" + agent + "*" + delimiter + text
+ }
+ }
+ return text
+}
+
+// isEchoOfForwardedMessage reports whether a Chatwoot webhook message is one
+// this app created when mirroring an outgoing WhatsApp message. The live
+// forwarder stamps such messages with source_id "WAID:<id>" (see
+// webhook_forward.go), so they must never be sent back to WhatsApp. This guard
+// is timing-independent: the source_id is set in the create request itself,
+// unlike the in-memory sent-message cache which is only populated after the
+// create call returns — so it closes the race where Chatwoot delivers the
+// message_created webhook before that cache entry exists.
+func isEchoOfForwardedMessage(payload chatwoot.WebhookPayload) bool {
+ return strings.HasPrefix(payload.SourceID, "WAID:")
+}
+
+func chatwootPayloadDeleted(payload chatwoot.WebhookPayload) bool {
+ raw, ok := payload.ContentAttributes["deleted"]
+ if !ok {
+ return false
+ }
+ switch deleted := raw.(type) {
+ case bool:
+ return deleted
+ case string:
+ return strings.EqualFold(strings.TrimSpace(deleted), "true")
+ default:
+ return false
+ }
+}
+
+func chatwootSecretMatches(expected, candidate string) bool {
+ expected = strings.TrimSpace(expected)
+ candidate = strings.TrimSpace(candidate)
+ if expected == "" || candidate == "" {
+ return false
+ }
+ return subtle.ConstantTimeCompare([]byte(expected), []byte(candidate)) == 1
+}
+
+func chatwootWebhookAuthorized(c *fiber.Ctx) bool {
+ secret := strings.TrimSpace(config.ChatwootWebhookSecret)
+ if secret == "" {
+ return true
+ }
- // Resolve device for outbound messages
- instance, resolvedID, err := h.DeviceManager.ResolveDevice(config.ChatwootDeviceID)
+ for _, candidate := range []string{
+ c.Get("X-Chatwoot-Webhook-Secret"),
+ c.Get("X-Gowa-Chatwoot-Secret"),
+ c.Query("secret"),
+ } {
+ if chatwootSecretMatches(secret, candidate) {
+ return true
+ }
+ }
+
+ signature := strings.TrimSpace(c.Get("X-Hub-Signature-256"))
+ if signature == "" {
+ return false
+ }
+
+ digest, err := utils.GetMessageDigestOrSignature(c.Body(), []byte(secret))
if err != nil {
- logrus.Errorf("Chatwoot Webhook: Failed to resolve device: %v", err)
- return c.Status(fiber.StatusServiceUnavailable).JSON(utils.ResponseData{
- Status: fiber.StatusServiceUnavailable,
- Code: "DEVICE_NOT_AVAILABLE",
- Message: fmt.Sprintf("No device available for Chatwoot: %v. Configure CHATWOOT_DEVICE_ID or ensure one device is registered.", err),
- })
+ logrus.Errorf("Chatwoot Webhook: Failed to compute webhook signature: %v", err)
+ return false
}
- logrus.Debugf("Chatwoot Webhook: Using device %s", resolvedID)
+ return chatwootSecretMatches("sha256="+digest, signature)
+}
+
+func chatwootLinkChatJID(destination string) string {
+ clean := utils.CleanPhoneForWhatsApp(destination)
+ if clean == "" {
+ return ""
+ }
+ if strings.Contains(clean, "@") {
+ return clean
+ }
+ return clean + config.WhatsappTypeUser
+}
- // Set device context for send operations
- c.SetUserContext(whatsapp.ContextWithDevice(c.UserContext(), instance))
+// resolveSendDestination computes the WhatsApp send target from a Chatwoot
+// contact's stored destination (a JID or phone number). Group (@g.us) and
+// privacy-masked (@lid) JIDs are returned verbatim so the send layer's JID
+// parsing (ParseJID) and LID resolution (ValidateJidWithLogin) can handle them;
+// a plain @s.whatsapp.net JID is reduced to its bare phone number, and a bare
+// phone number passes through unchanged.
+//
+// Stripping the suffix for every non-group JID (the previous behavior) turned
+// an @lid destination into a bare LID id, which ParseJID then misrouted into
+// the @s.whatsapp.net space — never reaching ResolveLIDToPhone and breaking
+// every agent reply to an @lid contact.
+func resolveSendDestination(destination string) (sendDestination string, isGroup bool) {
+ isGroup = utils.IsGroupJID(destination)
+ sendDestination = utils.CleanPhoneForWhatsApp(destination)
+ if isGroup {
+ return sendDestination, true
+ }
+ if strings.HasSuffix(sendDestination, config.WhatsappTypeUser) {
+ sendDestination = utils.ExtractPhoneFromJID(sendDestination)
+ }
+ return sendDestination, false
+}
+
+func chatwootStorageDeviceID(instance *whatsapp.DeviceInstance, fallback string) string {
+ if instance == nil {
+ return fallback
+ }
+ if jid := instance.JID(); jid != "" {
+ return jid
+ }
+ return fallback
+}
+
+type chatwootWebhookRoute struct {
+ DeviceID string
+ Destination string
+}
+
+func chatwootContactAttrString(attrs map[string]any, key string) string {
+ if attrs == nil {
+ return ""
+ }
+ val, ok := attrs[key]
+ if !ok {
+ return ""
+ }
+ strVal, ok := val.(string)
+ if !ok {
+ return ""
+ }
+ return strings.TrimSpace(strVal)
+}
+
+func (h *ChatwootHandler) resolveChatwootWebhookRoute(payload chatwoot.WebhookPayload) chatwootWebhookRoute {
+ if h != nil && h.ChatStorageRepo != nil && payload.Conversation.ID != 0 {
+ link, err := h.ChatStorageRepo.GetLatestChatwootMessageLinkByConversation(payload.Conversation.ID)
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to lookup conversation route %d: %v", payload.Conversation.ID, err)
+ } else if link != nil && strings.TrimSpace(link.DeviceID) != "" && strings.TrimSpace(link.WhatsAppChatJID) != "" {
+ return chatwootWebhookRoute{
+ DeviceID: strings.TrimSpace(link.DeviceID),
+ Destination: strings.TrimSpace(link.WhatsAppChatJID),
+ }
+ }
+ }
+
+ contact := payload.Conversation.Meta.Sender
+ route := chatwootWebhookRoute{
+ DeviceID: config.ChatwootDeviceID,
+ Destination: chatwootContactAttrString(contact.CustomAttributes, "gowa_whatsapp_jid"),
+ }
+ if deviceID := chatwootContactAttrString(contact.CustomAttributes, "gowa_device_id"); deviceID != "" {
+ route.DeviceID = deviceID
+ }
+ if route.Destination == "" {
+ route.Destination = contact.PhoneNumber
+ }
+ return route
+}
+
+func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
+ if !chatwootWebhookAuthorized(c) {
+ logrus.Warn("Chatwoot Webhook: Rejected request with invalid secret")
+ return c.SendStatus(fiber.StatusUnauthorized)
+ }
+
+ logrus.Debugf("Chatwoot Webhook raw body: %s", string(c.Body()))
var payload chatwoot.WebhookPayload
if err := c.BodyParser(&payload); err != nil {
@@ -64,6 +233,9 @@ func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
payload.Event, payload.MessageType, contact.ID, contact.PhoneNumber)
if payload.Event != "message_created" {
+ if payload.Event == "message_updated" && chatwootPayloadDeleted(payload) {
+ return h.handleDeletedChatwootMessage(c, payload)
+ }
return c.SendStatus(fiber.StatusOK)
}
@@ -80,71 +252,233 @@ func (h *ChatwootHandler) HandleWebhook(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusOK)
}
- customAttrs := contact.CustomAttributes
- var destination string
- if val, ok := customAttrs["waha_whatsapp_jid"]; ok {
- if strVal, ok := val.(string); ok {
- destination = strVal
- }
- }
- if destination == "" && contact.PhoneNumber != "" {
- destination = contact.PhoneNumber
+ // Belt-and-suspenders echo guard: our live forwarder stamps mirrored
+ // outgoing messages with source_id "WAID:<id>". Skipping them here closes
+ // the race where Chatwoot delivers this webhook before MarkMessageAsSent
+ // has recorded the new message id in the in-memory cache above.
+ if isEchoOfForwardedMessage(payload) {
+ logrus.Debugf("Chatwoot Webhook: Skipping echo message %d (source_id=%s)", payload.ID, payload.SourceID)
+ return c.SendStatus(fiber.StatusOK)
}
+ // Resolve device only after the webhook is known to be a real Chatwoot
+ // agent reply. Non-message/status webhooks should not fail just because the
+ // WhatsApp device is offline.
+ route := h.resolveChatwootWebhookRoute(payload)
+ if h.DeviceManager == nil {
+ err := fmt.Errorf("device manager not initialized")
+ logrus.Errorf("Chatwoot Webhook: Failed to resolve device: %v", err)
+ h.notifySendFailure(payload, err)
+ return c.SendStatus(fiber.StatusOK)
+ }
+ instance, resolvedID, err := h.DeviceManager.ResolveDevice(route.DeviceID)
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to resolve device: %v", err)
+ h.notifySendFailure(payload, fmt.Errorf("no WhatsApp device available: %w", err))
+ return c.SendStatus(fiber.StatusOK)
+ }
+ logrus.Debugf("Chatwoot Webhook: Using device %s", resolvedID)
+ storageDeviceID := chatwootStorageDeviceID(instance, resolvedID)
+
+ // Build the device-bearing context once and reuse it for the send
+ // operations below. The send usecases resolve the WhatsApp client from this
+ // context (whatsapp.ClientFromContext), so without it the reply goes out
+ // from the global default device instead of the routed one — a cross-account
+ // mis-delivery in multi-device deployments. It is also stored on the fiber
+ // user-context because the read/revoke paths read c.UserContext().
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), instance)
+ c.SetUserContext(ctx)
+
+ destination := route.Destination
if destination == "" {
logrus.Warnf("Chatwoot Webhook: No destination phone for contact ID %d", contact.ID)
return c.SendStatus(fiber.StatusOK)
}
- // Check if this is a group message (JID ends with @g.us)
- isGroup := utils.IsGroupJID(destination)
+ linkChatJID := chatwootLinkChatJID(destination)
- // Clean up the destination for WhatsApp sending
- destination = utils.CleanPhoneForWhatsApp(destination)
+ // Resolve the WhatsApp send target. Groups (@g.us) and privacy-masked (@lid)
+ // JIDs are preserved verbatim so the send layer's JID parsing and LID
+ // resolution can handle them; only a plain @s.whatsapp.net JID is reduced to
+ // its bare phone number.
+ sendDestination, isGroup := resolveSendDestination(destination)
- // For private chats, strip the @s.whatsapp.net suffix if present
- // For groups, keep the full JID (including @g.us)
- if !isGroup {
- destination = utils.ExtractPhoneFromJID(destination)
- }
+ logrus.Debugf("Chatwoot Webhook: Sending to destination=%s isGroup=%v", sendDestination, isGroup)
- logrus.Debugf("Chatwoot Webhook: Sending to destination=%s isGroup=%v", destination, isGroup)
+ // Translate Chatwoot markdown to WhatsApp formatting and apply the optional
+ // agent signature once, so both the attachment caption and the text path use
+ // the same composed body.
+ outgoingText := composeOutgoingText(payload)
// Handle attachments if present
if len(payload.Attachments) > 0 {
- for _, attachment := range payload.Attachments {
- if err := h.handleAttachment(c, destination, attachment, payload.Content); err != nil {
+ sentAny := false
+ for i, attachment := range payload.Attachments {
+ // The caption belongs to the message as a whole, so it rides on the
+ // first attachment only — otherwise a multi-file reply repeats the
+ // same caption under every file.
+ caption := ""
+ if i == 0 {
+ caption = outgoingText
+ }
+ resp, err := h.handleAttachment(ctx, sendDestination, attachment, caption)
+ if err != nil {
logrus.Errorf("Chatwoot Webhook: Failed to send attachment %d: %v", attachment.ID, err)
+ h.notifySendFailure(payload, fmt.Errorf("attachment %d failed: %w", attachment.ID, err))
+ continue
}
+ sentAny = true
+ h.storeChatwootOutboundLink(storageDeviceID, linkChatJID, payload, resp.MessageID)
+ }
+ if sentAny {
+ h.markLatestInboundAsRead(c, storageDeviceID, linkChatJID)
}
// Return early after sending attachments - caption was already included
return c.SendStatus(fiber.StatusOK)
}
// If content is present (and not just an attachment caption), send it as text
- if payload.Content != "" {
+ if outgoingText != "" {
req := domainSend.MessageRequest{
- Message: payload.Content,
+ Message: outgoingText,
}
- req.Phone = destination
+ req.Phone = sendDestination
- _, err := h.SendUsecase.SendText(c.Context(), req)
+ resp, err := h.SendUsecase.SendText(ctx, req)
if err != nil {
// Log with more context but still return 200 to prevent Chatwoot retries
logrus.WithFields(logrus.Fields{
- "destination": destination,
+ "destination": sendDestination,
"is_group": isGroup,
"error": err.Error(),
}).Error("Chatwoot Webhook: Failed to send message (returning 200 to prevent retry)")
+ h.notifySendFailure(payload, err)
return c.SendStatus(fiber.StatusOK)
}
- logrus.Infof("Chatwoot Webhook: Sent text message to %s", destination)
+ logrus.Infof("Chatwoot Webhook: Sent text message to %s", sendDestination)
+ h.storeChatwootOutboundLink(storageDeviceID, linkChatJID, payload, resp.MessageID)
+ h.markLatestInboundAsRead(c, storageDeviceID, linkChatJID)
}
return c.SendStatus(fiber.StatusOK)
}
-func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatwoot.Attachment, caption string) error {
+func (h *ChatwootHandler) handleDeletedChatwootMessage(c *fiber.Ctx, payload chatwoot.WebhookPayload) error {
+ if !config.ChatwootMessageDelete {
+ return c.SendStatus(fiber.StatusOK)
+ }
+ if h.MessageUsecase == nil || h.ChatStorageRepo == nil || h.DeviceManager == nil {
+ logrus.Warn("Chatwoot Webhook: Cannot handle deleted message without message usecase, storage, and device manager")
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ route := h.resolveChatwootWebhookRoute(payload)
+ instance, resolvedID, err := h.DeviceManager.ResolveDevice(route.DeviceID)
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to resolve device for delete: %v", err)
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ storageDeviceID := chatwootStorageDeviceID(instance, resolvedID)
+ link, err := h.ChatStorageRepo.GetChatwootMessageLinkByChatwootID(storageDeviceID, payload.ID)
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to lookup deleted Chatwoot message %d: %v", payload.ID, err)
+ return c.SendStatus(fiber.StatusOK)
+ }
+ if link == nil {
+ return c.SendStatus(fiber.StatusOK)
+ }
+ if link.Direction != "outgoing" {
+ logrus.Debugf("Chatwoot Webhook: Not revoking inbound WhatsApp message %s for Chatwoot delete %d", link.WhatsAppMessageID, payload.ID)
+ return c.SendStatus(fiber.StatusOK)
+ }
+
+ ctx := whatsapp.ContextWithDevice(c.UserContext(), instance)
+ if _, err := h.MessageUsecase.RevokeMessage(ctx, domainMessage.RevokeRequest{
+ MessageID: link.WhatsAppMessageID,
+ Phone: link.WhatsAppChatJID,
+ }); err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to revoke WhatsApp message %s for Chatwoot delete %d: %v", link.WhatsAppMessageID, payload.ID, err)
+ h.notifySendFailure(payload, err)
+ }
+ return c.SendStatus(fiber.StatusOK)
+}
+
+func (h *ChatwootHandler) storeChatwootOutboundLink(deviceID, chatJID string, payload chatwoot.WebhookPayload, waMessageID string) {
+ if h.ChatStorageRepo == nil || deviceID == "" || chatJID == "" || payload.ID == 0 || waMessageID == "" {
+ return
+ }
+ if err := h.ChatStorageRepo.UpsertChatwootMessageLink(&domainChatStorage.ChatwootMessageLink{
+ DeviceID: deviceID,
+ WhatsAppMessageID: waMessageID,
+ WhatsAppChatJID: chatJID,
+ ChatwootMessageID: payload.ID,
+ ChatwootConversationID: payload.Conversation.ID,
+ ChatwootInboxID: config.ChatwootInboxID,
+ ChatwootContactInboxSourceID: chatJID,
+ SourceID: payload.SourceID,
+ Direction: "outgoing",
+ IsRead: true,
+ CreatedAt: time.Now(),
+ }); err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to store outbound message link for Chatwoot %d / WhatsApp %s: %v", payload.ID, waMessageID, err)
+ }
+}
+
+func (h *ChatwootHandler) markLatestInboundAsRead(c *fiber.Ctx, deviceID, chatJID string) {
+ if !config.ChatwootMessageRead || h.MessageUsecase == nil || h.ChatStorageRepo == nil || chatJID == "" {
+ return
+ }
+
+ link, err := h.ChatStorageRepo.GetLatestUnreadChatwootMessageLinkByChat(deviceID, chatJID)
+ if err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to lookup latest unread message for %s: %v", chatJID, err)
+ return
+ }
+ if link == nil {
+ return
+ }
+
+ if _, err := h.MessageUsecase.MarkAsRead(c.UserContext(), domainMessage.MarkAsReadRequest{
+ MessageID: link.WhatsAppMessageID,
+ Phone: link.WhatsAppChatJID,
+ }); err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to mark WhatsApp message %s read: %v", link.WhatsAppMessageID, err)
+ return
+ }
+ link.IsRead = true
+ if err := h.ChatStorageRepo.UpsertChatwootMessageLink(link); err != nil {
+ logrus.Errorf("Chatwoot Webhook: Failed to persist read state for %s: %v", link.WhatsAppMessageID, err)
+ }
+}
+
+func chatwootSendFailureContent(err error) string {
+ content := "Message was not sent to WhatsApp."
+ if err != nil {
+ content += "\n\nError: " + err.Error()
+ }
+ return content
+}
+
+func (h *ChatwootHandler) notifySendFailure(payload chatwoot.WebhookPayload, sendErr error) {
+ conversationID := payload.Conversation.ID
+ if conversationID == 0 {
+ logrus.Warn("Chatwoot Webhook: Cannot create send-failure note without conversation id")
+ return
+ }
+
+ cwClient := chatwoot.GetDefaultClient()
+ if !cwClient.IsConfigured() {
+ logrus.Warn("Chatwoot Webhook: Cannot create send-failure note because Chatwoot client is not configured")
+ return
+ }
+
+ if _, err := cwClient.CreateMessage(conversationID, chatwootSendFailureContent(sendErr), "outgoing", nil, chatwoot.MessageOptions{Private: true}); err != nil {
+ logrus.Warnf("Chatwoot Webhook: Failed to create send-failure note: %v", err)
+ }
+}
+
+func (h *ChatwootHandler) handleAttachment(ctx context.Context, phone string, att chatwoot.Attachment, caption string) (domainSend.GenericResponse, error) {
switch att.FileType {
case "image":
req := domainSend.ImageRequest{
@@ -152,11 +486,11 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
Caption: caption,
ImageURL: &att.DataURL,
}
- _, err := h.SendUsecase.SendImage(c.Context(), req)
+ resp, err := h.SendUsecase.SendImage(ctx, req)
if err == nil {
logrus.Infof("Chatwoot Webhook: Sent image attachment to %s", phone)
}
- return err
+ return resp, err
case "audio":
req := domainSend.AudioRequest{
@@ -164,10 +498,10 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
AudioURL: &att.DataURL,
PTT: true, // Send as PTT (Voice Note) for better mobile experience
}
- _, err := h.SendUsecase.SendAudio(c.Context(), req)
+ resp, err := h.SendUsecase.SendAudio(ctx, req)
if err == nil {
logrus.Infof("Chatwoot Webhook: Sent audio attachment to %s", phone)
- return nil
+ return resp, nil
}
logrus.Warnf("Chatwoot Webhook: Failed to send as audio (%v), retrying as file...", err)
@@ -177,11 +511,11 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
FileURL: &att.DataURL,
Caption: caption,
}
- _, err = h.SendUsecase.SendFile(c.Context(), reqFile)
+ resp, err = h.SendUsecase.SendFile(ctx, reqFile)
if err == nil {
logrus.Infof("Chatwoot Webhook: Sent audio as file attachment to %s", phone)
}
- return err
+ return resp, err
case "video":
req := domainSend.VideoRequest{
@@ -189,11 +523,11 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
Caption: caption,
VideoURL: &att.DataURL,
}
- _, err := h.SendUsecase.SendVideo(c.Context(), req)
+ resp, err := h.SendUsecase.SendVideo(ctx, req)
if err == nil {
logrus.Infof("Chatwoot Webhook: Sent video attachment to %s", phone)
}
- return err
+ return resp, err
default:
// Default to file for other types
@@ -202,33 +536,29 @@ func (h *ChatwootHandler) handleAttachment(c *fiber.Ctx, phone string, att chatw
FileURL: &att.DataURL,
Caption: caption,
}
- _, err := h.SendUsecase.SendFile(c.Context(), req)
+ resp, err := h.SendUsecase.SendFile(ctx, req)
if err == nil {
logrus.Infof("Chatwoot Webhook: Sent file attachment to %s", phone)
}
- return err
+ return resp, err
}
}
// SyncHistory triggers a message history sync to Chatwoot
// POST /chatwoot/sync
func (h *ChatwootHandler) SyncHistory(c *fiber.Ctx) error {
- // Parse request body
var req chatwoot.SyncRequest
- if err := c.BodyParser(&req); err != nil {
- // Try query parameters as fallback
- req.DeviceID = c.Query("device_id", config.ChatwootDeviceID)
- req.DaysLimit = c.QueryInt("days", config.ChatwootDaysLimitImportMessages)
- req.IncludeMedia = c.QueryBool("media", true)
- req.IncludeGroups = c.QueryBool("groups", true)
+ if strings.TrimSpace(string(c.Body())) != "" {
+ if err := c.BodyParser(&req); err != nil {
+ return utils.ResponseError(c, "Invalid payload")
+ }
}
- // Default values
if req.DeviceID == "" {
- req.DeviceID = config.ChatwootDeviceID
+ req.DeviceID = c.Query("device_id", config.ChatwootDeviceID)
}
if req.DaysLimit <= 0 {
- req.DaysLimit = config.ChatwootDaysLimitImportMessages
+ req.DaysLimit = c.QueryInt("days", config.ChatwootDaysLimitImportMessages)
}
// Resolve device
@@ -278,8 +608,16 @@ func (h *ChatwootHandler) SyncHistory(c *fiber.Ctx) error {
// Build sync options
opts := chatwoot.DefaultSyncOptions()
opts.DaysLimit = req.DaysLimit
- opts.IncludeMedia = req.IncludeMedia
- opts.IncludeGroups = req.IncludeGroups
+ if req.IncludeMedia != nil {
+ opts.IncludeMedia = *req.IncludeMedia
+ } else if c.Query("media") != "" {
+ opts.IncludeMedia = c.QueryBool("media", opts.IncludeMedia)
+ }
+ if req.IncludeGroups != nil {
+ opts.IncludeGroups = *req.IncludeGroups
+ } else if c.Query("groups") != "" {
+ opts.IncludeGroups = c.QueryBool("groups", opts.IncludeGroups)
+ }
// Start async sync
go func() {
diff --git a/src/ui/rest/chatwoot_test.go b/src/ui/rest/chatwoot_test.go
new file mode 100644
index 00000000..29db42ab
--- /dev/null
+++ b/src/ui/rest/chatwoot_test.go
@@ -0,0 +1,375 @@
+package rest
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/config"
+ domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/gofiber/fiber/v2"
+)
+
+// withSignConfig sets the Chatwoot signature globals for the duration of a
+// single subtest and restores their prior values on cleanup, so sibling tests
+// always observe the package defaults (sign disabled, "\n\n" delimiter).
+func withSignConfig(t *testing.T, signMsg bool, delimiter string) {
+ t.Helper()
+ prevSign := config.ChatwootSignMsg
+ prevDelim := config.ChatwootSignDelimiter
+ config.ChatwootSignMsg = signMsg
+ config.ChatwootSignDelimiter = delimiter
+ t.Cleanup(func() {
+ config.ChatwootSignMsg = prevSign
+ config.ChatwootSignDelimiter = prevDelim
+ })
+}
+
+func withChatwootWebhookSecret(t *testing.T, secret string) {
+ t.Helper()
+ prevSecret := config.ChatwootWebhookSecret
+ config.ChatwootWebhookSecret = secret
+ t.Cleanup(func() {
+ config.ChatwootWebhookSecret = prevSecret
+ })
+}
+
+type chatwootRouteTestRepo struct {
+ domainChatStorage.IChatStorageRepository
+ link *domainChatStorage.ChatwootMessageLink
+}
+
+func (r *chatwootRouteTestRepo) GetLatestChatwootMessageLinkByConversation(conversationID int) (*domainChatStorage.ChatwootMessageLink, error) {
+ if r.link == nil || r.link.ChatwootConversationID != conversationID {
+ return nil, nil
+ }
+ cloned := *r.link
+ return &cloned, nil
+}
+
+func TestComposeOutgoingText(t *testing.T) {
+ tests := []struct {
+ name string
+ // signMsg/delimiter drive the CHATWOOT_SIGN_* config globals for the case.
+ signMsg bool
+ delimiter string
+ content string
+ sender string
+ want string
+ }{
+ {
+ // Core reason this function exists: GFM/Chatwoot markdown is
+ // rewritten to WhatsApp's syntax before delivery — bold (**bold**->
+ // *bold*), italic (*it*->_it_), and strike (~~s~~->~s~) all translate.
+ name: "markdown translated chatwoot to whatsapp",
+ signMsg: false,
+ delimiter: "\n\n",
+ content: "**bold** *it* ~~s~~",
+ sender: "",
+ want: "*bold* _it_ ~s~",
+ },
+ {
+ // Empty content has no body, so there is nothing to send.
+ name: "empty content returns empty",
+ signMsg: false,
+ delimiter: "\n\n",
+ content: "",
+ sender: "",
+ want: "",
+ },
+ {
+ // Sign disabled: never attach a signature, even when the agent name
+ // is present — the body must pass through (markdown-translated) only.
+ name: "sign disabled ignores sender name",
+ signMsg: false,
+ delimiter: "\n\n",
+ content: "hello",
+ sender: "Agent Smith",
+ want: "hello",
+ },
+ {
+ // Sign enabled with a name: prefix "*<name>*" + delimiter + body.
+ // Default delimiter "\n\n" carries literal backslash-n escapes that
+ // must be expanded to real newlines.
+ name: "sign enabled default delimiter expands escapes",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "hello",
+ sender: "Agent Smith",
+ want: "*Agent Smith*\n\nhello",
+ },
+ {
+ // Same path but the delimiter is the literal two-character escape
+ // sequence backslash-n-backslash-n; composeOutgoingText must expand
+ // each "\n" into a real newline rune in the output.
+ name: "sign enabled literal backslash-n delimiter expanded",
+ signMsg: true,
+ delimiter: "\\n\\n",
+ content: "hello",
+ sender: "Agent Smith",
+ want: "*Agent Smith*\n\nhello",
+ },
+ {
+ // Signing still translates the body markdown before prefixing the
+ // signature, so both transforms compose in the signed path.
+ name: "sign enabled also translates body markdown",
+ signMsg: true,
+ delimiter: " | ",
+ content: "**bold**",
+ sender: "Bob",
+ want: "*Bob* | *bold*",
+ },
+ {
+ // Empty sender name => no signature; the body alone is returned.
+ name: "sign enabled empty sender name no signature",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "hello",
+ sender: "",
+ want: "hello",
+ },
+ {
+ // Whitespace-only sender name is trimmed to empty => no signature.
+ name: "sign enabled whitespace sender name no signature",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "hello",
+ sender: " \t ",
+ want: "hello",
+ },
+ {
+ // Sign enabled but no body: the guard text != "" prevents emitting a
+ // lone signature with no message underneath.
+ name: "sign enabled empty content no lone signature",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "",
+ sender: "Agent Smith",
+ want: "",
+ },
+ {
+ // A surrounding sender name is trimmed before being wrapped, so the
+ // signature uses the cleaned name, not the padded original.
+ name: "sign enabled sender name trimmed before wrapping",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "hello",
+ sender: " Agent Smith ",
+ want: "*Agent Smith*\n\nhello",
+ },
+ {
+ // Plain text with no markdown delimiters is passed through unchanged
+ // (the markdown translator short-circuits when no * ~ are present).
+ name: "plain text no markdown unchanged",
+ signMsg: false,
+ delimiter: "\n\n",
+ content: "just plain text",
+ sender: "",
+ want: "just plain text",
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ withSignConfig(t, tt.signMsg, tt.delimiter)
+
+ payload := chatwoot.WebhookPayload{
+ Content: tt.content,
+ Sender: chatwoot.Contact{Name: tt.sender},
+ }
+
+ got := composeOutgoingText(payload)
+ if got != tt.want {
+ t.Errorf("composeOutgoingText() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+// TestComposeOutgoingTextDefaultsRestored asserts the config globals are left at
+// their package defaults after the table-driven cases run, guarding against a
+// save/restore leak that would make unrelated package tests flaky.
+func TestComposeOutgoingTextDefaultsRestored(t *testing.T) {
+ if config.ChatwootSignMsg != false {
+ t.Errorf("ChatwootSignMsg leaked: got %v, want false", config.ChatwootSignMsg)
+ }
+ if config.ChatwootSignDelimiter != "\n\n" {
+ t.Errorf("ChatwootSignDelimiter leaked: got %q, want %q", config.ChatwootSignDelimiter, "\n\n")
+ }
+}
+
+func TestIsEchoOfForwardedMessage(t *testing.T) {
+ tests := []struct {
+ name string
+ sourceID string
+ want bool
+ }{
+ {"forwarded message", "WAID:3EB0ABC123", true},
+ {"agent reply, no source_id", "", false},
+ {"unrelated source_id", "12345", false},
+ {"prefix only as substring elsewhere", "X-WAID:3EB0", false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ payload := chatwoot.WebhookPayload{SourceID: tt.sourceID}
+ if got := isEchoOfForwardedMessage(payload); got != tt.want {
+ t.Errorf("isEchoOfForwardedMessage(source_id=%q) = %v, want %v", tt.sourceID, got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootSendFailureContent(t *testing.T) {
+ tests := []struct {
+ name string
+ err error
+ want string
+ }{
+ {
+ name: "with error",
+ err: errors.New("device offline"),
+ want: "Message was not sent to WhatsApp.\n\nError: device offline",
+ },
+ {
+ name: "nil error",
+ err: nil,
+ want: "Message was not sent to WhatsApp.",
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := chatwootSendFailureContent(tt.err); got != tt.want {
+ t.Fatalf("chatwootSendFailureContent() = %q, want %q", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootPayloadDeleted(t *testing.T) {
+ tests := []struct {
+ name string
+ in map[string]any
+ want bool
+ }{
+ {name: "bool true", in: map[string]any{"deleted": true}, want: true},
+ {name: "bool false", in: map[string]any{"deleted": false}, want: false},
+ {name: "string true", in: map[string]any{"deleted": "true"}, want: true},
+ {name: "missing", in: nil, want: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ payload := chatwoot.WebhookPayload{ContentAttributes: tt.in}
+ if got := chatwootPayloadDeleted(payload); got != tt.want {
+ t.Fatalf("chatwootPayloadDeleted() = %v, want %v", got, tt.want)
+ }
+ })
+ }
+}
+
+func TestChatwootWebhookRejectsInvalidSecret(t *testing.T) {
+ withChatwootWebhookSecret(t, "expected-secret")
+
+ app := fiber.New()
+ handler := &ChatwootHandler{}
+ app.Post("/chatwoot/webhook", handler.HandleWebhook)
+
+ req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook", strings.NewReader(`{"event":"message_created"}`))
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("X-Chatwoot-Webhook-Secret", "wrong-secret")
+
+ resp, err := app.Test(req)
+ if err != nil {
+ t.Fatalf("app.Test: %v", err)
+ }
+ if resp.StatusCode != fiber.StatusUnauthorized {
+ t.Fatalf("status = %d, want %d", resp.StatusCode, fiber.StatusUnauthorized)
+ }
+}
+
+func TestResolveChatwootWebhookRoutePrefersConversationLink(t *testing.T) {
+ handler := &ChatwootHandler{
+ ChatStorageRepo: &chatwootRouteTestRepo{
+ link: &domainChatStorage.ChatwootMessageLink{
+ DeviceID: "[email protected]",
+ WhatsAppMessageID: "wa-1",
+ WhatsAppChatJID: "[email protected]",
+ ChatwootConversationID: 202,
+ },
+ },
+ }
+
+ route := handler.resolveChatwootWebhookRoute(chatwoot.WebhookPayload{
+ Conversation: chatwoot.ConversationWebhook{
+ ID: 202,
+ Meta: chatwoot.ConversationMeta{
+ Sender: chatwoot.Contact{
+ PhoneNumber: "+628999999999",
+ CustomAttributes: map[string]any{
+ "gowa_whatsapp_jid": "[email protected]",
+ },
+ },
+ },
+ },
+ })
+
+ if route.DeviceID != "[email protected]" {
+ t.Fatalf("DeviceID = %q, want [email protected]", route.DeviceID)
+ }
+ if route.Destination != "[email protected]" {
+ t.Fatalf("Destination = %q, want linked WhatsApp chat", route.Destination)
+ }
+}
+
+func TestResolveSendDestination(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ wantDest string
+ wantIsGroup bool
+ }{
+ // Plain @s.whatsapp.net JIDs are reduced to the bare phone number.
+ {name: "private jid stripped to phone", in: "[email protected]", wantDest: "628123456789", wantIsGroup: false},
+ // A "+"-prefixed phone is cleaned and passes through with no @ suffix.
+ {name: "plus phone cleaned", in: "+628123456789", wantDest: "628123456789", wantIsGroup: false},
+ // A bare phone number is unchanged.
+ {name: "bare phone unchanged", in: "628123456789", wantDest: "628123456789", wantIsGroup: false},
+ // Groups keep the full @g.us JID and report isGroup=true.
+ {name: "group jid preserved", in: "[email protected]", wantDest: "[email protected]", wantIsGroup: true},
+ // Regression: privacy-masked @lid JIDs must be preserved verbatim so the
+ // send layer's LID resolution can run. Stripping the suffix here misroutes
+ // the reply into @s.whatsapp.net and breaks delivery to @lid contacts.
+ {name: "lid jid preserved verbatim", in: "1234567890123@lid", wantDest: "1234567890123@lid", wantIsGroup: false},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ gotDest, gotIsGroup := resolveSendDestination(tt.in)
+ if gotDest != tt.wantDest || gotIsGroup != tt.wantIsGroup {
+ t.Fatalf("resolveSendDestination(%q) = (%q, %v), want (%q, %v)", tt.in, gotDest, gotIsGroup, tt.wantDest, tt.wantIsGroup)
+ }
+ })
+ }
+}
+
+func TestChatwootLinkChatJID(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {name: "phone gets whatsapp suffix", in: "+628123456789", want: "[email protected]"},
+ {name: "private jid stays jid", in: "[email protected]", want: "[email protected]"},
+ {name: "group jid stays jid", in: "[email protected]", want: "[email protected]"},
+ {name: "lid jid stays jid", in: "abc@lid", want: "abc@lid"},
+ {name: "empty", in: "", want: ""},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ if got := chatwootLinkChatJID(tt.in); got != tt.want {
+ t.Fatalf("chatwootLinkChatJID(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ })
+ }
+}
diff --git a/src/usecase/AGENTS.md b/src/usecase/AGENTS.md
index 9a5ce1e8..54f81526 100644
--- a/src/usecase/AGENTS.md
+++ b/src/usecase/AGENTS.md
@@ -1,6 +1,6 @@
# USECASE
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
diff --git a/src/validations/AGENTS.md b/src/validations/AGENTS.md
index 36ef9e50..c8d81250 100644
--- a/src/validations/AGENTS.md
+++ b/src/validations/AGENTS.md
@@ -1,6 +1,6 @@
# VALIDATIONS
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW
diff --git a/src/views/AGENTS.md b/src/views/AGENTS.md
index f163167b..a2002f21 100644
--- a/src/views/AGENTS.md
+++ b/src/views/AGENTS.md
@@ -1,6 +1,6 @@
# EMBEDDED WEB UI
-Generated: 2026-06-05
+Generated: 2026-06-06
## OVERVIEW