# HalaVoice AI Agent for Salla — Technical Architecture

## Overview

**HalaVoice AI Agent for Salla** is a Laravel-based bridge between the Salla e‑commerce platform and the existing HalaVoice AI voice‑agent platform. The Laravel app handles all Salla-specific OAuth, webhook, and embedded-dashboard concerns while delegating telephony, WhatsApp, and AI orchestration to HalaVoice's existing REST API.

## System Context

```
┌─────────────────────────────────────────────────────────────────┐
│                        Salla Platform                           │
│  ┌─────────────┐  ┌──────────────┐  ┌────────────────────────┐ │
│  │  Salla App   │  │  Webhooks    │  │  Embedded SDK (iframe) │ │
│  │  Store       │  │  (events)    │  │  (merchant dashboard)  │ │
│  └──────┬───────┘  └──────┬───────┘  └───────────┬────────────┘ │
└─────────┼─────────────────┼──────────────────────┼──────────────┘
          │ OAuth 2.0       │ POST /webhook        │ iframe embed
          ▼                 ▼                       ▼
┌──────────────────────────────────────────────────────────────────┐
│              Laravel Salla App (this project)                    │
│                                                                  │
│  ┌──────────┐  ┌──────────────┐  ┌───────────────────────────┐  │
│  │OAuth     │  │ Webhook      │  │ Embedded Dashboard         │  │
│  │Controller│  │ Controller   │  │ (Blade/Inertia + SDK)      │  │
│  ├──────────┤  ├──────────────┤  ├───────────────────────────┤  │
│  │Store     │  │ Jobs/Queues  │  │ Overview, Settings, Logs,  │  │
│  │Service   │  │ (webhook     │  │ Reports, Automation Rules, │  │
│  │          │  │  processing) │  │ Voice Scripts, Billing     │  │
│  └────┬─────┘  └──────┬───────┘  └───────────────────────────┘  │
│       │               │                                          │
│  ┌────▼───────────────▼──────────────────────────────────────┐  │
│  │              Service Layer                                 │  │
│  │  ┌─────────────┐  ┌──────────────┐  ┌───────────────────┐ │  │
│  │  │SallaApiClient│  │HalaVoice     │  │ WhatsApp Service  │ │  │
│  │  │(OAuth + API) │  │Client        │  │ (via HalaVoice)   │ │  │
│  │  └─────────────┘  └──────┬───────┘  └───────────────────┘ │  │
│  └──────────────────────────┼────────────────────────────────┘  │
└─────────────────────────────┼────────────────────────────────────┘
                              │ HTTP REST
                              ▼
┌──────────────────────────────────────────────────────────────────┐
│                    HalaVoice Platform                            │
│                                                                  │
│  ┌────────────┐  ┌────────────┐  ┌───────────┐  ┌────────────┐ │
│  │ Twilio     │  │ ElevenLabs │  │ Plivo     │  │ BullMQ     │ │
│  │ Telephony  │  │ AI Agents  │  │ Telephony │  │ Queues     │ │
│  ├────────────┤  ├────────────┤  ├───────────┤  ├────────────┤ │
│  │ WhatsApp   │  │ Campaigns  │  │ Webhooks  │  │ PostgreSQL │ │
│  │ (Twilio)   │  │ & Flows    │  │ Delivery  │  │ (Drizzle)  │ │
│  └────────────┘  └────────────┘  └───────────┘  └────────────┘ │
└──────────────────────────────────────────────────────────────────┘
```

## Integration Points with HalaVoice

The Laravel app calls HalaVoice's **existing REST API** (no changes needed on the HalaVoice side). The key endpoints consumed:

| Endpoint | Method | Purpose |
|---|---|---|
| `/api/outbound/call` | POST | Trigger AI voice call |
| `/api/whatsapp/send` | POST | Send WhatsApp message |
| `/api/calls/:id` | GET | Fetch call result/status |
| `/api/calls/:id/transcript` | GET | Fetch call transcript |
| `/api/calls/:id/recording` | GET | Get recording URL |
| `/api/calls/:id/summary` | GET | Get AI summary |
| `/api/contacts` | POST | Create/update contact |
| `/api/campaigns` | POST | Create campaign |
| `/api/usage` | GET | Get platform usage stats |

## Technology Stack

- **Backend**: Laravel 13.x (PHP 8.3+)
- **OAuth**: `salla/oauth2-merchant` package
- **Frontend**: Blade + Salla Embedded SDK (vanilla JS)
- **Queue**: Laravel Queue (database/redis driver)
- **Database**: MySQL/PostgreSQL (via Laravel Migrations)
- **HTTP Client**: Guzzle (for Salla Merchant API & HalaVoice API)
- **Cache**: Redis (for rate limiting & session)

## Salla App Architecture

### App Type: Embedded + Webhook
The app registers as a Salla Public App using:
- **Easy Mode OAuth** (tokens delivered via `app.store.authorize` webhook)
- **Embedded Pages** (inside Salla Dashboard via iframe + Embedded SDK)
- **Store Event Webhooks** (event-driven automation)
- **App Event Webhooks** (lifecycle: install, uninstall, subscription, settings)

### Required Salla Scopes
See `REQUIRED_SCOPES.md` for full list. Core scopes:
- `orders.read` — read order data for COD confirmation
- `customers.read` — look up customer info
- `products.read` — product catalog for WhatsApp AI
- `carts.read` — abandoned cart recovery
- `settings.read` — store settings
- `webhooks.read_write` — manage webhook subscriptions
- `offline_access` — refresh tokens

## Database Schema

See `database/migrations/` for full schema. 17 tables total:

1. **salla_stores** — merchant store records
2. **salla_tokens** — encrypted OAuth tokens
3. **salla_subscriptions** — billing/subscription tracking
4. **salla_customers** — synced customer data
5. **salla_orders** — synced order data
6. **salla_abandoned_carts** — cart recovery tracking
7. **automation_rules** — merchant-configured rules
8. **call_jobs** — outbound voice call queue
9. **whatsapp_jobs** — outbound WhatsApp queue
10. **conversation_logs** — all communications
11. **call_transcripts** — call transcripts from HalaVoice
12. **ai_summaries** — AI-generated summaries
13. **usage_logs** — API usage tracking
14. **billing_usage** — metered billing counters
15. **webhook_events** — raw webhook payloads
16. **sync_errors** — failed sync operations
17. **app_settings** — merchant configuration

## Key Workflows

### COD Order Confirmation
```
order.created (webhook) → WebhookController
  → ProcessSallaWebhook job (idempotency check)
  → SallaApiClient: fetch order details
  → AutomationRule: check if COD + enabled
  → MakeOutboundCall job (scheduled with delay)
  → HalaVoiceClient: createOutboundCall(phone, script)
  → Poll call result:
    - confirmed → update order notes in Salla
    - cancelled → notify merchant
    - no answer → retry logic
  → SendWhatsAppMessage: confirmation message
  → Log to conversation_logs, usage_logs
```

### Abandoned Cart Recovery
```
abandoned.cart (webhook) → WebhookController
  → ProcessSallaWebhook job
  → Save to salla_abandoned_carts
  → Delay(configurable) → RecoverAbandonedCart job
  → HalaVoiceClient: sendWhatsAppMessage(reminder)
  → If cart value > threshold:
     → MakeOutboundCall job with recovery script
  → Track conversion via order.created webhook matching
```

## Security

- **Token encryption**: All Salla tokens encrypted at rest (Laravel `encrypt()` + APP_KEY)
- **Webhook verification**: HMAC-SHA256 signature verification on every webhook
- **Rate limiting**: Per-merchant rate limiting on API routes
- **Audit logging**: Every state-changing operation logged
- **Data retention**: Configurable retention period for transcripts/recordings
- **AI training opt-out**: Flag to prevent customer data from being used for model training

## Queue Architecture

All async work uses Laravel Queues with these jobs:
- `ProcessSallaWebhook` — all webhooks, idempotent by event_id
- `MakeOutboundCall` — to HalaVoice API with retry
- `SendWhatsAppMessage` — to HalaVoice WhatsApp API
- `RecoverAbandonedCart` — delayed cart recovery
- `SyncOrderToHalaVoice` — push order data for AI context
- `GenerateReport` — periodic report generation
- `CleanupExpiredData` — data retention enforcement
