# Multi-Tenant WhatsApp & Messenger AI Chatbot — Project Plan (Laravel)

## 1. Overview

A SaaS platform where each **tenant** (a business) connects its WhatsApp number (Messenger later), uploads its own **knowledge base**, and an AI bot (OpenAI API) replies to customers using that knowledge.

**Core features**
- Multi-tenancy (each tenant's data fully isolated)
- WhatsApp Cloud API integration (Phase 1), Facebook Messenger (Phase 2)
- OpenAI-powered replies grounded in the tenant's knowledge base
- Tenant dashboard: knowledge base, conversations, usage, block list, limits
- Subscription plans with **manual payment** (admin approves) at first
- Usage tracking: every incoming message, every bot reply, tokens used
- Block list of WhatsApp phone numbers per tenant
- Security limits: per-minute rate limit and daily limit per tenant and per customer number

---

## 2. Tech Stack

| Layer | Choice |
|---|---|
| Framework | Laravel 12+ (PHP 8.3+) |
| Database | MySQL 8 (or PostgreSQL) |
| Cache / Rate limiting / Queues | Redis |
| Queue worker | Laravel Horizon |
| Dashboard UI | Livewire 3 + Tailwind (or Filament 3 for fast admin panels) |
| Auth | Laravel Breeze / Fortify (+ optional 2FA) |
| AI | OpenAI PHP client (`openai-php/laravel`) |
| Knowledge retrieval | OpenAI Vector Stores + `file_search` tool (one vector store per tenant) |
| WhatsApp | Meta WhatsApp Cloud API (Graph API) |
| Messenger (Phase 2) | Meta Messenger Platform (Graph API) |
| File storage | S3 / local disk (for uploaded knowledge files & payment receipts) |
| Monitoring | Laravel Pulse, Telescope (local only), Sentry |

> **Tenancy approach:** single database with a `tenant_id` column on every tenant-owned table + a global Eloquent scope (`BelongsToTenant` trait). Simpler to run and scale than database-per-tenant for this kind of SaaS. (Alternative: `stancl/tenancy` if you later need DB-per-tenant.)

---

## 3. User Roles

| Role | Description |
|---|---|
| **Super Admin** | Platform owner. Manages tenants, plans, approves manual payments, sees global usage. |
| **Tenant Owner** | Owns the tenant account. Manages channels, knowledge, users, subscription. |
| **Tenant Agent** | Tenant staff. Can view conversations, reply manually, manage block list. |

---

## 4. Database Schema

### 4.1 Platform-level tables

**`tenants`**
- `id`, `name`, `slug`, `status` (`active`, `suspended`, `pending`), `timezone`, `locale`, `created_at`, `updated_at`

**`users`**
- `id`, `tenant_id` (nullable for super admin), `name`, `email`, `password`, `role` (`super_admin`, `owner`, `agent`), `two_factor_secret`, timestamps

**`plans`**
- `id`, `name`, `price`, `currency`, `billing_period` (`monthly`, `yearly`)
- `monthly_message_limit` (bot replies per month)
- `max_knowledge_files`, `max_knowledge_size_mb`
- `max_channels`, `max_agents`
- `default_rate_limit_per_minute`, `default_daily_limit`
- `features` (JSON), `is_active`, timestamps

**`subscriptions`**
- `id`, `tenant_id`, `plan_id`, `status` (`pending`, `active`, `expired`, `cancelled`)
- `starts_at`, `ends_at`, `approved_by` (user_id), `approved_at`, timestamps

**`payments`** (manual payments)
- `id`, `tenant_id`, `subscription_id`, `amount`, `currency`
- `method` (`bank_transfer`, `cash`, `instapay`, `vodafone_cash`, `other`)
- `reference_number`, `receipt_path` (uploaded image/PDF)
- `status` (`pending`, `approved`, `rejected`), `admin_note`
- `reviewed_by`, `reviewed_at`, timestamps

### 4.2 Tenant-level tables (all have `tenant_id`)

**`channels`**
- `id`, `tenant_id`, `type` (`whatsapp`, `messenger`)
- `name`, `is_active`
- WhatsApp: `phone_number_id`, `waba_id`, `display_phone_number`
- Messenger: `page_id`
- `access_token` (**encrypted cast**), `app_secret` (**encrypted**), `verify_token`
- timestamps

**`bot_settings`**
- `id`, `tenant_id`
- `bot_name`, `system_prompt` (tone, persona, rules), `language`
- `model` (e.g. from config), `temperature`, `max_output_tokens`
- `fallback_message` (when bot can't answer), `handover_keywords` (JSON, e.g. "agent", "human")
- `business_hours` (JSON), `out_of_hours_message`
- `is_bot_enabled`, timestamps

**`knowledge_sources`**
- `id`, `tenant_id`, `type` (`text`, `faq`, `file`, `url`)
- `title`, `content` (for text/FAQ), `file_path`, `url`
- `openai_file_id`, `status` (`pending`, `processing`, `ready`, `failed`), `error`
- timestamps

**`tenant_vector_stores`**
- `id`, `tenant_id`, `openai_vector_store_id`, timestamps

**`contacts`** (customers who message the tenant)
- `id`, `tenant_id`, `channel_id`, `external_id` (WhatsApp phone / Messenger PSID)
- `name`, `last_message_at`, `is_bot_paused` (agent took over), timestamps
- unique (`tenant_id`, `channel_id`, `external_id`)

**`conversations`**
- `id`, `tenant_id`, `channel_id`, `contact_id`
- `status` (`open`, `bot`, `human`, `closed`), `openai_conversation_id` / `previous_response_id`
- `last_message_at`, timestamps

**`messages`**
- `id`, `tenant_id`, `conversation_id`, `contact_id`, `channel_id`
- `direction` (`inbound`, `outbound`)
- `sender_type` (`customer`, `bot`, `agent`, `system`)
- `type` (`text`, `image`, `audio`, `document`, `template`, …), `body`, `media_url`
- `external_message_id` (WhatsApp `wamid`) — **unique** (for idempotency)
- `status` (`received`, `queued`, `sent`, `delivered`, `read`, `failed`, `blocked`, `rate_limited`)
- `reply_to_message_id` (links bot reply → customer message)
- `prompt_tokens`, `completion_tokens`, `total_tokens`, `ai_latency_ms`
- `error`, timestamps

**`blocked_numbers`**
- `id`, `tenant_id`, `channel_type`, `phone_number` (E.164 normalized, e.g. `+201001234567`)
- `reason`, `blocked_by` (user_id or `system`), `expires_at` (nullable = permanent)
- timestamps; unique (`tenant_id`, `phone_number`)

**`security_settings`**
- `id`, `tenant_id`
- `tenant_rate_limit_per_minute` (all messages the tenant's bot handles)
- `tenant_daily_limit`
- `contact_rate_limit_per_minute` (per customer phone number)
- `contact_daily_limit`
- `max_message_length` (ignore/trim very long inputs)
- `auto_block_enabled`, `auto_block_threshold` (e.g. exceeds per-minute limit X times → auto block), `auto_block_duration_minutes`
- `rate_limit_message` (optional reply when limited, or stay silent)
- timestamps

> Plan defaults fill `security_settings` on tenant creation; tenant can only set values **≤ plan maximum**.

**`usage_daily`** (aggregated for fast dashboards)
- `id`, `tenant_id`, `date`
- `inbound_count`, `bot_reply_count`, `agent_reply_count`, `failed_count`
- `blocked_count`, `rate_limited_count`
- `prompt_tokens`, `completion_tokens`, `estimated_cost`
- unique (`tenant_id`, `date`)

**`audit_logs`**
- `id`, `tenant_id`, `user_id`, `action`, `subject_type`, `subject_id`, `meta` (JSON), `ip`, timestamps

---

## 5. Message Flow (WhatsApp)

```
Customer ──► WhatsApp ──► Meta Webhook ──► POST /webhooks/whatsapp
                                              │
                         1. Verify X-Hub-Signature-256 (app secret)
                         2. Find channel by phone_number_id → tenant
                         3. Return 200 immediately
                         4. Dispatch ProcessInboundMessage job (queue)
                                              │
                      ┌───────────────────────┴───────────────────────┐
                      │            ProcessInboundMessage job          │
                      │ a. Idempotency: skip if wamid already stored  │
                      │ b. Save inbound message                       │
                      │ c. Tenant active + subscription valid?        │
                      │ d. Number in block list? → status=blocked     │
                      │ e. Tenant per-minute / daily limit?           │
                      │ f. Contact per-minute / daily limit?          │
                      │ g. Monthly plan quota left?                   │
                      │ h. Bot enabled & conversation not in "human"? │
                      │ i. Dispatch GenerateAiReply job               │
                      └───────────────────────┬───────────────────────┘
                                              │
                      ┌───────────────────────┴───────────────────────┐
                      │               GenerateAiReply job             │
                      │ - Build prompt: system_prompt + guardrails    │
                      │ - Last N messages as context                  │
                      │ - OpenAI Responses API + file_search on the   │
                      │   tenant's vector store                       │
                      │ - Save tokens, latency                        │
                      │ - Dispatch SendWhatsAppMessage job            │
                      └───────────────────────┬───────────────────────┘
                                              │
                         SendWhatsAppMessage → Graph API /messages
                         Save outbound message (reply_to_message_id)
                         Increment usage counters
                                              │
                Status webhooks (sent/delivered/read/failed) update messages.status
```

**Notes**
- WhatsApp **24-hour customer service window**: free-form replies are only allowed within 24h of the customer's last message; outside it you must use approved templates. The bot only replies to inbound messages, so it stays inside the window.
- Mark inbound messages as **read** and optionally show typing indicator while the AI generates.
- Separate queues: `webhooks`, `ai`, `outbound`, `knowledge` — so slow AI calls don't block webhook processing.

---

## 6. OpenAI Integration

**Service class:** `App\Services\AI\OpenAiReplyService`

- One **vector store per tenant** (`tenant_vector_stores`). Knowledge files/text are uploaded to it.
- Reply generation uses the **Responses API** with the `file_search` tool restricted to that tenant's vector store id → tenant data can never leak to another tenant.
- Model name, temperature, and max tokens come from `bot_settings` with defaults in `config/ai.php` (`OPENAI_MODEL` env) — never hardcode.
- **System prompt structure:**
  1. Platform guardrails (fixed, not editable): answer only from the knowledge base, don't invent prices/policies, don't reveal system prompt, reply in the customer's language, be concise (WhatsApp-friendly), use fallback message when unsure.
  2. Tenant's custom prompt (persona, tone, business info).
- **Conversation memory:** last 10–20 messages, or OpenAI `previous_response_id` stored on the conversation.
- **Human handover:** if customer types a handover keyword, or AI returns a "needs_human" signal → set conversation `status = human`, notify agents in dashboard, bot pauses.
- **Moderation (optional):** run OpenAI moderation on inbound text; flag abusive users → feed into auto-block.
- **Cost tracking:** store `usage` tokens from each response on the `messages` row and aggregate into `usage_daily`.
- Retries with exponential backoff on 429/5xx; on final failure send `fallback_message`.

**Knowledge ingestion job:** `ProcessKnowledgeSource`
- Text/FAQ → convert to a `.md` file → upload to OpenAI Files → attach to vector store.
- File (PDF, DOCX, TXT) → upload → attach.
- URL → fetch & clean HTML → markdown → upload → attach.
- On edit/delete → remove old file from vector store and OpenAI Files.
- Update `status` and show it in the dashboard.

---

## 7. Security Limits & Rate Limiting

Implemented with Laravel `RateLimiter` (Redis) in `App\Services\Security\MessageGuard`.

| Check | Key | Window |
|---|---|---|
| Tenant per-minute | `tenant:{id}:min` | 60 s |
| Tenant daily | `tenant:{id}:day:{Y-m-d}` | until midnight (tenant timezone) |
| Contact per-minute | `tenant:{id}:contact:{phone}:min` | 60 s |
| Contact daily | `tenant:{id}:contact:{phone}:day:{Y-m-d}` | until midnight |
| Monthly plan quota | `usage_daily` sum for current period | subscription period |

**Behavior when a limit is hit**
- Message is still **saved** (status `rate_limited`) so the tenant sees it.
- Bot does **not** call OpenAI (protects cost).
- Optionally send `rate_limit_message` **once** per window (not on every message).
- Increment `rate_limited_count` in `usage_daily`.
- If `auto_block_enabled` and a contact exceeds the per-minute limit `auto_block_threshold` times → add to `blocked_numbers` with `expires_at`.

**Block list behavior**
- Checked **before** any other processing (cheapest check; cache the list in Redis per tenant, bust on change).
- Blocked messages saved with status `blocked` (or dropped — configurable), no reply, no AI cost.
- Phone numbers normalized to E.164 using `giggsey/libphonenumber-for-php`.
- Dashboard: add/remove, reason, temporary vs permanent, import CSV, "Block" button directly from a conversation.

**Other security**
- Verify Meta webhook signature (`X-Hub-Signature-256`) on every request.
- Webhook verify token per channel.
- Encrypt tokens/secrets with Laravel `encrypted` casts.
- Global `tenant_id` scope + Policies on every model; tests that tenant A can't read tenant B.
- Laravel rate limiting on dashboard login & API routes; 2FA for owners and super admin.
- Max inbound message length; strip prompt-injection attempts are handled by guardrail prompt + never giving the model tools beyond `file_search`.
- Audit log for sensitive actions (token changes, block list, limits, payments).

---

## 8. Subscriptions & Manual Payment

**Flow (Phase 1 — manual)**
1. Tenant registers → status `pending`, optionally a free **trial** plan (e.g. 7 days, 100 replies).
2. Tenant chooses a plan → sees payment instructions (bank account, InstaPay, Vodafone Cash, …).
3. Tenant uploads receipt + reference number → `payments.status = pending`.
4. Super admin gets notification → reviews → **Approve** or **Reject** (with note).
5. On approve: create/extend `subscription` (`starts_at`, `ends_at`), tenant `active`, apply plan limits to `security_settings`.
6. Scheduled command `subscriptions:check-expiry` (daily):
   - Reminder emails 7, 3, 1 days before expiry.
   - On expiry → status `expired`, bot stops replying (optional grace period, e.g. 3 days).

**Enforcement:** `EnsureActiveSubscription` check inside `MessageGuard` (no active subscription → no AI reply) + dashboard banner.

**Later (Phase 4):** online gateway (Paymob / Stripe / Fawry) using the same `payments` table with `method = gateway`.

---

## 9. Tenant Dashboard

| Page | Contents |
|---|---|
| **Overview** | Today / this month: inbound messages, bot replies, agent replies, failed, blocked, rate-limited, tokens & estimated cost, quota used (%), chart last 30 days |
| **Conversations (Inbox)** | List of conversations, search by phone/name, filter by status; chat view; agent can reply manually, take over / give back to bot, block number |
| **Knowledge Base** | Add text/FAQ, upload files, add URLs; status per item (processing/ready/failed); edit/delete; **"Test bot"** playground to ask questions before going live |
| **Bot Settings** | Bot name, persona/system prompt, language, fallback message, handover keywords, business hours, enable/disable bot |
| **Channels** | Connect WhatsApp (phone number id, WABA id, access token), webhook URL + verify token to copy, connection test; Messenger (Phase 2) |
| **Block List** | Table of blocked numbers, add/remove, reason, expiry, CSV import/export |
| **Security & Limits** | Per-minute & daily limits (tenant + per contact), auto-block settings, max message length, rate-limit reply text — capped by plan |
| **Usage & Reports** | Daily table: messages received, replied, failed, blocked, limited, tokens; export CSV |
| **Subscription** | Current plan, expiry date, usage vs quota, upgrade, upload payment receipt, payment history |
| **Team** | Invite agents, roles |

## 10. Super Admin Panel

- Tenants list: status, plan, expiry, usage; suspend / activate; impersonate (with audit log)
- Plans CRUD
- **Payments review queue** (approve / reject with receipt preview)
- Global usage & OpenAI cost per tenant
- Failed jobs / webhook errors overview
- Global block list (optional, numbers blocked across all tenants)

---

## 11. Project Structure (suggested)

```
app/
├── Models/                      Tenant, User, Plan, Subscription, Payment, Channel,
│                                BotSetting, KnowledgeSource, Contact, Conversation,
│                                Message, BlockedNumber, SecuritySetting, UsageDaily
├── Models/Concerns/BelongsToTenant.php   (global scope + auto-fill tenant_id)
├── Http/
│   ├── Controllers/Webhooks/WhatsAppWebhookController.php
│   ├── Controllers/Webhooks/MessengerWebhookController.php   (Phase 2)
│   └── Middleware/VerifyMetaSignature.php, SetCurrentTenant.php
├── Jobs/
│   ├── ProcessInboundMessage.php
│   ├── GenerateAiReply.php
│   ├── SendChannelMessage.php
│   ├── ProcessKnowledgeSource.php
│   └── UpdateMessageStatus.php
├── Services/
│   ├── Channels/ChannelDriver.php (interface: send(), parseWebhook(), markRead())
│   ├── Channels/WhatsAppDriver.php
│   ├── Channels/MessengerDriver.php           (Phase 2)
│   ├── AI/OpenAiReplyService.php
│   ├── AI/KnowledgeService.php
│   ├── Security/MessageGuard.php              (block list + limits + quota)
│   ├── Usage/UsageRecorder.php
│   └── Billing/SubscriptionService.php
├── Livewire/ (or Filament resources)  Tenant dashboard + Admin panel
├── Policies/
└── Console/Commands/  CheckSubscriptionExpiry, CleanupExpiredBlocks, AggregateUsage
```

> The `ChannelDriver` interface is the key to adding Messenger (and later Instagram/Telegram) without touching the core flow.

---

## 12. Implementation Phases

### Phase 0 — Setup (Week 1)
- [x] `laravel new chatbot` (Laravel 12, PHP 8.2) — **DONE**
- [x] Database: MySQL 8 (`chatbot` DB via DBngin, utf8mb4) — **DONE**
- [x] Local queue/cache: `database` driver (Redis not installed locally) — **DONE**
- [ ] Production: Redis + Horizon
- [x] Auth (Breeze Livewire/Volt) + roles (`super_admin`, `owner`, `agent`, `role:` middleware) — **DONE**
- [ ] 2FA for owners & super admin
- [x] Tenancy: `tenants` table, `BelongsToTenant` trait, `TenantContext`, `SetCurrentTenant` middleware, sign-up creates tenant — **DONE**
- [x] Base dashboard layout (Livewire + Tailwind sidebar, admin panel shell) — **DONE**
- [x] UI refresh: brand theme (green + ink, Plus Jakarta Sans / IBM Plex Sans Arabic), icon sidebar, split-screen login/register, tenant Overview with stats + setup checklist — **DONE**
- [x] Landing page at `/` (hero + WhatsApp mockup, features, how it works, pricing from `config/landing.php`, FAQ, CTA) — **DONE**
- [x] Pest test setup + tenant isolation tests — **DONE**
- [x] Tenant subdomains: `{subdomain}.chatbot.test` dashboard per tenant, landing/sign-up/admin on the central domain, users kept on their own subdomain, reserved names, separate login per host (`SESSION_DOMAIN=null`) — **DONE**
- [x] Seeder creates only the super admin (tenants are added from the admin panel or sign-up) — **DONE**

### Phase 1 — WhatsApp MVP (Weeks 2–4)
- [ ] Meta developer app, WhatsApp Cloud API test number (you do this in Meta for Developers)
- [x] `channels` dashboard page (add / edit / enable-disable / test connection, webhook URL + verify token to copy) — **DONE**
- [x] Webhook verification endpoint (GET) and receiver (POST) `/webhooks/whatsapp` — **DONE**
- [x] Signature verification (`X-Hub-Signature-256`), idempotency by `wamid` — **DONE**
- [x] Contacts, conversations, messages storage — **DONE**
- [x] `WhatsAppDriver`: send text, mark as read, status webhooks (no going backwards) — **DONE**
- [x] OpenAI integration: vector store per tenant, `ProcessKnowledgeSource` ingestion job — **DONE**
- [x] Knowledge Base page (text, Q&A, website URL, file upload; edit / retry / delete; live status) + Test Bot playground — **DONE**
- [x] Bot Settings page (enable, name, persona prompt, language, fallback, handover keywords, model, temperature, memory) — **DONE**
- [ ] Business hours / out-of-hours message (moved to Phase 5)
- [x] `GenerateAiReply` with guardrails, history, fallback, handover marker, burst debounce — **DONE**
- [x] Human handover (keywords + AI marker) — **DONE**
- [x] Conversations inbox + manual agent reply + take over / give back to bot / close, 24h window warning — **DONE**
- [x] Feature tests: webhook flow, AI reply, handover, idempotency, status updates, dashboard pages — **DONE**

### Phase 2 — Security, Limits & Block List (Week 5)
- [ ] `security_settings` + Security & Limits page
- [ ] `MessageGuard`: block list, tenant/contact per-minute & daily limits
- [ ] Block list page + block from conversation + CSV import
- [ ] Auto-block on abuse + `CleanupExpiredBlocks` command
- [ ] Audit logs

### Phase 3 — Usage Tracking & Subscriptions (Week 6–7)
- [x] Token & message tracking on every message; `usage_daily` daily counters (inbound, bot replies, test-chat replies, agent replies, failed, rate-limited, tokens) — **DONE**
- [x] "Test your bot" replies count toward the plan's monthly AI replies (and stop at the limit) — **DONE**
- [ ] Overview dashboard + Usage reports + CSV export
- [x] Plans CRUD (Admin → Plans: price, currency, monthly/yearly, limits, extra features, featured, default for sign-ups, hide/show) — **DONE**
- [x] Plan per tenant (choose on Add tenant, change from the tenants list, filter by plan; sign-ups get the default plan) — **DONE**
- [x] Plan limits enforced: WhatsApp numbers, knowledge items, monthly AI replies (bot stops, message marked `rate_limited`), no plan = no replies; usage shown on tenant Overview — **DONE**
- [ ] Team members limit (`max_agents`) — enforce when the Team page is built
- [x] Landing page pricing loaded from active plans — **DONE**
- [ ] Manual payment flow: receipt upload → admin approve/reject
- [x] Plan period per tenant (start + renew date, monthly/yearly), admin **Renew** button, renew date in tenants list, expired plan stops the bot, "Your plan" card with renew date & usage — **DONE**
- [ ] Subscription expiry reminder emails (7/3/1 days) + grace period
- [x] Super Admin overview (tenants, active numbers, messages, tokens this month) — **DONE**
- [x] Super Admin **Tenants** page: list / search / filter, add tenant + owner, suspend / activate, delete with all data (type slug to confirm) — **DONE**
- [x] Super Admin tenant details page (stats, plan & usage, users, WhatsApp numbers, change a user's password with logout everywhere); tenants table with sortable columns, rows per page, eager loading & pagination — **DONE**
- [ ] Super Admin: payments review, global usage per tenant

### Phase 4 — Messenger (Week 8–9)
- [ ] `MessengerDriver` implementing `ChannelDriver`
- [ ] Facebook Page connect (page access token), webhook, PSID contacts
- [ ] Block list & limits by PSID for Messenger

### Phase 5 — Enhancements (later)
- [ ] Online payment gateway (Paymob / Stripe)
- [ ] Embedded Signup for WhatsApp (tenant connects number in one click)
- [ ] Voice notes → transcription; image understanding
- [ ] WhatsApp template messages / broadcasts
- [x] Multi-language dashboard (Arabic RTL + English): tenant dashboard, admin panel and auth pages, Cairo font, per-user language switcher (translations in `lang/`; landing page still English) — **DONE**
- [ ] Analytics: top questions, unanswered questions → suggest knowledge to add
- [ ] Instagram DM, Telegram, website chat widget

---

## 13. Testing Checklist

- Tenant isolation: tenant A cannot access tenant B's knowledge, messages, contacts (feature tests + policies)
- Webhook: invalid signature rejected, duplicate `wamid` processed once
- Block list: blocked number → no AI call, no reply, saved as `blocked`
- Rate limits: per-minute and daily (tenant + contact) cut off correctly and reset
- Plan quota: no reply after quota reached
- Expired subscription: bot stops replying
- Human handover: bot pauses when agent takes over
- OpenAI failure: fallback message sent, error logged
- Fake OpenAI and Graph API with `Http::fake()` in tests

---

## 14. Environment Variables

```env
OPENAI_API_KEY=
OPENAI_MODEL=            # default model for replies
OPENAI_REQUEST_TIMEOUT=30

META_APP_ID=
META_APP_SECRET=
META_GRAPH_VERSION=      # e.g. current Graph API version
WHATSAPP_WEBHOOK_VERIFY_TOKEN=

QUEUE_CONNECTION=redis
CACHE_STORE=redis
```

---

## 15. Running Locally

```bash
composer install && npm install && npm run build
php artisan migrate:fresh --seed     # admin@example.com / password (super admin, on http://chatbot.test/admin)
composer dev                          # server + queue worker (all queues) + logs + vite
# or, with Herd serving http://chatbot.test, just run the worker:
php artisan queue:work --queue=webhooks,ai,outbound,knowledge,default
php artisan test
```

- Set `OPENAI_API_KEY` (and optionally `OPENAI_MODEL`) in `.env`.
- Tenants open their dashboard at `http://{subdomain}.chatbot.test` (Herd serves subdomains automatically).
  In production set `CENTRAL_DOMAIN=yourdomain.com`, keep `SESSION_DOMAIN=null`, and add a wildcard DNS record + SSL for `*.yourdomain.com`.
- To receive WhatsApp webhooks locally, expose the site with `herd share` (or ngrok) and use
  `https://<public-url>/webhooks/whatsapp` as the Callback URL in Meta, with the verify token shown on the Channels page.
- Implementation notes: the vector store id is stored on `bot_settings.openai_vector_store_id` (instead of a separate `tenant_vector_stores` table). Queues: `webhooks`, `ai`, `outbound`, `knowledge`.

---

## 16. Deployment

- Laravel Forge / Ploi on a VPS, or Laravel Cloud
- HTTPS required (Meta webhooks)
- Supervisor running Horizon; scheduler cron (`schedule:run`)
- Daily DB backups; log retention policy for messages (e.g. configurable per plan)
