Files
Ho Ngoc Hai 76d75c753b Migrate
2026-05-23 18:37:02 +07:00

17 KiB

Tài Liệu Kiến Trúc

Dịch vụ: mkt-whatsapp-service-net
Phiên bản: 1.0
Cập nhật lần cuối: 2026-01-18

Tổng Quan Hệ Thống

MKT WhatsApp Service là một microservice toàn diện được xây dựng trên nguyên tắc Clean Architecture, triển khai các pattern Domain-Driven Design (DDD) và CQRS. Dịch vụ cung cấp ba khả năng cốt lõi:

  1. Chatbot Tự Động: Luồng hội thoại dựa trên quy tắc
  2. AI Chatbot: Phản hồi thông minh được hỗ trợ bởi LLM
  3. Quản Lý Khách Hàng: CRM thống nhất cho tương tác WhatsApp

Kiến Trúc Cấp Cao

graph TB
    subgraph External["Bên Ngoài"]
        WA[WhatsApp Cloud API]
        OPENAI[OpenAI GPT-4]
        Customer[Người Dùng Cuối]
    end
    
    subgraph "GoodGo Platform"
        GATEWAY[Traefik Gateway]
        
        subgraph "mkt-whatsapp-service-net"
            API[API Layer]
            APP[Application Layer]
            DOMAIN[Domain Layer]
            INFRA[Infrastructure Layer]
        end
        
        PG[(PostgreSQL)]
        REDIS[(Redis)]
        RABBIT[RabbitMQ]
    end
    
    subgraph "Other Services"["Dịch Vụ Khác"]
        MERCHANT[merchant-service]
        ANALYTICS[analytics-service]
    end
    
    Customer -->|Tin nhắn| WA
    WA -->|Webhooks| GATEWAY
    GATEWAY --> API
    API --> APP
    APP --> DOMAIN
    APP --> INFRA
    INFRA --> PG
    INFRA --> REDIS
    INFRA --> WA
    INFRA --> OPENAI
    INFRA --> RABBIT
    RABBIT --> MERCHANT
    RABBIT --> ANALYTICS
    
    style Customer fill:#2C3E50,color:#ECF0F1,stroke:#34495E,stroke-width:3px
    style WA fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
    style OPENAI fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
    style GATEWAY fill:#3498DB,color:#ECF0F1,stroke:#2980B9,stroke-width:3px
    style API fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style APP fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style DOMAIN fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style INFRA fill:#8E44AD,color:#ECF0F1,stroke:#7D3C98,stroke-width:2px
    style PG fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
    style REDIS fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
    style RABBIT fill:#34495E,color:#ECF0F1,stroke:#2C3E50,stroke-width:2px
    style MERCHANT fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px
    style ANALYTICS fill:#27AE60,color:#ECF0F1,stroke:#229954,stroke-width:2px

Các Tầng Clean Architecture

1. Tầng API (MktWhatsAppService.API)

Trách Nhiệm: Giao diện HTTP, xử lý request/response

Controllers

  • WebhooksController - Xác minh webhook WhatsApp và sự kiện tin nhắn
  • WhatsAppAccountsController - Quản lý kết nối tài khoản
  • ConversationsController - Endpoints hội thoại và tin nhắn
  • CustomersController - Quản lý hồ sơ khách hàng
  • AutomationFlowsController - CRUD luồng tự động
  • AIAgentsController - Cấu hình AI agent
  • AnalyticsController - Số liệu và báo cáo

Background Jobs

  • ConversationExpiryJob - Đóng hội thoại hết hạn 24h
  • MessageStatusSyncJob - Đồng bộ trạng thái gửi/đã đọc từ WhatsApp
  • FlowSchedulerJob - Kích hoạt luồng tự động theo thời gian

2. Tầng Application (MktWhatsAppService.API/Application)

Trách Nhiệm: Use cases, điều phối, CQRS

Commands (Ghi)

Tài Khoản WhatsApp

  • ConnectWhatsAppAccountCommand - Đăng ký tài khoản mới
  • UpdateWebhookCommand - Cập nhật cấu hình webhook
  • DisconnectWhatsAppAccountCommand - Vô hiệu hóa tài khoản

Tin Nhắn

  • ProcessIncomingMessageCommand - Xử lý tin nhắn WhatsApp đến
  • SendMessageCommand - Gửi tin nhắn đi
  • SendTemplateMessageCommand - Gửi template đã phê duyệt

Tự Động

  • CreateAutomationFlowCommand - Định nghĩa luồng mới
  • UpdateFlowStepCommand - Sửa logic luồng
  • ActivateFlowCommand - Bật tự động
  • DeactivateFlowCommand - Tắt tự động

AI Agent

  • CreateAIAgentCommand - Cấu hình chatbot AI
  • UpdateAgentPersonalityCommand - Sửa hành vi AI
  • GenerateAIResponseCommand - Lấy trả lời AI

Khách Hàng

  • CreateCustomerCommand - Đăng ký khách hàng mới
  • UpdateCustomerOptInCommand - Quản lý đồng ý opt-in
  • TagCustomerCommand - Thêm/xóa tags

Queries (Đọc)

Hội Thoại

  • GetConversationQuery - Một hội thoại với tin nhắn
  • GetActiveConversationsQuery - Liệt kê hội thoại đang diễn ra
  • SearchConversationsQuery - Tìm kiếm toàn văn bản

Khách Hàng

  • GetCustomerQuery - Hồ sơ khách hàng theo WaId
  • GetCustomersQuery - Danh sách khách hàng có phân trang
  • GetCustomerConversationHistoryQuery - Tất cả hội thoại trong quá khứ

Phân Tích

  • GetMessageStatsQuery - Số liệu lượng tin nhắn
  • GetConversationMetricsQuery - Thời gian phản hồi, tỷ lệ giải quyết
  • GetAutomationPerformanceQuery - Thống kê thực thi luồng

MediatR Pipeline Behaviors

  1. Logging Behavior - Ghi log tất cả commands/queries
  2. Validation Behavior - Tích hợp FluentValidation
  3. Transaction Behavior - Unit of Work cho commands

3. Tầng Domain (MktWhatsAppService.Domain)

Trách Nhiệm: Logic nghiệp vụ, entities, quy tắc nghiệp vụ

Aggregates

WhatsAppAccount Aggregate

Aggregate Root: WhatsAppAccount

Thuộc Tính:

  • Id (Guid)
  • ShopId (Guid)
  • PhoneNumberId (string) - ID số điện thoại WhatsApp
  • AccessToken (string, mã hóa)
  • WebhookUrl (string)
  • Status (Active/Suspended)
  • MessageTier (1K/10K/100K/Unlimited)

Phương Thức Nghiệp Vụ:

  • Activate() - Kích hoạt tài khoản
  • UpdateWebhook(url) - Thay đổi URL webhook
  • Suspend() - Tạm ngừng tài khoản

Domain Events:

  • WhatsAppAccountConnectedEvent
  • WebhookVerifiedEvent
Conversation Aggregate

Aggregate Root: Conversation

Thuộc Tính:

  • Id (Guid)
  • ShopId (Guid)
  • CustomerWaId (string)
  • Status (Active/Closed/Expired)
  • AssignedAgentId (Guid, nullable)
  • LastMessageAt (DateTime)
  • Tags (List)

Entities:

  • Message
    • Id (Guid)
    • WhatsAppMessageId (string)
    • Direction (Inbound/Outbound)
    • Content (MessageContent value object)
    • Status (Sent/Delivered/Read/Failed)
    • Timestamp (DateTime)

Phương Thức Nghiệp Vụ:

  • AddMessage(content, direction) - Thêm tin nhắn vào hội thoại
  • AssignToAgent(agentId) - Gán hội thoại
  • Close() - Đóng hội thoại
  • CheckExpiry() - Kiểm tra cửa sổ 24h

Domain Events:

  • ConversationStartedEvent
  • MessageReceivedEvent
  • MessageSentEvent
  • ConversationClosedEvent
AutomationFlow Aggregate

Aggregate Root: AutomationFlow

Thuộc Tính:

  • Id (Guid)
  • ShopId (Guid)
  • FlowName (string)
  • TriggerType (Keyword/Event/Schedule)
  • TriggerConfig (JSON)
  • IsActive (bool)

Entities:

  • FlowStep
    • Order (int)
    • Action (SendMessage/TagCustomer/CallWebhook/Delay)
    • ActionConfig (JSON)
    • Conditions (JSON, optional)
    • NextStepId (int, nullable)

Phương Thức Nghiệp Vụ:

  • AddStep(action, config, conditions) - Thêm bước luồng
  • ValidateFlow() - Kiểm tra chu trình, xác thực cấu trúc
  • Activate() - Bật luồng
  • Deactivate() - Tắt luồng
AIAgent Aggregate

Aggregate Root: AIAgent

Thuộc Tính:

  • Id (Guid)
  • ShopId (Guid)
  • AgentName (string)
  • Personality (AgentPersonality value object)
  • KnowledgeBaseId (Guid, nullable)
  • IsActive (bool)

Value Objects:

  • AgentPersonality
    • Tone (Friendly/Professional/Casual)
    • Language (Vietnamese/English)
    • Constraints (List)
    • PromptTemplate (string)

Phương Thức Nghiệp Vụ:

  • UpdatePersonality(personality) - Thay đổi hành vi AI
  • Activate() - Bật phản hồi AI
  • Deactivate() - Tắt AI
Customer Aggregate

Aggregate Root: Customer

Thuộc Tính:

  • Id (Guid)
  • WaId (string) - ID WhatsApp (số điện thoại)
  • ShopId (Guid)
  • Name (string)
  • ProfilePictureUrl (string, nullable)
  • Consent (OptInConsent value object)
  • Tags (List)
  • CustomFields (Dictionary<string, string>)
  • FirstContactedAt (DateTime)

Value Objects:

  • OptInConsent
    • Status (OptedIn/OptedOut/Pending)
    • Timestamp (DateTime)
    • Source (Web/WhatsApp/Manual)

Phương Thức Nghiệp Vụ:

  • UpdateOptIn(status, source) - Quản lý đồng ý
  • AddTag(tag) - Thêm tag khách hàng
  • RemoveTag(tag) - Xóa tag
  • UpdateCustomField(key, value) - Đặt trường tùy chỉnh

4. Tầng Infrastructure (MktWhatsAppService.Infrastructure)

Trách Nhiệm: Mối quan tâm bên ngoài, lưu trữ, API clients

Truy Cập Dữ Liệu

  • MktWhatsAppServiceContext - EF Core DbContext
  • Cấu hình Entity sử dụng Fluent API
  • Repositories triển khai interfaces domain

Dịch Vụ Bên Ngoài

WhatsAppCloudApiClient

HTTP client cho WhatsApp Cloud API với chính sách resilience Polly:

Phương Thức:

  • SendMessageAsync() - Gửi tin nhắn văn bản/media/tương tác
  • SendTemplateMessageAsync() - Gửi templates đã phê duyệt
  • MarkMessageAsReadAsync() - Gửi biên nhận đã đọc
  • GetMediaAsync() - Tải xuống file media

Resilience:

  • Retry: 3 lần thử, backoff mũ (500ms, 1.5s, 4.5s)
  • Circuit Breaker: Tỷ lệ lỗi 50%, lấy mẫu 30s, ngắt 30s
  • Timeout: 10s mỗi request
LlmService

Trừu tượng hóa nhà cung cấp LLM (triển khai OpenAI):

Phương Thức:

  • GenerateResponseAsync() - Lấy phản hồi AI với ngữ cảnh
  • ExtractIntentAsync() - Phân loại ý định người dùng
  • StreamResponseAsync() - Streaming cho phản hồi dài

Tính Năng:

  • Theo dõi sử dụng token
  • Tính toán chi phí
  • Quản lý cửa sổ ngữ cảnh (10 tin nhắn cuối)
  • Bộ lọc an toàn

Luồng Xử Lý Tin Nhắn

Luồng Tin Nhắn Đến

sequenceDiagram
    participant WA as WhatsApp
    participant Webhook as WebhooksController
    participant Cmd as ProcessIncomingMessageHandler
    participant AutoEngine as AutomationEngine
    participant AIEngine as AIEngine
    participant DB as Database
    
    WA->>Webhook: POST /webhooks (sự kiện tin nhắn)
    Webhook->>Webhook: Xác minh chữ ký
    Webhook->>Cmd: ProcessIncomingMessageCommand
    Webhook-->>WA: 200 OK (ngay lập tức)
    
    Cmd->>DB: Lấy/Tạo Hội Thoại
    Cmd->>DB: Lưu Tin Nhắn
    
    alt Luồng Tự Động Hoạt Động
        Cmd->>AutoEngine: Kiểm tra triggers
        AutoEngine->>AutoEngine: Khớp từ khóa/điều kiện
        AutoEngine->>WA: Gửi phản hồi tự động
    else AI Agent Hoạt Động
        Cmd->>AIEngine: GenerateAIResponseCommand
        AIEngine->>DB: Lấy lịch sử (10 tin nhắn cuối)
        AIEngine->>AIEngine: Xây dựng prompt
        AIEngine->>OpenAI: Chat completion
        OpenAI-->>AIEngine: Phản hồi AI
        AIEngine->>WA: Gửi tin nhắn AI
    else Phản Hồi Thủ Công
        Cmd->>DB: Đánh dấu hội thoại chờ xử lý
        Cmd->>RabbitMQ: Phát hành event
    end

Luồng Tin Nhắn Đi

sequenceDiagram
    participant API as ConversationsController
    participant Cmd as SendMessageHandler
    participant Domain as Conversation Aggregate
    participant WA as WhatsAppCloudApiClient
    participant DB as Database
    
    API->>Cmd: SendMessageCommand
    Cmd->>DB: Lấy Hội Thoại
    Cmd->>Domain: CheckExpiry()
    
    alt Trong Cửa Sổ 24h
        Domain-->>Cmd: Cửa sổ hợp lệ
        Cmd->>WA: SendMessageAsync()
        WA-->>Cmd: ID tin nhắn WhatsApp
        Cmd->>Domain: AddMessage()
        Cmd->>DB: Lưu
    else Ngoài Cửa Sổ 24h
        Domain-->>Cmd: Cửa sổ hết hạn
        Cmd->>WA: SendTemplateMessageAsync()
        WA-->>Cmd: ID tin nhắn (cửa sổ mới)
        Cmd->>Domain: AddMessage()
        Cmd->>DB: Lưu
    end

Mô Hình Dữ Liệu

Database Schema

Xem Tài Liệu Database Schema để biết cấu trúc bảng chi tiết và indexes.

Các bảng chính:

  • whatsapp_accounts - Kết nối tài khoản doanh nghiệp
  • conversations - Hội thoại khách hàng
  • messages - Tin nhắn riêng lẻ (thuộc sở hữu của hội thoại)
  • customers - Hồ sơ khách hàng
  • automation_flows - Định nghĩa luồng tự động
  • flow_steps - Cấu hình bước luồng
  • ai_agents - Cấu hình AI agent

Indexes Quan Trọng

-- Truy vấn lưu lượng cao
CREATE INDEX idx_conversations_shop_status ON conversations(shop_id, status);
CREATE INDEX idx_messages_conversation_timestamp ON messages(conversation_id, timestamp DESC);
CREATE INDEX idx_customers_shop_waid ON customers(shop_id, wa_id);

-- Tra cứu tự động
CREATE INDEX idx_flows_shop_active ON automation_flows(shop_id, is_active);

Integration Events

Dịch vụ phát hành events đến RabbitMQ để các dịch vụ khác tiêu thụ:

Published Events

WhatsAppMessageReceivedEvent

  • Phát ra khi: Khách hàng gửi tin nhắn đến shop
  • Người tiêu thụ: analytics-service (số liệu), merchant-service (thông báo)

ConversationClosedEvent

  • Phát ra khi: Hội thoại được đóng hoặc hết hạn
  • Người tiêu thụ: analytics-service (thời lượng hội thoại), merchant-service

AITokenUsageEvent

  • Phát ra khi: AI agent tạo phản hồi
  • Người tiêu thụ: wallet-service (thanh toán), analytics-service (theo dõi chi phí)

CustomerOptInChangedEvent

  • Phát ra khi: Trạng thái opt-in khách hàng thay đổi
  • Người tiêu thụ: dịch vụ marketing (cập nhật quyền)

Cân Nhắc Bảo Mật

Xác Minh Chữ Ký Webhook

Tất cả webhooks đến từ WhatsApp được xác minh sử dụng HMAC-SHA256:

var signature = Request.Headers["X-Hub-Signature-256"];
var payload = await ReadBodyAsStringAsync();
var computedSignature = ComputeHmacSha256(payload, _appSecret);

if (!SecureCompare(signature, computedSignature))
    return Unauthorized();

Mã Hóa Access Token

WhatsApp access tokens được mã hóa khi lưu trữ sử dụng AES-256-GCM:

// Lưu trong database dưới dạng bytes đã mã hóa
public string AccessToken 
{ 
    get => _encryption.Decrypt(_encryptedToken);
    private set => _encryptedToken = _encryption.Encrypt(value);
}

Rate Limiting

Bộ rate limiter phân tán dựa trên Redis:

  • 60 requests/phút mỗi shop
  • 1000 requests/phút mỗi service instance

Tuân Thủ GDPR

  • Dữ liệu khách hàng có thể được xuất qua API
  • Quyền bị lãng quên: xóa mềm với ẩn danh hóa dữ liệu
  • Theo dõi đồng ý opt-in với timestamps
  • Áp dụng chính sách lưu giữ dữ liệu

Tối Ưu Hóa Hiệu Suất

Chiến Lược Caching

Sử Dụng Redis Cache:

  1. Ngữ Cảnh Hội Thoại - 10 tin nhắn cuối (TTL: 1 giờ)
  2. Hồ Sơ Khách Hàng - Khách hàng được truy cập thường xuyên (TTL: 30 phút)
  3. Luồng Hoạt Động - Luồng tự động (TTL: 5 phút)
  4. Bộ Đếm Rate Limit - Số lượng request mỗi shop (TTL: 1 phút)

Tối Ưu Hóa Truy Vấn

  • Sử dụng Dapper cho truy vấn đọc nhiều (bỏ qua EF Core)
  • Triển khai phân trang cho tất cả list endpoints
  • Index trên foreign keys và cột được lọc thường xuyên
  • Không có truy vấn N+1 (sử dụng Include() hoặc projections)

Xử Lý Nền

  • Xử lý webhook trả về 200 ngay lập tức
  • Gửi tin nhắn được xếp hàng đến background job
  • Thực thi luồng chạy không đồng bộ

Monitoring & Observability

Health Checks

builder.Services.AddHealthChecks()
    .AddNpgSql(connectionString, name: "postgres")
    .AddRedis(redisConnection, name: "redis")
    .AddRabbitMQ(rabbitConnection, name: "rabbitmq")
    .AddCheck<WhatsAppApiHealthCheck>("whatsapp-api")
    .AddCheck<OpenAIHealthCheck>("openai-api");

Metrics (Prometheus)

  • whatsapp_messages_received_total - Counter
  • whatsapp_messages_sent_total - Counter
  • whatsapp_conversation_duration_seconds - Histogram
  • whatsapp_ai_tokens_used_total - Counter
  • whatsapp_webhook_processing_duration_ms - Histogram

Logging (Loki)

Structured logging với Serilog:

  • Correlation IDs Request/response
  • Làm giàu với ShopId, ConversationId
  • Dữ liệu nhạy cảm (tokens, messages) được che giấu

Kiến Trúc Triển Khai

Xem Hướng Dẫn Triển Khai để biết Kubernetes manifests và chiến lược scaling.

Triggers Scaling:

  • CPU > 70% → Scale up pods
  • Webhook queue > 1000 messages → Scale up
  • Memory > 80% → Điều tra + scale

Giới Hạn Tài Nguyên:

  • Requests: 256Mi memory, 250m CPU
  • Limits: 512Mi memory, 500m CPU

Tài Liệu Tham Khảo