# MKT WhatsApp Service / Dịch Vụ MKT WhatsApp

> **EN**: WhatsApp Business API Marketing Service with Chatbot Automation, AI-Powered Messaging, and Customer Management  
> **VI**: Dịch vụ Marketing WhatsApp Business API với Chatbot Tự Động, Nhắn Tin AI, và Quản Lý Khách Hàng

[![.NET Version](https://img.shields.io/badge/.NET-8.0-512BD4)](https://dotnet.microsoft.com/)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

## Features / Tính Năng

### 1. 🤖 CHATBOT Automation Messenger

**EN**: Flow-based automation with business rules and triggers
- Visual automation flow builder with steps and conditions
- Keyword triggers and event-based activation
- Quick replies and interactive buttons
- Multi-step conversation flows
- Conditional branching logic
- A/B testing for flows

**VI**: Tự động hóa dựa trên flow với business rules và triggers
- Trình tạo flow tự động trực quan với các bước và điều kiện
- Triggers theo từ khóa và kích hoạt theo sự kiện
- Quick replies và nút tương tác
- Flows hội thoại nhiều bước
- Logic phân nhánh có điều kiện
- A/B testing cho các flows

### 2. 🧠 CHATBOT AI Messenger

**EN**: Intelligent chatbot powered by LLM (OpenAI GPT-4)
- Natural language understanding and generation
- Context-aware conversations with memory
- Customizable AI personality and tone
- Knowledge base integration
- Multi-turn dialogue support
- Fallback to human agent
- Token usage tracking and cost optimization

**VI**: Chatbot thông minh được hỗ trợ bởi LLM (OpenAI GPT-4)
- Hiểu và sinh ngôn ngữ tự nhiên
- Hội thoại theo ngữ cảnh với bộ nhớ
- Tùy chỉnh tính cách và giọng điệu AI
- Tích hợp knowledge base
- Hỗ trợ đối thoại nhiều lượt
- Chuyển giao cho nhân viên
- Theo dõi token usage và tối ưu chi phí

### 3. 👥 Quản Lý Khách Hàng / Customer Management

**EN**: Comprehensive customer relationship management
- Customer profiles with WhatsApp ID
- Conversation history tracking
- Custom fields and tags
- Opt-in consent management (GDPR compliant)
- Customer segmentation
- Export customer data
- Integration with CRM systems

**VI**: Quản lý quan hệ khách hàng toàn diện
- Hồ sơ khách hàng với WhatsApp ID
- Theo dõi lịch sử hội thoại
- Custom fields và tags
- Quản lý đồng ý nhận tin (tuân thủ GDPR)
- Phân khúc khách hàng
- Xuất dữ liệu khách hàng
- Tích hợp với hệ thống CRM

## Quick Start / Bắt Đầu Nhanh

### Prerequisites / Yêu Cầu

- .NET 8.0 SDK
- PostgreSQL 15+ (hoặc Neon serverless)
- Redis 7+
- RabbitMQ 3.12+
- Docker & Docker Compose (cho local development)
- **Meta Business Account** với WhatsApp Business API access
- **WhatsApp Business Phone Number** (verified)
- **OpenAI API Key** (cho AI Chatbot)

### Configuration / Cấu Hình

```bash
# EN: Copy environment template / VI: Sao chép template môi trường
cp .env.example .env

# EN: Update configuration / VI: Cập nhật cấu hình
# - DATABASE_URL (PostgreSQL connection string)
# - REDIS_URL
# - RABBITMQ_URL
# - WHATSAPP_PHONE_NUMBER_ID
# - WHATSAPP_ACCESS_TOKEN
# - WHATSAPP_WEBHOOK_VERIFY_TOKEN
# - WHATSAPP_APP_SECRET (for signature verification)
# - OPENAI_API_KEY (AI chatbot)
```

### Local Development / Phát Triển Local

```bash
# EN: Restore dependencies / VI: Khôi phục dependencies
dotnet restore

# EN: Apply migrations / VI: Áp dụng migrations
dotnet ef database update --project src/MktWhatsAppService.Infrastructure

# EN: Run service / VI: Chạy service
dotnet run --project src/MktWhatsAppService.API

# Service available at http://localhost:5000
# Swagger UI: http://localhost:5000/swagger
```

### Docker Deployment / Triển Khai Docker

```bash
# EN: Build and run with Docker Compose / VI: Build và chạy với Docker Compose
cd deployments/local
docker-compose up -d mkt-whatsapp-service-net

# EN: View logs / VI: Xem logs
docker-compose logs -f mkt-whatsapp-service-net

# EN: Access via Traefik / VI: Truy cập qua Traefik
# http://localhost/api/v1/whatsapp
```

## Architecture / Kiến Trúc

```mermaid
graph TB
    subgraph "External / Bên Ngoài"
        WA["WhatsApp Cloud API<br/>(Meta)"]
        LLM["OpenAI GPT-4"]
        Customer["Customer<br/>(WhatsApp User)"]
    end
    
    subgraph "mkt-whatsapp-service-net"
        WH["Webhooks Controller"]
        API["REST API Controllers"]
        APP["Application Layer<br/>CQRS"]
        DOM["Domain Layer<br/>Aggregates"]
        INFRA["Infrastructure Layer"]
        BG["Background Jobs"]
    end
    
    subgraph "Data Stores"
        PG[("PostgreSQL")]
        RD[("Redis Cache")]
        RMQ["RabbitMQ"]
    end
    
    Customer -->|"Send Message"| WA
    WA -->|"Webhook Event"| WH
    WH -->|"Process Command"| APP
    API -->|"Commands/Queries"| APP
    APP -->|"Business Logic"| DOM
    APP -->|"Persistence"| INFRA
    INFRA -->|"EF Core"| PG
    INFRA -->|"Caching"| RD
    INFRA -->|"Events"| RMQ
    APP -->|"Send Message"| INFRA
    INFRA -->|"API Call"| WA
    APP -->|"AI Response"| INFRA
    INFRA -->|"API Call"| LLM
    BG -->|"Scheduled Tasks"| INFRA
    
    style WA fill:#25D366
    style LLM fill:#74AA9C
```

### Technology Stack / Công Nghệ

| Layer | Technology / Công Nghệ |
|-------|------------------------|
| **Backend** | .NET 8, ASP.NET Core 8 |
| **Architecture** | Clean Architecture, DDD, CQRS |
| **Database** | PostgreSQL 15+, EF Core 8 |
| **Cache** | Redis, StackExchange.Redis |
| **Messaging** | RabbitMQ, MassTransit |
| **HTTP Client** | HttpClient Factory, Polly |
| **AI** | OpenAI SDK |
| **API Gateway** | Traefik |
| **Documentation** | Swagger/OpenAPI 3.0 |

## API Endpoints

### Webhooks (WhatsApp)

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/webhooks` | GET | WhatsApp webhook verification |
| `/api/v1/whatsapp/webhooks` | POST | Receive WhatsApp message events |

### WhatsApp Account Management

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/accounts` | POST | Connect WhatsApp Business Account |
| `/api/v1/whatsapp/accounts/{shopId}` | GET | Get account details |
| `/api/v1/whatsapp/accounts/{shopId}` | DELETE | Disconnect account |

### Conversations

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/conversations` | GET | List conversations / Danh sách hội thoại |
| `/api/v1/whatsapp/conversations/{id}` | GET | Get conversation with messages |
| `/api/v1/whatsapp/conversations/{id}/messages` | POST | Send message / Gửi tin nhắn |
| `/api/v1/whatsapp/conversations/{id}/assign` | POST | Assign to agent |
| `/api/v1/whatsapp/conversations/{id}/close` | POST | Close conversation |

### Customers

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/customers` | GET | List customers / Danh sách khách hàng |
| `/api/v1/whatsapp/customers/{waId}` | GET | Customer details |
| `/api/v1/whatsapp/customers/{waId}/tags` | PUT | Update tags |
| `/api/v1/whatsapp/customers/{waId}/opt-in` | PUT | Update opt-in consent |

### Automation Flows

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/flows` | GET | List automation flows |
| `/api/v1/whatsapp/flows` | POST | Create automation flow |
| `/api/v1/whatsapp/flows/{id}` | PUT | Update flow |
| `/api/v1/whatsapp/flows/{id}/activate` | POST | Activate flow |
| `/api/v1/whatsapp/flows/{id}/deactivate` | POST | Deactivate flow |

### AI Agents

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/ai-agents` | POST | Create AI agent |
| `/api/v1/whatsapp/ai-agents/{id}` | GET | Get AI agent config |
| `/api/v1/whatsapp/ai-agents/{id}` | PUT | Update personality/prompts |
| `/api/v1/whatsapp/ai-agents/{id}/activate` | POST | Enable AI responses |

### Analytics

| Endpoint | Method | Description / Mô Tả |
|----------|--------|---------------------|
| `/api/v1/whatsapp/analytics/messages` | GET | Message statistics |
| `/api/v1/whatsapp/analytics/conversations` | GET | Conversation metrics |
| `/api/v1/whatsapp/analytics/automations` | GET | Automation performance |

## Documentation / Tài Liệu

### English Documentation
- [Architecture Documentation](docs/en/ARCHITECTURE.md) - System design and domain models
- [API Reference](docs/en/API.md) - Complete API specification with examples
- [WhatsApp Setup Guide](docs/en/WHATSAPP_SETUP.md) - Meta Business Account and API setup
- [Automation Guide](docs/en/AUTOMATION_GUIDE.md) - Creating automation flows
- [AI Chatbot Guide](docs/en/AI_CHATBOT_GUIDE.md) - AI agent configuration

### Vietnamese Documentation / Tài Liệu Tiếng Việt
- [Tài Liệu Kiến Trúc](docs/vi/ARCHITECTURE.md) - Thiết kế hệ thống và domain models
- [Tài Liệu API](docs/vi/API.md) - Đặc tả API đầy đủ với ví dụ
- [Hướng Dẫn Cài Đặt WhatsApp](docs/vi/WHATSAPP_SETUP.md) - Thiết lập Meta Business Account và API
- [Hướng Dẫn Tự Động Hóa](docs/vi/AUTOMATION_GUIDE.md) - Tạo flows tự động
- [Hướng Dẫn AI Chatbot](docs/vi/AI_CHATBOT_GUIDE.md) - Cấu hình AI agent

## Project Structure / Cấu Trúc Dự Án

```
mkt-whatsapp-service-net/
├── src/
│   ├── MktWhatsAppService.API/              # API Layer
│   │   ├── Controllers/                     # REST Controllers
│   │   │   ├── WebhooksController.cs
│   │   │   ├── WhatsAppAccountsController.cs
│   │   │   ├── ConversationsController.cs
│   │   │   ├── CustomersController.cs
│   │   │   ├── AutomationFlowsController.cs
│   │   │   ├── AIAgentsController.cs
│   │   │   └── AnalyticsController.cs
│   │   ├── Application/                     # CQRS Layer
│   │   │   ├── Commands/
│   │   │   ├── Queries/
│   │   │   └── Handlers/
│   │   ├── BackgroundJobs/
│   │   └── Program.cs
│   │
│   ├── MktWhatsAppService.Domain/           # Domain Layer
│   │   ├── AggregatesModel/
│   │   │   ├── WhatsAppAccountAggregate/
│   │   │   ├── ConversationAggregate/
│   │   │   ├── CustomerAggregate/
│   │   │   ├── AutomationFlowAggregate/
│   │   │   └── AIAgentAggregate/
│   │   ├── Exceptions/
│   │   ├── Events/
│   │   └── SeedWork/
│   │
│   └── MktWhatsAppService.Infrastructure/   # Infrastructure Layer
│       ├── Data/                            # EF Core
│       ├── Repositories/
│       └── ExternalServices/
│           ├── WhatsAppCloudApiClient.cs
│           └── LlmService.cs
│
├── tests/
│   ├── MktWhatsAppService.UnitTests/
│   └── MktWhatsAppService.IntegrationTests/
│
├── docs/                                    # Documentation
│   ├── en/                                  # English docs
│   └── vi/                                  # Vietnamese docs
│
├── Dockerfile
├── .env.example
└── MktWhatsAppService.slnx
```

## Environment Variables / Biến Môi Trường

| Variable | Description / Mô Tả | Default |
|----------|---------------------|---------|
| `DATABASE_URL` | PostgreSQL connection string | - |
| `REDIS_URL` | Redis connection string | `localhost:6379` |
| `RABBITMQ_URL` | RabbitMQ connection string | `localhost:5672` |
| `WHATSAPP_PHONE_NUMBER_ID` | WhatsApp Business phone number ID | - |
| `WHATSAPP_ACCESS_TOKEN` | WhatsApp Cloud API access token | - |
| `WHATSAPP_WEBHOOK_VERIFY_TOKEN` | Webhook verification token | - |
| `WHATSAPP_APP_SECRET` | WhatsApp app secret for signature verification | - |
| `WHATSAPP_API_VERSION` | WhatsApp API version | `v21.0` |
| `OPENAI_API_KEY` | OpenAI API key | - |
| `OPENAI_MODEL` | OpenAI model name | `gpt-4-turbo` |
| `ASPNETCORE_ENVIRONMENT` | Environment (Development/Production) | `Development` |

## Development Workflow / Quy Trình Phát Triển

### Phase 1: Domain Layer
1. Tạo Aggregates (WhatsAppAccount, Conversation, Customer, AutomationFlow, AIAgent)
2. Định nghĩa Entities và Value Objects
3. Implement business rules trong domain methods
4. Raise Domain Events

### Phase 2: Infrastructure Layer
1. Setup EF Core DbContext và entity configurations
2. Create repositories implementing domain interfaces
3. Implement WhatsAppCloudApiClient với Polly resilience
4. Implement LlmService (OpenAI integration)
5. Apply database migrations

### Phase 3: Application Layer (CQRS)
1. Create Commands (ProcessIncomingMessage, SendMessage, CreateFlow)
2. Create Queries (GetConversations, GetCustomers)
3. Implement MediatR Handlers
4. Add FluentValidation validators
5. Setup Pipeline Behaviors

### Phase 4: API Layer
1. Implement WebhooksController cho WhatsApp events
2. Create REST API Controllers
3. Add Swagger annotations
4. Configure authentication & authorization
5. Setup health checks và background jobs

## Testing / Kiểm Thử

```bash
# EN: Run all tests / VI: Chạy tất cả tests
dotnet test

# EN: Run unit tests only / VI: Chỉ chạy unit tests
dotnet test tests/MktWhatsAppService.UnitTests/

# EN: Run with coverage / VI: Chạy với coverage
dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=opencover
```

## Key Differences from Other Platforms / Điểm Khác Biệt

### WhatsApp vs Facebook Messenger vs Zalo

| Feature | WhatsApp | Facebook Messenger | Zalo |
|---------|----------|-------------------|------|
| **Message Window** | 24 hours | 24 hours | 7 days |
| **Template Requirement** | Required outside window | Optional | Required (ZNS) |
| **Pricing** | Per conversation | Free | Per message |
| **API Type** | Cloud API (recommended) | Graph API | Zalo OA API |
| **Opt-in Requirement** | Strict (required) | Recommended | Required |

## Rate Limits & Costs / Giới Hạn & Chi Phí

### WhatsApp Cloud API Rate Limits
- **Tier 1**: 1,000 conversations/day
- **Tier 2**: 10,000 conversations/day
- **Tier 3**: 100,000 conversations/day
- **Unlimited** (phải request từ Meta)

### Pricing (Example: Vietnam)
- **Marketing conversations**: ~$0.065 USD
- **Utility conversations**: ~$0.039 USD
- **Authentication**: ~$0.021 USD
- **Service**: ~$0.022 USD

*Note: 1 conversation = 24-hour window, nhiều messages trong cùng window = 1 conversation*

## Contributing / Đóng Góp

Please follow the [GoodGo Project Rules](../../.agent/skills/project-rules/SKILL.md) and [.NET Microservice Workflow](../../.agent/skills/dotnet-microservice-workflow/SKILL.md).

## License

MIT License

## Resources / Tài Nguyên

### WhatsApp Business Platform
- [WhatsApp Cloud API Documentation](https://developers.facebook.com/docs/whatsapp/cloud-api)
- [Webhook Reference](https://developers.facebook.com/docs/whatsapp/cloud-api/webhooks)
- [Message Templates](https://developers.facebook.com/docs/whatsapp/business-management-api/message-templates)

### OpenAI
- [OpenAI API Documentation](https://platform.openai.com/docs/introduction)
- [Chat Completions Guide](https://platform.openai.com/docs/guides/chat-completions)

### Internal Skills
- [API Design Skill](../../.agent/skills/api-design/SKILL.md)
- [CQRS MediatR Skill](../../.agent/skills/cqrs-mediatr/SKILL.md)
- [Domain-Driven Design Skill](../../.agent/skills/domain-driven-design/SKILL.md)
- [Inter-Service Communication](../../.agent/skills/inter-service-communication/SKILL.md)
