UNPKG

@warriorteam/redai-zalo-sdk

Version:

Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip

229 lines (187 loc) 7.28 kB
# Multiple Users Promotion - Gửi Promotion đến nhiều Users với Tracking ## Tổng quan Method `sendCustomPromotionToMultipleUsers()` cho phép gửi promotion message đến nhiều user IDs cùng lúc với tính năng tracking real-time và error handling nâng cao. ## Tính năng chính ### 🚀 **Dual Sending Modes** - **Sequential**: Gửi tuần tự với delay tùy chỉnh để tránh rate limit - **Parallel**: Gửi song song để tối ưu tốc độ ### 📊 **Real-time Tracking** - Progress callback theo thời gian thực - Estimated time remaining - Success/failure statistics - Current user being processed ### 🛡️ **Error Handling** - Error isolation - lỗi của 1 user không ảnh hưởng các user khác - Continue on error option - Detailed error information cho từng user - Success rate calculation ### 📈 **Performance Metrics** - Execution time tracking - Success rate percentage - Detailed results cho từng user - Start/end timestamps ## Cách sử dụng ### Basic Usage ```typescript import { PromotionService } from './services/promotion.service'; const promotionService = new PromotionService(zaloClient); const result = await promotionService.sendCustomPromotionToMultipleUsers( accessToken, ["user1", "user2", "user3"], { banner: { attachment_id: "your_attachment_id" }, // Hoặc { image_url: "https://example.com/image.jpg" } headerContent: "🎉 Khuyến mãi đặc biệt!", textContent: "Ưu đãi độc quyền dành riêng cho bạn", tableData: [ { key: "Mã giảm giá", value: "SAVE50" }, { key: "Giảm giá", value: "50%" } ], buttons: [ { title: "Mua ngay", type: "oa.open.url", payload: { url: "https://shop.example.com" } } ] } ); console.log(`Sent to ${result.successful}/${result.total} users`); ``` ### Advanced Usage với Tracking ```typescript // Ví dụ promotionData với banner config const promotionData = { banner: { attachment_id: "your_attachment_id" }, // Hoặc { image_url: "https://example.com/banner.jpg" } headerContent: "🎉 Khuyến mãi đặc biệt!", textContent: "Ưu đãi độc quyền dành riêng cho bạn", tableData: [ { key: "Mã giảm giá", value: "SAVE50" }, { key: "Giảm giá", value: "50%" } ], buttons: [ { title: "Mua ngay", type: "oa.open.url", payload: { url: "https://shop.example.com" } } ] }; const result = await promotionService.sendCustomPromotionToMultipleUsers( accessToken, userIds, promotionData, { mode: "sequential", delayMs: 2000, continueOnError: true, // Real-time progress tracking onProgress: (progress) => { const percent = Math.round((progress.completed / progress.total) * 100); console.log(`📊 Progress: ${percent}% (${progress.completed}/${progress.total})`); console.log(`✅ Success: ${progress.successful} | ❌ Failed: ${progress.failed}`); if (progress.currentUserId) { console.log(`🔄 Processing: ${progress.currentUserId}`); } if (progress.estimatedTimeRemaining) { const eta = Math.round(progress.estimatedTimeRemaining / 1000); console.log(`⏱️ ETA: ~${eta}s`); } }, // Callback cho từng user onUserComplete: (userResult) => { if (userResult.success) { console.log(`✅ ${userResult.userId}: ${userResult.result?.message_id}`); } else { console.log(`❌ ${userResult.userId}: ${userResult.error?.message}`); } } } ); ``` ### Parallel Mode ```typescript const result = await promotionService.sendCustomPromotionToMultipleUsers( accessToken, userIds, promotionData, { mode: "parallel", // Gửi tất cả cùng lúc continueOnError: true, onProgress: (progress) => { console.log(`⚡ Parallel: ${progress.completed}/${progress.total}`); } } ); console.log(`⚡ Completed in ${result.executionTime}ms`); ``` ## Options Parameters ### SendingOptions ```typescript interface SendingOptions { mode?: "sequential" | "parallel"; // Chế độ gửi (default: "sequential") delayMs?: number; // Delay giữa tin nhắn (default: 1000ms) continueOnError?: boolean; // Tiếp tục khi có lỗi (default: true) onProgress?: (progress: MultiplePromotionProgress) => void; onUserComplete?: (result: PromotionUserResult) => void; } ``` ### Progress Tracking Interface ```typescript interface MultiplePromotionProgress { total: number; // Tổng số users completed: number; // Số users đã xử lý successful: number; // Số users gửi thành công failed: number; // Số users gửi thất bại currentUserId: string | null; // User ID đang xử lý (sequential mode) startTime: number; // Timestamp bắt đầu estimatedTimeRemaining: number | null; // Thời gian còn lại (ms) } ``` ### Result Interface ```typescript interface MultiplePromotionResult { total: number; // Tổng số users successful: number; // Số users thành công failed: number; // Số users thất bại results: PromotionUserResult[]; // Chi tiết kết quả từng user executionTime: number; // Thời gian thực hiện (ms) mode: "sequential" | "parallel"; // Chế độ đã sử dụng startTime: Date; // Thời gian bắt đầu endTime: Date; // Thời gian kết thúc successRate: number; // Tỷ lệ thành công (%) } ``` ## Best Practices ### 1. **Chọn Mode phù hợp** - **Sequential**: Cho campaigns lớn, tránh rate limit - **Parallel**: Cho urgent notifications, tối ưu tốc độ ### 2. **Delay Configuration** - Minimum 1000ms để tránh rate limit - Tăng delay nếu gặp rate limit errors - Test với số lượng nhỏ trước khi scale ### 3. **Error Handling** - Luôn set `continueOnError: true` cho campaigns lớn - Log chi tiết errors để debug - Retry failed users nếu cần ### 4. **Performance Monitoring** - Sử dụng `onProgress` để monitor real-time - Track success rate và adjust strategy - Monitor execution time cho optimization ## Error Codes - **2001**: Ngoài khung giờ cho phép (8:00-22:00) - **2002**: User đã từ chối nhận tin truyền thông - **2003**: Vượt quá giới hạn 1 tin/ngày - **2004**: Template chưa được phê duyệt - **2005**: Nội dung vi phạm chính sách - **2006**: OA chưa có quyền gửi tin truyền thông ## Examples Xem file `examples/promotion-examples.ts` để có ví dụ chi tiết về: - Sequential sending với progress tracking - Parallel sending cho tốc độ - Error handling và retry logic - Performance monitoring và optimization ## Rate Limits - **Sending Time**: 8:00 - 22:00 hàng ngày - **Frequency**: Tối đa 1 tin truyền thông/ngày/user - **Concurrent**: Khuyến nghị sequential mode cho campaigns lớn - **Delay**: Minimum 1000ms giữa các tin nhắn