# User Flow: Sign Up → Connect WhatsApp → Agents Handle Messages

This document describes how **a person** (your client) signs up in your system, **connects their WhatsApp number**, and how **your solution** (agents handling their messages for products, leads, etc.) works end to end.

---

## 1. Your system in one sentence

**You provide a platform where different people (businesses) can connect their WhatsApp number; messages sent to that number are received by your system and handled by agents (in a shared inbox) for sales, leads, support, etc.**

---

## 2. High-level flow

```
[Person] → Sign up → Create/join Business → Connect WhatsApp (their number)
                                                      ↓
[Their customer] sends WhatsApp to that number → Meta → Your webhook → Your DB (per business)
                                                      ↓
[Your agent] sees conversation in Inbox → Replies (products, leads, etc.) → Sent via Meta to customer
```

---

## 3. Step-by-step: how a person uses your system

### Step 1: Sign up (register)

- **Who:** A new person (e.g. shop owner, agency) who wants to use your solution.
- **Where:** Your app’s **Register** page.
- **What happens:**
  - They enter email, password, name, etc.
  - Your backend creates a **User** (`users` table).
  - They are logged in and (optionally) redirected to onboarding or dashboard.

**In your code:** Auth (register) → `users` row. No business or WhatsApp yet.

---

### Step 2: Create or join a business (tenant)

- **Who:** The same user (or an admin inviting them).
- **What happens:**
  - Either they **create a business** (e.g. “My Shop”) → backend creates **Business profile** (`business_profiles`) with `owner_id` = this user.
  - Or they **join an existing business** (invite/link) → they get access to that business (e.g. via team_members or business_id).
  - From now on, all data (contacts, conversations, inbox) is **scoped by this business**.

**In your code:** Business creation/linking → `business_profiles`; user is owner or member of that business.

---

### Step 3: Connect WhatsApp to the business

- **Who:** The user (or admin) for that business.
- **Goal:** Link **their WhatsApp Business number** to your platform so that messages sent to that number are received by your system and shown in the Inbox for that business.

**Option A – Embedded Signup (recommended for “everyone connects their number”)**

1. In your app, the user opens a “Connect WhatsApp” or “Add channel” screen.
2. You embed **Meta’s Embedded Signup** flow (iframe or redirect). They log in with Facebook/Meta and register or select their WhatsApp Business number.
3. Meta returns to your app with **WABA ID**, **Phone Number ID**, and **access token** (and possibly system user).
4. Your backend:
   - Creates or updates an **Integration** for this business: `integration_type: "whatsapp"`, `business_id` = this business.
   - Stores **API keys** for that integration: `phone_number_id`, `access_token` (in `api_keys`).
5. From now on, **incoming messages** to that number are sent by Meta to **your one webhook URL**. Your backend uses `metadata.phone_number_id` in the payload to find this business and stores the message under that business’s conversations.

**Option B – Manual / admin setup (simpler, fewer users)**

1. Admin or the user goes to **Settings** or **Integrations** in your app.
2. They paste **Phone Number ID** and **access token** (from Meta Developer Dashboard / WhatsApp Manager for their number).
3. Your backend creates `integrations` + `api_keys` for that business with those values.
4. In Meta’s App Dashboard, the **webhook URL** is already set to your platform’s single URL; no per-user URL needed.

**Result:** This business now has **one (or more) WhatsApp number** linked. All messages to that number hit your webhook and are stored under this business.

---

### Step 4: How messages are received (customer → your system)

1. **Their customer** sends a WhatsApp message to **the business’s connected number** (e.g. a product question, lead inquiry).
2. **Meta** receives it and sends a **webhook POST** to your app’s **single webhook URL** (e.g. `https://api.yours.com/api/v1/webhooks/whatsapp`).
3. **Your backend:**
   - Reads `metadata.phone_number_id` from the payload.
   - Looks up which **business** has that `phone_number_id` (via `api_keys` → `integrations` → `business_id`).
   - Finds or creates **Contact** (customer’s phone) and **Conversation** for that business.
   - Saves the **Message** and emits a real-time event (e.g. Socket.io) for that business.
4. **Agents** (users who belong to that business) see the new message in the **Inbox** (filtered by their business). They can reply, tag as lead, log as sale, etc.

So: **one webhook URL for the whole app**; you **route by `phone_number_id`** to the correct business. No need for a different URL per person.

---

### Step 5: How agents handle messages (products, leads, etc.)

1. **Agent** (or the business owner) opens **Inbox** and selects a conversation (customer thread).
2. They see the history and reply. Your frontend calls **send message** API with `businessId`, `to` (customer phone), `messageText`.
3. **Your backend** uses that business’s **integration** (WhatsApp) and its **access_token** + **phone_number_id** to call **Meta’s API** and send the message.
4. The **customer** receives the reply on WhatsApp. You can add automation (keywords, AI, templates) later; the base flow is: agent replies from Inbox → your backend → Meta → customer.

For **products, leads, etc.:** agents use the same Inbox and (optionally) **Contacts** (lead status, tags), **Leads** module, and **Dashboard**; all are already scoped by `business_id`, so each business only sees their own data.

---

## 4. Flow diagram (simplified)

```
┌─────────────────────────────────────────────────────────────────────────────┐
│  PERSON (your client)                                                        │
└─────────────────────────────────────────────────────────────────────────────┘
   │
   │ 1. Sign up (Register)
   ▼
┌─────────────────┐     2. Create/join Business      ┌──────────────────────┐
│  User account   │ ───────────────────────────────► │  Business (tenant)    │
└─────────────────┘                                  └──────────────────────┘
                                                               │
                                                               │ 3. Connect WhatsApp
                                                               │    (Embedded Signup or manual)
                                                               ▼
                                                     ┌──────────────────────┐
                                                     │  Integration         │
                                                     │  + API keys          │
                                                     │  (phone_number_id,   │
                                                     │   access_token)      │
                                                     └──────────────────────┘

┌─────────────────────────────────────────────────────────────────────────────┐
│  THEIR CUSTOMER                                                               │
└─────────────────────────────────────────────────────────────────────────────┘
   │
   │ Sends WhatsApp to business’s number
   ▼
   Meta  ──────►  Your webhook (one URL)  ──────►  Look up business by phone_number_id
                                                               │
                                                               ▼
                                                     Save: Contact, Conversation, Message
                                                               │
                                                               ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│  YOUR AGENT (or their team)                                                  │
└─────────────────────────────────────────────────────────────────────────────┘
   │
   │ Sees conversation in Inbox (per business)
   │ Replies / marks lead / etc.
   ▼
   Your backend  ──────►  Meta API (send)  ──────►  Customer receives reply on WhatsApp
```

---

## 5. What you need to implement (if not already)

| Step | What you have | What to add / clarify |
|------|----------------|------------------------|
| Sign up | Register, Login, User | Optional: onboarding step “Create your business” after first login. |
| Business | business_profiles, owner_id | Ensure every user has (or joins) a business before using Inbox. |
| Connect WhatsApp | integrations + api_keys, webhook by phone_number_id | **Embedded Signup** UI + backend: exchange Meta token, get WABA/Phone Number ID, create integration + api_keys for that business. Or keep manual “paste credentials” for now. |
| Incoming messages | Webhook POST, extractBusinessId, save message | Already aligned with “one URL, route by phone_number_id”. |
| Agent replies | Inbox, send message API, use business’s token | Already in place; ensure UI always sends correct businessId. |

---

## 6. Short answers to “how will they use it?” and “how will they connect WhatsApp?”

- **How will a person use it?**  
  They sign up → create or join a business → connect their WhatsApp number (Embedded Signup or manual) → then they (or their agents) use **Inbox** to handle all messages to that number (products, leads, support). They can use **Contacts**, **Leads**, **Dashboard** for the same business.

- **How will they connect WhatsApp?**  
  Either (A) **Embedded Signup**: in your app they click “Connect WhatsApp”, complete Meta’s flow, and your backend saves the returned Phone Number ID and token for their business; or (B) **Manual**: they (or admin) paste Phone Number ID and token from Meta into your app, and you save them in `integrations` + `api_keys` for that business. In both cases, **one webhook URL** for your app is enough; you route by `phone_number_id` to the right business so that “our agent will handle their messages” works per business.

---

*For multi-tenant and “one URL vs full URL per user”, see **WHATSAPP_MULTI_USER_RESEARCH.md**.*
