# Recipient Sync from an External App — Design

**Date:** 2026-08-06
**Status:** Design (approved)
**Author:** Wilson Santa Cruz

## Problem

A recipient becomes usable in this app only by messaging the business on WhatsApp
and walking the onboarding question chain (or submitting an onboarding WA Flow).
Both paths end in the same downstream state: identity fields on the
`channel_recipients` row, one `channel_recipient_variables` row per answer, the
`onboarded_user` gate variable, and an `es_recipient_identifiers` row carrying
the external system's guid and login URL.

We already hold those details for people who signed up in a separate app. Making
them re-answer the same questions over WhatsApp is redundant, and until they do,
the journey's `if-condition` gate routes them into onboarding on first contact.

We want to push a person's details in from the other app and have them arrive in
exactly the state native onboarding would have produced.

## Goal & Scope

**In scope:** one authenticated endpoint that upserts a recipient, writes the
onboarding data through the same code native onboarding uses, and records the
external identifiers.

**Out of scope:**

- Bulk/batch requests. One recipient per call. See *Deliberate omissions*.
- Sending any WhatsApp message on sync. The existing `POST /api/v1/workflow`
  already does that and can be called after.
- Dispatching the outbound `user` integration. See *Why sync never pushes*.
- Pull-based sync or any scheduled reconciliation. The source app pushes.

## Existing code this builds on

| Thing | Location |
|---|---|
| Channel-scoped API guard | `config/auth.php:50` (`api-channel`, provider `channels`) |
| Existing routes under that guard | `routes/api.php:73-86` |
| Channel from token | `MessagingAPIController:51` — `$channel = Auth::user()` |
| Native recipient creator | `ChannelService::findOrCreateRecipient()` — `app/Skale/Services/ChannelService.php:184` |
| Native "answers → onboarded" routine | `InteractiveFlowService::bridgeToRecipient()` — `:157` |
| Answer-key → column map | `InteractiveFlowService::RECIPIENT_COLUMN_MAP` — `:26` |
| Variable encryption list | `ChannelRecipientVariables::EncryptedLists` — `:43` |
| External identifier row | `ChannelRecipients::esRecipientIdentifier()` — `:158` |
| How that row is written natively | `ProcessIntegration::callbackUserWebhook()` — `:183-204` |
| Domain → channel registry | `oauth_client_aliases` (`client_id`, `client_alias`, `channel_id`, `domain`) |

## Endpoint

`POST /api/v1/recipients/sync`, added to the existing `auth:api-channel` group in
`routes/api.php`. New controller
`app/Http/Controllers/Api/RecipientSyncController.php`, extending
`BaseApiController` like its siblings.

```json
{
  "mobile":    "639171234567",
  "user_guid": "abc-123",
  "login_url": "https://es.example.com/login/xyz",
  "fields": {
    "name":   "Ana Cruz",
    "email":  "ana@example.com",
    "outlet": "SM North"
  }
}
```

Validation lives in `app/Http/Requests/Api/RecipientSyncRequest.php`:

| Field | Rule | Why |
|---|---|---|
| `mobile` | `required`, `digits_between:8,15` | Matches the `to` rule the WA activation endpoint already uses |
| `user_guid` | `required`, `string`, `max:255` | `es_recipient_identifiers.user_guid` is `varchar(255)` NOT NULL |
| `login_url` | `required`, `url` | See *Why login_url is required* |
| `fields` | `required`, `array`, `min:1` | An empty sync is a caller bug, not a no-op |
| `fields.*` | `required`, scalar (`string`/`numeric`/`boolean`) | An array cannot go on a recipient column; reject rather than guess |

Responses use the existing `ApiResponseTrait` envelope, so the shape matches
every other endpoint in the group. Success is `respondSuccess($message, $data)`:

```json
{ "success": true,
  "message": "Recipient synced.",
  "data": { "id": "1f8c...", "created": true, "onboarded": true } }
```

`201` is not used even when a recipient is created — `respondCreated` would make
the status depend on whether the caller had synced this mobile before, which
turns a retry into a different response code for no benefit. The `created` flag
carries that information instead.

`id` is `ChannelRecipients::getUUIDKey()`. The integer key is in the model's
`$hidden` and must never leave the app.

Guard and validation failures use `respondUnprocessingEntity($message)`, which
returns `422` with `{success: false, message, error_code}`.

### Authentication and channel resolution

The channel is `Auth::user()` — under the `api-channel` guard the authenticated
entity **is** a `Channels` model. There is no `channel_id` in the payload, and a
caller cannot reach another channel's data by editing the body.

Routing the channel off the `login_url` domain was considered and rejected.
`integrations.wa_account_id` resolves to a WA *account*, and `WaAccounts::channels()`
is `hasMany` — so a domain match cannot pick a single channel. More importantly,
`login_url` is caller-supplied; deriving the channel from it would let the caller
choose the target by editing a string, replacing the token's proof with a hint.

### Domain guard

`oauth_client_aliases` maps `domain` to `channel_id` and is already used by
`OAuthController::createUser()` (`:67-76`). Its `domain` column is currently dead
— `OAuthController:62` assigns `$domain = $client_alias->domain;` and never reads
it.

This design revives it as a **guard, not a router**:

> If the authenticated channel has one or more `oauth_client_aliases` rows, and
> `parse_url($login_url, PHP_URL_HOST)` matches none of their `domain` values,
> respond `422` with `The login_url host does not match a domain registered for
> this channel.` and write nothing.

A channel with no alias rows skips the check entirely, so this adds no setup
burden to existing channels. Host comparison is case-insensitive and ignores
port. No unique index is added to `oauth_client_aliases.domain`: this design only
reads the column to compare, never to look a channel up, so duplicates are
harmless here.

## Behaviour

Four steps. Three of them are existing code.

**1. Resolve or create the recipient.**

```php
$this->channelService->setChannel($channel);
$recipient = $this->channelService->findOrCreateRecipient($validated['mobile']);
```

This is the same call the webhook and `MessagingAPIController:69` make.
Consequences come for free: `RecipientWasCreated` fires, `RecipientListener`
increments `channel_chat_stats.num_recipient`, and matching follows the native
STEP 1–3 order (`user_id` → `recipient_mobile` → `username`).

**2. Apply the onboarding fields.**

Steps a–c of `bridgeToRecipient()` move verbatim into a new public method:

```php
ChannelRecipientService::applyOnboardingFields(ChannelRecipients $r, array $fields): void
```

- Every key upserts a `channel_recipient_variables` row —
  `variable_name = key`, `variable_value = value` — written through the model so
  `EncryptedLists` encryption and the `VariableWasCreated` event both fire.
- `RECIPIENT_COLUMN_MAP` mirrors `name`, `email`, and `mobile` onto the
  `channel_recipients` row.
- `onboarded_user` is upserted to `'1'`.

`InteractiveFlowService::bridgeToRecipient()` is then rewritten to call this
method and keep only step d (the integration push). The flow path's behaviour is
unchanged; net line count is roughly flat.

Arbitrary keys matter. A journey template reading `{{outlet}}` renders blank for
a synced person unless the sync writes variables the same way onboarding does —
which is why `fields` is an open bag rather than a fixed schema.

**3. Write the external identifiers.**

```php
$recipient->esRecipientIdentifier()->updateOrCreate(
    ['channel_recipient_id' => $recipient->getKey()],
    ['user_guid' => $validated['user_guid'], 'login_url' => $validated['login_url']],
);
```

`updateOrCreate`, deliberately — not the `if (!$existing)` guard
`callbackUserWebhook:188` uses. A corrected guid from the source must propagate
rather than be silently dropped. `login_url` is encrypted by the model's
`setLoginUrlAttribute()`, which also populates `masked_login_url`.

**4. Stop.** No `ProcessIntegration` dispatch, no message send, no `joined_at`.

### Why sync never pushes the `user` integration

The `user` integration pushes recipient details *out* to the client's backend. If
the app being synced *from* is that backend, sync-in → onboarded → push-out →
back to source is an echo loop. `ProcessIntegration` is
`ShouldBeUniqueUntilProcessing` keyed on the recipient, which dedupes queued jobs
but is not a loop guard.

The push also cannot run cleanly here even if wanted: `ProcessIntegration`
requires a `RecipientChatSessions` and a non-null `WorkflowNodes`
(`initialMonitorData()` dereferences the node), and a synced recipient has
neither.

The data the push exists to obtain — `guid` and `login_url` — is supplied
directly in the payload instead.

### Why `login_url` is required

`{{login_url}}` is a live template variable. `ChannelTemplateService:373-374`
resolves it from `esRecipientIdentifier.login_url` with `?: '-'`, and seeded
journeys embed it in message bodies — `PokkaRoadShowPosmJourneySeeder:107` sends
`{{login_url}}/UVI6cm9hZHNob3c=`. A recipient with no identifier row receives a
WhatsApp message reading `-/UVI6cm9hZHNob3c=`.

Requiring it fails a misconfigured sync at the door instead of in a customer's
inbox. The column is `text` (widened by
`2023_08_09_163051_alter_table_for_pii_encryption`), so encryption cannot
truncate a long URL.

### Why no `recipient_stats.joined_at`

`joined_at` is set by `MessageQueableListener::updateUserJoinedDateIfEmpty()`
(`:132`) on the recipient's first **inbound** message. It means "has replied to
us", which a synced person has not. Leaving it null preserves the
engaged-vs-onboarded distinction.

Synced recipients still appear on `/chat`:
`ChannelRecipientRepository::getListWithLastMsg()` uses LEFT joins, and the
comment at `:536` documents this exact case — "a recipient who finished
onboarding but never sent an inbound message".

## Bundled fixes

Three defects found while tracing the guid, all directly implicated by this work.

**1. `{{guid}}` renders `-` for everyone.** `ChannelTemplateService:378` reads
`esRecipientIdentifier.guid`; the column is `user_guid` and the model has no
`guid` accessor. One-word fix. Without it, requiring `user_guid` on sync buys
nothing at render time.

**2. `ReferralService::getRefererGuidIfHas()` (`:92-98`) null-dereferences.**
`return $r->esRecipientIdentifier->user_guid;` throws when the referrer has no
identifier row. It is called from `getUserCreationAttrs()`, which builds the
payload for *every* integration type — so one referrer without a guid breaks the
referred person's integration push. Add a null-safe operator.

**3. No unique constraint on `es_recipient_identifiers.channel_recipient_id`.**
The column is indexed, not unique, yet `ChannelRecipients::esRecipientIdentifier()`
is a `hasOne` and the only duplicate guard is the app-level check at
`ProcessIntegration:188`. Two concurrent writes produce two rows and `hasOne`
silently picks one. Add a unique index; the `updateOrCreate` in step 3 then has a
real constraint behind it.

The migration must handle pre-existing duplicates: delete all but the
lowest-`id` row per `channel_recipient_id` before adding the index.

## Error handling

| Condition | Response |
|---|---|
| Any validation rule fails | `422` from the FormRequest — Laravel's default `{message, errors}` bag, nothing written |
| `login_url` host matches no registered domain for the channel | `422` via `respondUnprocessingEntity()` — `{success, message, error_code}`, nothing written |
| Missing or invalid bearer token | `401` from the `api-channel` guard |
| Any step throws | Wrap steps 1–3 in a `DB::transaction()` so a partial recipient is never left behind |

The two `422` shapes differ because the FormRequest fires before the controller
runs. This already happens across the existing API — `RegistrationRequest` and
`UserCreationRequest` both emit Laravel's bag while their controllers emit the
trait's envelope — so the sync endpoint matches its neighbours rather than
inventing a third convention.

Steps 1–3 run inside one transaction. `RecipientWasCreated` listeners write to
`channel_chat_stats` within it, so a rollback also unwinds the counter.

## Testing

`tests/Feature/Api/RecipientSyncTest.php`, no live HTTP:

1. Unknown mobile creates a recipient; `created: true`; variables written;
   `onboarded_user` is `1`.
2. Same mobile twice yields one recipient row, `created: false`, and updated
   values.
3. `name` and `email` land on the `channel_recipients` columns *and* as variables.
4. `outlet` lands as a variable only.
5. The `email` variable is stored encrypted (it is in `EncryptedLists`).
6. `Bus::fake()` — no `ProcessIntegration` job is dispatched.
7. An `es_recipient_identifiers` row is written with both fields; a re-sync with
   a changed `user_guid` overwrites it rather than leaving the old value.
8. A channel with a registered alias domain rejects a `login_url` on a different
   host with `422` and writes nothing.
9. A channel with no alias rows accepts any `login_url` host.
10. `recipient_stats.joined_at` stays null.
11. `422` for: missing `user_guid`, missing `login_url`, non-URL `login_url`,
    non-numeric `mobile`, an array inside `fields`.
12. **Channel isolation** — channel B syncing a mobile that already exists under
    channel A creates a second, separate recipient and does not touch A's.

`tests/Unit/ChannelTemplateServiceTest.php`:

13. `{{guid}}` and `{{login_url}}` render real values for a recipient that has an
    identifier row. This pins fix 1.

`tests/Unit/ReferralServiceTest.php`:

14. `getRefererGuidIfHas()` returns null — rather than throwing — when the
    referrer has no identifier row. This pins fix 2.

## Deliberate omissions

| Omitted | Add when |
|---|---|
| Batch endpoint | A backfill proves too slow one request at a time. The service method is already the unit of work, so a batch route is a thin loop over it. |
| Outbound `user` integration push on sync | A third system — not the sync source — needs to hear about synced recipients. It would need a synthetic session and workflow node first. |
| Unique index on `oauth_client_aliases.domain` | The domain is used to look a channel *up*, rather than only to compare against the authenticated one. |
| Rate limiting on the endpoint | A source app misbehaves. The `api` middleware group's default throttle applies until then. |
| Deleting or deactivating a synced recipient | The source app needs removals to propagate. |
| Verifying the mobile is reachable on WhatsApp | Bad numbers become common enough to be worth a pre-check. Today a bad number fails at Meta on first send, as it does for any recipient. |
