Files
worker/lib/core/constants/api_constants.dart
2025-11-07 11:52:06 +07:00

412 lines
14 KiB
Dart

/// API-related constants for the Worker app
///
/// This file contains all API endpoints, timeouts, and network-related configurations.
/// Base URLs should be configured per environment (dev, staging, production).
class ApiConstants {
// Private constructor to prevent instantiation
ApiConstants._();
// ============================================================================
// Base URLs
// ============================================================================
/// Base URL for development environment
static const String devBaseUrl = 'https://dev-api.worker.example.com';
/// Base URL for staging environment
static const String stagingBaseUrl = 'https://staging-api.worker.example.com';
/// Base URL for production environment
static const String prodBaseUrl = 'https://api.worker.example.com';
/// Current base URL (should be configured based on build flavor)
static const String baseUrl = devBaseUrl; // TODO: Configure with flavors
/// API version prefix
static const String apiVersion = '/v1';
/// Full API base URL with version
static String get apiBaseUrl => '$baseUrl$apiVersion';
// ============================================================================
// Timeout Configurations
// ============================================================================
/// Connection timeout in milliseconds (30 seconds)
static const Duration connectionTimeout = Duration(milliseconds: 30000);
/// Receive timeout in milliseconds (30 seconds)
static const Duration receiveTimeout = Duration(milliseconds: 30000);
/// Send timeout in milliseconds (30 seconds)
static const Duration sendTimeout = Duration(milliseconds: 30000);
// ============================================================================
// Retry Configurations
// ============================================================================
/// Maximum number of retry attempts for failed requests
static const int maxRetryAttempts = 3;
/// Initial retry delay in milliseconds
static const Duration initialRetryDelay = Duration(milliseconds: 1000);
/// Maximum retry delay in milliseconds
static const Duration maxRetryDelay = Duration(milliseconds: 5000);
/// Retry delay multiplier for exponential backoff
static const double retryDelayMultiplier = 2.0;
// ============================================================================
// Cache Configurations
// ============================================================================
/// Default cache duration (1 hour)
static const Duration defaultCacheDuration = Duration(hours: 1);
/// Products cache duration (24 hours)
static const Duration productsCacheDuration = Duration(hours: 24);
/// Profile cache duration (1 hour)
static const Duration profileCacheDuration = Duration(hours: 1);
/// Categories cache duration (48 hours)
static const Duration categoriesCacheDuration = Duration(hours: 48);
/// Maximum cache size in bytes (50 MB)
static const int maxCacheSize = 50 * 1024 * 1024;
// ============================================================================
// Request Headers
// ============================================================================
/// Content-Type header for JSON requests
static const String contentTypeJson = 'application/json';
/// Accept header for JSON responses
static const String acceptJson = 'application/json';
/// Accept-Language header for Vietnamese
static const String acceptLanguageVi = 'vi';
/// Accept-Language header for English
static const String acceptLanguageEn = 'en';
// ============================================================================
// Authentication Endpoints
// ============================================================================
/// Request OTP for phone number login
/// POST /auth/request-otp
/// Body: { "phone": "+84912345678" }
static const String requestOtp = '/auth/request-otp';
/// Verify OTP code
/// POST /auth/verify-otp
/// Body: { "phone": "+84912345678", "otp": "123456" }
static const String verifyOtp = '/auth/verify-otp';
/// Register new user
/// POST /auth/register
/// Body: { "name": "...", "phone": "...", "email": "...", "userType": "..." }
static const String register = '/auth/register';
/// Refresh access token
/// POST /auth/refresh-token
/// Headers: { "Authorization": "Bearer {refreshToken}" }
static const String refreshToken = '/auth/refresh-token';
/// Logout user
/// POST /auth/logout
static const String logout = '/auth/logout';
/// Get current user profile
/// GET /auth/me
static const String getCurrentUser = '/auth/me';
// ============================================================================
// Loyalty Program Endpoints
// ============================================================================
/// Get loyalty points and tier information
/// GET /loyalty/points
static const String getLoyaltyPoints = '/loyalty/points';
/// Get loyalty points transaction history
/// GET /loyalty/transactions?page={page}&limit={limit}
static const String getPointsHistory = '/loyalty/transactions';
/// Get available rewards for redemption
/// GET /loyalty/rewards?category={category}
static const String getRewards = '/loyalty/rewards';
/// Redeem a reward
/// POST /loyalty/rewards/{rewardId}/redeem
static const String redeemReward = '/loyalty/rewards';
/// Get user's redeemed gifts
/// GET /loyalty/gifts?status={active|used|expired}
static const String getGifts = '/loyalty/gifts';
/// Get referral information
/// GET /loyalty/referral
static const String getReferralInfo = '/loyalty/referral';
/// Share referral link
/// POST /loyalty/referral/share
/// Body: { "method": "whatsapp|telegram|sms" }
static const String shareReferral = '/loyalty/referral/share';
// ============================================================================
// Product Endpoints
// ============================================================================
/// Get all products with pagination
/// GET /products?page={page}&limit={limit}&category={categoryId}
static const String getProducts = '/products';
/// Get product details by ID
/// GET /products/{productId}
static const String getProductDetails = '/products';
/// Search products
/// GET /products/search?q={query}&page={page}&limit={limit}
static const String searchProducts = '/products/search';
/// Get product categories
/// GET /categories
static const String getCategories = '/categories';
/// Get products by category
/// GET /categories/{categoryId}/products
static const String getProductsByCategory = '/categories';
// ============================================================================
// Order Endpoints
// ============================================================================
/// Create new order
/// POST /orders
/// Body: { "items": [...], "deliveryAddress": {...}, "paymentMethod": "..." }
static const String createOrder = '/orders';
/// Get user's orders
/// GET /orders?status={status}&page={page}&limit={limit}
static const String getOrders = '/orders';
/// Get order details by ID
/// GET /orders/{orderId}
static const String getOrderDetails = '/orders';
/// Cancel order
/// POST /orders/{orderId}/cancel
static const String cancelOrder = '/orders';
/// Get payment transactions
/// GET /payments?page={page}&limit={limit}
static const String getPayments = '/payments';
/// Get payment details
/// GET /payments/{paymentId}
static const String getPaymentDetails = '/payments';
// ============================================================================
// Project Endpoints
// ============================================================================
/// Create new project
/// POST /projects
static const String createProject = '/projects';
/// Get user's projects
/// GET /projects?status={status}&page={page}&limit={limit}
static const String getProjects = '/projects';
/// Get project details by ID
/// GET /projects/{projectId}
static const String getProjectDetails = '/projects';
/// Update project
/// PUT /projects/{projectId}
static const String updateProject = '/projects';
/// Update project progress
/// PATCH /projects/{projectId}/progress
/// Body: { "progress": 75 }
static const String updateProjectProgress = '/projects';
/// Delete project
/// DELETE /projects/{projectId}
static const String deleteProject = '/projects';
// ============================================================================
// Quote Endpoints
// ============================================================================
/// Create new quote
/// POST /quotes
static const String createQuote = '/quotes';
/// Get user's quotes
/// GET /quotes?status={status}&page={page}&limit={limit}
static const String getQuotes = '/quotes';
/// Get quote details by ID
/// GET /quotes/{quoteId}
static const String getQuoteDetails = '/quotes';
/// Update quote
/// PUT /quotes/{quoteId}
static const String updateQuote = '/quotes';
/// Send quote to client
/// POST /quotes/{quoteId}/send
/// Body: { "email": "client@example.com" }
static const String sendQuote = '/quotes';
/// Convert quote to order
/// POST /quotes/{quoteId}/convert
static const String convertQuoteToOrder = '/quotes';
// ============================================================================
// Chat Endpoints
// ============================================================================
/// WebSocket endpoint for real-time chat
static const String chatWebSocket = '/ws/chat';
/// Get chat messages
/// GET /chat/messages?roomId={roomId}&before={messageId}&limit={limit}
static const String getChatMessages = '/chat/messages';
/// Send chat message
/// POST /chat/messages
/// Body: { "roomId": "...", "text": "...", "attachments": [...] }
static const String sendChatMessage = '/chat/messages';
/// Mark messages as read
/// POST /chat/messages/read
/// Body: { "messageIds": [...] }
static const String markMessagesAsRead = '/chat/messages/read';
// ============================================================================
// Account & Profile Endpoints
// ============================================================================
/// Get user profile
/// GET /profile
static const String getProfile = '/profile';
/// Update user profile
/// PUT /profile
static const String updateProfile = '/profile';
/// Upload avatar
/// POST /profile/avatar
/// Form-data: { "avatar": File }
static const String uploadAvatar = '/profile/avatar';
/// Change password
/// POST /profile/change-password
/// Body: { "currentPassword": "...", "newPassword": "..." }
static const String changePassword = '/profile/change-password';
/// Get user addresses
/// GET /addresses
static const String getAddresses = '/addresses';
/// Add new address
/// POST /addresses
static const String addAddress = '/addresses';
/// Update address
/// PUT /addresses/{addressId}
static const String updateAddress = '/addresses';
/// Delete address
/// DELETE /addresses/{addressId}
static const String deleteAddress = '/addresses';
/// Set default address
/// POST /addresses/{addressId}/set-default
static const String setDefaultAddress = '/addresses';
// ============================================================================
// Promotion Endpoints
// ============================================================================
/// Get active promotions
/// GET /promotions?category={category}
static const String getPromotions = '/promotions';
/// Get promotion details
/// GET /promotions/{promotionId}
static const String getPromotionDetails = '/promotions';
/// Claim promotion
/// POST /promotions/{promotionId}/claim
static const String claimPromotion = '/promotions';
// ============================================================================
// Notification Endpoints
// ============================================================================
/// Get notifications
/// GET /notifications?type={type}&page={page}&limit={limit}
static const String getNotifications = '/notifications';
/// Mark notification as read
/// POST /notifications/{notificationId}/read
static const String markNotificationAsRead = '/notifications';
/// Mark all notifications as read
/// POST /notifications/read-all
static const String markAllNotificationsAsRead = '/notifications/read-all';
/// Clear all notifications
/// DELETE /notifications
static const String clearAllNotifications = '/notifications';
/// Register FCM token for push notifications
/// POST /notifications/fcm-token
/// Body: { "token": "..." }
static const String registerFcmToken = '/notifications/fcm-token';
// ============================================================================
// Helper Methods
// ============================================================================
/// Build full URL for endpoint
///
/// Example:
/// ```dart
/// final url = ApiConstants.buildUrl('/products', {'page': '1', 'limit': '20'});
/// // Returns: https://api.worker.example.com/v1/products?page=1&limit=20
/// ```
static String buildUrl(String endpoint, [Map<String, String>? queryParams]) {
final uri = Uri.parse('$apiBaseUrl$endpoint');
if (queryParams != null && queryParams.isNotEmpty) {
return uri.replace(queryParameters: queryParams).toString();
}
return uri.toString();
}
/// Build URL with path parameters
///
/// Example:
/// ```dart
/// final url = ApiConstants.buildUrlWithParams('/products/{id}', {'id': '123'});
/// // Returns: https://api.worker.example.com/v1/products/123
/// ```
static String buildUrlWithParams(
String endpoint,
Map<String, String> params,
) {
String url = endpoint;
params.forEach((key, value) {
url = url.replaceAll('{$key}', value);
});
return '$apiBaseUrl$url';
}
}