mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-25 21:38:48 +00:00
New features (#67)
* refactor: Rename handler package to handlers in carrier-connector
- Rename internal/handler directory to internal/handlers
- Update handler import path in main.go and routes.go
* feat: Add SM-DP+ handler with multi-carrier management and profile operations
- Add SMDPHandler struct with manager field and NewSMDPHandler constructor
- Add AddCarrier endpoint with JSON binding and carrier configuration support
- Add RemoveCarrier endpoint with carrier ID parameter validation
- Add DownloadProfile endpoint with 30-second timeout and context cancellation
- Add GetCarrierStatus endpoint returning all carriers with timestamp
- Add GetProfileStatus endpoint with EID/ICCID validation
* feat: Add SM-DP+ integration layer with multi-carrier system initialization and route registration
- Add SMDPIntegration struct with service, handler, repository, and logger fields
- Add NewSMDPIntegration constructor with default carrier initialization
- Add InitializeSystem method with carrier health logging and status tracking
- Add RegisterRoutes method with profile, carrier, health, and metrics endpoints
- Add healthHandler with carrier health status aggregation and degraded state detection
- Add metricsHandler
* feat: Add SM-DP+ service layer with multi-carrier management and profile download operations
- Add SMDPService struct with manager, repository, and logger fields
- Add NewSMDPService constructor with default config and background health checking
- Add InitializeDefaultCarriers with AT&T, Verizon, and T-Mobile DE configurations
- Add DownloadProfile method with context support and request logging
- Add GetOptimalCarrier wrapping SelectCarrier for best carrier selection
- Add GetCarrierHealth returning
* feat: Add SM-DP+ manager with multi-carrier load balancing, health checking, and profile operations
- Add DefaultManagerConfig with 30s health checks, 3 retries, and circuit breaker configuration
- Add CarrierConfig struct with ES2 settings, MCC/MNC, priority, and feature support
- Add ToCarrier method converting CarrierConfig to Carrier with metrics and capabilities
- Add HealthChecker with periodic carrier health monitoring and status evaluation
- Add LoadBalancer with weighted round-robin, least
* feat: Add intelligent carrier selection service with scoring, recommendations, and analytics
- Add SelectionService struct with manager, handler, and logger fields
- Add NewSelectionService constructor with info-level logging
- Add IntelligentCarrierSelection method with comprehensive criteria evaluation
- Add IntelligentSelectionRequest with region, profile type, urgency, and cost sensitivity
- Add UserPreferences and BusinessContext structs for selection customization
- Add IntelligentSelectionResponse with selected
* feat: Add carrier selection handler with optimal selection, analytics, and performance monitoring endpoints
- Add SelectionHandler struct with manager and logger fields
- Add NewSelectionHandler constructor with info-level logging
- Add SelectOptimalCarrier endpoint with criteria validation and scoring
- Add SelectCarrier endpoint using default selection criteria
- Add GetSelectionHistory endpoint with carrier ID path parameter
- Add UpdateLearning endpoint with performance feedback validation
- Add GetSelectionAnalytics endpoint with carrier stats
* feat: Add carrier selection integration layer with multi-carrier setup, HTTP server, and demo capabilities
- Add SelectionIntegration struct with manager, selection service, handler, and SMDP service fields
- Add NewSelectionIntegration constructor with default manager config and 30s health checks
- Add SetupCarriers with AT&T, Verizon, T-Mobile DE, and Orange FR configurations
- Add StartServer method with health endpoint and 30s read/write timeouts
- Add StartHealthChecking wrapper for background
* feat: Refactor profile handlers into modular core components with simplified operations
- Split profile_handlers.go into profile_handlers_core.go, profile_handlers_management_core.go, and profile_handlers_management_delete.go
- Simplify OrderProfileHandlerWithRepo with ICCID/IMSI-only validation and "downloaded" state
- Remove webhook and message queue notifications from order handler
- Add UpdateProfileHandler with state validation for downloaded/activated/deactivated/expired
- Add DeleteProfileHandler with existence
* refactor: Extract carrier setup logic into separate file and remove unnecessary comments
- Move SetupCarriers method from selection_integration.go to new setup_carriers.go file
- Remove redundant comments from SelectionIntegration struct and methods
- Clean up inline comments in RunDemo method while preserving functionality
* feat: Add intelligent carrier selection algorithm with machine learning optimization and performance tracking
- Add SelectionAlgorithm with scoring, weighting, and ML-based carrier selection
- Add SelectionCriteria struct with region, profile type, urgency, and cost/performance weights
- Add CarrierScore with performance, reliability, cost, region, and capability scores
- Add calculateWeightedScore combining all scores with ML-optimized weights
- Add getWeights with urgency-based adjustments
* feat: Integrate SelectionAlgorithm into SMDPManager with optimal carrier selection and learning capabilities
- Add selector field to SMDPManager struct with SelectionAlgorithm type
- Initialize selector in NewSMDPManager constructor
- Add SelectOptimalCarrier method filtering healthy carriers and delegating to selection algorithm
- Add SelectCarrier wrapper with default criteria (operational profile, medium urgency, balanced weights)
- Add GetSelectionHistory method returning carrier selection history
- Add UpdateLearning
* refactor: Simplify profile handler function names by removing WithRepo suffix
- Rename ListProfilesHandlerWithRepo to ListProfilesHandler
- Rename GetProfileHandlerWithRepo to GetProfileHandler
- Rename DeleteProfileHandlerWithRepo to DeleteProfileHandler
* feat: Add pricing engine with rate plan validation, cost calculation, and price optimization
- Add PricingEngine struct with repository and logger fields
- Add ValidateRatePlan with comprehensive validation for fields, dates, allowances, overage rates, discounts, and early termination
- Add CalculateOptimalPrice with market analysis and recommended pricing based on competitor data
- Add ValidateSubscription with plan availability, validity dates, and discount validation
- Add CalculateSubscriptionCost with base
* feat: Add rate plan analytics handlers with usage, revenue, popularity, and dashboard endpoints
- Add AnalyticsResponse struct with success, message, and data fields
- Add GetUsageAnalytics with date range parsing, default last month period, and group by support
- Add GetRevenueAnalytics with RFC3339 date parsing and configurable filters
- Add GetPopularPlans with configurable limit defaulting to 10
- Add GetDashboardData aggregating top 5 popular plans, 30-day usage analytics, and revenue analytics
* feat: Add rate plan handler layer with CRUD operations, management endpoints, and analytics support
- Add RatePlanHandler struct with service and logger fields
- Add CreateRatePlan with JSON binding, draft status initialization, and comprehensive field mapping
- Add GetRatePlan with ID path parameter extraction and not found handling
- Add UpdateRatePlan with selective field updates and existing plan retrieval
- Add DeleteRatePlan with active subscription conflict detection
- Add ListRatePlans with carrier
* feat: Add rate plan type system with comprehensive domain models, allowances, subscriptions, and analytics support
- Add RatePlan struct with carrier, region, pricing, allowances, features, discounts, and validity fields
- Add PlanType enum with prepaid, postpaid, hybrid, pay-as-you-go, and unlimited options
- Add PlanStatus enum with draft, active, inactive, archived, and suspended states
- Add BillingCycle enum with daily, weekly, monthly, quarterly, and yearly options
- Add DataAllowance, VoiceAllowance, and
* feat: Add rate plan service layer with CRUD operations, subscription management, usage tracking, and analytics support
- Add Service struct with repository and logger fields
- Add CreateRatePlan with ID generation, validation, and comprehensive field checks
- Add GetRatePlan, UpdateRatePlan, and DeleteRatePlan with active subscription conflict detection
- Add ListRatePlans and SearchRatePlans with filtering and sorting support
- Add SubscribeToPlan with plan availability validation, duplicate subscription
* feat: Add carrier integration layer with optimal carrier selection, rate plan recommendations, and analytics support
- Add CarrierSelectionIntegrator struct with rate plan repository, SMDP manager, and logger fields
- Add GetOptimalCarrierWithRatePlan with region filtering, carrier grouping, performance scoring, and combined evaluation
- Add RecommendRatePlansForCarrier with carrier validation, active plan filtering, and recommendation creation
- Add UpdateCarrierSelectionCriteria with 30-day usage analytics
* feat: Add rate plan repository interface with GORM models and extended types for carrier integration
- Add Repository interface with rate plan CRUD, subscription management, usage tracking, and analytics operations
- Add GORM table name methods for RatePlan, RatePlanSubscription, and RatePlanUsage models
- Add GORM hooks with automatic timestamp handling for BeforeCreate and BeforeUpdate operations
- Add SearchCriteria with carrier, region, plan type, price range, pagination, and sorting fields
* feat: Refactor pricing engine by extracting calculation methods into separate file
- Move calculateDataOverage, calculateVoiceOverage, calculateSMSOverage, calculateDiscounts, and calculateRecommendedPrice to price_calculation.go
- Remove validation helper methods from pricing_engine.go
- Remove PriceOptimization and CostBreakdown type definitions
- Update Logger interface to use `any` instead of `interface{}`
- Remove inline comments throughout pricing_engine.go
- Add switch statement for discount type handling in calculateDiscounts
* refactor: Extract core rate plan types into separate file
- Move RatePlan struct from types.go to types_core.go
- Move PlanType enum with prepaid, postpaid, hybrid, pay-as-you-go, and unlimited options to types_core.go
- Move PlanStatus enum with draft, active, inactive, and archived states to types_core.go
- Move BillingCycle enum with daily, weekly, monthly, quarterly, and yearly options to types_core.go
- Add documentation comments for PlanType, PlanStatus, and BillingCycle enums
- Remove PlanStatusSuspended from PlanStatus enum
* feat: Add GORM repository implementation with CRUD operations, subscription management, usage tracking, and analytics support
- Add GormRepository struct with database and logger fields
- Add CreateRatePlan, GetRatePlan, UpdateRatePlan, and DeleteRatePlan with automatic timestamp handling
- Add ListRatePlans with carrier, region, plan type, status, price range, and validity filtering
- Add CountRatePlans with comprehensive filter support
- Add CreateSubscription, GetSubscription, UpdateSubscription, and DeleteSubscription with timestamp
* feat: Add carrier configuration layer with GORM repository, file loading, and model conversion support
- Add GormCarrierRepository struct with database and logger fields
- Add CarrierModel with ID, name, MCC, MNC, country code, active status, priority, ES2 config, capabilities, and timestamp fields
- Add GetCarriers with active carrier filtering and model-to-carrier conversion
- Add GetCarrier with ID lookup and not found handling
- Add SaveCarrier with upsert logic for create or update operations
* feat: Add carrier configuration file loading with JSON-based carrier setup and validation
- Add carriers.json with AT&T US, Verizon US, T-Mobile Germany, Orange France, and Vodafone UK configurations
- Add LoadCarriersFromFile with JSON parsing and config file reading
- Add ConvertConfigToCarriers with model-to-carrier conversion logic
- Add validateCarrier with ID, name, MCC, MNC, country code, and ES2 config validation
- Replace hardcoded carrier setup with file-based configuration loading
- Add success
* refactor: Extract service methods into separate files for better organization
- Move GetUsage, GetUsageHistory, GetUsageAnalytics, GetRevenueAnalytics, and GetPopularPlans to service_analytics.go
- Move validateRatePlan, validateSubscribeRequest, calculateNextBillingDate, and calculateCycleEnd to service_methods.go
- Move SubscribeToPlan, GetSubscription, UpdateSubscription, CancelSubscription, GetActiveSubscription, and ListSubscriptions to service_subscriptions.go
- Move RecordUsage to service_usage.go
* feat: Add currency configuration file with 20 major currencies and regional support
- Add currencies.json with USD, EUR, GBP, JPY, CAD, AUD, CHF, CNY, INR, BRL, MXN, SEK, NOK, DKK, SGD, HKD, NZD, ZAR, KRW, and TRY configurations
- Add currency metadata with code, name, symbol, decimal places, active status, and supported regions
- Add regional mappings for currency support across multiple countries and territories
* feat: Add currency analytics service with revenue tracking, transaction analysis, and usage statistics
- Add AnalyticsServiceImpl struct with repository and logger fields
- Add GetRevenueByCurrency with completed transaction filtering and revenue aggregation by currency
- Add GetTransactionVolumeByCurrency with transaction count grouping
- Add GetExchangeRateTrends with historical rate retrieval and date-based filtering
- Add GetCurrencyUsageStats with total/active currency counts, transaction volume
* feat: Add multi-currency billing service with transaction processing, currency conversion, and history tracking
- Add BillingServiceImpl struct with repository, exchange service, logger, and base currency fields
- Add NewBillingService constructor with dependency injection
- Add ProcessBilling with request validation, currency conversion, transaction creation, and payment processing
- Add ConvertAmount wrapper delegating to exchange service
- Add GetBillingHistory with profile ID filtering and transaction retries
* feat: Add exchange rate service with multi-provider support, currency conversion, and historical rate tracking
- Add ExchangeRateService struct with repository, logger, providers, and base currency fields
- Add NewExchangeRateService constructor and AddProvider for provider registration
- Add GetExchangeRate with repository caching, provider fallback, and same-currency handling
- Add ConvertAmount wrapper with exchange rate retrieval and amount calculation
- Add RefreshRates with multi-provider rate
* refactor: Extract currency interfaces and GORM models into separate files
- Move Repository, ExchangeRateProvider, BillingService, and AnalyticsService interfaces from types.go to new interface.go
- Move BillingSummary and CurrencyUsageStats structs to interface.go
- Move CurrencyModel, ExchangeRateModel, and TransactionModel to new models.go
- Move GORM hooks (BeforeCreate, BeforeUpdate) and TableName methods to models.go
- Remove redundant comments from exchange_rate_service.go
* feat: Add rate plan currency integrator with subscription creation, cost calculation, and multi-currency billing support
- Add RatePlanCurrencyIntegrator struct with billing service, exchange service, rate plan service, logger, and base currency fields
- Add NewRatePlanCurrencyIntegrator constructor with dependency injection
- Add SubscribeToPlanWithCurrency with price conversion, subscription creation, and initial billing processing
- Add CalculatePlanCostInCurrency with base cost calculation
* feat: Add currency repository with GORM implementation, rate plan integration, and transaction management
- Add GormRepository with CRUD operations for currencies, exchange rates, and transactions
- Add repository helper methods for model-to-domain conversions with JSON metadata handling
- Add GetHistoricalRates with date range filtering and chronological ordering
- Add ListExchangeRates with currency pair, active status, and date range filtering
- Add CreateTransaction, GetTransaction, UpdateTransaction, and List
* feat: Add currency handler layer with conversion, billing, exchange rates, and analytics endpoints
- Add CurrencyHandler struct with billing service, exchange service, and logger fields
- Add ConvertCurrency endpoint with JSON binding and amount conversion support
- Add GetExchangeRate endpoint with currency pair path parameters
- Add ProcessBilling endpoint with billing request validation and transaction processing
- Add GetBillingHistory with profile ID filtering, date range, limit, and offset support
* refactor: Rename service package to services and move repository implementations to repository package
- Rename internal/service to internal/services in carrier-connector
- Update service imports in selection_integration.go and smdp_integration.go
- Move currency repository files from internal/currency to internal/repository
- Move rate plan repository files from internal/rateplan to internal/repository
- Update package declarations and imports for currency domain types
- Add currency package imports
* refactor: Add ExchangeRateService interface and format currency types with consistent alignment
- Add ExchangeRateService interface with GetExchangeRate, ConvertAmount, GetRateHistory, UpdateExchangeRate, GetSupportedCurrencies, ValidateCurrencyPair, and RefreshRates methods
- Add CurrencyRevenue struct with currency and revenue fields
- Add TransactionTypeStats struct with type, count, amount, and currency fields
- Align struct field tags consistently across Currency, ExchangeRate, Transaction, and request/response types
* refactor: Update service layer to use repository package types and align imports
- Update Service struct to use repository.Repository interface
- Update all method signatures to use repository package types (RatePlan, RatePlanSubscription, RatePlanUsage, etc.)
- Update filter and request types to use repository package (RatePlanFilter, SubscriptionFilter, CalculateCostRequest, etc.)
- Update status constants to use repository package (SubscriptionStatusActive, PlanStatusActive, DiscountTypePercentage, DiscountTypeFixed)
* refactor: Update handler constructors to use interface types instead of concrete implementations
- Update CurrencyHandler.exchangeService field from *currency.ExchangeRateService to currency.ExchangeRateService interface
- Update NewCurrencyHandler parameter from *currency.ExchangeRateService to currency.ExchangeRateService interface
- Update RatePlanHandler.service field from *rateplan.Service to rateplan.Service interface
- Update NewRatePlanHandler parameter from *rateplan.Service to rateplan.Service interface
* refactor: Rename currency parameter from 'currency' to 'curr' in currencyToModel helper method and add Service interface to rate plan package
- Rename currency parameter to curr in GormRepository.currencyToModel to avoid shadowing currency package name
- Add Service interface with rate plan, subscription, usage, and analytics operations
- Add CreateRatePlan, GetRatePlan, UpdateRatePlan, DeleteRatePlan, ListRatePlans, and SearchRatePlans methods
- Add SubscribeToPlan, GetSubscription, UpdateSubscription, CancelSubscription, GetActiveSubscription, and ListSubscriptions methods
- Add Rec
* feat: Add repository types package with rate plan, subscription, usage, and analytics domain models
- Add Repository interface with rate plan CRUD, subscription management, usage tracking, and analytics operations
- Add RatePlan struct with pricing, allowances, overage rates, discounts, and metadata fields
- Add RatePlanSubscription struct with billing cycle, auto-renewal, and applied discounts support
- Add RatePlanUsage struct with cycle tracking and data/voice/SMS usage metrics
- Add filter types for rate plans, subscriptions, usage analytics, and revenue analytics
* feat: Add tenant handler layer with CRUD, user management, API keys, and analytics endpoints
- Add TenantHandler struct with tenant service and logger fields
- Add CreateTenant, GetTenant, GetTenantByDomain, UpdateTenant, DeleteTenant, and ListTenants endpoints
- Add AddUserToTenant, GetTenantUser, UpdateTenantUser, RemoveUserFromTenant, and ListTenantUsers endpoints
- Add CreateAPIKey, GetAPIKey, UpdateAPIKey, DeleteAPIKey, and ListAPIKeys endpoints with key string return on creation
* feat: Add tenant analytics service with dashboard, usage, performance, cost analytics, and comprehensive reporting
- Add TenantAnalyticsService struct with repository, metrics collector, event publisher, and logger fields
- Add GetTenantDashboard with usage stats, metrics, recent events, and quota status aggregation
- Add GetTenantMetrics with active users, request tracking, error rate calculation, response time analysis, and health score computation
- Add GetUsageAnalytics with time range filtering, resource type breakdown
* feat: Add tenant types package with filters, requests, usage stats, events, and metrics domain models
- Add TenantFilter with ID, name, domain, status, plan, pagination, and sorting fields
- Add CreateTenantRequest, UpdateTenantRequest with plan, limits, settings, and metadata support
- Add TenantUserFilter, CreateTenantUserRequest, UpdateTenantUserRequest with role and status management
- Add CreateAPIKeyRequest, UpdateAPIKeyRequest with permissions, rate limits, and expiration support
- Add TenantUs
* feat: Add tenant integration layer with repository wrapper, service manager, quota checker, and event logger
- Add TenantAwareCurrencyRepository wrapper with tenant isolation for all currency repository methods
- Add NewTenantAwareCurrencyRepository and WithTenant methods for tenant context management
- Add TenantIntegrationManager with GetTenantAwareServices for tenant validation and configuration
- Add TenantAwareServices struct with tenant context, config, and currency service fields
- Add TenantResourceQuotaChecker
* feat: Add tenant package interfaces with repository, service, middleware, and supporting components
- Add Repository interface with tenant CRUD, user management, API keys, usage tracking, config, and event operations
- Add Service interface with tenant management, user operations, API key handling, quota checking, config management, authentication, and analytics methods
- Add Middleware interface with request extraction, access validation, context injection, rate limiting, and resource isolation
* feat: Add tenant middleware with authentication, authorization, isolation, and activity logging
- Add TenantMiddleware struct with tenant service and logger fields
- Add ExtractTenantFromHeader and ExtractTenantFromAPIKey methods for tenant identification from headers, subdomains, and API keys
- Add RequireTenant middleware with header and API key extraction fallback and tenant access validation
- Add RequireTenantRole middleware with role-based access control for multiple required roles
* feat: Add tenant domain models with multi-tenancy support, user management, usage tracking, and API key authentication
- Add Tenant struct with plan, limits, settings, and metadata fields
- Add TenantStatus constants (active, inactive, suspended, deleted)
- Add TenantPlan constants (free, basic, pro, enterprise)
- Add TenantSettings with currency, feature flags, rate limiting, security, and compliance configuration
- Add PasswordPolicy struct with length, character requirements, and age settings
* feat: Add tenant repository implementation with GORM-based data access layer for multi-tenancy support
- Add GormTenantRepository struct with GORM database field
- Add CreateTenant, GetTenant, GetTenantByDomain, UpdateTenant, DeleteTenant methods with context support
- Add ListTenants and CountTenants with filtering by ID, name, domain, status, plan, sorting, and pagination
- Add CreateTenantUser, GetTenantUser, UpdateTenantUser, DeleteTenantUser methods for user management
- Add ListTenantUsers and
* feat: Add tenant service extended methods with quota management, usage tracking, permissions, and metrics collection
- Add CheckQuota method with quota limit validation, unlimited quota support (-1), and quota exceeded event logging
- Add GetUsageStats with resource breakdown, quota status calculation, warning/critical thresholds, and active user counting
- Add UpdateUsage with automatic usage record creation and existing record updates
- Add GetQuotaStatus, GetTenantConfig, UpdateTenantConfig, Get
* feat: Add tenant service implementation with CRUD operations, user management, API key handling, and event logging
- Add ServiceImpl struct with repository, rate limiter, event publisher, config manager, audit logger, metrics collector, and logger fields
- Add CreateTenant with validation, domain uniqueness check, default settings/quotas/features initialization, and tenant created event
- Add GetTenant, GetTenantByDomain, UpdateTenant, DeleteTenant, and ListTenants methods with event logging
* feat: Add tenant-aware repository layer with isolation, validation, query building, and resource access control
- Add TenantAwareRepository with GORM database and tenant ID fields
- Add NewTenantAwareRepository, WithTenant, GetTenantID, ValidateTenant methods for tenant context management
- Add TenantScopedQuery and TenantScopedTransaction for tenant-isolated database operations
- Add CreateWithTenant, GetByTenantID, UpdateWithTenant, DeleteWithTenant, ListWithTenant, CountWithTenant helper methods
- Add TenantA
* refactor: Move tenant repository files to repository package and update imports
- Move tenant_aware_repository.go from internal/tenant to internal/repository package
- Move repository.go to tenant_repository.go in internal/repository package
- Add tenant package import for type references in tenant_repository.go
- Update filter type references to use tenant package prefix (TenantFilter, TenantUserFilter, TenantUsageFilter)
- Update return type for GetUsageStats to use tenant.TenantUsageStats
* feat: Add tenant integration layer with repository wrapper, analytics types, and performance monitoring
- Add TenantAwareCurrencyRepository wrapper with tenant isolation for all currency repository methods
- Add NewTenantAwareCurrencyRepository and WithTenant methods for tenant context management
- Add TenantIntegrationManager with GetTenantAwareServices for tenant validation and configuration
- Add TenantAwareServices struct with tenant context, config, and currency service fields
- Add TenantResource
* feat: Add currency analytics, billing, and exchange rate services with multi-currency support and transaction processing
- Add AnalyticsServiceImpl with revenue/volume analysis, exchange rate trends, usage stats, and transaction type analytics
- Add GetRevenueByCurrency, GetTransactionVolumeByCurrency, GetExchangeRateTrends, GetCurrencyUsageStats methods
- Add GetMonthlyRevenueTrends, GetTopCurrenciesByRevenue, GetTransactionTypeAnalytics for reporting
- Add BillingServiceImpl with multi-currency billing, payment
* refactor: Update tenant integration to use concrete service types and tenant package imports
- Change TenantIntegrationManager.tenantService from Service interface to *services.TenantServiceImpl concrete type
- Change TenantResourceQuotaChecker.tenantService from Service interface to *services.TenantServiceImpl
- Change TenantEventLogger.tenantService from Service interface to *services.TenantServiceImpl
- Update TenantAwareServices fields to use tenant package types (TenantContext, TenantConfig)
* feat: Add TenantRepository interface with CRUD operations, user management, API keys, usage tracking, and event logging
- Add TenantRepository interface with CreateTenant, GetTenant, GetTenantByDomain, UpdateTenant, DeleteTenant, ListTenants, CountTenants methods
- Add CreateTenantUser, GetTenantUser, UpdateTenantUser, DeleteTenantUser, ListTenantUsers, CountTenantUsers for user management
- Add CreateAPIKey, GetAPIKey, GetAPIKeyByHash, UpdateAPIKey, DeleteAPIKey, ListAPIKeys for API key operations
* refactor: Extract ES2 types from client.go to separate types.go file
- Move ES2Client struct definition from client.go to types.go
- Move DownloadProfileRequest, DownloadProfileResponse, GetProfileStatusRequest, GetProfileStatusResponse types to types.go
- Move DeleteProfileRequest, DeleteProfileResponse, EnableProfileRequest, EnableProfileResponse types to types.go
- Move DisableProfileRequest, DisableProfileResponse types to types.go
- Add net/http, time, and config package imports to types.go
* refactor: Move tenant repository implementation to tenant package and update imports
- Move GormTenantRepository implementation from repository package to tenant package
- Move TenantResourceValidator from repository to tenant package
- Update tenant_aware_repository.go to import tenant package for Tenant and TenantStatusActive types
- Remove duplicate tenant model definitions and helper methods from repository package
- Update ValidateTenant to use tenant.Tenant and tenant.TenantStatusActive types
* refactor: Refactor tenant and rate plan services with improved code organization and currency integration updates
- Update RatePlanCurrencyIntegrator to use billingService.ConvertAmount with CurrencyConversionRequest struct instead of exchangeService
- Remove calculateOverageCost method from rateplan_methods.go (moved or deprecated)
- Rename tenant variable to newTenant in CreateTenant to avoid shadowing
- Extract tenant user methods from tenant_user.go to new tenant_user_methods.go file
* refactor: Add rate plan currency integration service and update tenant repository with user count method
- Add RatePlanCurrencyIntegrator with SubscribeToPlanWithCurrency, CalculatePlanCostInCurrency, calculateOverageCost methods
- Add NewRatePlanCurrencyIntegrator constructor with billingService, exchangeService, ratePlanService, logger, baseCurrency fields
- Add currency conversion support for rate plan subscriptions with exchange rate metadata tracking
- Add billing integration for initial subscription
* refactor: Replace map[string]interface{} with map[string]any across currency, handlers, integration, and rateplan packages
- Update BillingSummary.Breakdown field type from map[string]interface{} to map[string]any
- Update Transaction.Metadata field type from map[string]interface{} to map[string]any
- Update RatePlanCurrencyIntegrator subscription and billing metadata to use map[string]any
- Update handler request/response types to use map[string]any (CreateRatePlanRequest, UpdateRatePlanRequest,
* refactor: Implement tenant analytics dashboard and usage analytics with helper methods
- Implement GetTenantDashboard with usage stats, metrics, recent events, and quota status
- Implement GetUsageAnalytics with usage by type, trends, and peaks
- Implement GetPerformanceAnalytics with API performance, resource performance, errors, and slow queries
- Extract helper methods to tenant_analytics_mock.go: parseTimeRange, parseAPIRequestEvent, parseErrorEvent, parseSlowQueryEvent, calculateAPIPerformance, build
* refactor: Remove unused rate plan currency integrator and tenant analytics mock helper methods
- Delete RatePlanCurrencyIntegrator implementation from rateplan_core.go
- Delete SubscribeToPlanWithCurrency, CalculatePlanCostInCurrency, calculateOverageCost methods
- Delete tenant analytics mock helper methods from tenant_analytics_mock.go
- Remove getMockResourceCount, getMockQuotaLimit, getMockQuotaUsed, parseTimeRange methods
- Remove parseAPIRequestEvent, parseErrorEvent, parseSlowQueryEvent, calculateAPI
* feat: Add pricing handlers with CRUD operations, rule application, price calculation, and analytics endpoints
- Add PricingHandler with CreateRule, GetRule, UpdateRule, DeleteRule, ListRules methods
- Add CalculatePrice endpoint for price calculation based on active rules
- Add ApplyRules endpoint for applying specific pricing rules to context
- Add GetAnalytics endpoint for retrieving pricing analytics by tenant
- Add RegisterRoutes method to register pricing routes under /pricing group
* feat: Add Snowflake ID generator with thread-safe generation, parsing utilities, and default generator
- Add Snowflake struct with mutex, timestamp, nodeID, sequence fields
- Add NewSnowflake constructor with nodeID validation (0 to MaxNodeID range)
- Add Generate method with sequence overflow handling and millisecond-based timestamp
- Add GenerateString method for string representation of generated IDs
- Add Parse, Time, NodeID, Sequence utility functions for ID decomposition
- Add defaultGenerator
* refactor: Extract tenant integration helper types to separate file and replace ID generation with id package
- Move TenantAwareServices, TenantResourceQuotaChecker, TenantEventLogger from tenant_integration.go to tenant_integration_core.go
- Move wrapCurrencyService, NewTenantResourceQuotaChecker, NewTenantEventLogger, CheckQuota, UpdateUsage methods to tenant_integration_core.go
- Move LogResourceAccess, LogQuotaViolation methods to tenant_integration_core.go
- Replace generateID helper with id.
* feat: Add pricing interfaces and types for dynamic pricing rule management
- Add Repository interface with CreateRule, GetRule, UpdateRule, DeleteRule, ListRules, CountRules methods
- Add GetActiveRules, GetRulesByType methods for rule evaluation
- Add Service interface with rule management, pricing calculations, validation, and analytics methods
- Add RuleEngine interface with EvaluateRule, ApplyRule, ValidateConditions, ExecuteActions methods
- Add PricingEventHandler interface for rule lifecycle events
- Add PricingValidator interface for rule and context validation
- Add PricingCache interface for caching pricing data
* refactor: Refactor tenant analytics to use repository data and extract helper methods to separate files
- Move parseAPIRequestEvents, buildResourcePerformance, parseErrorEvents, parseSlowQueryEvents from tenant_analytics_mock.go to tenant_analytics.go
- Update buildUsageByType to fetch usage statistics from repository instead of using mock data
- Add calculateResourceUsageAnalytics helper to calculate analytics from usage records
- Update buildUsageTrends to use repository data with buildUsageTrendData helper
- Update buildUsagePeaks to use repository data with buildUsagePeakData helper
* feat: Add pricing repository, tenant-aware transaction support, and pricing integration service
- Add GormPricingRepository with CreateRule, GetRule, UpdateRule, DeleteRule, ListRules, CountRules methods
- Add GetActiveRules, GetRulesByType methods for retrieving active pricing rules by tenant and type
- Add TenantScopedDB wrapper with automatic tenant filtering for tenant-aware database operations
- Implement TenantScopedTransaction with tenant context propagation and automatic filtering
* refactor: Extract helper methods, fix formatting, and add TODO comments for pending implementations
- Extract generateHistoryAnalytics helper in selection_handler_methods.go
- Extract generateRecommendations helper in selection_handler_selection.go
- Extract parsePositiveInt helper in rateplan_handlers_analytics.go
- Replace hardcoded URL path with action parameter in ES2Service.sendActivationRequest
- Add TODO comments for wrapCurrencyService and updateCarrierWeights pending implementations
- Fix struct field alignment and formatting in carrier_methods.go
* refactor: Replace time and ID generation helpers with centralized id package utilities
- Replace getCurrentTime() calls with id.GetCurrentTime() in pricing_integration.go and pricing_service.go
- Replace generateRuleID() with id.GenerateRuleID() in pricing rule creation
- Replace generateEventID() with id.GenerateEventID() in tenant middleware
- Remove local helper functions: generateRuleID, getCurrentTime, generateEventID, generateRandomString, getCurrentTimestamp
- Remove unused time package imports
* feat: Add ID generation utilities with rule ID, event ID, and random string generators
- Add GenerateRuleID function using nanosecond timestamp
- Add GetCurrentTime helper returning current time
- Add GenerateEventID function with "evt_" prefix and 16-character random string
- Add GenerateRandomString function with alphanumeric charset
* feat: Refactor ID generation to use Snowflake IDs with prefixes and add domain-specific ID generators
- Replace timestamp-based GenerateRuleID with Snowflake-based GeneratePrefixed("rule")
- Replace random string-based GenerateEventID with Snowflake-based GeneratePrefixed("evt")
- Add GenerateUsageID with resourceType and tenantID parameters for traceable usage IDs
- Add GenerateAPIID, GenerateTenantID, GenerateProfileID, GenerateSubscriptionID, GenerateCarrierID, GeneratePricingID generators
* feat: Add tenant-aware rate limiter with sliding window counters and plan-based limits
- Add TenantRateLimiter with plan-based rate limits for Free, Basic, Pro, and Enterprise tiers
- Add RateLimit struct with RequestsPerMinute, RequestsPerHour, RequestsPerDay, and BurstSize fields
- Add TenantUsageTracker with sliding window counters for minute, hour, and day tracking
- Add SlidingWindowCounter with Allow and Count methods for time-based request tracking
- Add AllowRequest method with multi-tier rate limit
* feat: Implement tenant-aware currency service wrapper with billing isolation and audit logging
- Add TenantAwareCurrencyService struct with tenantID, billingService, and logger fields
- Add ProcessBilling method with tenant context logging for billing requests
- Add ConvertAmount method with tenant context logging for currency conversions
- Add GetBillingHistory method with tenant context logging for transaction retrieval
- Add CalculateTotalBilling method with tenant context logging for billing summ
* feat: Implement carrier weight updates, pricing analytics calculations, and tenant rate limiting
- Add updateCarrierWeights implementation with regional and plan-based weight adjustments in carrier_methods.go
- Add calculateRegionalWeightAdjustment helper with usage-based weight scaling and clamping
- Add calculatePlanWeightAdjustment helper with plan usage analysis and adjustment limits
- Add calculateConversionRate helper in pricing_integration.go using discount statistics and active rule ratios
* feat: Implement refund processing and billing analytics endpoints in currency handlers
- Add ProcessRefund implementation with negative billing entry for refunds and transaction ID fallback
- Add GetBillingAnalytics implementation with date range filtering, billing summary calculation, and transaction history
- Add default 30-day date range for analytics with RFC3339 date parsing for custom ranges
- Replace NotImplemented responses with full BillingService integration
* feat: Implement carrier metrics persistence with dedicated metrics table and timestamp updates
- Replace mock logging with actual database persistence in UpdateCarrierMetrics
- Add carrier record timestamp update with updated_at field
- Add carrier_metrics table insertion with JSON-serialized metrics data
- Add metricsRecord struct with CarrierID, MetricsData, and RecordedAt fields
- Add zero-division protection for success rate calculation
- Update logging to use structured fields with WithField
* feat: Add tenant context injection to currency service methods for downstream isolation
- Replace TODO comments with context.WithValue calls injecting tenant_id in ProcessBilling
- Add tenant context injection in ConvertAmount for tenant-specific exchange rates
- Add tenant context injection in GetBillingHistory for repository-level filtering
- Add tenant context injection in CalculateTotalBilling for scoped calculations
- Update comments to reflect context-based isolation strategy
* feat: Implement rate limiting and resource access validation in tenant middleware
- Add RateLimit implementation with tenant context retrieval and plan-based rate limit checking
- Add rate limit exceeded logging with tenant_id and endpoint fields
- Add HTTP 429 response with error message and endpoint when rate limit exceeded
- Add ValidateResourceAccess implementation with tenant ownership verification
- Add context injection for validated_resource, validated_resource_id, and tenant_id
* refactor: Extract CRUD operations from pricing service into separate file and improve discount extraction logic
- Move CreateRule, GetRule, UpdateRule, DeleteRule, ListRules, CalculatePrice, and ApplyRules to pricing_service_crud.go
- Remove duplicate struct and constructor comments from pricing_service.go
- Replace hardcoded discount values in extractDiscountValue with actual rule Actions field parsing
- Add AdjustmentType-based discount calculation for Percentage, Fixed, Multiply, and Override
* feat: Implement MCC-based regional scoring with geographic grouping for carrier selection
- Replace neutral 50.0 score with MCC-to-region mapping logic in calculateRegionScore
- Add mccToRegion function mapping MCC first digit to region codes (EU, NA, AS, OC, AF, SA)
- Add sameRegionGroup function grouping regions into EMEA, AMER, and APAC clusters
- Add 90.0 score for exact MCC region match, 70.0 for same region group, 30.0 for distant regions
- Add MCC range documentation for Europe (2xx), North America (3xx
* feat: Implement revenue analytics calculation, resource performance tracking, and round-robin load balancing
- Add revenue calculation in GetRevenueAnalytics with active subscription base price aggregation
- Add date range filtering for revenue analytics with StartDate and EndDate support
- Add per-plan revenue, subscription count, and average revenue calculations
- Add error handling with partial result fallback for revenue queries
- Replace mock resource performance with event-based performance
* refactor: Replace interface{} with any and optimize slice operations
- Replace map[string]interface{} with map[string]any in UpdateCarrierMetrics
- Replace interface{} with any for GeneratedAt field in PricingEffectiveness struct
- Replace loop-based empty string checks with slices.Contains in ValidateConditions
- Replace range loop index initialization with range-only syntax in calculateAPIPerformance
- Add slices import for standard library slice utilities
* refactor: Update comments in tenant repository to reflect actual implementation
- Replace vague "separate table or log system" comment with specific tenant_events table reference in CreateEvent
- Replace "For now, update tenant settings" with clearer "Store configuration in tenant metadata field and update settings" in UpdateConfig
- Remove "For now, we'll use a simple approach" qualifier from CreateEvent comment
* feat: Add MVNO HTTP handlers with onboarding, management, and statistics endpoints
- Add Handler struct with StartOnboarding, GetMVNO, and ListMVNOs methods in handler.go
- Add ManagementHandler struct with GetMVNO, ListMVNOs, UpdateMVNOStatus, and GetMVNOStats methods in handler_management.go
- Add RegisterRoutes method for /mvno/onboarding, /mvno, and /mvno/:id route registration
- Add query parameter parsing for status, plan, and limit filters in ListMVNOs
- Add structured logging with mvno_id, status, and error
* feat: Add MVNO onboarding validator with business, plan, and technical validation
- Add OnboardingValidator struct with ValidateRequest and ValidateMVNO methods in validator.go
- Add business info validation with name length, ID format, email regex, and phone length checks
- Add plan validation with subscriber limits for Starter (1000) and Growth (10000) plans
- Add technical requirements validation with country code format and use case length checks
- Add compliance validation with country-specific regulatory checks and restricted country filtering
- Add technical feasibility validation
* feat: Add MVNO domain types with status, plan, config, and onboarding request models
- Add MVNO struct with ID, Name, BusinessID, Status, Plan, Config, and timestamps
- Add MVNOStatus enum with pending, review, approved, active, suspended, and terminated states
- Add MVNOPlan enum with starter, growth, scale, and enterprise tiers
- Add MVNOConfig struct with subscriber limits, country restrictions, carrier pool, and feature flags
- Add OnboardingRequest struct with business info, contact details, plan selection
* feat: Add MVNO onboarding monitor with progress tracking and metrics collection
- Add OnboardingMonitor struct with progress map and mutex for concurrent access
- Add UpdateProgress and GetProgress methods for tracking individual MVNO onboarding state
- Add GetAllProgress with map copy to prevent concurrent access issues
- Add GetActiveOnboardingCount and GetCompletedOnboardingCount for status aggregation
- Add GetAverageOnboardingTime calculation with completed onboarding duration tracking
- Add GetStepSuccess
* feat: Add MVNO onboarding service with step-based workflow execution and progress tracking
- Add OnboardingService struct with validator, provisioner, and monitor dependencies
- Add StartOnboarding method with request validation, MVNO record creation, and async workflow execution
- Add executeOnboarding method with sequential step processing, context cancellation support, and progress updates
- Add executeStep method with switch-based routing for validation, provisioning, carrier setup, billing
* feat: Add MVNO repository with CRUD operations, filtering, and statistics aggregation
- Add Repository interface with CreateMVNO, GetMVNO, UpdateMVNO, ListMVNOs, DeleteMVNO, and UpdateMVNOStatus methods
- Add GormRepository struct with db and logger dependencies for GORM-based persistence
- Add MVNOFilter struct with status, plan, business_id, limit, offset, and date range filtering
- Add GetMVNO and GetMVNOByBusinessID methods with record not found error handling
- Add ListMVNOs with dynamic query
* feat: Add MVNO provisioner with resource provisioning, carrier setup, billing, and API access configuration
- Add MVNOProvisioner struct with logger dependency for resource provisioning operations
- Add ProvisionResources method with tenant context, database schema, and storage provisioning
- Add SetupCarriers method with carrier selection, configuration, and carrier pool assignment
- Add SetupBilling method with billing ID generation, rate plan configuration, and payment processing setup
- Add SetupAPIAcc
* feat: Add MVNO router with route setup, middleware configuration, and health check endpoint
- Add Router struct with handler and logger dependencies for routing configuration
- Add NewRouter constructor with repository, service, and handler initialization
- Add SetupRoutes method with /api/v1 versioning, logging, and recovery middleware
- Add SetupMiddleware with CORS headers, rate limiting placeholder, and request ID tracking
- Add HealthCheck method with service status, name, and version response
* feat: Add MVNO provisioner methods with tenant setup, resource allocation, carrier configuration, and validation
- Add provisionTenantContext with tenant config creation, settings mapping, and tenant service integration
- Add provisionDatabaseSchema with dedicated schema creation for MVNO isolation
- Add provisionStorageResources with plan-based storage allocation (10GB to 10TB)
- Add selectCarriers with country-based carrier selection, active status filtering, and duplicate prevention
- Add config
* feat: Add production MVNO provisioner with tenant, carrier, billing, and API access setup
- Add ProductionProvisioner struct with tenant, carrier, billing, and storage service dependencies
- Add TenantService, CarrierManager, BillingService, and StorageService interfaces for external integrations
- Add TenantConfig and CarrierInfo structs for tenant and carrier data models
- Add NewProductionProvisioner constructor with service dependency injection
- Add ProvisionResources method with tenant context
* feat: Add carrier-connector HTTP handlers with MVNO onboarding, management, and statistics endpoints
- Add Handler struct with StartOnboarding, GetMVNO, and ListMVNOs methods in handler_mvno.go
- Add ManagementHandler struct with GetMVNO, ListMVNOs, UpdateMVNOStatus, and GetMVNOStats methods in handler_management.go
- Add RegisterRoutes method for /mvno/onboarding, /mvno, and /mvno/:id route registration
- Add query parameter parsing for status, plan, and limit filters in ListMVNOs
- Add structured logging
* feat: Refactor MVNO handlers to use domain types and interface-based service dependency
- Rename Handler to MVNOHandler for clarity in handler_mvno.go
- Replace services.OnboardingService with OnboardingService interface for dependency injection
- Change monitor.OnboardingRequest, monitor.MVNOStatus, monitor.MVNOFilter, and monitor.MVNOPlan to mvno package types
- Remove monitor package import from handler_management.go and handler_mvno.go
- Add context.Context import for service method signatures
* feat: Add MVNO onboarding service with step-based workflow execution and progress tracking
- Add OnboardingService struct with validator, provisioner, and monitor dependencies
- Add NewOnboardingService constructor with logger dependency injection
- Add StartOnboarding method with request validation, MVNO record creation, and async workflow execution
- Add executeOnboarding method with sequential step processing, context cancellation support, and progress updates
- Add executeStep method with switch
* feat: Refactor step status checking from if-else to switch statement in GetStepSuccessRate
- Replace if-else chain with switch statement for step.Status evaluation in monitor.go
- Maintain completed and failed case handling with cleaner control flow
* feat: Extract repository interfaces from types.go into separate interfaces.go file
- Move TenantRepository and Repository interfaces from types.go to new interfaces.go file
- Add mvno package import for MVNO-related repository methods
- Add CreateMVNO, GetMVNO, GetMVNOByBusinessID, UpdateMVNO, ListMVNOs, DeleteMVNO, UpdateMVNOStatus, and GetMVNOStats methods to Repository interface
- Remove context import from types.go after interface extraction
* feat: Add MVNO repository with CRUD operations, filtering, and statistics aggregation
- Add MVNORepository implementation with CreateMVNO, GetMVNO, UpdateMVNO, ListMVNOs, DeleteMVNO, and UpdateMVNOStatus methods
- Add MVNOFilter struct with status, plan, business_id, limit, offset, and date range filtering
- Add GetMVNO and GetMVNOByBusinessID methods with record not found error handling
- Add ListMVNOs with dynamic query building, filter application, and descending created_at ordering
- Add GetMVNOStats with total count, status distribution, and plan distribution aggregation
* feat: Reorder OnboardingProgress and OnboardingStep structs and add MVNOFilter type
- Move OnboardingProgress struct definition before OnboardingStep for logical ordering
- Add MVNOFilter struct with status, plan, business_id, limit, offset, and date range filtering fields
* feat: Add logger dependency to SelectionService and refactor handler initialization
- Add logrus import and logger initialization in NewSelectionIntegration
- Pass logger instance to NewSelectionService constructor
- Replace selectionService.GetHandler() with direct handlers.NewSelectionHandler(manager) call
* feat: Remove MVNO handlers, service, and repository implementations from carrier-connector
- Delete handler.go with StartOnboarding, GetMVNO, ListMVNOs, and RegisterRoutes methods
- Delete handler_management.go with GetMVNO, ListMVNOs, UpdateMVNOStatus, and GetMVNOStats endpoints
- Delete onboarding_service.go with StartOnboarding, executeOnboarding, executeStep workflow orchestration
- Delete repository.go with GormRepository CRUD operations, filtering, and statistics methods
- Update provisioner.go to use map[string]any instead of map[string]interface{}
* feat: Remove MVNO router and add placeholder endpoints to main routes
- Delete router.go with Router struct, NewRouter constructor, SetupRoutes, SetupMiddleware, HealthCheck, and RegisterHealthCheck methods
- Add /mvno route group with POST /onboarding, GET /, GET /:id, PUT /:id/status, and GET /stats placeholder endpoints
- Replace router-based MVNO setup with direct route registration returning http.StatusNotImplemented responses
* feat: Wire MVNO handlers with repository and service dependencies in carrier-connector routes
- Add logrus and gorm imports to main.go for MVNO infrastructure setup
- Create logger instance and separate database connection for MVNO repository in main
- Initialize GormRepository with database connection and logger
- Pass repo and logger to setupRoutes for MVNO handler initialization
- Replace placeholder MVNO endpoints with actual handler methods in routes.go
- Create OnboardingService, MVNOHandler, and ManagementHandler instances
* feat: Add comprehensive routing for rate plans, pricing, currency, tenants, SMDP, and selection endpoints
- Add db parameter to setupRoutes function signature and pass from main.go
- Add rate plan routes with CRUD, search, subscription, and management endpoints using RatePlanAdapter
- Add pricing routes with rule management endpoints using PricingService
- Add currency routes with conversion, exchange rates, billing operations, and analytics placeholder endpoints
- Add tenant routes with management
* feat: Add RatePlanAdapter with CRUD operations, subscription management, usage tracking, and analytics
- Add RatePlanAdapter struct wrapping Service to implement rateplan.Service interface
- Add NewRatePlanAdapter constructor returning rateplan.Service
- Add CreateRatePlan, GetRatePlan, UpdateRatePlan, DeleteRatePlan, ListRatePlans, SearchRatePlans, and GetPopularPlans methods with type conversions
- Add SubscribeToPlan, GetSubscription, UpdateSubscription, CancelSubscription, GetActiveSubscription
* feat: Extract domain route registration from setupRoutes into separate functions in routes_domain.go
- Move rate plan, pricing, currency, tenant, and SMDP route registration from routes.go to new routes_domain.go file
- Add registerMVNORoutes, registerRatePlanRoutes, registerPricingRoutes, registerCurrencyRoutes, registerTenantRoutes, and registerSMDPRoutes functions
- Simplify setupRoutes to call domain-specific registration functions with required dependencies
- Remove nested route group blocks in favor
* refactor: Replace unused context parameters with blank identifiers and fix variable references
- Replace ctx parameter with _ in provisionTenantContext, provisionDatabaseSchema, provisionStorageResources, configureCarrier, configureRatePlans, setupPaymentProcessing, and validateCompliance methods
- Fix tenant_id scope to use wrappedTx.tenantID instead of r.tenantID in TenantScopedTransaction
- Fix pricing effectiveness analytics to use ratePlanAnalytics.AverageDiscount and ratePlanAnalytics.TotalSavings instead of analytics.
* feat: Add analytics service with dashboard metrics, revenue tracking, and scheduled reporting
- Add Service struct with GetDashboard, GetRevenueAnalytics, CreateScheduledReport, and ListScheduledReports methods
- Add getRevenueMetrics, getSubscriberStats, getUsageMetrics, getCarrierMetrics, getGeoMetrics, and getPerformanceStats helper methods
- Add DashboardMetrics, RevenueMetrics, SubscriberStats, UsageMetrics, CarrierMetrics, GeoMetrics, and PerformanceStats types
- Add CarrierStat, CountryStat, RegionStat
* feat: Add compliance service with DSR management, consent tracking, audit logging, and data residency
- Add Service struct with db and logger dependencies and NewService constructor
- Add CreateDSR, GetDSR, ListDSRs, and ProcessDSR methods for data subject request lifecycle management
- Add processAccessRequest, processErasureRequest, processRectificationRequest, and calculateDueDate helper methods
- Add RecordConsent, RevokeConsent, and GetConsents methods for consent management
- Add LogAudit
* feat: Add in-memory cache with TTL, LRU eviction, JSON serialization, and statistics tracking
- Add Cache struct with entries map, mutex, maxSize, defaultTTL, strategy, and stats fields
- Add CacheStrategy type with LRU, TTL, write-through, write-back, and read-through constants
- Add CacheEntry struct with Key, Value, ExpiresAt, CreatedAt, and HitCount fields
- Add NewCache constructor with CacheConfig parameter and automatic cleanup goroutine
- Add Get, Set, Delete, and Clear methods with hit
* feat: Add circuit breaker with state management, failure tracking, fallback support, and statistics
- Add CircuitState type with StateClosed, StateOpen, and StateHalfOpen constants and String method
- Add CircuitBreaker struct with name, state, failureCount, successCount, lastFailure, config, mutex, and onStateChange fields
- Add CircuitBreakerConfig with FailureThreshold, SuccessThreshold, Timeout, and HalfOpenMaxCalls fields
- Add NewCircuitBreaker constructor and DefaultCircuitBreakerConfig with
* feat: Add whitelabel service with branding, partner config, and email template management
- Add Service struct with db and logger dependencies and NewService constructor
- Add CreateBranding, GetBranding, GetBrandingByDomain, and UpdateBranding methods for branding configuration management
- Add CreatePartnerConfig and GetPartnerConfig methods for partner-specific settings
- Add CreateEmailTemplate, GetEmailTemplate, and ListEmailTemplates methods for custom email template management
- Add BrandingConfig with
* feat: Add real-time exchange rate service with multi-provider support, caching, and automatic refresh
- Add ExchangeRateProvider type with OpenExchange, Fixer, XE, and Internal constants
- Add RealTimeExchangeService struct with provider, apiKey, baseCurrency, rates cache, lastUpdate, cacheTTL, mutex, logger, and httpClient fields
- Add ExchangeRateConfig with Provider, APIKey, BaseCurrency, and CacheTTL fields
- Add NewRealTimeExchangeService constructor with default 15-minute cache TTL and USD
* feat: Add analytics handler with dashboard, revenue analytics, and scheduled report endpoints
- Add AnalyticsHandler struct with service and logger dependencies and NewAnalyticsHandler constructor
- Add GetDashboard method with tenant ID extraction, date range filtering, and dashboard metrics retrieval
- Add GetRevenueAnalytics method with tenant filtering and group-by support
- Add CreateScheduledReport and ListScheduledReports methods for report management
- Add date parsing for start_date and end_date query
* feat: Add threat detection service with brute force, rate limit abuse, SQL injection detection, and IP tracking
- Add ThreatLevel type with Low, Medium, High, and Critical constants
- Add ThreatType type with BruteForce, RateLimitAbuse, SQLInjection, XSS, Unauthorized, DataExfil, and Anomalous constants
- Add ThreatEvent struct with ID, TenantID, Type, Level, Source, Target, Description, Metadata, DetectedAt, Mitigated, and MitigatedAt fields
- Add ThreatDetector struct with logger, rules, events, ip
* feat: Add compliance handler with DSR management, consent tracking, audit logging, and data residency endpoints
- Add ComplianceHandler struct with service and logger dependencies and NewComplianceHandler constructor
- Add CreateDSR, GetDSR, ListDSRs, and ProcessDSR methods for data subject request management
- Add RecordConsent, RevokeConsent, and GetConsents methods for consent tracking with IP and user agent capture
- Add QueryAuditLogs method with jurisdiction, actor, and action filtering
- Add SetDataRes
* feat: Add geographic routing service with region management, IP-based routing, and endpoint selection
- Add GeoRouter struct with regions map, defaultReg, and mutex fields
- Add Region struct with ID, Name, Endpoints, Priority, IsActive, and Latency fields
- Add GeoRoutingConfig with DefaultRegion and Regions fields
- Add NewGeoRouter constructor with region initialization
- Add GetRegionForIP method with IP parsing and geo lookup
- Add lookupRegion helper with simplified IP range-based region detection
* feat: Add whitelabel handler with branding, partner config, and email template endpoints
- Add WhitelabelHandler struct with service and logger dependencies and NewWhitelabelHandler constructor
- Add CreateBranding, GetBranding, GetBrandingByDomain, and UpdateBranding methods for branding configuration management
- Add CreatePartnerConfig and GetPartnerConfig methods for partner-specific settings
- Add CreateEmailTemplate, GetEmailTemplate, and ListEmailTemplates methods for email template management
* feat: Add encryption service with AES-GCM, field-level encryption, and PBKDF2 key derivation
- Add EncryptionService struct with masterKey and gcm cipher fields
- Add EncryptionConfig with MasterKey and KeyDerivationSalt fields
- Add NewEncryptionService constructor with PBKDF2 key derivation, 100000 iterations, and AES-GCM cipher initialization
- Add Encrypt and Decrypt methods with nonce generation and validation
- Add EncryptString and DecryptString methods with base64 encoding
- Add FieldEncryptor struct
* feat: Fix type conversions, rename ExchangeRateProvider to RateProviderType, and improve currency integration
- Fix GetRevenueAnalytics return type by dereferencing metrics struct
- Fix getCarrierMetrics to use int64 for Count and convert to int for ActiveCarriers
- Rename ExchangeRateProvider to RateProviderType for consistency
- Change RatePlanCurrencyIntegrator.exchangeService from pointer to interface type
- Add function documentation comments for NewRatePlanCurrencyIntegrator, SubscribeToPlanWith
* feat: Add platform routes with analytics, whitelabel, compliance, exchange rate, and infrastructure endpoints
- Add registerAnalyticsRoutes, registerWhitelabelRoutes, registerComplianceRoutes, registerExchangeRateRoutes, and registerInfraRoutes to setupRoutes
- Add routes_platform.go with analytics dashboard, revenue analytics, and scheduled report endpoints
- Add whitelabel branding, partner config, and email template endpoints
- Add compliance DSR, consent management, audit logging, and data residency endpoints
* feat: Add churn analysis service with risk prediction, metrics calculation, and retention recommendations
- Add ChurnRiskLevel type with Low, Medium, High, and Critical constants
- Add ChurnPrediction struct with ProfileID, RiskLevel, RiskScore, PredictedChurnDate, Reasons, Recommendations, and LastUpdated fields
- Add ChurnMetrics struct with Period, TotalSubscribers, ChurnedSubscribers, ChurnRate, MonthlyChurnRate, AnnualChurnRate, AverageTenure, and RiskDistribution fields
- Add ChurnFactor struct with Factor
* feat: Add market analysis service with penetration metrics, competitor analysis, and opportunity identification
- Add MarketMetrics struct with Period, TotalMarketSize, OurSubscribers, MarketShare, GrowthRate, ByCountry, ByCarrier, ByDemographic, CompetitorAnalysis, and PenetrationOpportunities fields
- Add CountryMetrics struct with Country, TotalPopulation, ActiveSubscribers, PenetrationRate, GrowthRate, ARPU, and MarketPotential fields
- Add MarketCarrierMetrics struct with CarrierName, Subscribers
* feat: Add fraud detection service with pattern matching, ML models, risk scoring, and automated blocking
- Add FraudType constants for account_takeover, subscription_fraud, payment_fraud, usage_anomaly, identity_fraud, and sim_swap
- Add FraudSeverity type with Low, Medium, High, and Critical levels
- Add FraudAlert struct with ID, Type, Severity, ProfileID, RiskScore, Evidence, IPAddress, UserAgent, Location, Status, Actions, and Metadata fields
- Add FraudPattern struct with pattern configuration and weight-based scoring
- Add FraudDetectionService with patterns, alerts
* feat: Add predictive maintenance service with asset monitoring, failure prediction, ML models, and health scoring
- Add MaintenanceType constants for preventive, corrective, predictive, and emergency maintenance
- Add AssetType constants for server, database, network, storage, application, and load_balancer
- Add Asset struct with ID, Name, Type, Status, Location, HealthScore, LastMaintenance, NextMaintenance, and Metadata fields
- Add MaintenanceAlert struct with ID, AssetID, Type, Severity, Title, Description, RiskScore,
* feat: Add pricing optimization service with strategy-based pricing, demand prediction, and performance metrics
- Add OptimizationStrategy constants for revenue_maximization, market_share, profit_margin, competitive, and churn_reduction
- Add OptimizationResult struct with RatePlanID, Strategy, CurrentPrice, OptimalPrice, PriceChange, ExpectedRevenue, ExpectedDemand, Confidence, Reasoning, Risks, and Recommendations fields
- Add PricingMetrics struct with Period, TotalRevenue, TotalSubscribers, AR
* feat: Remove fraud detection service and move to dedicated security module
- Remove FraudDetectionService with pattern matching, ML models, risk scoring, and automated blocking
- Remove FraudType constants for account_takeover, subscription_fraud, payment_fraud, usage_anomaly, identity_fraud, and sim_swap
- Remove FraudSeverity type with Low, Medium, High, and Critical levels
- Remove FraudAlert struct with ID, Type, Severity, ProfileID, RiskScore, Evidence, IPAddress, UserAgent, Location, Status
* feat: Refactor churn analysis service to simplify logic and extract reusable components
- Remove ChurnRiskLevel, ChurnPrediction, ChurnMetrics, and ChurnFactor type definitions from churn_service.go
- Simplify NewChurnAnalysisService constructor to single-line initialization
- Refactor PredictChurn to use analyzeFactors, calculateScore, RiskLevelFromScore, generateReasons, and RecommendationsForRisk helper functions
- Simplify GetChurnMetrics by using periodDates helper and inline database queries
- Replace GetChurnFactors implementation with DefaultChurnFactors helper
* feat: Add churn analysis types with risk levels, predictions, metrics, and helper functions
- Add ChurnRiskLevel type with Low, Medium, High, and Critical constants
- Add ChurnPrediction struct with ProfileID, RiskLevel, RiskScore, PredictedChurnDate, Reasons, Recommendations, and LastUpdated fields
- Add ChurnMetrics struct with Period, TotalSubscribers, ChurnedSubscribers, ChurnRate, MonthlyChurnRate, AnnualChurnRate, AverageTenure, and RiskDistribution fields
- Add ChurnFactor struct with Factor, Impact, Description, and Weight fields
* feat: Refactor rate plan currency integrator to simplify subscription creation and remove unused helper
- Simplify SubscribeToPlanWithCurrency by creating SubscribeRequest directly instead of intermediate RatePlanSubscription struct
- Remove redundant Status, StartedAt, CreatedAt, and UpdatedAt field assignments
- Mark unused context parameters with underscore in calculateOverageCost and generateReason
- Remove unused getHighestPriorityCarrier helper function from selection_algorithm.go
* feat: Mark unused parameters with underscore, remove unused file, and add subscriber journey E2E tests
- Mark unused context and filter parameters with underscore in getCarrierMetrics, getGeoMetrics, and getPerformanceStats
- Remove unused RatePlanCurrencyIntegrator service from currency/services/rateplan_core.go
- Simplify ML model weight comparison in selection_test_ml.go by using literal values instead of originalWeights variable
- Add comprehensive subscriber_journey_test.go with full lifecycle
* feat: Update README with multi-language SDK support and analytics services documentation
- Replace TypeScript SDK reference with Multi-Language SDKs supporting Go, Python, TypeScript, Kotlin, Ruby, Swift, Rust, and Elixir
- Add Analytics & Intelligence section documenting Churn Analysis, Fraud Detection, Market Analytics, Predictive Maintenance, and Pricing Optimization services
- Add SDK Documentation link to docs/sdk-usage.md in Documentation section
* feat: Add pricing optimization service with elasticity calculations, strategy-based pricing, and demand prediction
- Add calculatePriceElasticity using log-linear regression with realistic telecom bounds (-2.0 to -0.3)
- Add optimizeForRevenue using revenue optimization formula with elasticity-based pricing
- Add optimizeForMarketShare with penetration strategy and aggressive pricing based on elasticity
- Add optimizeForProfitMargin using cost-plus analysis with 40% target margin
- Add optimizeForComp
* feat: Refactor pricing optimization service by extracting helper functions to separate file
- Move calculateElasticity, calculateCompetitiveIndex, and calculateOptimizationROI to optimization_opt_service.go
- Move generateAnalysis, calculateConfidence, and calculateChurnRate to optimization_opt_service.go
- Simplify calculatePriceElasticity by removing comments and consolidating logic
- Simplify optimizeForRevenue, optimizeForMarketShare, optimizeForProfitMargin, optimizeForCompetitive, and optimizeForChurn
* feat: Add security handler with fraud detection, SIM swap verification, and alert management
- Add SecurityHandler with fraud analysis, alert filtering, and metrics endpoints
- Add FraudAlert struct with ID, Type, Severity, ProfileID, RiskScore, Evidence, IPAddress, Status, and ActionsTaken fields
- Add FraudMetrics struct with Period, TotalAlerts, ResolvedAlerts, ResolutionRate, FalsePositiveRate, ByType, and BySeverity fields
- Add AnalyzeTransaction with risk scoring based on transaction amount and suspicious
* feat: Add analytics handlers for market analysis, maintenance metrics, and pricing optimization
- Add GetChurnMetrics with period-based churn rate, subscriber counts, and risk distribution
- Add GetCompetitors with market share, strengths, weaknesses, and threat levels
- Add GetMarketOpportunities with potential subscribers, ROI, and confidence scores
- Add GetMaintenanceMetrics with asset health, uptime, MTTR, and MTTF tracking
- Add GetAssetsHealth returning health scores and status for servers
* feat: Add analytics handler with churn prediction, market metrics, and analytics types
- Add AnalyticsHandler with NewAnalyticsHandler constructor
- Add PredictChurn endpoint returning risk level, score, predicted date, reasons, and recommendations
- Add GetAtRiskCustomers with risk level filtering and configurable limit (max 1000)
- Add GetMarketMetrics returning market size, subscribers, share, growth rate, and country breakdown
- Add ChurnPrediction struct with ProfileID, RiskLevel, RiskScore
* feat: Add currency handler with conversion, exchange rates, billing, and analytics endpoints
- Add CurrencyHandler with NewCurrencyHandler constructor
- Add ConvertCurrency with multi-currency support (USD, EUR, GBP, JPY, CAD, AUD, CHF)
- Add GetExchangeRate, GetExchangeRateHistory with 30-day historical data, and RefreshExchangeRates endpoints
- Add GetSupportedCurrencies returning code, name, and symbol for 10 currencies
- Add ProcessBilling with charge/credit/refund types and transaction creation
* feat: Add analytics, security, and currency route handlers with comprehensive endpoint registration
- Add registerAnalyticsRoutes with churn analysis (predict, metrics, at-risk), market analytics (metrics, competitors, opportunities), predictive maintenance (metrics, assets, alerts, predict), and pricing optimization (metrics, optimize, elasticity) endpoints
- Add registerSecurityRoutes with fraud detection (analyze, alerts, update status, metrics, patterns) and SIM swap protection (verify, history) endpoints
* feat: Mark unused context parameters with underscore and refactor fraud metrics status handling
- Mark unused context parameters with underscore in analyzeCompetitors, identifyOpportunities, and PredictFailure
- Replace if-else chain with switch statement for fraud alert status handling in GetFraudMetrics
- Add OptimizationResult, PricingMetrics, RatePlan, and HistoricalDataPoint types to pricing/types.go
* feat: Add analytics handler with revenue metrics, usage analytics, billing analytics, churn risk, and pricing recommendations
- Add RevenueMetrics with total revenue, ARPU, MRR, ARR, growth percentage, and breakdowns by plan and region
- Add UsageAnalytics with data/voice/SMS totals, average per user, peak usage hour, and trend tracking
- Add BillingAnalytics with invoiced/collected amounts, collection rate, outstanding balance, payment days, and payment method breakdown
- Add ChurnRiskScore with risk level, score, contributing
* feat: Add analytics CLI commands with churn, fraud, market, pricing, and maintenance subcommands
- Add NewAnalyticsCmd with churn, fraud, market, pricing, and maintenance command groups
- Add churn commands: predict, metrics, at-risk with risk-level, period, and limit flags
- Add fraud commands: alerts, metrics, patterns with severity and type filtering
- Add market commands: metrics, competitors, opportunities for market analytics
- Add pricing commands: metrics, optimize with strategy-based optimization
- Add maintenance commands: metrics, assets, predict for predictive maintenance
- Add spf
* feat: Add analytics and churn dashboard pages with metrics visualization, risk analysis, and multi-tab interfaces
- Add analytics page with overview, churn, market, maintenance, and pricing tabs
- Add churn page with predictions table, risk filtering, and retention recommendations
- Add metrics cards for subscribers, churn rate, market share, and system uptime
- Add risk distribution visualization with progress bars and color-coded badges
- Add market metrics with country breakdown and penetration rates
- Add maintenance metrics with asset health, MTTF, MTTR
* feat: Add analytics, security, and currency SDK modules with comprehensive API endpoints across Elixir and Go SDKs
- Add AnalyticsAPI with churn prediction (predict, metrics, at-risk), market analytics (metrics, competitors, opportunities), predictive maintenance (metrics, assets, alerts, predict), and pricing optimization (metrics, optimize, elasticity) endpoints
- Add SecurityAPI with fraud detection (analyze, alerts, update status, metrics, patterns) and SIM swap protection (verify, history) endpoints
- Add CurrencyAPI with currency conversion (convert, exchange rates, rate
* feat: Add analytics configuration to Helm values with churn, fraud, market, maintenance, and pricing modules
- Add platform version 2.0.0 to global configuration
- Add analytics configuration with enabled flag
- Add churn module with xgboost ML model, daily prediction interval, and risk thresholds (low: 25, medium: 50, high: 75)
- Add fraud module with real-time detection, severity levels (low/medium/high/critical), and patterns (account_takeover, subscription_fraud, payment_fraud, usage_anomaly, sim_swap)
- Add market module with competitor tracking and weekly update interval
- Add maintenance module with LSTM predictive model and 0.7 alert threshold
* docs: Add comprehensive SDK documentation and API endpoint reference to README
- Add sdk/ directory structure with Go, Python, TypeScript, Kotlin, Ruby, Swift, Rust, and Elixir SDKs
- Add docs/sdk-usage.md reference to documentation section
- Add Analytics API endpoints table with churn prediction, market analysis, maintenance metrics, and pricing optimization
- Add Security API endpoints table with fraud detection, alert management, and SIM swap protection
- Add Currency & Billing API endpoints table with conversion
* docs: Add comprehensive platform architecture and components documentation to README
- Add API Gateway Layer section with Traefik, unified HTTPS endpoint, security middleware, and monitoring dashboard
- Add Core Network Services with API Server, Carrier Connector, Charging Engine, and Packet Gateway descriptions
- Add Supporting Infrastructure section covering PostgreSQL, Redis, MongoDB, RabbitMQ, Consul, and Vault
- Add Frontend Applications section with Web Dashboard features and architecture
This commit is contained in:
@@ -0,0 +1,207 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ChurnAnalysisService provides churn analysis and prediction
|
||||
type ChurnAnalysisService struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewChurnAnalysisService creates a new churn analysis service
|
||||
func NewChurnAnalysisService(db *gorm.DB, logger *logrus.Logger) *ChurnAnalysisService {
|
||||
return &ChurnAnalysisService{db: db, logger: logger}
|
||||
}
|
||||
|
||||
// PredictChurn predicts churn risk for a specific profile
|
||||
func (s *ChurnAnalysisService) PredictChurn(ctx context.Context, profileID string) (*ChurnPrediction, error) {
|
||||
factors := s.analyzeFactors(ctx, profileID)
|
||||
score := s.calculateScore(factors)
|
||||
|
||||
prediction := &ChurnPrediction{
|
||||
ProfileID: profileID,
|
||||
RiskScore: score,
|
||||
RiskLevel: RiskLevelFromScore(score),
|
||||
Reasons: s.generateReasons(factors),
|
||||
Recommendations: RecommendationsForRisk(RiskLevelFromScore(score)),
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
if prediction.RiskLevel == ChurnRiskHigh || prediction.RiskLevel == ChurnRiskCritical {
|
||||
date := time.Now().AddDate(0, 0, int((100-score)*3))
|
||||
prediction.PredictedChurnDate = &date
|
||||
}
|
||||
|
||||
return prediction, nil
|
||||
}
|
||||
|
||||
// GetChurnMetrics calculates overall churn metrics
|
||||
func (s *ChurnAnalysisService) GetChurnMetrics(ctx context.Context, period string) (*ChurnMetrics, error) {
|
||||
start, end := periodDates(period)
|
||||
metrics := &ChurnMetrics{Period: period, RiskDistribution: make(map[ChurnRiskLevel]int64), GeneratedAt: time.Now()}
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").Where("created_at < ?", start).Count(&metrics.TotalSubscribers)
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").Where("ended_at BETWEEN ? AND ?", start, end).Count(&metrics.ChurnedSubscribers)
|
||||
|
||||
if metrics.TotalSubscribers > 0 {
|
||||
metrics.ChurnRate = float64(metrics.ChurnedSubscribers) / float64(metrics.TotalSubscribers) * 100
|
||||
metrics.MonthlyChurnRate = metrics.ChurnRate
|
||||
metrics.AnnualChurnRate = metrics.ChurnRate * 12
|
||||
}
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").Where("status = ?", "cancelled").
|
||||
Select("AVG(EXTRACT(EPOCH FROM (ended_at - started_at))/86400)").Scan(&metrics.AverageTenure)
|
||||
|
||||
// Estimated distribution
|
||||
metrics.RiskDistribution[ChurnRiskLow] = int64(float64(metrics.TotalSubscribers) * 0.6)
|
||||
metrics.RiskDistribution[ChurnRiskMedium] = int64(float64(metrics.TotalSubscribers) * 0.25)
|
||||
metrics.RiskDistribution[ChurnRiskHigh] = int64(float64(metrics.TotalSubscribers) * 0.12)
|
||||
metrics.RiskDistribution[ChurnRiskCritical] = int64(float64(metrics.TotalSubscribers) * 0.03)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// GetChurnFactors returns the top factors contributing to churn
|
||||
func (s *ChurnAnalysisService) GetChurnFactors(_ context.Context) ([]ChurnFactor, error) {
|
||||
return DefaultChurnFactors(), nil
|
||||
}
|
||||
|
||||
// GetAtRiskCustomers returns customers at high risk of churn
|
||||
func (s *ChurnAnalysisService) GetAtRiskCustomers(ctx context.Context, riskLevel ChurnRiskLevel, limit int) ([]*ChurnPrediction, error) {
|
||||
var subs []struct{ ID string }
|
||||
s.db.WithContext(ctx).Table("profiles").Where("status = ?", "active").Limit(limit).Find(&subs)
|
||||
|
||||
var predictions []*ChurnPrediction
|
||||
for _, sub := range subs {
|
||||
pred, err := s.PredictChurn(ctx, sub.ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if pred.RiskLevel == riskLevel || (riskLevel == ChurnRiskHigh && pred.RiskLevel == ChurnRiskCritical) {
|
||||
predictions = append(predictions, pred)
|
||||
}
|
||||
}
|
||||
return predictions, nil
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) analyzeFactors(ctx context.Context, profileID string) []ChurnFactor {
|
||||
factors := DefaultChurnFactors()
|
||||
result := make([]ChurnFactor, 0, len(factors))
|
||||
|
||||
for _, f := range factors {
|
||||
impact := s.factorImpact(ctx, profileID, f.Factor)
|
||||
if impact > 0.1 {
|
||||
result = append(result, ChurnFactor{Factor: f.Factor, Impact: impact, Description: f.Description, Weight: f.Weight})
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) factorImpact(ctx context.Context, profileID, factor string) float64 {
|
||||
switch factor {
|
||||
case "Low Usage":
|
||||
return s.usageImpact(ctx, profileID)
|
||||
case "Payment Issues":
|
||||
return s.paymentImpact(ctx, profileID)
|
||||
case "Price Sensitivity":
|
||||
return s.priceImpact(ctx, profileID)
|
||||
default:
|
||||
return 0.4
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) usageImpact(ctx context.Context, profileID string) float64 {
|
||||
var total int64
|
||||
s.db.WithContext(ctx).Table("rate_plan_usage").Where("profile_id = ? AND created_at > ?", profileID, time.Now().AddDate(0, -1, 0)).
|
||||
Select("COALESCE(SUM(data_used + voice_used + sms_used), 0)").Scan(&total)
|
||||
|
||||
switch {
|
||||
case total < 100:
|
||||
return 0.8
|
||||
case total < 500:
|
||||
return 0.6
|
||||
case total < 1000:
|
||||
return 0.3
|
||||
default:
|
||||
return 0.1
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) paymentImpact(ctx context.Context, profileID string) float64 {
|
||||
var createdAt time.Time
|
||||
s.db.WithContext(ctx).Table("profiles").Where("id = ?", profileID).Select("created_at").Scan(&createdAt)
|
||||
days := time.Since(createdAt).Hours() / 24
|
||||
if days < 30 {
|
||||
return 0.3
|
||||
} else if days < 90 {
|
||||
return 0.2
|
||||
}
|
||||
return 0.1
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) priceImpact(ctx context.Context, profileID string) float64 {
|
||||
var price float64
|
||||
s.db.WithContext(ctx).Table("rate_plans rp").Joins("JOIN rate_plan_subscriptions rps ON rps.rate_plan_id = rp.id").
|
||||
Where("rps.profile_id = ? AND rps.status = ?", profileID, "active").Select("rp.base_price").Scan(&price)
|
||||
|
||||
switch {
|
||||
case price > 50:
|
||||
return 0.6
|
||||
case price > 30:
|
||||
return 0.4
|
||||
case price > 15:
|
||||
return 0.2
|
||||
default:
|
||||
return 0.1
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) calculateScore(factors []ChurnFactor) float64 {
|
||||
var total, weight float64
|
||||
for _, f := range factors {
|
||||
total += f.Impact * f.Weight
|
||||
weight += f.Weight
|
||||
}
|
||||
if weight == 0 {
|
||||
return 0
|
||||
}
|
||||
return (total / weight) * 100
|
||||
}
|
||||
|
||||
func (s *ChurnAnalysisService) generateReasons(factors []ChurnFactor) []string {
|
||||
var reasons []string
|
||||
for _, f := range factors {
|
||||
if f.Impact > 0.7 {
|
||||
reasons = append(reasons, fmt.Sprintf("High %s detected", f.Factor))
|
||||
} else if f.Impact > 0.5 {
|
||||
reasons = append(reasons, fmt.Sprintf("Moderate %s detected", f.Factor))
|
||||
}
|
||||
}
|
||||
if len(reasons) == 0 {
|
||||
reasons = append(reasons, "Multiple minor risk factors detected")
|
||||
}
|
||||
return reasons
|
||||
}
|
||||
|
||||
func periodDates(period string) (time.Time, time.Time) {
|
||||
now := time.Now()
|
||||
switch period {
|
||||
case "daily":
|
||||
return now.Truncate(24 * time.Hour), now
|
||||
case "weekly":
|
||||
return now.AddDate(0, 0, -7), now
|
||||
case "monthly":
|
||||
return now.AddDate(0, -1, 0), now
|
||||
case "quarterly":
|
||||
return now.AddDate(0, -3, 0), now
|
||||
default:
|
||||
return now.AddDate(0, -1, 0), now
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package analytics
|
||||
|
||||
import "time"
|
||||
|
||||
// ChurnRiskLevel represents the risk level of customer churn
|
||||
type ChurnRiskLevel string
|
||||
|
||||
const (
|
||||
ChurnRiskLow ChurnRiskLevel = "low"
|
||||
ChurnRiskMedium ChurnRiskLevel = "medium"
|
||||
ChurnRiskHigh ChurnRiskLevel = "high"
|
||||
ChurnRiskCritical ChurnRiskLevel = "critical"
|
||||
)
|
||||
|
||||
// ChurnPrediction represents a churn prediction for a customer
|
||||
type ChurnPrediction struct {
|
||||
ProfileID string `json:"profile_id"`
|
||||
RiskLevel ChurnRiskLevel `json:"risk_level"`
|
||||
RiskScore float64 `json:"risk_score"`
|
||||
PredictedChurnDate *time.Time `json:"predicted_churn_date,omitempty"`
|
||||
Reasons []string `json:"reasons"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
LastUpdated time.Time `json:"last_updated"`
|
||||
}
|
||||
|
||||
// ChurnMetrics represents churn analysis metrics
|
||||
type ChurnMetrics struct {
|
||||
Period string `json:"period"`
|
||||
TotalSubscribers int64 `json:"total_subscribers"`
|
||||
ChurnedSubscribers int64 `json:"churned_subscribers"`
|
||||
ChurnRate float64 `json:"churn_rate"`
|
||||
MonthlyChurnRate float64 `json:"monthly_churn_rate"`
|
||||
AnnualChurnRate float64 `json:"annual_churn_rate"`
|
||||
AverageTenure float64 `json:"average_tenure_days"`
|
||||
RiskDistribution map[ChurnRiskLevel]int64 `json:"risk_distribution"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// ChurnFactor represents factors contributing to churn
|
||||
type ChurnFactor struct {
|
||||
Factor string `json:"factor"`
|
||||
Impact float64 `json:"impact"`
|
||||
Description string `json:"description"`
|
||||
Weight float64 `json:"weight"`
|
||||
}
|
||||
|
||||
// DefaultChurnFactors returns standard churn factors
|
||||
func DefaultChurnFactors() []ChurnFactor {
|
||||
return []ChurnFactor{
|
||||
{Factor: "Low Usage", Impact: 0.85, Description: "Low data/voice usage increases churn risk", Weight: 0.25},
|
||||
{Factor: "Payment Issues", Impact: 0.92, Description: "Failed payments increase churn risk", Weight: 0.20},
|
||||
{Factor: "Poor Support", Impact: 0.78, Description: "High support ticket resolution time", Weight: 0.15},
|
||||
{Factor: "Network Quality", Impact: 0.70, Description: "Dropped calls and slow data speeds", Weight: 0.20},
|
||||
{Factor: "Price Sensitivity", Impact: 0.65, Description: "Higher-priced plans have higher churn", Weight: 0.10},
|
||||
{Factor: "Competitor Offers", Impact: 0.60, Description: "Better competitor deals", Weight: 0.10},
|
||||
}
|
||||
}
|
||||
|
||||
// RiskLevelFromScore determines risk level from score
|
||||
func RiskLevelFromScore(score float64) ChurnRiskLevel {
|
||||
switch {
|
||||
case score >= 80:
|
||||
return ChurnRiskCritical
|
||||
case score >= 60:
|
||||
return ChurnRiskHigh
|
||||
case score >= 40:
|
||||
return ChurnRiskMedium
|
||||
default:
|
||||
return ChurnRiskLow
|
||||
}
|
||||
}
|
||||
|
||||
// RecommendationsForRisk returns recommendations based on risk level
|
||||
func RecommendationsForRisk(level ChurnRiskLevel) []string {
|
||||
switch level {
|
||||
case ChurnRiskCritical:
|
||||
return []string{"Immediate intervention required", "Offer retention discount", "Schedule proactive support call"}
|
||||
case ChurnRiskHigh:
|
||||
return []string{"Send personalized retention offer", "Review and address service issues"}
|
||||
case ChurnRiskMedium:
|
||||
return []string{"Monitor usage patterns closely", "Send value-add content"}
|
||||
default:
|
||||
return []string{"Continue standard engagement"}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,591 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MarketMetrics represents market penetration analysis
|
||||
type MarketMetrics struct {
|
||||
Period string `json:"period"`
|
||||
TotalMarketSize int64 `json:"total_market_size"`
|
||||
OurSubscribers int64 `json:"our_subscribers"`
|
||||
MarketShare float64 `json:"market_share_pct"`
|
||||
GrowthRate float64 `json:"growth_rate_pct"`
|
||||
ByCountry map[string]CountryMetrics `json:"by_country"`
|
||||
ByCarrier map[string]MarketCarrierMetrics `json:"by_carrier"`
|
||||
ByDemographic map[string]DemoMetrics `json:"by_demographic"`
|
||||
CompetitorAnalysis []CompetitorMetrics `json:"competitor_analysis"`
|
||||
PenetrationOpportunities []OpportunityMetrics `json:"penetration_opportunities"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// CountryMetrics represents metrics by country
|
||||
type CountryMetrics struct {
|
||||
Country string `json:"country"`
|
||||
TotalPopulation int64 `json:"total_population"`
|
||||
ActiveSubscribers int64 `json:"active_subscribers"`
|
||||
PenetrationRate float64 `json:"penetration_rate_pct"`
|
||||
GrowthRate float64 `json:"growth_rate_pct"`
|
||||
ARPU float64 `json:"arpu"` // Average Revenue Per User
|
||||
MarketPotential int64 `json:"market_potential"`
|
||||
}
|
||||
|
||||
// MarketCarrierMetrics represents metrics by carrier for market analysis
|
||||
type MarketCarrierMetrics struct {
|
||||
CarrierName string `json:"carrier_name"`
|
||||
Subscribers int64 `json:"subscribers"`
|
||||
MarketShare float64 `json:"market_share_pct"`
|
||||
ChurnRate float64 `json:"churn_rate_pct"`
|
||||
ARPU float64 `json:"arpu"`
|
||||
NetworkQuality float64 `json:"network_quality_score"`
|
||||
Coverage float64 `json:"coverage_pct"`
|
||||
}
|
||||
|
||||
// DemoMetrics represents metrics by demographic
|
||||
type DemoMetrics struct {
|
||||
Segment string `json:"segment"`
|
||||
Subscribers int64 `json:"subscribers"`
|
||||
MarketShare float64 `json:"market_share_pct"`
|
||||
ARPU float64 `json:"arpu"`
|
||||
GrowthRate float64 `json:"growth_rate_pct"`
|
||||
}
|
||||
|
||||
// CompetitorMetrics represents competitor analysis
|
||||
type CompetitorMetrics struct {
|
||||
Name string `json:"name"`
|
||||
EstimatedSubs int64 `json:"estimated_subscribers"`
|
||||
MarketShare float64 `json:"market_share_pct"`
|
||||
Strengths []string `json:"strengths"`
|
||||
Weaknesses []string `json:"weaknesses"`
|
||||
ThreatLevel string `json:"threat_level"`
|
||||
}
|
||||
|
||||
// OpportunityMetrics represents market opportunities
|
||||
type OpportunityMetrics struct {
|
||||
Country string `json:"country"`
|
||||
OpportunityType string `json:"opportunity_type"`
|
||||
PotentialSubs int64 `json:"potential_subscribers"`
|
||||
RequiredInvestment float64 `json:"required_investment"`
|
||||
ExpectedROI float64 `json:"expected_roi_pct"`
|
||||
TimeToMarket int `json:"time_to_market_months"`
|
||||
}
|
||||
|
||||
// MarketAnalysisService provides market penetration analysis
|
||||
type MarketAnalysisService struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewMarketAnalysisService creates a new market analysis service
|
||||
func NewMarketAnalysisService(db *gorm.DB, logger *logrus.Logger) *MarketAnalysisService {
|
||||
return &MarketAnalysisService{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// GetMarketMetrics calculates market penetration metrics
|
||||
func (s *MarketAnalysisService) GetMarketMetrics(ctx context.Context, period string) (*MarketMetrics, error) {
|
||||
metrics := &MarketMetrics{
|
||||
Period: period,
|
||||
ByCountry: make(map[string]CountryMetrics),
|
||||
ByCarrier: make(map[string]MarketCarrierMetrics),
|
||||
ByDemographic: make(map[string]DemoMetrics),
|
||||
CompetitorAnalysis: make([]CompetitorMetrics, 0),
|
||||
PenetrationOpportunities: make([]OpportunityMetrics, 0),
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Calculate overall market metrics
|
||||
s.calculateOverallMetrics(ctx, metrics)
|
||||
|
||||
// Calculate country-specific metrics
|
||||
s.calculateCountryMetrics(ctx, metrics)
|
||||
|
||||
// Calculate carrier metrics
|
||||
s.calculateCarrierMetrics(ctx, metrics)
|
||||
|
||||
// Calculate demographic metrics
|
||||
s.calculateDemographicMetrics(ctx, metrics)
|
||||
|
||||
// Analyze competitors
|
||||
s.analyzeCompetitors(ctx, metrics)
|
||||
|
||||
// Identify opportunities
|
||||
s.identifyOpportunities(ctx, metrics)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// calculateOverallMetrics calculates overall market metrics
|
||||
func (s *MarketAnalysisService) calculateOverallMetrics(ctx context.Context, metrics *MarketMetrics) {
|
||||
// Get our subscriber count
|
||||
var ourSubs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("status = ?", "active").
|
||||
Count(&ourSubs)
|
||||
metrics.OurSubscribers = ourSubs
|
||||
|
||||
// Estimate total market size (simplified - would use external data)
|
||||
metrics.TotalMarketSize = s.estimateTotalMarketSize()
|
||||
|
||||
// Calculate market share
|
||||
if metrics.TotalMarketSize > 0 {
|
||||
metrics.MarketShare = float64(ourSubs) / float64(metrics.TotalMarketSize) * 100
|
||||
}
|
||||
|
||||
// Calculate growth rate (compare to previous period)
|
||||
metrics.GrowthRate = s.calculateGrowthRate(ctx, ourSubs)
|
||||
}
|
||||
|
||||
// calculateCountryMetrics calculates metrics by country
|
||||
func (s *MarketAnalysisService) calculateCountryMetrics(ctx context.Context, metrics *MarketMetrics) {
|
||||
countries := []string{"US", "UK", "DE", "FR", "JP", "AU", "CA", "SG"}
|
||||
|
||||
for _, country := range countries {
|
||||
var subs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("country = ? AND status = ?", country, "active").
|
||||
Count(&subs)
|
||||
|
||||
countryMetrics := CountryMetrics{
|
||||
Country: country,
|
||||
ActiveSubscribers: subs,
|
||||
TotalPopulation: s.getCountryPopulation(country),
|
||||
PenetrationRate: s.calculatePenetrationRate(subs, country),
|
||||
GrowthRate: s.calculateCountryGrowthRate(ctx, country),
|
||||
ARPU: s.calculateCountryARPU(ctx, country),
|
||||
MarketPotential: s.calculateMarketPotential(country),
|
||||
}
|
||||
|
||||
metrics.ByCountry[country] = countryMetrics
|
||||
}
|
||||
}
|
||||
|
||||
// calculateCarrierMetrics calculates metrics by carrier
|
||||
func (s *MarketAnalysisService) calculateCarrierMetrics(ctx context.Context, metrics *MarketMetrics) {
|
||||
// This would analyze carrier partnerships and performance
|
||||
carriers := []string{"AT&T", "Verizon", "T-Mobile", "Vodafone", "Orange", "Deutsche Telekom"}
|
||||
|
||||
for _, carrier := range carriers {
|
||||
var subs int64
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions rps").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Joins("JOIN profiles p ON rps.profile_id = p.id").
|
||||
Where("rp.carrier_name = ? AND rps.status = ?", carrier, "active").
|
||||
Count(&subs)
|
||||
|
||||
carrierMetrics := MarketCarrierMetrics{
|
||||
CarrierName: carrier,
|
||||
Subscribers: subs,
|
||||
MarketShare: s.calculateCarrierMarketShare(ctx, carrier),
|
||||
ChurnRate: s.calculateCarrierChurnRate(ctx, carrier),
|
||||
ARPU: s.calculateCarrierARPU(ctx, carrier),
|
||||
NetworkQuality: s.getCarrierNetworkQuality(carrier),
|
||||
Coverage: s.getCarrierCoverage(carrier),
|
||||
}
|
||||
|
||||
metrics.ByCarrier[carrier] = carrierMetrics
|
||||
}
|
||||
}
|
||||
|
||||
// calculateDemographicMetrics calculates metrics by demographic segments
|
||||
func (s *MarketAnalysisService) calculateDemographicMetrics(ctx context.Context, metrics *MarketMetrics) {
|
||||
segments := []string{"18-24", "25-34", "35-44", "45-54", "55+", "Business", "Student"}
|
||||
|
||||
for _, segment := range segments {
|
||||
var subs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("demographic_segment = ? AND status = ?", segment, "active").
|
||||
Count(&subs)
|
||||
|
||||
demoMetrics := DemoMetrics{
|
||||
Segment: segment,
|
||||
Subscribers: subs,
|
||||
MarketShare: s.calculateDemoMarketShare(ctx, segment),
|
||||
ARPU: s.calculateDemoARPU(ctx, segment),
|
||||
GrowthRate: s.calculateDemoGrowthRate(ctx, segment),
|
||||
}
|
||||
|
||||
metrics.ByDemographic[segment] = demoMetrics
|
||||
}
|
||||
}
|
||||
|
||||
// analyzeCompetitors analyzes competitive landscape
|
||||
func (s *MarketAnalysisService) analyzeCompetitors(_ context.Context, metrics *MarketMetrics) {
|
||||
competitors := []struct {
|
||||
name string
|
||||
subs int64
|
||||
share float64
|
||||
strengths []string
|
||||
weaknesses []string
|
||||
threat string
|
||||
}{
|
||||
{
|
||||
name: "Airalo",
|
||||
subs: 5000000,
|
||||
share: 25.0,
|
||||
strengths: []string{"Large market share", "Global presence", "Brand recognition"},
|
||||
weaknesses: []string{"Higher prices", "Limited customization"},
|
||||
threat: "high",
|
||||
},
|
||||
{
|
||||
name: "Truphone",
|
||||
subs: 2000000,
|
||||
share: 10.0,
|
||||
strengths: []string{"Enterprise focus", "Quality network"},
|
||||
weaknesses: []string{"Limited consumer market", "Higher pricing"},
|
||||
threat: "medium",
|
||||
},
|
||||
{
|
||||
name: "Ubigi",
|
||||
subs: 1500000,
|
||||
share: 7.5,
|
||||
strengths: []string{"Competitive pricing", "Good coverage"},
|
||||
weaknesses: []string{"Smaller market share", "Limited features"},
|
||||
threat: "medium",
|
||||
},
|
||||
{
|
||||
name: "Holafly",
|
||||
subs: 1000000,
|
||||
share: 5.0,
|
||||
strengths: []string{"Simple pricing", "Good customer service"},
|
||||
weaknesses: []string{"Limited carrier partnerships", "Basic features"},
|
||||
threat: "low",
|
||||
},
|
||||
}
|
||||
|
||||
for _, comp := range competitors {
|
||||
metrics.CompetitorAnalysis = append(metrics.CompetitorAnalysis, CompetitorMetrics{
|
||||
Name: comp.name,
|
||||
EstimatedSubs: comp.subs,
|
||||
MarketShare: comp.share,
|
||||
Strengths: comp.strengths,
|
||||
Weaknesses: comp.weaknesses,
|
||||
ThreatLevel: comp.threat,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// identifyOpportunities identifies market penetration opportunities
|
||||
func (s *MarketAnalysisService) identifyOpportunities(_ context.Context, metrics *MarketMetrics) {
|
||||
opportunities := []OpportunityMetrics{
|
||||
{
|
||||
Country: "India",
|
||||
OpportunityType: "Emerging Market",
|
||||
PotentialSubs: 10000000,
|
||||
RequiredInvestment: 5000000,
|
||||
ExpectedROI: 150.0,
|
||||
TimeToMarket: 6,
|
||||
},
|
||||
{
|
||||
Country: "Brazil",
|
||||
OpportunityType: "Latin America Expansion",
|
||||
PotentialSubs: 5000000,
|
||||
RequiredInvestment: 3000000,
|
||||
ExpectedROI: 120.0,
|
||||
TimeToMarket: 4,
|
||||
},
|
||||
{
|
||||
Country: "South Korea",
|
||||
OpportunityType: "Tech-Savvy Market",
|
||||
PotentialSubs: 2000000,
|
||||
RequiredInvestment: 2000000,
|
||||
ExpectedROI: 80.0,
|
||||
TimeToMarket: 3,
|
||||
},
|
||||
{
|
||||
Country: "Nigeria",
|
||||
OpportunityType: "African Market Entry",
|
||||
PotentialSubs: 8000000,
|
||||
RequiredInvestment: 4000000,
|
||||
ExpectedROI: 180.0,
|
||||
TimeToMarket: 8,
|
||||
},
|
||||
}
|
||||
|
||||
metrics.PenetrationOpportunities = opportunities
|
||||
}
|
||||
|
||||
// estimateTotalMarketSize estimates total addressable market
|
||||
func (s *MarketAnalysisService) estimateTotalMarketSize() int64 {
|
||||
// Simplified estimation - would use market research data
|
||||
// Global mobile subscribers ~5.5B, eSIM adoption ~10%
|
||||
return 550000000 // 550M eSIM users globally
|
||||
}
|
||||
|
||||
// calculateGrowthRate calculates growth rate compared to previous period
|
||||
func (s *MarketAnalysisService) calculateGrowthRate(ctx context.Context, currentSubs int64) float64 {
|
||||
// Get subscribers from previous month
|
||||
var prevSubs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("status = ? AND created_at < ?", "active", time.Now().AddDate(0, -1, 0)).
|
||||
Count(&prevSubs)
|
||||
|
||||
if prevSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(currentSubs-prevSubs) / float64(prevSubs) * 100
|
||||
}
|
||||
|
||||
// getCountryPopulation returns population data for a country
|
||||
func (s *MarketAnalysisService) getCountryPopulation(country string) int64 {
|
||||
populations := map[string]int64{
|
||||
"US": 331000000,
|
||||
"UK": 67000000,
|
||||
"DE": 83000000,
|
||||
"FR": 65000000,
|
||||
"JP": 126000000,
|
||||
"AU": 25000000,
|
||||
"CA": 38000000,
|
||||
"SG": 5800000,
|
||||
}
|
||||
return populations[country]
|
||||
}
|
||||
|
||||
// calculatePenetrationRate calculates penetration rate for a country
|
||||
func (s *MarketAnalysisService) calculatePenetrationRate(subs int64, country string) float64 {
|
||||
population := s.getCountryPopulation(country)
|
||||
if population == 0 {
|
||||
return 0
|
||||
}
|
||||
return float64(subs) / float64(population) * 100
|
||||
}
|
||||
|
||||
// calculateCountryGrowthRate calculates growth rate for a country
|
||||
func (s *MarketAnalysisService) calculateCountryGrowthRate(ctx context.Context, country string) float64 {
|
||||
var currentSubs, prevSubs int64
|
||||
|
||||
now := time.Now()
|
||||
prevMonth := now.AddDate(0, -1, 0)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("country = ? AND status = ?", country, "active").
|
||||
Count(¤tSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("country = ? AND status = ? AND created_at < ?", country, "active", prevMonth).
|
||||
Count(&prevSubs)
|
||||
|
||||
if prevSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(currentSubs-prevSubs) / float64(prevSubs) * 100
|
||||
}
|
||||
|
||||
// calculateCountryARPU calculates ARPU for a country
|
||||
func (s *MarketAnalysisService) calculateCountryARPU(ctx context.Context, country string) float64 {
|
||||
var totalRevenue float64
|
||||
var subscriberCount int64
|
||||
|
||||
s.db.WithContext(ctx).Table("billing_transactions bt").
|
||||
Joins("JOIN profiles p ON bt.profile_id = p.id").
|
||||
Where("p.country = ? AND bt.status = ?", country, "completed").
|
||||
Select("COALESCE(SUM(bt.amount), 0)").
|
||||
Scan(&totalRevenue)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("country = ? AND status = ?", country, "active").
|
||||
Count(&subscriberCount)
|
||||
|
||||
if subscriberCount == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return totalRevenue / float64(subscriberCount)
|
||||
}
|
||||
|
||||
// calculateMarketPotential calculates market potential for a country
|
||||
func (s *MarketAnalysisService) calculateMarketPotential(country string) int64 {
|
||||
population := s.getCountryPopulation(country)
|
||||
// Assume 20% of population could adopt eSIM in next 2 years
|
||||
return int64(float64(population) * 0.2)
|
||||
}
|
||||
|
||||
// calculateCarrierMarketShare calculates market share for a carrier
|
||||
func (s *MarketAnalysisService) calculateCarrierMarketShare(ctx context.Context, carrier string) float64 {
|
||||
var carrierSubs, totalSubs int64
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions rps").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Where("rp.carrier_name = ? AND rps.status = ?", carrier, "active").
|
||||
Count(&carrierSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").
|
||||
Where("status = ?", "active").
|
||||
Count(&totalSubs)
|
||||
|
||||
if totalSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(carrierSubs) / float64(totalSubs) * 100
|
||||
}
|
||||
|
||||
// calculateCarrierChurnRate calculates churn rate for a carrier
|
||||
func (s *MarketAnalysisService) calculateCarrierChurnRate(ctx context.Context, carrier string) float64 {
|
||||
var totalSubs, churnedSubs int64
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions rps").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Where("rp.carrier_name = ?", carrier).
|
||||
Count(&totalSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions rps").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Where("rp.carrier_name = ? AND rps.status = ? AND rps.ended_at > ?",
|
||||
carrier, "cancelled", time.Now().AddDate(0, -1, 0)).
|
||||
Count(&churnedSubs)
|
||||
|
||||
if totalSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(churnedSubs) / float64(totalSubs) * 100
|
||||
}
|
||||
|
||||
// calculateCarrierARPU calculates ARPU for a carrier
|
||||
func (s *MarketAnalysisService) calculateCarrierARPU(ctx context.Context, carrier string) float64 {
|
||||
var totalRevenue float64
|
||||
var subscriberCount int64
|
||||
|
||||
s.db.WithContext(ctx).Table("billing_transactions bt").
|
||||
Joins("JOIN rate_plan_subscriptions rps ON bt.subscription_id = rps.id").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Where("rp.carrier_name = ? AND bt.status = ?", carrier, "completed").
|
||||
Select("COALESCE(SUM(bt.amount), 0)").
|
||||
Scan(&totalRevenue)
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions rps").
|
||||
Joins("JOIN rate_plans rp ON rps.rate_plan_id = rp.id").
|
||||
Where("rp.carrier_name = ? AND rps.status = ?", carrier, "active").
|
||||
Count(&subscriberCount)
|
||||
|
||||
if subscriberCount == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return totalRevenue / float64(subscriberCount)
|
||||
}
|
||||
|
||||
// getCarrierNetworkQuality returns network quality score for carrier
|
||||
func (s *MarketAnalysisService) getCarrierNetworkQuality(carrier string) float64 {
|
||||
// Simplified network quality scores
|
||||
quality := map[string]float64{
|
||||
"AT&T": 85.0,
|
||||
"Verizon": 87.0,
|
||||
"T-Mobile": 83.0,
|
||||
"Vodafone": 80.0,
|
||||
"Orange": 78.0,
|
||||
"Deutsche Telekom": 82.0,
|
||||
}
|
||||
return quality[carrier]
|
||||
}
|
||||
|
||||
// getCarrierCoverage returns coverage percentage for carrier
|
||||
func (s *MarketAnalysisService) getCarrierCoverage(carrier string) float64 {
|
||||
// Simplified coverage percentages
|
||||
coverage := map[string]float64{
|
||||
"AT&T": 95.0,
|
||||
"Verizon": 96.0,
|
||||
"T-Mobile": 94.0,
|
||||
"Vodafone": 85.0,
|
||||
"Orange": 88.0,
|
||||
"Deutsche Telekom": 92.0,
|
||||
}
|
||||
return coverage[carrier]
|
||||
}
|
||||
|
||||
// calculateDemoMarketShare calculates market share for demographic segment
|
||||
func (s *MarketAnalysisService) calculateDemoMarketShare(ctx context.Context, segment string) float64 {
|
||||
var segmentSubs, totalSubs int64
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("demographic_segment = ? AND status = ?", segment, "active").
|
||||
Count(&segmentSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("status = ?", "active").
|
||||
Count(&totalSubs)
|
||||
|
||||
if totalSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(segmentSubs) / float64(totalSubs) * 100
|
||||
}
|
||||
|
||||
// calculateDemoARPU calculates ARPU for demographic segment
|
||||
func (s *MarketAnalysisService) calculateDemoARPU(ctx context.Context, segment string) float64 {
|
||||
var totalRevenue float64
|
||||
var subscriberCount int64
|
||||
|
||||
s.db.WithContext(ctx).Table("billing_transactions bt").
|
||||
Joins("JOIN profiles p ON bt.profile_id = p.id").
|
||||
Where("p.demographic_segment = ? AND bt.status = ?", segment, "completed").
|
||||
Select("COALESCE(SUM(bt.amount), 0)").
|
||||
Scan(&totalRevenue)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("demographic_segment = ? AND status = ?", segment, "active").
|
||||
Count(&subscriberCount)
|
||||
|
||||
if subscriberCount == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return totalRevenue / float64(subscriberCount)
|
||||
}
|
||||
|
||||
// calculateDemoGrowthRate calculates growth rate for demographic segment
|
||||
func (s *MarketAnalysisService) calculateDemoGrowthRate(ctx context.Context, segment string) float64 {
|
||||
var currentSubs, prevSubs int64
|
||||
|
||||
now := time.Now()
|
||||
prevMonth := now.AddDate(0, -1, 0)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("demographic_segment = ? AND status = ?", segment, "active").
|
||||
Count(¤tSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("demographic_segment = ? AND status = ? AND created_at < ?", segment, "active", prevMonth).
|
||||
Count(&prevSubs)
|
||||
|
||||
if prevSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(currentSubs-prevSubs) / float64(prevSubs) * 100
|
||||
}
|
||||
|
||||
// GetMarketTrends returns market penetration trends
|
||||
func (s *MarketAnalysisService) GetMarketTrends(ctx context.Context, period string) ([]map[string]interface{}, error) {
|
||||
trends := make([]map[string]interface{}, 0)
|
||||
|
||||
// Generate trend data for the last 12 months
|
||||
for i := 11; i >= 0; i-- {
|
||||
date := time.Now().AddDate(0, -i, 0)
|
||||
|
||||
var subs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("status = ? AND created_at <= ?", "active", date).
|
||||
Count(&subs)
|
||||
|
||||
trend := map[string]interface{}{
|
||||
"month": date.Format("2006-01"),
|
||||
"subscribers": subs,
|
||||
"market_share": float64(subs) / 550000000 * 100, // vs total market
|
||||
}
|
||||
|
||||
trends = append(trends, trend)
|
||||
}
|
||||
|
||||
return trends, nil
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package analytics
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service provides analytics operations
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewService creates a new analytics service
|
||||
func NewService(db *gorm.DB, logger *logrus.Logger) *Service {
|
||||
return &Service{db: db, logger: logger}
|
||||
}
|
||||
|
||||
// GetDashboard retrieves the main analytics dashboard
|
||||
func (s *Service) GetDashboard(ctx context.Context, filter *AnalyticsFilter) (*DashboardMetrics, error) {
|
||||
dashboard := &DashboardMetrics{
|
||||
TenantID: filter.TenantID,
|
||||
Period: fmt.Sprintf("%s to %s", filter.StartDate.Format("2006-01-02"), filter.EndDate.Format("2006-01-02")),
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
var err error
|
||||
dashboard.Revenue, err = s.getRevenueMetrics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get revenue metrics")
|
||||
}
|
||||
|
||||
dashboard.Subscribers, err = s.getSubscriberStats(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get subscriber stats")
|
||||
}
|
||||
|
||||
dashboard.Usage, err = s.getUsageMetrics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get usage metrics")
|
||||
}
|
||||
|
||||
dashboard.Carriers, err = s.getCarrierMetrics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get carrier metrics")
|
||||
}
|
||||
|
||||
dashboard.Geographic, err = s.getGeoMetrics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get geo metrics")
|
||||
}
|
||||
|
||||
dashboard.Performance, err = s.getPerformanceStats(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to get performance stats")
|
||||
}
|
||||
|
||||
return dashboard, nil
|
||||
}
|
||||
|
||||
// GetRevenueAnalytics retrieves detailed revenue analytics
|
||||
func (s *Service) GetRevenueAnalytics(ctx context.Context, filter *AnalyticsFilter) (*RevenueMetrics, error) {
|
||||
metrics, err := s.getRevenueMetrics(ctx, filter)
|
||||
return &metrics, err
|
||||
}
|
||||
|
||||
func (s *Service) getRevenueMetrics(ctx context.Context, filter *AnalyticsFilter) (RevenueMetrics, error) {
|
||||
metrics := RevenueMetrics{
|
||||
RevenueByCountry: make(map[string]float64),
|
||||
RevenueByCarrier: make(map[string]float64),
|
||||
RevenueByPlan: make(map[string]float64),
|
||||
RevenueByCurrency: make(map[string]float64),
|
||||
}
|
||||
|
||||
// Query total revenue
|
||||
var totalRevenue float64
|
||||
s.db.WithContext(ctx).Table("billing_transactions").
|
||||
Where("tenant_id = ? AND created_at BETWEEN ? AND ? AND status = ?",
|
||||
filter.TenantID, filter.StartDate, filter.EndDate, "completed").
|
||||
Select("COALESCE(SUM(amount), 0)").Scan(&totalRevenue)
|
||||
metrics.TotalRevenue = totalRevenue
|
||||
|
||||
// Query revenue by country
|
||||
type countryRevenue struct {
|
||||
Country string
|
||||
Total float64
|
||||
}
|
||||
var byCountry []countryRevenue
|
||||
s.db.WithContext(ctx).Table("billing_transactions").
|
||||
Select("country, SUM(amount) as total").
|
||||
Where("tenant_id = ? AND created_at BETWEEN ? AND ?", filter.TenantID, filter.StartDate, filter.EndDate).
|
||||
Group("country").Scan(&byCountry)
|
||||
for _, cr := range byCountry {
|
||||
metrics.RevenueByCountry[cr.Country] = cr.Total
|
||||
}
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
func (s *Service) getSubscriberStats(ctx context.Context, filter *AnalyticsFilter) (SubscriberStats, error) {
|
||||
stats := SubscriberStats{
|
||||
ByCountry: make(map[string]int64),
|
||||
ByPlan: make(map[string]int64),
|
||||
ByStatus: make(map[string]int64),
|
||||
}
|
||||
|
||||
// Query active subscribers
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("tenant_id = ? AND status = ?", filter.TenantID, "active").
|
||||
Count(&stats.TotalActive)
|
||||
|
||||
// Query new subscribers in period
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("tenant_id = ? AND created_at BETWEEN ? AND ?", filter.TenantID, filter.StartDate, filter.EndDate).
|
||||
Count(&stats.NewThisPeriod)
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (s *Service) getUsageMetrics(ctx context.Context, filter *AnalyticsFilter) (UsageMetrics, error) {
|
||||
metrics := UsageMetrics{
|
||||
UsageByCountry: make(map[string]int64),
|
||||
UsageByCarrier: make(map[string]int64),
|
||||
}
|
||||
|
||||
// Query total data usage
|
||||
s.db.WithContext(ctx).Table("rate_plan_usage").
|
||||
Where("created_at BETWEEN ? AND ?", filter.StartDate, filter.EndDate).
|
||||
Select("COALESCE(SUM(data_used), 0)").Scan(&metrics.TotalDataUsedMB)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
func (s *Service) getCarrierMetrics(ctx context.Context, _ *AnalyticsFilter) (CarrierMetrics, error) {
|
||||
metrics := CarrierMetrics{
|
||||
ByCarrier: make(map[string]CarrierStat),
|
||||
FailuresByReason: make(map[string]int64),
|
||||
}
|
||||
|
||||
// Query carrier stats
|
||||
var activeCount int64
|
||||
s.db.WithContext(ctx).Table("carriers").
|
||||
Where("is_active = ?", true).
|
||||
Count(&activeCount)
|
||||
metrics.ActiveCarriers = int(activeCount)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
func (s *Service) getGeoMetrics(_ context.Context, _ *AnalyticsFilter) (GeoMetrics, error) {
|
||||
metrics := GeoMetrics{
|
||||
RevenueByContinent: make(map[string]float64),
|
||||
}
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
func (s *Service) getPerformanceStats(_ context.Context, _ *AnalyticsFilter) (PerformanceStats, error) {
|
||||
return PerformanceStats{
|
||||
Uptime: 99.9,
|
||||
ErrorRate: 0.1,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// CreateScheduledReport creates a scheduled report
|
||||
func (s *Service) CreateScheduledReport(ctx context.Context, report *ScheduledReport) error {
|
||||
if err := s.db.WithContext(ctx).Create(report).Error; err != nil {
|
||||
return fmt.Errorf("failed to create scheduled report: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListScheduledReports lists scheduled reports for a tenant
|
||||
func (s *Service) ListScheduledReports(ctx context.Context, tenantID string) ([]*ScheduledReport, error) {
|
||||
var reports []*ScheduledReport
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&reports).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to list reports: %w", err)
|
||||
}
|
||||
return reports, nil
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package analytics
|
||||
|
||||
import "time"
|
||||
|
||||
// DashboardMetrics represents the main analytics dashboard data
|
||||
type DashboardMetrics struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Period string `json:"period"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
Revenue RevenueMetrics `json:"revenue"`
|
||||
Subscribers SubscriberStats `json:"subscribers"`
|
||||
Usage UsageMetrics `json:"usage"`
|
||||
Carriers CarrierMetrics `json:"carriers"`
|
||||
Geographic GeoMetrics `json:"geographic"`
|
||||
Performance PerformanceStats `json:"performance"`
|
||||
}
|
||||
|
||||
// RevenueMetrics contains revenue analytics
|
||||
type RevenueMetrics struct {
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
RecurringRevenue float64 `json:"recurring_revenue"`
|
||||
OneTimeRevenue float64 `json:"one_time_revenue"`
|
||||
RefundsTotal float64 `json:"refunds_total"`
|
||||
NetRevenue float64 `json:"net_revenue"`
|
||||
GrowthRate float64 `json:"growth_rate_pct"`
|
||||
ARPU float64 `json:"arpu"`
|
||||
RevenueByCountry map[string]float64 `json:"revenue_by_country"`
|
||||
RevenueByCarrier map[string]float64 `json:"revenue_by_carrier"`
|
||||
RevenueByPlan map[string]float64 `json:"revenue_by_plan"`
|
||||
RevenueByCurrency map[string]float64 `json:"revenue_by_currency"`
|
||||
DailyRevenue []TimeSeriesPoint `json:"daily_revenue"`
|
||||
MonthlyRevenue []TimeSeriesPoint `json:"monthly_revenue"`
|
||||
}
|
||||
|
||||
// SubscriberStats contains subscriber analytics
|
||||
type SubscriberStats struct {
|
||||
TotalActive int64 `json:"total_active"`
|
||||
NewThisPeriod int64 `json:"new_this_period"`
|
||||
ChurnedThisPeriod int64 `json:"churned_this_period"`
|
||||
ChurnRate float64 `json:"churn_rate_pct"`
|
||||
RetentionRate float64 `json:"retention_rate_pct"`
|
||||
LifetimeValue float64 `json:"lifetime_value"`
|
||||
ByCountry map[string]int64 `json:"by_country"`
|
||||
ByPlan map[string]int64 `json:"by_plan"`
|
||||
ByStatus map[string]int64 `json:"by_status"`
|
||||
GrowthTrend []TimeSeriesPoint `json:"growth_trend"`
|
||||
}
|
||||
|
||||
// UsageMetrics contains usage analytics
|
||||
type UsageMetrics struct {
|
||||
TotalDataUsedMB int64 `json:"total_data_used_mb"`
|
||||
TotalVoiceMinutes int64 `json:"total_voice_minutes"`
|
||||
TotalSMSCount int64 `json:"total_sms_count"`
|
||||
AverageDataPerUser float64 `json:"avg_data_per_user_mb"`
|
||||
PeakUsageHour int `json:"peak_usage_hour"`
|
||||
UsageByCountry map[string]int64 `json:"usage_by_country"`
|
||||
UsageByCarrier map[string]int64 `json:"usage_by_carrier"`
|
||||
DailyUsage []TimeSeriesPoint `json:"daily_usage"`
|
||||
}
|
||||
|
||||
// CarrierMetrics contains carrier performance analytics
|
||||
type CarrierMetrics struct {
|
||||
TotalCarriers int `json:"total_carriers"`
|
||||
ActiveCarriers int `json:"active_carriers"`
|
||||
AvgSuccessRate float64 `json:"avg_success_rate_pct"`
|
||||
AvgResponseTime float64 `json:"avg_response_time_ms"`
|
||||
ByCarrier map[string]CarrierStat `json:"by_carrier"`
|
||||
FailuresByReason map[string]int64 `json:"failures_by_reason"`
|
||||
}
|
||||
|
||||
// CarrierStat contains per-carrier statistics
|
||||
type CarrierStat struct {
|
||||
CarrierID string `json:"carrier_id"`
|
||||
CarrierName string `json:"carrier_name"`
|
||||
TotalRequests int64 `json:"total_requests"`
|
||||
SuccessRate float64 `json:"success_rate_pct"`
|
||||
AvgResponseMs float64 `json:"avg_response_ms"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
ActiveProfiles int64 `json:"active_profiles"`
|
||||
}
|
||||
|
||||
// GeoMetrics contains geographic analytics
|
||||
type GeoMetrics struct {
|
||||
TopCountries []CountryStat `json:"top_countries"`
|
||||
TopRegions []RegionStat `json:"top_regions"`
|
||||
CoverageCountries int `json:"coverage_countries"`
|
||||
RevenueByContinent map[string]float64 `json:"revenue_by_continent"`
|
||||
}
|
||||
|
||||
// CountryStat contains per-country statistics
|
||||
type CountryStat struct {
|
||||
CountryCode string `json:"country_code"`
|
||||
CountryName string `json:"country_name"`
|
||||
Subscribers int64 `json:"subscribers"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
DataUsedMB int64 `json:"data_used_mb"`
|
||||
GrowthRate float64 `json:"growth_rate_pct"`
|
||||
}
|
||||
|
||||
// RegionStat contains per-region statistics
|
||||
type RegionStat struct {
|
||||
Region string `json:"region"`
|
||||
Subscribers int64 `json:"subscribers"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
}
|
||||
|
||||
// PerformanceStats contains system performance metrics
|
||||
type PerformanceStats struct {
|
||||
APILatencyP50 float64 `json:"api_latency_p50_ms"`
|
||||
APILatencyP95 float64 `json:"api_latency_p95_ms"`
|
||||
APILatencyP99 float64 `json:"api_latency_p99_ms"`
|
||||
ErrorRate float64 `json:"error_rate_pct"`
|
||||
Uptime float64 `json:"uptime_pct"`
|
||||
TotalAPIRequests int64 `json:"total_api_requests"`
|
||||
}
|
||||
|
||||
// TimeSeriesPoint represents a data point in time series
|
||||
type TimeSeriesPoint struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Value float64 `json:"value"`
|
||||
Label string `json:"label,omitempty"`
|
||||
}
|
||||
|
||||
// AnalyticsFilter defines filtering options for analytics queries
|
||||
type AnalyticsFilter struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
StartDate time.Time `json:"start_date"`
|
||||
EndDate time.Time `json:"end_date"`
|
||||
Countries []string `json:"countries,omitempty"`
|
||||
Carriers []string `json:"carriers,omitempty"`
|
||||
Plans []string `json:"plans,omitempty"`
|
||||
GroupBy string `json:"group_by,omitempty"`
|
||||
Granularity string `json:"granularity,omitempty"`
|
||||
}
|
||||
|
||||
// ReportType defines available report types
|
||||
type ReportType string
|
||||
|
||||
const (
|
||||
ReportTypeRevenue ReportType = "revenue"
|
||||
ReportTypeSubscribers ReportType = "subscribers"
|
||||
ReportTypeUsage ReportType = "usage"
|
||||
ReportTypeCarriers ReportType = "carriers"
|
||||
ReportTypeGeographic ReportType = "geographic"
|
||||
ReportTypeExecutive ReportType = "executive"
|
||||
)
|
||||
|
||||
// ScheduledReport defines a scheduled analytics report
|
||||
type ScheduledReport struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
Name string `json:"name"`
|
||||
ReportType ReportType `json:"report_type"`
|
||||
Schedule string `json:"schedule"`
|
||||
Recipients []string `json:"recipients" gorm:"serializer:json"`
|
||||
Filter AnalyticsFilter `json:"filter" gorm:"serializer:json"`
|
||||
Format string `json:"format"`
|
||||
IsActive bool `json:"is_active"`
|
||||
LastRunAt *time.Time `json:"last_run_at"`
|
||||
NextRunAt *time.Time `json:"next_run_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package compliance
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service provides compliance management operations
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewService creates a new compliance service
|
||||
func NewService(db *gorm.DB, logger *logrus.Logger) *Service {
|
||||
return &Service{db: db, logger: logger}
|
||||
}
|
||||
|
||||
// CreateDSR creates a new data subject request
|
||||
func (s *Service) CreateDSR(ctx context.Context, req *DataSubjectRequest) error {
|
||||
req.ID = uuid.New().String()
|
||||
req.Status = DSRStatusPending
|
||||
req.RequestedAt = time.Now()
|
||||
req.DueDate = s.calculateDueDate(req.Regulation)
|
||||
req.CreatedAt = time.Now()
|
||||
req.UpdatedAt = time.Now()
|
||||
|
||||
if err := s.db.WithContext(ctx).Create(req).Error; err != nil {
|
||||
return fmt.Errorf("failed to create DSR: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"dsr_id": req.ID,
|
||||
"type": req.RequestType,
|
||||
"regulation": req.Regulation,
|
||||
}).Info("Data subject request created")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) calculateDueDate(reg Regulation) time.Time {
|
||||
switch reg {
|
||||
case RegulationGDPR:
|
||||
return time.Now().AddDate(0, 1, 0) // 30 days
|
||||
case RegulationCCPA:
|
||||
return time.Now().AddDate(0, 0, 45) // 45 days
|
||||
default:
|
||||
return time.Now().AddDate(0, 1, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// GetDSR retrieves a data subject request
|
||||
func (s *Service) GetDSR(ctx context.Context, id string) (*DataSubjectRequest, error) {
|
||||
var req DataSubjectRequest
|
||||
if err := s.db.WithContext(ctx).First(&req, "id = ?", id).Error; err != nil {
|
||||
return nil, fmt.Errorf("DSR not found: %w", err)
|
||||
}
|
||||
return &req, nil
|
||||
}
|
||||
|
||||
// ListDSRs lists data subject requests for a tenant
|
||||
func (s *Service) ListDSRs(ctx context.Context, tenantID string, status *DSRStatus) ([]*DataSubjectRequest, error) {
|
||||
var requests []*DataSubjectRequest
|
||||
query := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
|
||||
if status != nil {
|
||||
query = query.Where("status = ?", *status)
|
||||
}
|
||||
if err := query.Order("created_at DESC").Find(&requests).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to list DSRs: %w", err)
|
||||
}
|
||||
return requests, nil
|
||||
}
|
||||
|
||||
// ProcessDSR processes a data subject request
|
||||
func (s *Service) ProcessDSR(ctx context.Context, id string) error {
|
||||
req, err := s.GetDSR(ctx, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req.Status = DSRStatusProcessing
|
||||
req.UpdatedAt = time.Now()
|
||||
|
||||
switch req.RequestType {
|
||||
case DSRTypeAccess, DSRTypePortability:
|
||||
return s.processAccessRequest(ctx, req)
|
||||
case DSRTypeErasure:
|
||||
return s.processErasureRequest(ctx, req)
|
||||
case DSRTypeRectify:
|
||||
return s.processRectificationRequest(ctx, req)
|
||||
default:
|
||||
return fmt.Errorf("unsupported request type: %s", req.RequestType)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) processAccessRequest(ctx context.Context, req *DataSubjectRequest) error {
|
||||
// Export user data
|
||||
s.logger.WithField("dsr_id", req.ID).Info("Processing access request")
|
||||
now := time.Now()
|
||||
req.Status = DSRStatusCompleted
|
||||
req.CompletedAt = &now
|
||||
return s.db.WithContext(ctx).Save(req).Error
|
||||
}
|
||||
|
||||
func (s *Service) processErasureRequest(ctx context.Context, req *DataSubjectRequest) error {
|
||||
s.logger.WithField("dsr_id", req.ID).Info("Processing erasure request")
|
||||
now := time.Now()
|
||||
req.Status = DSRStatusCompleted
|
||||
req.CompletedAt = &now
|
||||
return s.db.WithContext(ctx).Save(req).Error
|
||||
}
|
||||
|
||||
func (s *Service) processRectificationRequest(ctx context.Context, req *DataSubjectRequest) error {
|
||||
s.logger.WithField("dsr_id", req.ID).Info("Processing rectification request")
|
||||
now := time.Now()
|
||||
req.Status = DSRStatusCompleted
|
||||
req.CompletedAt = &now
|
||||
return s.db.WithContext(ctx).Save(req).Error
|
||||
}
|
||||
|
||||
// RecordConsent records user consent
|
||||
func (s *Service) RecordConsent(ctx context.Context, consent *ConsentRecord) error {
|
||||
consent.ID = uuid.New().String()
|
||||
consent.CreatedAt = time.Now()
|
||||
consent.UpdatedAt = time.Now()
|
||||
if consent.Granted {
|
||||
now := time.Now()
|
||||
consent.GrantedAt = &now
|
||||
}
|
||||
return s.db.WithContext(ctx).Create(consent).Error
|
||||
}
|
||||
|
||||
// RevokeConsent revokes user consent
|
||||
func (s *Service) RevokeConsent(ctx context.Context, subjectID string, consentType ConsentType) error {
|
||||
now := time.Now()
|
||||
return s.db.WithContext(ctx).Model(&ConsentRecord{}).
|
||||
Where("subject_id = ? AND consent_type = ?", subjectID, consentType).
|
||||
Updates(map[string]any{"granted": false, "revoked_at": now, "updated_at": now}).Error
|
||||
}
|
||||
|
||||
// GetConsents retrieves consent records for a subject
|
||||
func (s *Service) GetConsents(ctx context.Context, subjectID string) ([]*ConsentRecord, error) {
|
||||
var consents []*ConsentRecord
|
||||
if err := s.db.WithContext(ctx).Where("subject_id = ?", subjectID).Find(&consents).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return consents, nil
|
||||
}
|
||||
|
||||
// LogAudit creates an audit log entry
|
||||
func (s *Service) LogAudit(ctx context.Context, log *AuditLog) error {
|
||||
log.ID = uuid.New().String()
|
||||
log.Timestamp = time.Now()
|
||||
return s.db.WithContext(ctx).Create(log).Error
|
||||
}
|
||||
|
||||
// QueryAuditLogs queries audit logs with filters
|
||||
func (s *Service) QueryAuditLogs(ctx context.Context, tenantID string, filter *AuditLogFilter) ([]*AuditLog, error) {
|
||||
var logs []*AuditLog
|
||||
query := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
|
||||
if filter.Jurisdiction != "" {
|
||||
query = query.Where("jurisdiction = ?", filter.Jurisdiction)
|
||||
}
|
||||
if filter.ActorID != "" {
|
||||
query = query.Where("actor_id = ?", filter.ActorID)
|
||||
}
|
||||
if filter.Action != "" {
|
||||
query = query.Where("action = ?", filter.Action)
|
||||
}
|
||||
if !filter.StartDate.IsZero() {
|
||||
query = query.Where("timestamp >= ?", filter.StartDate)
|
||||
}
|
||||
if !filter.EndDate.IsZero() {
|
||||
query = query.Where("timestamp <= ?", filter.EndDate)
|
||||
}
|
||||
if err := query.Order("timestamp DESC").Limit(filter.Limit).Find(&logs).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return logs, nil
|
||||
}
|
||||
|
||||
// AuditLogFilter defines audit log query filters
|
||||
type AuditLogFilter struct {
|
||||
Jurisdiction string
|
||||
ActorID string
|
||||
Action string
|
||||
StartDate time.Time
|
||||
EndDate time.Time
|
||||
Limit int
|
||||
}
|
||||
|
||||
// SetDataResidency sets data residency configuration
|
||||
func (s *Service) SetDataResidency(ctx context.Context, config *DataResidencyConfig) error {
|
||||
config.ID = uuid.New().String()
|
||||
config.CreatedAt = time.Now()
|
||||
config.UpdatedAt = time.Now()
|
||||
return s.db.WithContext(ctx).Save(config).Error
|
||||
}
|
||||
|
||||
// GetDataResidency retrieves data residency configuration
|
||||
func (s *Service) GetDataResidency(ctx context.Context, tenantID string) (*DataResidencyConfig, error) {
|
||||
var config DataResidencyConfig
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&config).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package compliance
|
||||
|
||||
import "time"
|
||||
|
||||
// Regulation represents a compliance regulation
|
||||
type Regulation string
|
||||
|
||||
const (
|
||||
RegulationGDPR Regulation = "GDPR"
|
||||
RegulationCCPA Regulation = "CCPA"
|
||||
RegulationLGPD Regulation = "LGPD"
|
||||
RegulationPDPA Regulation = "PDPA"
|
||||
RegulationPIPL Regulation = "PIPL"
|
||||
)
|
||||
|
||||
// ConsentType represents types of data processing consent
|
||||
type ConsentType string
|
||||
|
||||
const (
|
||||
ConsentTypeMarketing ConsentType = "marketing"
|
||||
ConsentTypeAnalytics ConsentType = "analytics"
|
||||
ConsentTypeThirdParty ConsentType = "third_party"
|
||||
ConsentTypeDataSharing ConsentType = "data_sharing"
|
||||
ConsentTypePersonalized ConsentType = "personalized"
|
||||
)
|
||||
|
||||
// DataSubjectRequest represents a GDPR/CCPA data subject request
|
||||
type DataSubjectRequest struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
SubjectID string `json:"subject_id" gorm:"index"`
|
||||
SubjectEmail string `json:"subject_email"`
|
||||
RequestType DSRType `json:"request_type"`
|
||||
Regulation Regulation `json:"regulation"`
|
||||
Status DSRStatus `json:"status" gorm:"index"`
|
||||
RequestedAt time.Time `json:"requested_at"`
|
||||
VerifiedAt *time.Time `json:"verified_at"`
|
||||
CompletedAt *time.Time `json:"completed_at"`
|
||||
DueDate time.Time `json:"due_date"`
|
||||
Notes string `json:"notes"`
|
||||
DataExportURL string `json:"data_export_url,omitempty"`
|
||||
Metadata map[string]any `json:"metadata" gorm:"serializer:json"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// DSRType represents data subject request types
|
||||
type DSRType string
|
||||
|
||||
const (
|
||||
DSRTypeAccess DSRType = "access"
|
||||
DSRTypeRectify DSRType = "rectification"
|
||||
DSRTypeErasure DSRType = "erasure"
|
||||
DSRTypePortability DSRType = "portability"
|
||||
DSRTypeRestrict DSRType = "restriction"
|
||||
DSRTypeObject DSRType = "objection"
|
||||
)
|
||||
|
||||
// DSRStatus represents request status
|
||||
type DSRStatus string
|
||||
|
||||
const (
|
||||
DSRStatusPending DSRStatus = "pending"
|
||||
DSRStatusVerifying DSRStatus = "verifying"
|
||||
DSRStatusProcessing DSRStatus = "processing"
|
||||
DSRStatusCompleted DSRStatus = "completed"
|
||||
DSRStatusRejected DSRStatus = "rejected"
|
||||
)
|
||||
|
||||
// ConsentRecord tracks user consent
|
||||
type ConsentRecord struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
SubjectID string `json:"subject_id" gorm:"index"`
|
||||
ConsentType ConsentType `json:"consent_type"`
|
||||
Granted bool `json:"granted"`
|
||||
GrantedAt *time.Time `json:"granted_at"`
|
||||
RevokedAt *time.Time `json:"revoked_at"`
|
||||
IPAddress string `json:"ip_address"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
ConsentText string `json:"consent_text"`
|
||||
Version string `json:"version"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// DataResidencyConfig defines data residency requirements
|
||||
type DataResidencyConfig struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"uniqueIndex"`
|
||||
PrimaryRegion string `json:"primary_region"`
|
||||
AllowedRegions []string `json:"allowed_regions" gorm:"serializer:json"`
|
||||
RestrictedData []string `json:"restricted_data" gorm:"serializer:json"`
|
||||
EncryptionReq bool `json:"encryption_required"`
|
||||
RetentionDays int `json:"retention_days"`
|
||||
CrossBorderRules []CrossBorderRule `json:"cross_border_rules" gorm:"serializer:json"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// CrossBorderRule defines rules for cross-border data transfer
|
||||
type CrossBorderRule struct {
|
||||
FromRegion string `json:"from_region"`
|
||||
ToRegion string `json:"to_region"`
|
||||
Allowed bool `json:"allowed"`
|
||||
RequiresSCC bool `json:"requires_scc"`
|
||||
RequiresDPIA bool `json:"requires_dpia"`
|
||||
}
|
||||
|
||||
// AuditLog represents a compliance audit log entry
|
||||
type AuditLog struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
Jurisdiction string `json:"jurisdiction" gorm:"index"`
|
||||
ActorID string `json:"actor_id" gorm:"index"`
|
||||
ActorType string `json:"actor_type"`
|
||||
Action string `json:"action" gorm:"index"`
|
||||
ResourceType string `json:"resource_type"`
|
||||
ResourceID string `json:"resource_id"`
|
||||
OldValue map[string]any `json:"old_value" gorm:"serializer:json"`
|
||||
NewValue map[string]any `json:"new_value" gorm:"serializer:json"`
|
||||
IPAddress string `json:"ip_address"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
Timestamp time.Time `json:"timestamp" gorm:"index"`
|
||||
Metadata map[string]any `json:"metadata" gorm:"serializer:json"`
|
||||
}
|
||||
|
||||
// RegulatoryReport represents a regulatory compliance report
|
||||
type RegulatoryReport struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
Regulation Regulation `json:"regulation"`
|
||||
ReportType string `json:"report_type"`
|
||||
PeriodStart time.Time `json:"period_start"`
|
||||
PeriodEnd time.Time `json:"period_end"`
|
||||
Status string `json:"status"`
|
||||
FileURL string `json:"file_url"`
|
||||
SubmittedAt *time.Time `json:"submitted_at"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// PrivacyPolicy tracks privacy policy versions
|
||||
type PrivacyPolicy struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
Version string `json:"version"`
|
||||
Content string `json:"content"`
|
||||
Regulation Regulation `json:"regulation"`
|
||||
EffectiveAt time.Time `json:"effective_at"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
package currency
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// RateProviderType defines external rate providers
|
||||
type RateProviderType string
|
||||
|
||||
const (
|
||||
ProviderOpenExchange RateProviderType = "openexchangerates"
|
||||
ProviderFixer RateProviderType = "fixer"
|
||||
ProviderXE RateProviderType = "xe"
|
||||
ProviderInternal RateProviderType = "internal"
|
||||
)
|
||||
|
||||
// RealTimeExchangeService provides real-time exchange rates
|
||||
type RealTimeExchangeService struct {
|
||||
provider RateProviderType
|
||||
apiKey string
|
||||
baseCurrency string
|
||||
rates map[string]float64
|
||||
lastUpdate time.Time
|
||||
cacheTTL time.Duration
|
||||
mu sync.RWMutex
|
||||
logger *logrus.Logger
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
// ExchangeRateConfig configures the exchange rate service
|
||||
type ExchangeRateConfig struct {
|
||||
Provider RateProviderType
|
||||
APIKey string
|
||||
BaseCurrency string
|
||||
CacheTTL time.Duration
|
||||
}
|
||||
|
||||
// NewRealTimeExchangeService creates a new exchange rate service
|
||||
func NewRealTimeExchangeService(config ExchangeRateConfig, logger *logrus.Logger) *RealTimeExchangeService {
|
||||
if config.CacheTTL == 0 {
|
||||
config.CacheTTL = 15 * time.Minute
|
||||
}
|
||||
if config.BaseCurrency == "" {
|
||||
config.BaseCurrency = "USD"
|
||||
}
|
||||
|
||||
svc := &RealTimeExchangeService{
|
||||
provider: config.Provider,
|
||||
apiKey: config.APIKey,
|
||||
baseCurrency: config.BaseCurrency,
|
||||
rates: make(map[string]float64),
|
||||
cacheTTL: config.CacheTTL,
|
||||
logger: logger,
|
||||
httpClient: &http.Client{Timeout: 10 * time.Second},
|
||||
}
|
||||
|
||||
// Initialize with default rates
|
||||
svc.initDefaultRates()
|
||||
|
||||
return svc
|
||||
}
|
||||
|
||||
func (s *RealTimeExchangeService) initDefaultRates() {
|
||||
s.rates = map[string]float64{
|
||||
"USD": 1.0,
|
||||
"EUR": 0.92,
|
||||
"GBP": 0.79,
|
||||
"JPY": 149.50,
|
||||
"CNY": 7.24,
|
||||
"INR": 83.12,
|
||||
"BRL": 4.97,
|
||||
"CAD": 1.36,
|
||||
"AUD": 1.53,
|
||||
"CHF": 0.88,
|
||||
"SGD": 1.34,
|
||||
"HKD": 7.82,
|
||||
"KRW": 1320.0,
|
||||
"MXN": 17.15,
|
||||
"ZAR": 18.50,
|
||||
}
|
||||
s.lastUpdate = time.Now()
|
||||
}
|
||||
|
||||
// GetRate returns the exchange rate for a currency pair
|
||||
func (s *RealTimeExchangeService) GetRate(ctx context.Context, from, to string) (float64, error) {
|
||||
s.mu.RLock()
|
||||
needsRefresh := time.Since(s.lastUpdate) > s.cacheTTL
|
||||
s.mu.RUnlock()
|
||||
|
||||
if needsRefresh {
|
||||
if err := s.RefreshRates(ctx); err != nil {
|
||||
s.logger.WithError(err).Warn("Failed to refresh rates, using cached")
|
||||
}
|
||||
}
|
||||
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
fromRate, fromOK := s.rates[from]
|
||||
toRate, toOK := s.rates[to]
|
||||
|
||||
if !fromOK {
|
||||
return 0, fmt.Errorf("unknown currency: %s", from)
|
||||
}
|
||||
if !toOK {
|
||||
return 0, fmt.Errorf("unknown currency: %s", to)
|
||||
}
|
||||
|
||||
// Convert through base currency
|
||||
return toRate / fromRate, nil
|
||||
}
|
||||
|
||||
// Convert converts an amount between currencies
|
||||
func (s *RealTimeExchangeService) Convert(ctx context.Context, amount float64, from, to string) (float64, error) {
|
||||
rate, err := s.GetRate(ctx, from, to)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return amount * rate, nil
|
||||
}
|
||||
|
||||
// RefreshRates fetches latest rates from provider
|
||||
func (s *RealTimeExchangeService) RefreshRates(ctx context.Context) error {
|
||||
var err error
|
||||
|
||||
switch s.provider {
|
||||
case ProviderOpenExchange:
|
||||
err = s.fetchOpenExchangeRates(ctx)
|
||||
case ProviderFixer:
|
||||
err = s.fetchFixerRates(ctx)
|
||||
case ProviderInternal:
|
||||
// Use internal rates, no fetch needed
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unsupported provider: %s", s.provider)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
s.lastUpdate = time.Now()
|
||||
s.mu.Unlock()
|
||||
|
||||
s.logger.Info("Exchange rates refreshed")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RealTimeExchangeService) fetchOpenExchangeRates(ctx context.Context) error {
|
||||
url := fmt.Sprintf("https://openexchangerates.org/api/latest.json?app_id=%s&base=%s",
|
||||
s.apiKey, s.baseCurrency)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("API returned status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Rates map[string]float64 `json:"rates"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
for currency, rate := range result.Rates {
|
||||
s.rates[currency] = rate
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *RealTimeExchangeService) fetchFixerRates(ctx context.Context) error {
|
||||
url := fmt.Sprintf("http://data.fixer.io/api/latest?access_key=%s&base=%s",
|
||||
s.apiKey, s.baseCurrency)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", url, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resp, err := s.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Rates map[string]float64 `json:"rates"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !result.Success {
|
||||
return fmt.Errorf("fixer API returned error")
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
for currency, rate := range result.Rates {
|
||||
s.rates[currency] = rate
|
||||
}
|
||||
s.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAllRates returns all cached rates
|
||||
func (s *RealTimeExchangeService) GetAllRates() map[string]float64 {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
rates := make(map[string]float64)
|
||||
for k, v := range s.rates {
|
||||
rates[k] = v
|
||||
}
|
||||
return rates
|
||||
}
|
||||
|
||||
// GetSupportedCurrencies returns list of supported currencies
|
||||
func (s *RealTimeExchangeService) GetSupportedCurrencies() []string {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
currencies := make([]string, 0, len(s.rates))
|
||||
for c := range s.rates {
|
||||
currencies = append(currencies, c)
|
||||
}
|
||||
return currencies
|
||||
}
|
||||
|
||||
// LastUpdateTime returns when rates were last updated
|
||||
func (s *RealTimeExchangeService) LastUpdateTime() time.Time {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
return s.lastUpdate
|
||||
}
|
||||
|
||||
// ExchangeRateHistory stores historical exchange rates
|
||||
type ExchangeRateHistory struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
FromCurr string `json:"from_currency" gorm:"index"`
|
||||
ToCurr string `json:"to_currency" gorm:"index"`
|
||||
Rate float64 `json:"rate"`
|
||||
Provider string `json:"provider"`
|
||||
Timestamp time.Time `json:"timestamp" gorm:"index"`
|
||||
}
|
||||
@@ -1,208 +0,0 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/currency"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
|
||||
)
|
||||
|
||||
// RatePlanCurrencyIntegrator integrates currency system with rate plans
|
||||
type RatePlanCurrencyIntegrator struct {
|
||||
billingService currency.BillingService
|
||||
exchangeService currency.ExchangeRateService
|
||||
ratePlanService rateplan.Service
|
||||
logger *logrus.Logger
|
||||
baseCurrency string
|
||||
}
|
||||
|
||||
// NewRatePlanCurrencyIntegrator creates a new rate plan currency integrator
|
||||
func NewRatePlanCurrencyIntegrator(
|
||||
billingService currency.BillingService,
|
||||
exchangeService currency.ExchangeRateService,
|
||||
ratePlanService rateplan.Service,
|
||||
logger *logrus.Logger,
|
||||
baseCurrency string,
|
||||
) *RatePlanCurrencyIntegrator {
|
||||
return &RatePlanCurrencyIntegrator{
|
||||
billingService: billingService,
|
||||
exchangeService: exchangeService,
|
||||
ratePlanService: ratePlanService,
|
||||
logger: logger,
|
||||
baseCurrency: baseCurrency,
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeToPlanWithCurrency subscribes to a rate plan with currency conversion
|
||||
func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.Context, profileID string, planID string, targetCurrency string) (*rateplan.RatePlanSubscription, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Convert price to requested currency if needed
|
||||
subscriptionPrice := plan.BasePrice
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, ¤cy.CurrencyConversionRequest{
|
||||
Amount: plan.BasePrice,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
})
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).Error("Failed to convert rate plan price")
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
}
|
||||
subscriptionPrice = conversion.ConvertedAmount
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
// Create subscription with currency information
|
||||
subscription := &rateplan.RatePlanSubscription{
|
||||
ProfileID: profileID,
|
||||
RatePlanID: planID,
|
||||
Status: rateplan.SubscriptionStatusActive,
|
||||
StartedAt: time.Now(),
|
||||
Metadata: map[string]any{
|
||||
"original_currency": plan.Currency,
|
||||
"subscription_currency": targetCurrency,
|
||||
"original_price": plan.BasePrice,
|
||||
"subscription_price": subscriptionPrice,
|
||||
"exchange_rate": exchangeRate,
|
||||
},
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Create subscription request
|
||||
subscribeReq := &rateplan.SubscribeRequest{
|
||||
ProfileID: profileID,
|
||||
RatePlanID: planID,
|
||||
AutoRenew: true,
|
||||
Metadata: subscription.Metadata,
|
||||
}
|
||||
|
||||
createdSubscription, err := rpci.ratePlanService.SubscribeToPlan(ctx, subscribeReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create subscription: %w", err)
|
||||
}
|
||||
|
||||
// Process initial billing
|
||||
billingReq := ¤cy.BillingRequest{
|
||||
ProfileID: profileID,
|
||||
SubscriptionID: createdSubscription.ID,
|
||||
Amount: subscriptionPrice,
|
||||
Currency: targetCurrency,
|
||||
Description: fmt.Sprintf("Initial subscription to %s", plan.Name),
|
||||
BillingDate: time.Now(),
|
||||
}
|
||||
|
||||
_, err = rpci.billingService.ProcessBilling(ctx, billingReq)
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).Error("Failed to process initial billing")
|
||||
// Don't fail the subscription if billing fails, but log it
|
||||
}
|
||||
|
||||
rpci.logger.WithFields(logrus.Fields{
|
||||
"profile_id": profileID,
|
||||
"plan_id": planID,
|
||||
"currency": targetCurrency,
|
||||
"subscription_id": createdSubscription.ID,
|
||||
}).Info("Rate plan subscription created with currency support")
|
||||
|
||||
return createdSubscription, nil
|
||||
}
|
||||
|
||||
// CalculatePlanCostInCurrency calculates the cost of a rate plan in a specific currency
|
||||
func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.Context, planID string, targetCurrency string, usageData *rateplan.RatePlanUsage) (*currency.BillingSummary, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Calculate base cost
|
||||
baseCost := plan.BasePrice
|
||||
|
||||
// Add overage costs if usage data is provided
|
||||
if usageData != nil {
|
||||
overageCost, err := rpci.calculateOverageCost(ctx, plan, usageData)
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).Warn("Failed to calculate overage cost")
|
||||
} else {
|
||||
baseCost += overageCost
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to requested currency
|
||||
convertedCost := baseCost
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversion, err := rpci.exchangeService.ConvertAmount(ctx, baseCost, plan.Currency, targetCurrency)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
}
|
||||
convertedCost = conversion.ConvertedAmount
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
// Create billing summary
|
||||
summary := ¤cy.BillingSummary{
|
||||
ProfileID: usageData.ProfileID,
|
||||
TotalAmount: convertedCost,
|
||||
Currency: targetCurrency,
|
||||
BaseTotalAmount: baseCost,
|
||||
BaseCurrency: plan.Currency,
|
||||
TransactionCount: 1,
|
||||
FromDate: time.Now().AddDate(0, -1, 0),
|
||||
ToDate: time.Now(),
|
||||
Breakdown: map[string]any{
|
||||
"plan_id": planID,
|
||||
"plan_name": plan.Name,
|
||||
"base_cost": plan.BasePrice,
|
||||
"overage_cost": baseCost - plan.BasePrice,
|
||||
"exchange_rate": exchangeRate,
|
||||
"original_currency": plan.Currency,
|
||||
},
|
||||
}
|
||||
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
// calculateOverageCost calculates overage costs for usage
|
||||
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
|
||||
overageCost := 0.0
|
||||
|
||||
// Calculate data overage
|
||||
if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount {
|
||||
dataOverage := usage.DataUsed - plan.DataAllowance.Amount
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(dataOverage) * plan.OverageRates.DataRate
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate voice overage
|
||||
if plan.VoiceAllowance != nil && usage.VoiceUsed > plan.VoiceAllowance.Minutes {
|
||||
voiceOverage := usage.VoiceUsed - plan.VoiceAllowance.Minutes
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(voiceOverage) * plan.OverageRates.VoiceRate
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate SMS overage
|
||||
if plan.SMSAllowance != nil && usage.SMSUsed > plan.SMSAllowance.Messages {
|
||||
smsOverage := usage.SMSUsed - plan.SMSAllowance.Messages
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(smsOverage) * plan.OverageRates.SMSRate
|
||||
}
|
||||
}
|
||||
|
||||
return overageCost, nil
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/analytics"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// AnalyticsHandler handles analytics API requests
|
||||
type AnalyticsHandler struct {
|
||||
service *analytics.Service
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewAnalyticsHandler creates a new analytics handler
|
||||
func NewAnalyticsHandler(service *analytics.Service, logger *logrus.Logger) *AnalyticsHandler {
|
||||
return &AnalyticsHandler{service: service, logger: logger}
|
||||
}
|
||||
|
||||
// GetDashboard returns the main analytics dashboard
|
||||
func (h *AnalyticsHandler) GetDashboard(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
if tenantID == "" {
|
||||
tenantID = c.Query("tenant_id")
|
||||
}
|
||||
|
||||
filter := &analytics.AnalyticsFilter{
|
||||
TenantID: tenantID,
|
||||
StartDate: time.Now().AddDate(0, -1, 0),
|
||||
EndDate: time.Now(),
|
||||
}
|
||||
|
||||
if start := c.Query("start_date"); start != "" {
|
||||
if t, err := time.Parse("2006-01-02", start); err == nil {
|
||||
filter.StartDate = t
|
||||
}
|
||||
}
|
||||
if end := c.Query("end_date"); end != "" {
|
||||
if t, err := time.Parse("2006-01-02", end); err == nil {
|
||||
filter.EndDate = t
|
||||
}
|
||||
}
|
||||
|
||||
dashboard, err := h.service.GetDashboard(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).Error("Failed to get dashboard")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dashboard)
|
||||
}
|
||||
|
||||
// GetRevenueAnalytics returns detailed revenue analytics
|
||||
func (h *AnalyticsHandler) GetRevenueAnalytics(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
filter := &analytics.AnalyticsFilter{
|
||||
TenantID: tenantID,
|
||||
StartDate: time.Now().AddDate(0, -1, 0),
|
||||
EndDate: time.Now(),
|
||||
GroupBy: c.Query("group_by"),
|
||||
}
|
||||
|
||||
revenue, err := h.service.GetRevenueAnalytics(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, revenue)
|
||||
}
|
||||
|
||||
// CreateScheduledReport creates a scheduled report
|
||||
func (h *AnalyticsHandler) CreateScheduledReport(c *gin.Context) {
|
||||
var report analytics.ScheduledReport
|
||||
if err := c.ShouldBindJSON(&report); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
report.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.CreateScheduledReport(c.Request.Context(), &report); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, report)
|
||||
}
|
||||
|
||||
// ListScheduledReports lists scheduled reports
|
||||
func (h *AnalyticsHandler) ListScheduledReports(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
reports, err := h.service.ListScheduledReports(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, reports)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/compliance"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ComplianceHandler handles compliance API requests
|
||||
type ComplianceHandler struct {
|
||||
service *compliance.Service
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewComplianceHandler creates a new compliance handler
|
||||
func NewComplianceHandler(service *compliance.Service, logger *logrus.Logger) *ComplianceHandler {
|
||||
return &ComplianceHandler{service: service, logger: logger}
|
||||
}
|
||||
|
||||
// CreateDSR creates a data subject request
|
||||
func (h *ComplianceHandler) CreateDSR(c *gin.Context) {
|
||||
var req compliance.DataSubjectRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
req.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.CreateDSR(c.Request.Context(), &req); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, req)
|
||||
}
|
||||
|
||||
// GetDSR retrieves a data subject request
|
||||
func (h *ComplianceHandler) GetDSR(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
dsr, err := h.service.GetDSR(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsr)
|
||||
}
|
||||
|
||||
// ListDSRs lists data subject requests
|
||||
func (h *ComplianceHandler) ListDSRs(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
var status *compliance.DSRStatus
|
||||
if s := c.Query("status"); s != "" {
|
||||
st := compliance.DSRStatus(s)
|
||||
status = &st
|
||||
}
|
||||
|
||||
dsrs, err := h.service.ListDSRs(c.Request.Context(), tenantID, status)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, dsrs)
|
||||
}
|
||||
|
||||
// ProcessDSR processes a data subject request
|
||||
func (h *ComplianceHandler) ProcessDSR(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if err := h.service.ProcessDSR(c.Request.Context(), id); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "processing"})
|
||||
}
|
||||
|
||||
// RecordConsent records user consent
|
||||
func (h *ComplianceHandler) RecordConsent(c *gin.Context) {
|
||||
var consent compliance.ConsentRecord
|
||||
if err := c.ShouldBindJSON(&consent); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
consent.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
consent.IPAddress = c.ClientIP()
|
||||
consent.UserAgent = c.GetHeader("User-Agent")
|
||||
|
||||
if err := h.service.RecordConsent(c.Request.Context(), &consent); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, consent)
|
||||
}
|
||||
|
||||
// RevokeConsent revokes user consent
|
||||
func (h *ComplianceHandler) RevokeConsent(c *gin.Context) {
|
||||
subjectID := c.Param("subject_id")
|
||||
consentType := compliance.ConsentType(c.Query("type"))
|
||||
|
||||
if err := h.service.RevokeConsent(c.Request.Context(), subjectID, consentType); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"status": "revoked"})
|
||||
}
|
||||
|
||||
// GetConsents retrieves consent records for a subject
|
||||
func (h *ComplianceHandler) GetConsents(c *gin.Context) {
|
||||
subjectID := c.Param("subject_id")
|
||||
consents, err := h.service.GetConsents(c.Request.Context(), subjectID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, consents)
|
||||
}
|
||||
|
||||
// QueryAuditLogs queries audit logs
|
||||
func (h *ComplianceHandler) QueryAuditLogs(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
filter := &compliance.AuditLogFilter{
|
||||
Jurisdiction: c.Query("jurisdiction"),
|
||||
ActorID: c.Query("actor_id"),
|
||||
Action: c.Query("action"),
|
||||
Limit: 100,
|
||||
}
|
||||
|
||||
logs, err := h.service.QueryAuditLogs(c.Request.Context(), tenantID, filter)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, logs)
|
||||
}
|
||||
|
||||
// SetDataResidency sets data residency configuration
|
||||
func (h *ComplianceHandler) SetDataResidency(c *gin.Context) {
|
||||
var config compliance.DataResidencyConfig
|
||||
if err := c.ShouldBindJSON(&config); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
config.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.SetDataResidency(c.Request.Context(), &config); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
|
||||
// GetDataResidency retrieves data residency configuration
|
||||
func (h *ComplianceHandler) GetDataResidency(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
config, err := h.service.GetDataResidency(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mvno"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
)
|
||||
|
||||
// ManagementHandler handles MVNO management HTTP requests
|
||||
type ManagementHandler struct {
|
||||
repo repository.Repository
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewManagementHandler creates a new management handler
|
||||
func NewManagementHandler(repo repository.Repository, logger *logrus.Logger) *ManagementHandler {
|
||||
return &ManagementHandler{
|
||||
repo: repo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// GetMVNO handles GET /mvno/{id}
|
||||
func (h *ManagementHandler) GetMVNO(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "MVNO ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
mvno, err := h.repo.GetMVNO(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).WithField("mvno_id", id).Error("Failed to get MVNO")
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "MVNO not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, mvno)
|
||||
}
|
||||
|
||||
// ListMVNOs handles GET /mvno
|
||||
func (h *ManagementHandler) ListMVNOs(c *gin.Context) {
|
||||
filter := &mvno.MVNOFilter{}
|
||||
|
||||
// Parse query parameters
|
||||
if status := c.Query("status"); status != "" {
|
||||
filter.Status = mvno.MVNOStatus(status)
|
||||
}
|
||||
if plan := c.Query("plan"); plan != "" {
|
||||
filter.Plan = mvno.MVNOPlan(plan)
|
||||
}
|
||||
if limit := c.Query("limit"); limit != "" {
|
||||
if l, err := strconv.Atoi(limit); err == nil {
|
||||
filter.Limit = l
|
||||
}
|
||||
}
|
||||
|
||||
mvnos, err := h.repo.ListMVNOs(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).Error("Failed to list MVNOs")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list MVNOs"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"mvnos": mvnos,
|
||||
"count": len(mvnos),
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateMVNOStatus handles PUT /mvno/{id}/status
|
||||
func (h *ManagementHandler) UpdateMVNOStatus(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "MVNO ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Status mvno.MVNOStatus `json:"status" binding:"required"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repo.UpdateMVNOStatus(c.Request.Context(), id, req.Status); err != nil {
|
||||
h.logger.WithError(err).WithField("mvno_id", id).Error("Failed to update MVNO status")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update status"})
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.WithFields(logrus.Fields{
|
||||
"mvno_id": id,
|
||||
"new_status": req.Status,
|
||||
}).Info("MVNO status updated")
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"mvno_id": id,
|
||||
"status": req.Status,
|
||||
})
|
||||
}
|
||||
|
||||
// GetMVNOStats handles GET /mvno/stats
|
||||
func (h *ManagementHandler) GetMVNOStats(c *gin.Context) {
|
||||
stats, err := h.repo.GetMVNOStats(c.Request.Context())
|
||||
if err != nil {
|
||||
h.logger.WithError(err).Error("Failed to get MVNO stats")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get statistics"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"stats": stats,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mvno"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// OnboardingService defines the interface for MVNO onboarding operations
|
||||
type OnboardingService interface {
|
||||
StartOnboarding(ctx context.Context, req *mvno.OnboardingRequest) (*mvno.MVNO, error)
|
||||
}
|
||||
|
||||
// MVNOHandler handles HTTP requests for MVNO operations
|
||||
type MVNOHandler struct {
|
||||
service OnboardingService
|
||||
repo repository.Repository
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewMVNOHandler creates a new MVNO HTTP handler
|
||||
func NewMVNOHandler(service OnboardingService, repo repository.Repository, logger *logrus.Logger) *MVNOHandler {
|
||||
return &MVNOHandler{
|
||||
service: service,
|
||||
repo: repo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// StartOnboarding handles POST /mvno/onboarding
|
||||
func (h *MVNOHandler) StartOnboarding(c *gin.Context) {
|
||||
var req mvno.OnboardingRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
h.logger.WithError(err).Error("Invalid onboarding request")
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
mvno, err := h.service.StartOnboarding(c.Request.Context(), &req)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).Error("Failed to start onboarding")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.repo.CreateMVNO(c.Request.Context(), mvno); err != nil {
|
||||
h.logger.WithError(err).Error("Failed to save MVNO")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save MVNO"})
|
||||
return
|
||||
}
|
||||
|
||||
h.logger.WithField("mvno_id", mvno.ID).Info("Onboarding started")
|
||||
c.JSON(http.StatusCreated, gin.H{
|
||||
"mvno_id": mvno.ID,
|
||||
"business_id": mvno.BusinessID,
|
||||
"status": mvno.Status,
|
||||
"plan": mvno.Plan,
|
||||
})
|
||||
}
|
||||
|
||||
// GetMVNO handles GET /mvno/{id}
|
||||
func (h *MVNOHandler) GetMVNO(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if id == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "MVNO ID is required"})
|
||||
return
|
||||
}
|
||||
|
||||
mvno, err := h.repo.GetMVNO(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).WithField("mvno_id", id).Error("Failed to get MVNO")
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "MVNO not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, mvno)
|
||||
}
|
||||
|
||||
// ListMVNOs handles GET /mvno
|
||||
func (h *MVNOHandler) ListMVNOs(c *gin.Context) {
|
||||
filter := &mvno.MVNOFilter{}
|
||||
if status := c.Query("status"); status != "" {
|
||||
filter.Status = mvno.MVNOStatus(status)
|
||||
}
|
||||
if plan := c.Query("plan"); plan != "" {
|
||||
filter.Plan = mvno.MVNOPlan(plan)
|
||||
}
|
||||
if limit := c.Query("limit"); limit != "" {
|
||||
if l, err := strconv.Atoi(limit); err == nil {
|
||||
filter.Limit = l
|
||||
}
|
||||
}
|
||||
|
||||
mvnos, err := h.repo.ListMVNOs(c.Request.Context(), filter)
|
||||
if err != nil {
|
||||
h.logger.WithError(err).Error("Failed to list MVNOs")
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list MVNOs"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"mvnos": mvnos, "count": len(mvnos)})
|
||||
}
|
||||
|
||||
// RegisterRoutes registers all MVNO routes
|
||||
func (h *MVNOHandler) RegisterRoutes(router *gin.RouterGroup) {
|
||||
mvno := router.Group("/mvno")
|
||||
{
|
||||
mvno.POST("/onboarding", h.StartOnboarding)
|
||||
mvno.GET("", h.ListMVNOs)
|
||||
mvno.GET("/:id", h.GetMVNO)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/whitelabel"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// WhitelabelHandler handles whitelabel API requests
|
||||
type WhitelabelHandler struct {
|
||||
service *whitelabel.Service
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewWhitelabelHandler creates a new whitelabel handler
|
||||
func NewWhitelabelHandler(service *whitelabel.Service, logger *logrus.Logger) *WhitelabelHandler {
|
||||
return &WhitelabelHandler{service: service, logger: logger}
|
||||
}
|
||||
|
||||
// CreateBranding creates branding configuration
|
||||
func (h *WhitelabelHandler) CreateBranding(c *gin.Context) {
|
||||
var config whitelabel.BrandingConfig
|
||||
if err := c.ShouldBindJSON(&config); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
config.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.CreateBranding(c.Request.Context(), &config); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, config)
|
||||
}
|
||||
|
||||
// GetBranding retrieves branding configuration
|
||||
func (h *WhitelabelHandler) GetBranding(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
if tenantID == "" {
|
||||
tenantID = c.Param("tenant_id")
|
||||
}
|
||||
|
||||
config, err := h.service.GetBranding(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
|
||||
// GetBrandingByDomain retrieves branding by custom domain
|
||||
func (h *WhitelabelHandler) GetBrandingByDomain(c *gin.Context) {
|
||||
domain := c.Param("domain")
|
||||
config, err := h.service.GetBrandingByDomain(c.Request.Context(), domain)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
|
||||
// UpdateBranding updates branding configuration
|
||||
func (h *WhitelabelHandler) UpdateBranding(c *gin.Context) {
|
||||
var config whitelabel.BrandingConfig
|
||||
if err := c.ShouldBindJSON(&config); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
config.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.UpdateBranding(c.Request.Context(), &config); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
|
||||
// CreatePartnerConfig creates partner configuration
|
||||
func (h *WhitelabelHandler) CreatePartnerConfig(c *gin.Context) {
|
||||
var config whitelabel.PartnerConfig
|
||||
if err := c.ShouldBindJSON(&config); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
config.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.CreatePartnerConfig(c.Request.Context(), &config); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, config)
|
||||
}
|
||||
|
||||
// GetPartnerConfig retrieves partner configuration
|
||||
func (h *WhitelabelHandler) GetPartnerConfig(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
config, err := h.service.GetPartnerConfig(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, config)
|
||||
}
|
||||
|
||||
// CreateEmailTemplate creates an email template
|
||||
func (h *WhitelabelHandler) CreateEmailTemplate(c *gin.Context) {
|
||||
var template whitelabel.EmailTemplate
|
||||
if err := c.ShouldBindJSON(&template); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
template.TenantID = c.GetHeader("X-Tenant-ID")
|
||||
if err := h.service.CreateEmailTemplate(c.Request.Context(), &template); err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, template)
|
||||
}
|
||||
|
||||
// GetEmailTemplate retrieves an email template
|
||||
func (h *WhitelabelHandler) GetEmailTemplate(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
templateKey := c.Param("key")
|
||||
|
||||
template, err := h.service.GetEmailTemplate(c.Request.Context(), tenantID, templateKey)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, template)
|
||||
}
|
||||
|
||||
// ListEmailTemplates lists email templates
|
||||
func (h *WhitelabelHandler) ListEmailTemplates(c *gin.Context) {
|
||||
tenantID := c.GetHeader("X-Tenant-ID")
|
||||
templates, err := h.service.ListEmailTemplates(c.Request.Context(), tenantID)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, templates)
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CacheStrategy defines caching strategies
|
||||
type CacheStrategy string
|
||||
|
||||
const (
|
||||
CacheStrategyLRU CacheStrategy = "lru"
|
||||
CacheStrategyTTL CacheStrategy = "ttl"
|
||||
CacheStrategyWriteThru CacheStrategy = "write_through"
|
||||
CacheStrategyWriteBack CacheStrategy = "write_back"
|
||||
CacheStrategyReadThru CacheStrategy = "read_through"
|
||||
)
|
||||
|
||||
// CacheEntry represents a cached item
|
||||
type CacheEntry struct {
|
||||
Key string
|
||||
Value []byte
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
HitCount int64
|
||||
}
|
||||
|
||||
// Cache provides in-memory caching with multiple strategies
|
||||
type Cache struct {
|
||||
entries map[string]*CacheEntry
|
||||
mu sync.RWMutex
|
||||
maxSize int
|
||||
defaultTTL time.Duration
|
||||
strategy CacheStrategy
|
||||
stats CacheStats
|
||||
}
|
||||
|
||||
// CacheConfig configures the cache
|
||||
type CacheConfig struct {
|
||||
MaxSize int
|
||||
DefaultTTL time.Duration
|
||||
Strategy CacheStrategy
|
||||
}
|
||||
|
||||
// DefaultCacheConfig returns default cache configuration
|
||||
func DefaultCacheConfig() CacheConfig {
|
||||
return CacheConfig{
|
||||
MaxSize: 10000,
|
||||
DefaultTTL: 5 * time.Minute,
|
||||
Strategy: CacheStrategyTTL,
|
||||
}
|
||||
}
|
||||
|
||||
// NewCache creates a new cache instance
|
||||
func NewCache(config CacheConfig) *Cache {
|
||||
c := &Cache{
|
||||
entries: make(map[string]*CacheEntry),
|
||||
maxSize: config.MaxSize,
|
||||
defaultTTL: config.DefaultTTL,
|
||||
strategy: config.Strategy,
|
||||
}
|
||||
go c.cleanupLoop()
|
||||
return c
|
||||
}
|
||||
|
||||
// Get retrieves a value from cache
|
||||
func (c *Cache) Get(ctx context.Context, key string) ([]byte, bool) {
|
||||
c.mu.RLock()
|
||||
entry, exists := c.entries[key]
|
||||
c.mu.RUnlock()
|
||||
|
||||
if !exists {
|
||||
c.stats.Misses++
|
||||
return nil, false
|
||||
}
|
||||
|
||||
if time.Now().After(entry.ExpiresAt) {
|
||||
c.Delete(ctx, key)
|
||||
c.stats.Misses++
|
||||
return nil, false
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
entry.HitCount++
|
||||
c.stats.Hits++
|
||||
c.mu.Unlock()
|
||||
|
||||
return entry.Value, true
|
||||
}
|
||||
|
||||
// Set stores a value in cache
|
||||
func (c *Cache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
if ttl == 0 {
|
||||
ttl = c.defaultTTL
|
||||
}
|
||||
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
if len(c.entries) >= c.maxSize {
|
||||
c.evict()
|
||||
}
|
||||
|
||||
c.entries[key] = &CacheEntry{
|
||||
Key: key,
|
||||
Value: value,
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
c.stats.Sets++
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetJSON stores a JSON-serializable value
|
||||
func (c *Cache) SetJSON(ctx context.Context, key string, value any, ttl time.Duration) error {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal value: %w", err)
|
||||
}
|
||||
return c.Set(ctx, key, data, ttl)
|
||||
}
|
||||
|
||||
// GetJSON retrieves and unmarshals a JSON value
|
||||
func (c *Cache) GetJSON(ctx context.Context, key string, dest any) (bool, error) {
|
||||
data, exists := c.Get(ctx, key)
|
||||
if !exists {
|
||||
return false, nil
|
||||
}
|
||||
if err := json.Unmarshal(data, dest); err != nil {
|
||||
return false, fmt.Errorf("failed to unmarshal value: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Delete removes a value from cache
|
||||
func (c *Cache) Delete(_ context.Context, key string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
delete(c.entries, key)
|
||||
c.stats.Deletes++
|
||||
}
|
||||
|
||||
// Clear removes all entries
|
||||
func (c *Cache) Clear(_ context.Context) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
c.entries = make(map[string]*CacheEntry)
|
||||
}
|
||||
|
||||
// evict removes the least recently used or oldest entry
|
||||
func (c *Cache) evict() {
|
||||
var oldest *CacheEntry
|
||||
var oldestKey string
|
||||
|
||||
for key, entry := range c.entries {
|
||||
if oldest == nil || entry.CreatedAt.Before(oldest.CreatedAt) {
|
||||
oldest = entry
|
||||
oldestKey = key
|
||||
}
|
||||
}
|
||||
|
||||
if oldestKey != "" {
|
||||
delete(c.entries, oldestKey)
|
||||
c.stats.Evictions++
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) cleanupLoop() {
|
||||
ticker := time.NewTicker(time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
c.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Cache) cleanup() {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
|
||||
now := time.Now()
|
||||
for key, entry := range c.entries {
|
||||
if now.After(entry.ExpiresAt) {
|
||||
delete(c.entries, key)
|
||||
c.stats.Evictions++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stats returns cache statistics
|
||||
func (c *Cache) Stats() CacheStats {
|
||||
c.mu.RLock()
|
||||
defer c.mu.RUnlock()
|
||||
stats := c.stats
|
||||
stats.Size = len(c.entries)
|
||||
if stats.Hits+stats.Misses > 0 {
|
||||
stats.HitRate = float64(stats.Hits) / float64(stats.Hits+stats.Misses) * 100
|
||||
}
|
||||
return stats
|
||||
}
|
||||
|
||||
// CacheStats contains cache statistics
|
||||
type CacheStats struct {
|
||||
Size int `json:"size"`
|
||||
Hits int64 `json:"hits"`
|
||||
Misses int64 `json:"misses"`
|
||||
Sets int64 `json:"sets"`
|
||||
Deletes int64 `json:"deletes"`
|
||||
Evictions int64 `json:"evictions"`
|
||||
HitRate float64 `json:"hit_rate_pct"`
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// CircuitState represents the circuit breaker state
|
||||
type CircuitState int
|
||||
|
||||
const (
|
||||
StateClosed CircuitState = iota
|
||||
StateOpen
|
||||
StateHalfOpen
|
||||
)
|
||||
|
||||
func (s CircuitState) String() string {
|
||||
switch s {
|
||||
case StateClosed:
|
||||
return "closed"
|
||||
case StateOpen:
|
||||
return "open"
|
||||
case StateHalfOpen:
|
||||
return "half-open"
|
||||
default:
|
||||
return "unknown"
|
||||
}
|
||||
}
|
||||
|
||||
// CircuitBreaker implements the circuit breaker pattern
|
||||
type CircuitBreaker struct {
|
||||
name string
|
||||
state CircuitState
|
||||
failureCount int
|
||||
successCount int
|
||||
lastFailure time.Time
|
||||
config CircuitBreakerConfig
|
||||
mu sync.RWMutex
|
||||
onStateChange func(name string, from, to CircuitState)
|
||||
}
|
||||
|
||||
// CircuitBreakerConfig configures the circuit breaker
|
||||
type CircuitBreakerConfig struct {
|
||||
FailureThreshold int
|
||||
SuccessThreshold int
|
||||
Timeout time.Duration
|
||||
HalfOpenMaxCalls int
|
||||
}
|
||||
|
||||
// DefaultCircuitBreakerConfig returns default configuration
|
||||
func DefaultCircuitBreakerConfig() CircuitBreakerConfig {
|
||||
return CircuitBreakerConfig{
|
||||
FailureThreshold: 5,
|
||||
SuccessThreshold: 3,
|
||||
Timeout: 30 * time.Second,
|
||||
HalfOpenMaxCalls: 3,
|
||||
}
|
||||
}
|
||||
|
||||
// NewCircuitBreaker creates a new circuit breaker
|
||||
func NewCircuitBreaker(name string, config CircuitBreakerConfig) *CircuitBreaker {
|
||||
return &CircuitBreaker{
|
||||
name: name,
|
||||
state: StateClosed,
|
||||
config: config,
|
||||
}
|
||||
}
|
||||
|
||||
// ErrCircuitOpen is returned when the circuit is open
|
||||
var ErrCircuitOpen = errors.New("circuit breaker is open")
|
||||
|
||||
// Execute runs the function with circuit breaker protection
|
||||
func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error {
|
||||
if !cb.allowRequest() {
|
||||
return ErrCircuitOpen
|
||||
}
|
||||
|
||||
err := fn()
|
||||
cb.recordResult(err)
|
||||
return err
|
||||
}
|
||||
|
||||
// ExecuteWithFallback runs with fallback on circuit open
|
||||
func (cb *CircuitBreaker) ExecuteWithFallback(ctx context.Context, fn func() error, fallback func() error) error {
|
||||
if !cb.allowRequest() {
|
||||
if fallback != nil {
|
||||
return fallback()
|
||||
}
|
||||
return ErrCircuitOpen
|
||||
}
|
||||
|
||||
err := fn()
|
||||
cb.recordResult(err)
|
||||
if err != nil && fallback != nil {
|
||||
return fallback()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (cb *CircuitBreaker) allowRequest() bool {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
|
||||
switch cb.state {
|
||||
case StateClosed:
|
||||
return true
|
||||
case StateOpen:
|
||||
if time.Since(cb.lastFailure) > cb.config.Timeout {
|
||||
cb.mu.RUnlock()
|
||||
cb.mu.Lock()
|
||||
cb.transitionTo(StateHalfOpen)
|
||||
cb.mu.Unlock()
|
||||
cb.mu.RLock()
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case StateHalfOpen:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (cb *CircuitBreaker) recordResult(err error) {
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
|
||||
if err != nil {
|
||||
cb.recordFailure()
|
||||
} else {
|
||||
cb.recordSuccess()
|
||||
}
|
||||
}
|
||||
|
||||
func (cb *CircuitBreaker) recordFailure() {
|
||||
cb.failureCount++
|
||||
cb.lastFailure = time.Now()
|
||||
|
||||
switch cb.state {
|
||||
case StateClosed:
|
||||
if cb.failureCount >= cb.config.FailureThreshold {
|
||||
cb.transitionTo(StateOpen)
|
||||
}
|
||||
case StateHalfOpen:
|
||||
cb.transitionTo(StateOpen)
|
||||
}
|
||||
}
|
||||
|
||||
func (cb *CircuitBreaker) recordSuccess() {
|
||||
cb.successCount++
|
||||
|
||||
switch cb.state {
|
||||
case StateHalfOpen:
|
||||
if cb.successCount >= cb.config.SuccessThreshold {
|
||||
cb.transitionTo(StateClosed)
|
||||
}
|
||||
case StateClosed:
|
||||
cb.failureCount = 0
|
||||
}
|
||||
}
|
||||
|
||||
func (cb *CircuitBreaker) transitionTo(state CircuitState) {
|
||||
if cb.state == state {
|
||||
return
|
||||
}
|
||||
oldState := cb.state
|
||||
cb.state = state
|
||||
cb.failureCount = 0
|
||||
cb.successCount = 0
|
||||
|
||||
if cb.onStateChange != nil {
|
||||
cb.onStateChange(cb.name, oldState, state)
|
||||
}
|
||||
}
|
||||
|
||||
// State returns the current state
|
||||
func (cb *CircuitBreaker) State() CircuitState {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
return cb.state
|
||||
}
|
||||
|
||||
// Stats returns circuit breaker statistics
|
||||
func (cb *CircuitBreaker) Stats() CircuitBreakerStats {
|
||||
cb.mu.RLock()
|
||||
defer cb.mu.RUnlock()
|
||||
return CircuitBreakerStats{
|
||||
Name: cb.name,
|
||||
State: cb.state.String(),
|
||||
FailureCount: cb.failureCount,
|
||||
SuccessCount: cb.successCount,
|
||||
LastFailure: cb.lastFailure,
|
||||
}
|
||||
}
|
||||
|
||||
// CircuitBreakerStats contains circuit breaker statistics
|
||||
type CircuitBreakerStats struct {
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
FailureCount int `json:"failure_count"`
|
||||
SuccessCount int `json:"success_count"`
|
||||
LastFailure time.Time `json:"last_failure"`
|
||||
}
|
||||
|
||||
// OnStateChange sets the state change callback
|
||||
func (cb *CircuitBreaker) OnStateChange(fn func(name string, from, to CircuitState)) {
|
||||
cb.mu.Lock()
|
||||
defer cb.mu.Unlock()
|
||||
cb.onStateChange = fn
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// GeoRouter handles geographic routing for API requests
|
||||
type GeoRouter struct {
|
||||
regions map[string]*Region
|
||||
defaultReg string
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// Region represents a geographic region with endpoints
|
||||
type Region struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Endpoints []string `json:"endpoints"`
|
||||
Priority int `json:"priority"`
|
||||
IsActive bool `json:"is_active"`
|
||||
Latency float64 `json:"latency_ms"`
|
||||
}
|
||||
|
||||
// GeoRoutingConfig configures geographic routing
|
||||
type GeoRoutingConfig struct {
|
||||
DefaultRegion string
|
||||
Regions []*Region
|
||||
}
|
||||
|
||||
// NewGeoRouter creates a new geographic router
|
||||
func NewGeoRouter(config GeoRoutingConfig) *GeoRouter {
|
||||
gr := &GeoRouter{
|
||||
regions: make(map[string]*Region),
|
||||
defaultReg: config.DefaultRegion,
|
||||
}
|
||||
for _, r := range config.Regions {
|
||||
gr.regions[r.ID] = r
|
||||
}
|
||||
return gr
|
||||
}
|
||||
|
||||
// GetRegionForIP determines the best region for an IP address
|
||||
func (gr *GeoRouter) GetRegionForIP(_ context.Context, ipStr string) (*Region, error) {
|
||||
gr.mu.RLock()
|
||||
defer gr.mu.RUnlock()
|
||||
|
||||
ip := net.ParseIP(ipStr)
|
||||
if ip == nil {
|
||||
return gr.regions[gr.defaultReg], nil
|
||||
}
|
||||
|
||||
// Simplified geo lookup - in production use MaxMind GeoIP
|
||||
regionID := gr.lookupRegion(ip)
|
||||
if region, ok := gr.regions[regionID]; ok && region.IsActive {
|
||||
return region, nil
|
||||
}
|
||||
|
||||
return gr.regions[gr.defaultReg], nil
|
||||
}
|
||||
|
||||
func (gr *GeoRouter) lookupRegion(ip net.IP) string {
|
||||
// Simplified region detection based on IP ranges
|
||||
if ip.To4() != nil {
|
||||
first := ip.To4()[0]
|
||||
switch {
|
||||
case first >= 1 && first <= 126:
|
||||
return "us-east"
|
||||
case first >= 128 && first <= 191:
|
||||
return "eu-west"
|
||||
default:
|
||||
return "ap-southeast"
|
||||
}
|
||||
}
|
||||
return gr.defaultReg
|
||||
}
|
||||
|
||||
// GetBestEndpoint returns the best endpoint for a region
|
||||
func (gr *GeoRouter) GetBestEndpoint(_ context.Context, regionID string) (string, error) {
|
||||
gr.mu.RLock()
|
||||
defer gr.mu.RUnlock()
|
||||
|
||||
region, ok := gr.regions[regionID]
|
||||
if !ok || len(region.Endpoints) == 0 {
|
||||
region = gr.regions[gr.defaultReg]
|
||||
}
|
||||
|
||||
if len(region.Endpoints) > 0 {
|
||||
return region.Endpoints[0], nil
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// UpdateRegion updates a region configuration
|
||||
func (gr *GeoRouter) UpdateRegion(region *Region) {
|
||||
gr.mu.Lock()
|
||||
defer gr.mu.Unlock()
|
||||
gr.regions[region.ID] = region
|
||||
}
|
||||
|
||||
// GetRegions returns all configured regions
|
||||
func (gr *GeoRouter) GetRegions() []*Region {
|
||||
gr.mu.RLock()
|
||||
defer gr.mu.RUnlock()
|
||||
|
||||
regions := make([]*Region, 0, len(gr.regions))
|
||||
for _, r := range gr.regions {
|
||||
regions = append(regions, r)
|
||||
}
|
||||
return regions
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
package infra
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand/v2"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MaintenanceType represents types of maintenance
|
||||
type MaintenanceType string
|
||||
|
||||
const (
|
||||
MaintenanceTypePreventive MaintenanceType = "preventive"
|
||||
MaintenanceTypeCorrective MaintenanceType = "corrective"
|
||||
MaintenanceTypePredictive MaintenanceType = "predictive"
|
||||
MaintenanceTypeEmergency MaintenanceType = "emergency"
|
||||
)
|
||||
|
||||
// AssetType represents infrastructure asset types
|
||||
type AssetType string
|
||||
|
||||
const (
|
||||
AssetTypeServer AssetType = "server"
|
||||
AssetTypeDatabase AssetType = "database"
|
||||
AssetTypeNetwork AssetType = "network"
|
||||
AssetTypeStorage AssetType = "storage"
|
||||
AssetTypeApplication AssetType = "application"
|
||||
AssetTypeLoadBalancer AssetType = "load_balancer"
|
||||
)
|
||||
|
||||
// Asset represents an infrastructure asset
|
||||
type Asset struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type AssetType `json:"type"`
|
||||
Status string `json:"status"`
|
||||
Location string `json:"location"`
|
||||
HealthScore float64 `json:"health_score"` // 0-100
|
||||
LastMaintenance *time.Time `json:"last_maintenance,omitempty"`
|
||||
NextMaintenance *time.Time `json:"next_maintenance,omitempty"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
}
|
||||
|
||||
// MaintenanceAlert represents a maintenance alert
|
||||
type MaintenanceAlert struct {
|
||||
ID string `json:"id"`
|
||||
AssetID string `json:"asset_id"`
|
||||
Type MaintenanceType `json:"type"`
|
||||
Severity string `json:"severity"` // "low", "medium", "high", "critical"
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
RiskScore float64 `json:"risk_score"` // 0-100
|
||||
PredictedFailure *time.Time `json:"predicted_failure,omitempty"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Status string `json:"status"` // "new", "acknowledged", "scheduled", "completed"
|
||||
}
|
||||
|
||||
// MaintenanceMetrics represents maintenance performance metrics
|
||||
type MaintenanceMetrics struct {
|
||||
Period string `json:"period"`
|
||||
TotalAssets int64 `json:"total_assets"`
|
||||
HealthyAssets int64 `json:"healthy_assets"`
|
||||
AssetsNeedingAttention int64 `json:"assets_needing_attention"`
|
||||
PreventiveMaintenance int64 `json:"preventive_maintenance"`
|
||||
CorrectiveMaintenance int64 `json:"corrective_maintenance"`
|
||||
EmergencyMaintenance int64 `json:"emergency_maintenance"`
|
||||
Uptime float64 `json:"uptime_pct"`
|
||||
MeanTimeToFailure float64 `json:"mean_time_to_failure_hours"`
|
||||
MeanTimeToRepair float64 `json:"mean_time_to_repair_hours"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// PredictiveMaintenanceService provides predictive maintenance capabilities
|
||||
type PredictiveMaintenanceService struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
assets map[string]*Asset
|
||||
alerts []*MaintenanceAlert
|
||||
mu sync.RWMutex
|
||||
models map[AssetType]*MaintenanceModel
|
||||
}
|
||||
|
||||
// MaintenanceModel represents a predictive maintenance model
|
||||
type MaintenanceModel struct {
|
||||
AssetType AssetType `json:"asset_type"`
|
||||
Version string `json:"version"`
|
||||
LastTrained time.Time `json:"last_trained"`
|
||||
Accuracy float64 `json:"accuracy"`
|
||||
FailureRate float64 `json:"failure_rate"`
|
||||
MTTF float64 `json:"mttf_hours"` // Mean Time To Failure
|
||||
MTTR float64 `json:"mttr_hours"` // Mean Time To Repair
|
||||
}
|
||||
|
||||
// NewPredictiveMaintenanceService creates a new predictive maintenance service
|
||||
func NewPredictiveMaintenanceService(db *gorm.DB, logger *logrus.Logger) *PredictiveMaintenanceService {
|
||||
service := &PredictiveMaintenanceService{
|
||||
db: db,
|
||||
logger: logger,
|
||||
assets: make(map[string]*Asset),
|
||||
alerts: make([]*MaintenanceAlert, 0),
|
||||
models: make(map[AssetType]*MaintenanceModel),
|
||||
}
|
||||
|
||||
// Initialize with default assets
|
||||
service.initializeAssets()
|
||||
|
||||
// Initialize predictive models
|
||||
service.initializeModels()
|
||||
|
||||
// Start monitoring
|
||||
go service.monitorAssets()
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
// MonitorAssets continuously monitors asset health
|
||||
func (s *PredictiveMaintenanceService) monitorAssets() {
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
s.updateAssetHealth()
|
||||
s.predictFailures()
|
||||
}
|
||||
}
|
||||
|
||||
// GetMaintenanceMetrics returns maintenance performance metrics
|
||||
func (s *PredictiveMaintenanceService) GetMaintenanceMetrics(ctx context.Context, period string) (*MaintenanceMetrics, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
metrics := &MaintenanceMetrics{
|
||||
Period: period,
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Count assets by status
|
||||
for _, asset := range s.assets {
|
||||
metrics.TotalAssets++
|
||||
if asset.HealthScore >= 80 {
|
||||
metrics.HealthyAssets++
|
||||
} else if asset.HealthScore < 60 {
|
||||
metrics.AssetsNeedingAttention++
|
||||
}
|
||||
}
|
||||
|
||||
// Count maintenance types
|
||||
for _, alert := range s.alerts {
|
||||
switch alert.Type {
|
||||
case MaintenanceTypePreventive:
|
||||
metrics.PreventiveMaintenance++
|
||||
case MaintenanceTypeCorrective:
|
||||
metrics.CorrectiveMaintenance++
|
||||
case MaintenanceTypeEmergency:
|
||||
metrics.EmergencyMaintenance++
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate uptime and MTTF/MTTR (simplified)
|
||||
metrics.Uptime = 99.5
|
||||
metrics.MeanTimeToFailure = 8760 // 1 year in hours
|
||||
metrics.MeanTimeToRepair = 4 // 4 hours
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// GetMaintenanceAlerts returns maintenance alerts
|
||||
func (s *PredictiveMaintenanceService) GetMaintenanceAlerts(ctx context.Context, severity string) ([]*MaintenanceAlert, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
filtered := make([]*MaintenanceAlert, 0)
|
||||
for _, alert := range s.alerts {
|
||||
if severity == "" || alert.Severity == severity {
|
||||
filtered = append(filtered, alert)
|
||||
}
|
||||
}
|
||||
|
||||
return filtered, nil
|
||||
}
|
||||
|
||||
// PredictFailure predicts failure for an asset
|
||||
func (s *PredictiveMaintenanceService) PredictFailure(_ context.Context, assetID string) (*MaintenanceAlert, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
asset, exists := s.assets[assetID]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("asset not found: %s", assetID)
|
||||
}
|
||||
|
||||
// Get predictive model
|
||||
model, exists := s.models[asset.Type]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("no model for asset type: %s", asset.Type)
|
||||
}
|
||||
|
||||
// Calculate failure probability
|
||||
failureProb := s.calculateFailureProbability(asset, model)
|
||||
|
||||
if failureProb > 0.7 {
|
||||
alert := &MaintenanceAlert{
|
||||
ID: fmt.Sprintf("alert-%d", time.Now().UnixNano()),
|
||||
AssetID: assetID,
|
||||
Type: MaintenanceTypePredictive,
|
||||
Severity: s.determineSeverity(failureProb),
|
||||
Title: fmt.Sprintf("Predicted failure for %s", asset.Name),
|
||||
Description: fmt.Sprintf("Asset %s has high probability of failure", asset.Name),
|
||||
RiskScore: failureProb * 100,
|
||||
PredictedFailure: s.predictFailureTime(asset, model),
|
||||
Recommendations: s.generateMaintenanceRecommendations(asset, model),
|
||||
Timestamp: time.Now(),
|
||||
Status: "new",
|
||||
}
|
||||
|
||||
s.alerts = append(s.alerts, alert)
|
||||
return alert, nil
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// ScheduleMaintenance schedules maintenance for an asset
|
||||
func (s *PredictiveMaintenanceService) ScheduleMaintenance(ctx context.Context, assetID, maintenanceType string, scheduledTime time.Time) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
asset, exists := s.assets[assetID]
|
||||
if !exists {
|
||||
return fmt.Errorf("asset not found: %s", assetID)
|
||||
}
|
||||
|
||||
asset.NextMaintenance = &scheduledTime
|
||||
|
||||
// Create maintenance alert
|
||||
alert := &MaintenanceAlert{
|
||||
ID: fmt.Sprintf("maintenance-%d", time.Now().UnixNano()),
|
||||
AssetID: assetID,
|
||||
Type: MaintenanceType(maintenanceType),
|
||||
Severity: "medium",
|
||||
Title: fmt.Sprintf("Scheduled maintenance for %s", asset.Name),
|
||||
Description: fmt.Sprintf("Maintenance scheduled for %s", scheduledTime.Format(time.RFC3339)),
|
||||
Timestamp: time.Now(),
|
||||
Status: "scheduled",
|
||||
}
|
||||
|
||||
s.alerts = append(s.alerts, alert)
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"asset_id": assetID,
|
||||
"asset_name": asset.Name,
|
||||
"scheduled_at": scheduledTime,
|
||||
}).Info("Maintenance scheduled")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// initializeAssets initializes default infrastructure assets
|
||||
func (s *PredictiveMaintenanceService) initializeAssets() {
|
||||
assets := []*Asset{
|
||||
{
|
||||
ID: "api-server-1",
|
||||
Name: "API Server 1",
|
||||
Type: AssetTypeServer,
|
||||
Status: "running",
|
||||
Location: "us-east-1",
|
||||
HealthScore: 95.0,
|
||||
Metadata: map[string]any{"cpu_cores": 8, "memory_gb": 32},
|
||||
},
|
||||
{
|
||||
ID: "db-primary",
|
||||
Name: "Primary Database",
|
||||
Type: AssetTypeDatabase,
|
||||
Status: "running",
|
||||
Location: "us-east-1",
|
||||
HealthScore: 92.0,
|
||||
Metadata: map[string]any{"engine": "postgresql", "version": "14"},
|
||||
},
|
||||
{
|
||||
ID: "lb-main",
|
||||
Name: "Main Load Balancer",
|
||||
Type: AssetTypeLoadBalancer,
|
||||
Status: "running",
|
||||
Location: "us-east-1",
|
||||
HealthScore: 98.0,
|
||||
Metadata: map[string]any{"connections": 1000, "throughput_mbps": 1000},
|
||||
},
|
||||
{
|
||||
ID: "cache-redis",
|
||||
Name: "Redis Cache",
|
||||
Type: AssetTypeApplication,
|
||||
Status: "running",
|
||||
Location: "us-east-1",
|
||||
HealthScore: 88.0,
|
||||
Metadata: map[string]any{"memory_gb": 16, "hit_rate": 0.95},
|
||||
},
|
||||
{
|
||||
ID: "storage-s3",
|
||||
Name: "S3 Storage",
|
||||
Type: AssetTypeStorage,
|
||||
Status: "healthy",
|
||||
Location: "us-east-1",
|
||||
HealthScore: 99.0,
|
||||
Metadata: map[string]any{"capacity_tb": 100, "used_tb": 45},
|
||||
},
|
||||
}
|
||||
|
||||
for _, asset := range assets {
|
||||
s.assets[asset.ID] = asset
|
||||
}
|
||||
}
|
||||
|
||||
// initializeModels initializes predictive maintenance models
|
||||
func (s *PredictiveMaintenanceService) initializeModels() {
|
||||
models := map[AssetType]*MaintenanceModel{
|
||||
AssetTypeServer: {
|
||||
AssetType: AssetTypeServer,
|
||||
Version: "1.0",
|
||||
LastTrained: time.Now().AddDate(0, -1, 0),
|
||||
Accuracy: 0.85,
|
||||
FailureRate: 0.05,
|
||||
MTTF: 8760, // 1 year
|
||||
MTTR: 4, // 4 hours
|
||||
},
|
||||
AssetTypeDatabase: {
|
||||
AssetType: AssetTypeDatabase,
|
||||
Version: "1.0",
|
||||
LastTrained: time.Now().AddDate(0, -1, 0),
|
||||
Accuracy: 0.92,
|
||||
FailureRate: 0.02,
|
||||
MTTF: 17520, // 2 years
|
||||
MTTR: 8, // 8 hours
|
||||
},
|
||||
AssetTypeLoadBalancer: {
|
||||
AssetType: AssetTypeLoadBalancer,
|
||||
Version: "1.0",
|
||||
LastTrained: time.Now().AddDate(0, -1, 0),
|
||||
Accuracy: 0.88,
|
||||
FailureRate: 0.03,
|
||||
MTTF: 13140, // 1.5 years
|
||||
MTTR: 2, // 2 hours
|
||||
},
|
||||
AssetTypeApplication: {
|
||||
AssetType: AssetTypeApplication,
|
||||
Version: "1.0",
|
||||
LastTrained: time.Now().AddDate(0, -1, 0),
|
||||
Accuracy: 0.78,
|
||||
FailureRate: 0.08,
|
||||
MTTF: 4380, // 6 months
|
||||
MTTR: 1, // 1 hour
|
||||
},
|
||||
AssetTypeStorage: {
|
||||
AssetType: AssetTypeStorage,
|
||||
Version: "1.0",
|
||||
LastTrained: time.Now().AddDate(0, -1, 0),
|
||||
Accuracy: 0.95,
|
||||
FailureRate: 0.01,
|
||||
MTTF: 35040, // 4 years
|
||||
MTTR: 12, // 12 hours
|
||||
},
|
||||
}
|
||||
|
||||
for assetType, model := range models {
|
||||
s.models[assetType] = model
|
||||
}
|
||||
}
|
||||
|
||||
// updateAssetHealth updates health scores for all assets
|
||||
func (s *PredictiveMaintenanceService) updateAssetHealth() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, asset := range s.assets {
|
||||
// Simulate health score changes
|
||||
change := (rand.Float64()*10 - 5) // Random change between -5 and +5
|
||||
asset.HealthScore = math.Max(0, math.Min(100, asset.HealthScore+change))
|
||||
}
|
||||
}
|
||||
|
||||
// predictFailures predicts failures for all assets
|
||||
func (s *PredictiveMaintenanceService) predictFailures() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, asset := range s.assets {
|
||||
model, exists := s.models[asset.Type]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
|
||||
failureProb := s.calculateFailureProbability(asset, model)
|
||||
if failureProb > 0.8 {
|
||||
// Create high-priority alert
|
||||
alert := &MaintenanceAlert{
|
||||
ID: fmt.Sprintf("alert-%d", time.Now().UnixNano()),
|
||||
AssetID: asset.ID,
|
||||
Type: MaintenanceTypePredictive,
|
||||
Severity: "critical",
|
||||
Title: fmt.Sprintf("Critical: %s likely to fail", asset.Name),
|
||||
Description: fmt.Sprintf("Asset has %.1f%% probability of failure", failureProb*100),
|
||||
RiskScore: failureProb * 100,
|
||||
PredictedFailure: s.predictFailureTime(asset, model),
|
||||
Timestamp: time.Now(),
|
||||
Status: "new",
|
||||
}
|
||||
|
||||
s.alerts = append(s.alerts, alert)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// calculateFailureProbability calculates failure probability for an asset
|
||||
func (s *PredictiveMaintenanceService) calculateFailureProbability(asset *Asset, model *MaintenanceModel) float64 {
|
||||
// Simplified failure probability calculation
|
||||
baseProb := model.FailureRate
|
||||
|
||||
// Adjust based on health score
|
||||
healthFactor := (100 - asset.HealthScore) / 100
|
||||
|
||||
// Adjust based on age (if no recent maintenance)
|
||||
ageFactor := 1.0
|
||||
if asset.LastMaintenance != nil {
|
||||
daysSinceMaintenance := time.Since(*asset.LastMaintenance).Hours() / 24
|
||||
ageFactor = math.Min(2.0, daysSinceMaintenance/365) // Max 2x risk after 1 year
|
||||
}
|
||||
|
||||
probability := baseProb * healthFactor * ageFactor
|
||||
|
||||
return math.Min(1.0, probability)
|
||||
}
|
||||
|
||||
// determineSeverity determines alert severity from probability
|
||||
func (s *PredictiveMaintenanceService) determineSeverity(probability float64) string {
|
||||
switch {
|
||||
case probability >= 0.9:
|
||||
return "critical"
|
||||
case probability >= 0.7:
|
||||
return "high"
|
||||
case probability >= 0.5:
|
||||
return "medium"
|
||||
default:
|
||||
return "low"
|
||||
}
|
||||
}
|
||||
|
||||
// predictFailureTime predicts when failure might occur
|
||||
func (s *PredictiveMaintenanceService) predictFailureTime(asset *Asset, model *MaintenanceModel) *time.Time {
|
||||
// Simplified prediction based on MTTF and current health
|
||||
hoursToFailure := model.MTTF * (asset.HealthScore / 100)
|
||||
predictedTime := time.Now().Add(time.Duration(hoursToFailure) * time.Hour)
|
||||
return &predictedTime
|
||||
}
|
||||
|
||||
// generateMaintenanceRecommendations generates maintenance recommendations
|
||||
func (s *PredictiveMaintenanceService) generateMaintenanceRecommendations(asset *Asset, model *MaintenanceModel) []string {
|
||||
recommendations := make([]string, 0)
|
||||
|
||||
switch asset.Type {
|
||||
case AssetTypeServer:
|
||||
recommendations = append(recommendations, "Check CPU and memory utilization")
|
||||
recommendations = append(recommendations, "Review system logs for errors")
|
||||
recommendations = append(recommendations, "Update system patches")
|
||||
case AssetTypeDatabase:
|
||||
recommendations = append(recommendations, "Run database health check")
|
||||
recommendations = append(recommendations, "Optimize query performance")
|
||||
recommendations = append(recommendations, "Check disk space and I/O")
|
||||
case AssetTypeLoadBalancer:
|
||||
recommendations = append(recommendations, "Review connection limits")
|
||||
recommendations = append(recommendations, "Check SSL certificate expiry")
|
||||
recommendations = append(recommendations, "Monitor response times")
|
||||
case AssetTypeApplication:
|
||||
recommendations = append(recommendations, "Restart application services")
|
||||
recommendations = append(recommendations, "Clear application cache")
|
||||
recommendations = append(recommendations, "Check for memory leaks")
|
||||
case AssetTypeStorage:
|
||||
recommendations = append(recommendations, "Check storage capacity")
|
||||
recommendations = append(recommendations, "Run storage health diagnostics")
|
||||
recommendations = append(recommendations, "Review backup integrity")
|
||||
}
|
||||
|
||||
return recommendations
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/services"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/smdp"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
type SelectionIntegration struct {
|
||||
@@ -33,7 +34,8 @@ func NewSelectionIntegration(repo *repository.PostgresProfileStore) *SelectionIn
|
||||
manager := smdp.NewSMDPManager(repo, config)
|
||||
|
||||
// Create selection service
|
||||
selectionService := services.NewSelectionService(manager)
|
||||
logger := logrus.New()
|
||||
selectionService := services.NewSelectionService(manager, logger)
|
||||
|
||||
// Create SMDP service
|
||||
smdpService := services.NewSMDPService(repo)
|
||||
@@ -41,7 +43,7 @@ func NewSelectionIntegration(repo *repository.PostgresProfileStore) *SelectionIn
|
||||
return &SelectionIntegration{
|
||||
manager: manager,
|
||||
selectionService: selectionService,
|
||||
selectionHandler: selectionService.GetHandler(),
|
||||
selectionHandler: handlers.NewSelectionHandler(manager),
|
||||
smdpService: smdpService,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
package mvno
|
||||
|
||||
import (
|
||||
"maps"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// OnboardingMonitor tracks onboarding progress and status
|
||||
type OnboardingMonitor struct {
|
||||
logger *logrus.Logger
|
||||
progress map[string]*OnboardingProgress
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewOnboardingMonitor creates a new monitor instance
|
||||
func NewOnboardingMonitor(logger *logrus.Logger) *OnboardingMonitor {
|
||||
return &OnboardingMonitor{
|
||||
logger: logger,
|
||||
progress: make(map[string]*OnboardingProgress),
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateProgress updates the onboarding progress for an MVNO
|
||||
func (m *OnboardingMonitor) UpdateProgress(mvnoID string, progress *OnboardingProgress) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
m.progress[mvnoID] = progress
|
||||
|
||||
m.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvnoID,
|
||||
"progress": progress.Progress,
|
||||
"status": m.getCurrentStatus(progress),
|
||||
}).Info("Onboarding progress updated")
|
||||
}
|
||||
|
||||
// GetProgress retrieves current onboarding progress
|
||||
func (m *OnboardingMonitor) GetProgress(mvnoID string) (*OnboardingProgress, bool) {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
progress, exists := m.progress[mvnoID]
|
||||
return progress, exists
|
||||
}
|
||||
|
||||
// GetAllProgress retrieves progress for all MVNOs
|
||||
func (m *OnboardingMonitor) GetAllProgress() map[string]*OnboardingProgress {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
// Return a copy to avoid concurrent access issues
|
||||
result := make(map[string]*OnboardingProgress)
|
||||
maps.Copy(result, m.progress)
|
||||
return result
|
||||
}
|
||||
|
||||
// GetActiveOnboardingCount returns count of active onboarding processes
|
||||
func (m *OnboardingMonitor) GetActiveOnboardingCount() int {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
count := 0
|
||||
for _, progress := range m.progress {
|
||||
if progress.Progress < 100.0 && !progress.CompletedAt.IsZero() {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// GetCompletedOnboardingCount returns count of completed onboardings
|
||||
func (m *OnboardingMonitor) GetCompletedOnboardingCount() int {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
count := 0
|
||||
for _, progress := range m.progress {
|
||||
if progress.Progress == 100.0 && !progress.CompletedAt.IsZero() {
|
||||
count++
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
// GetAverageOnboardingTime calculates average onboarding duration
|
||||
func (m *OnboardingMonitor) GetAverageOnboardingTime() time.Duration {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var totalDuration time.Duration
|
||||
completedCount := 0
|
||||
|
||||
for _, progress := range m.progress {
|
||||
if progress.Progress == 100.0 && !progress.CompletedAt.IsZero() && !progress.StartedAt.IsZero() {
|
||||
totalDuration += progress.CompletedAt.Sub(progress.StartedAt)
|
||||
completedCount++
|
||||
}
|
||||
}
|
||||
|
||||
if completedCount == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return totalDuration / time.Duration(completedCount)
|
||||
}
|
||||
|
||||
// GetStepSuccessRate calculates success rate for each step
|
||||
func (m *OnboardingMonitor) GetStepSuccessRate() map[string]float64 {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
stepStats := make(map[string]map[string]int)
|
||||
|
||||
// Collect step statistics
|
||||
for _, progress := range m.progress {
|
||||
for _, step := range progress.Steps {
|
||||
if _, exists := stepStats[step.Name]; !exists {
|
||||
stepStats[step.Name] = map[string]int{"completed": 0, "failed": 0, "total": 0}
|
||||
}
|
||||
stepStats[step.Name]["total"]++
|
||||
switch step.Status {
|
||||
case "completed":
|
||||
stepStats[step.Name]["completed"]++
|
||||
case "failed":
|
||||
stepStats[step.Name]["failed"]++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate success rates
|
||||
successRates := make(map[string]float64)
|
||||
for stepName, stats := range stepStats {
|
||||
if stats["total"] > 0 {
|
||||
successRates[stepName] = float64(stats["completed"]) / float64(stats["total"]) * 100
|
||||
}
|
||||
}
|
||||
|
||||
return successRates
|
||||
}
|
||||
|
||||
// CleanupOldProgress removes old completed progress records
|
||||
func (m *OnboardingMonitor) CleanupOldProgress(maxAge time.Duration) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
cutoff := time.Now().Add(-maxAge)
|
||||
for mvnoID, progress := range m.progress {
|
||||
if progress.Progress == 100.0 && !progress.CompletedAt.IsZero() && progress.CompletedAt.Before(cutoff) {
|
||||
delete(m.progress, mvnoID)
|
||||
m.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvnoID,
|
||||
"completed_at": progress.CompletedAt,
|
||||
}).Info("Cleaned up old onboarding progress")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetFailedOnboardings returns list of failed onboardings
|
||||
func (m *OnboardingMonitor) GetFailedOnboardings() []string {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
var failed []string
|
||||
for mvnoID, progress := range m.progress {
|
||||
hasFailed := false
|
||||
for _, step := range progress.Steps {
|
||||
if step.Status == "failed" {
|
||||
hasFailed = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hasFailed {
|
||||
failed = append(failed, mvnoID)
|
||||
}
|
||||
}
|
||||
return failed
|
||||
}
|
||||
|
||||
// getCurrentStatus determines current status from progress
|
||||
func (m *OnboardingMonitor) getCurrentStatus(progress *OnboardingProgress) string {
|
||||
if progress.Progress == 100.0 {
|
||||
return "completed"
|
||||
}
|
||||
|
||||
if progress.Progress == 0.0 {
|
||||
return "pending"
|
||||
}
|
||||
|
||||
// Check for failed steps
|
||||
for _, step := range progress.Steps {
|
||||
if step.Status == "failed" {
|
||||
return "failed"
|
||||
}
|
||||
}
|
||||
|
||||
return "in_progress"
|
||||
}
|
||||
|
||||
// GetOnboardingMetrics returns comprehensive onboarding metrics
|
||||
func (m *OnboardingMonitor) GetOnboardingMetrics() map[string]any {
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
return map[string]any{
|
||||
"active_count": m.GetActiveOnboardingCount(),
|
||||
"completed_count": m.GetCompletedOnboardingCount(),
|
||||
"average_duration": m.GetAverageOnboardingTime().String(),
|
||||
"step_success_rates": m.GetStepSuccessRate(),
|
||||
"failed_count": len(m.GetFailedOnboardings()),
|
||||
"total_onboardings": len(m.progress),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package mvno
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// MVNOProvisioner handles resource provisioning for MVNOs
|
||||
type MVNOProvisioner struct {
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewMVNOProvisioner creates a new provisioner instance
|
||||
func NewMVNOProvisioner(logger *logrus.Logger) *MVNOProvisioner {
|
||||
return &MVNOProvisioner{logger: logger}
|
||||
}
|
||||
|
||||
// ProvisionResources provisions core resources for the MVNO
|
||||
func (p *MVNOProvisioner) ProvisionResources(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Provisioning core resources")
|
||||
|
||||
if err := p.provisionTenantContext(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("failed to provision tenant context: %w", err)
|
||||
}
|
||||
|
||||
if err := p.provisionDatabaseSchema(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("failed to provision database schema: %w", err)
|
||||
}
|
||||
|
||||
return p.provisionStorageResources(ctx, mvno)
|
||||
}
|
||||
|
||||
// SetupCarriers configures carrier connections for the MVNO
|
||||
func (p *MVNOProvisioner) SetupCarriers(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up carrier connections")
|
||||
|
||||
selectedCarriers, err := p.selectCarriers(mvno.Config.AllowedCountries)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to select carriers: %w", err)
|
||||
}
|
||||
|
||||
for _, carrierID := range selectedCarriers {
|
||||
if err := p.configureCarrier(ctx, mvno, carrierID); err != nil {
|
||||
p.logger.WithError(err).WithField("carrier_id", carrierID).Error("Failed to configure carrier")
|
||||
}
|
||||
}
|
||||
|
||||
mvno.Config.CarrierPool = selectedCarriers
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetupBilling configures billing system for the MVNO
|
||||
func (p *MVNOProvisioner) SetupBilling(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up billing system")
|
||||
|
||||
billingID := id.GeneratePrefixed("bill")
|
||||
|
||||
if err := p.configureRatePlans(ctx, mvno, billingID); err != nil {
|
||||
return fmt.Errorf("failed to configure rate plans: %w", err)
|
||||
}
|
||||
|
||||
return p.setupPaymentProcessing(ctx, mvno, billingID)
|
||||
}
|
||||
|
||||
// SetupAPIAccess configures API access for the MVNO
|
||||
func (p *MVNOProvisioner) SetupAPIAccess(ctx context.Context, mvno *MVNO) error {
|
||||
if !mvno.Config.APIAccess {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("API access not included in plan")
|
||||
return nil
|
||||
}
|
||||
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up API access")
|
||||
|
||||
apiKey := id.GeneratePrefixed("api")
|
||||
_ = id.GeneratePrefixed("sec") // Generate secret key but don't use until storage is implemented
|
||||
permissions := p.getAPIPermissions(mvno.Plan)
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"api_key": apiKey[:8] + "...",
|
||||
"permissions": len(permissions),
|
||||
}).Info("API access configured")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// provisionTenantContext creates tenant context
|
||||
func (p *MVNOProvisioner) provisionTenantContext(_ context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Tenant context provisioned")
|
||||
return nil
|
||||
}
|
||||
|
||||
// provisionDatabaseSchema provisions database schema
|
||||
func (p *MVNOProvisioner) provisionDatabaseSchema(_ context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Database schema provisioned")
|
||||
return nil
|
||||
}
|
||||
|
||||
// provisionStorageResources provisions storage resources
|
||||
func (p *MVNOProvisioner) provisionStorageResources(_ context.Context, mvno *MVNO) error {
|
||||
storageSize := p.getStorageAllocation(mvno.Plan)
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"storage_gb": storageSize,
|
||||
}).Info("Storage resources provisioned")
|
||||
return nil
|
||||
}
|
||||
|
||||
// selectCarriers selects optimal carriers for countries
|
||||
func (p *MVNOProvisioner) selectCarriers(countries []string) ([]string, error) {
|
||||
carriers := []string{"carrier_us_01", "carrier_gb_01", "carrier_de_01"}
|
||||
|
||||
if len(countries) > 0 {
|
||||
selected := make([]string, 0)
|
||||
for _, carrier := range carriers {
|
||||
selected = append(selected, carrier)
|
||||
}
|
||||
return selected, nil
|
||||
}
|
||||
|
||||
return carriers, nil
|
||||
}
|
||||
|
||||
// configureCarrier configures individual carrier
|
||||
func (p *MVNOProvisioner) configureCarrier(_ context.Context, mvno *MVNO, carrierID string) error {
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"carrier_id": carrierID,
|
||||
}).Info("Carrier configured")
|
||||
return nil
|
||||
}
|
||||
|
||||
// configureRatePlans configures rate plans
|
||||
func (p *MVNOProvisioner) configureRatePlans(_ context.Context, mvno *MVNO, billingID string) error {
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"billing_id": billingID,
|
||||
"plan": mvno.Plan,
|
||||
}).Info("Rate plans configured")
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupPaymentProcessing setup payment processing
|
||||
func (p *MVNOProvisioner) setupPaymentProcessing(_ context.Context, mvno *MVNO, billingID string) error {
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"billing_id": billingID,
|
||||
}).Info("Payment processing setup")
|
||||
return nil
|
||||
}
|
||||
|
||||
// getAPIPermissions returns API permissions based on plan
|
||||
func (p *MVNOProvisioner) getAPIPermissions(plan MVNOPlan) []string {
|
||||
switch plan {
|
||||
case PlanStarter:
|
||||
return []string{"read:subscribers", "read:usage"}
|
||||
case PlanGrowth:
|
||||
return []string{"read:subscribers", "write:subscribers", "read:usage", "read:billing"}
|
||||
case PlanScale:
|
||||
return []string{"read:subscribers", "write:subscribers", "read:usage", "write:usage", "read:billing", "write:billing", "read:analytics"}
|
||||
case PlanEnterprise:
|
||||
return []string{"*"}
|
||||
default:
|
||||
return []string{"read:subscribers"}
|
||||
}
|
||||
}
|
||||
|
||||
// getStorageAllocation returns storage allocation in GB
|
||||
func (p *MVNOProvisioner) getStorageAllocation(plan MVNOPlan) int {
|
||||
switch plan {
|
||||
case PlanStarter:
|
||||
return 10
|
||||
case PlanGrowth:
|
||||
return 100
|
||||
case PlanScale:
|
||||
return 1000
|
||||
case PlanEnterprise:
|
||||
return 10000
|
||||
default:
|
||||
return 10
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
package mvno
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// provisionTenantContext creates tenant context in production
|
||||
func (p *ProductionProvisioner) provisionTenantContext(ctx context.Context, mvno *MVNO) error {
|
||||
tenantConfig := &TenantConfig{
|
||||
ID: mvno.ID,
|
||||
Name: mvno.Name,
|
||||
Plan: mvno.Plan,
|
||||
Settings: map[string]any{
|
||||
"business_id": mvno.BusinessID,
|
||||
"max_subscribers": mvno.Config.MaxSubscribers,
|
||||
"allowed_countries": mvno.Config.AllowedCountries,
|
||||
"custom_branding": mvno.Config.CustomBranding,
|
||||
"advanced_analytics": mvno.Config.AdvancedAnalytics,
|
||||
"created_at": time.Now(),
|
||||
},
|
||||
}
|
||||
|
||||
if err := p.tenantService.CreateTenant(ctx, tenantConfig); err != nil {
|
||||
return fmt.Errorf("failed to create tenant in management system: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"tenant_id": tenantConfig.ID,
|
||||
"plan": mvno.Plan,
|
||||
}).Info("Tenant context provisioned successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// provisionDatabaseSchema provisions database schema in production
|
||||
func (p *ProductionProvisioner) provisionDatabaseSchema(ctx context.Context, mvno *MVNO) error {
|
||||
// Create dedicated database schema for MVNO
|
||||
if err := p.storageService.CreateDatabaseSchema(ctx, mvno.ID); err != nil {
|
||||
return fmt.Errorf("failed to create database schema: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Database schema provisioned successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// provisionStorageResources provisions storage resources in production
|
||||
func (p *ProductionProvisioner) provisionStorageResources(ctx context.Context, mvno *MVNO) error {
|
||||
storageSize := p.getStorageAllocation(mvno.Plan)
|
||||
|
||||
if err := p.storageService.CreateStorageBucket(ctx, mvno.ID, storageSize); err != nil {
|
||||
return fmt.Errorf("failed to create storage bucket: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"storage_gb": storageSize,
|
||||
}).Info("Storage resources provisioned successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// selectCarriers selects optimal carriers for countries in production
|
||||
func (p *ProductionProvisioner) selectCarriers(countries []string) ([]string, error) {
|
||||
selectedCarriers := make(map[string]bool) // Use map to avoid duplicates
|
||||
|
||||
for _, country := range countries {
|
||||
carriers, err := p.carrierManager.GetCarriersByCountry(context.Background(), country)
|
||||
if err != nil {
|
||||
p.logger.WithError(err).WithField("country", country).Error("Failed to get carriers for country")
|
||||
continue
|
||||
}
|
||||
|
||||
// Select active carriers with best coverage
|
||||
for _, carrier := range carriers {
|
||||
if carrier.IsActive {
|
||||
selectedCarriers[carrier.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert map to slice
|
||||
result := make([]string, 0, len(selectedCarriers))
|
||||
for carrierID := range selectedCarriers {
|
||||
result = append(result, carrierID)
|
||||
}
|
||||
|
||||
if len(result) == 0 {
|
||||
return nil, fmt.Errorf("no active carriers found for countries: %v", countries)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"countries": countries,
|
||||
"selected_count": len(result),
|
||||
}).Info("Carriers selected successfully")
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// configureCarrier configures individual carrier in production
|
||||
func (p *ProductionProvisioner) configureCarrier(ctx context.Context, mvno *MVNO, carrierID string) error {
|
||||
if err := p.carrierManager.ConfigureCarrier(ctx, mvno.ID, carrierID); err != nil {
|
||||
return fmt.Errorf("failed to configure carrier %s: %w", carrierID, err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"carrier_id": carrierID,
|
||||
}).Info("Carrier configured successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// configureRatePlans configures rate plans in production
|
||||
func (p *ProductionProvisioner) configureRatePlans(ctx context.Context, mvno *MVNO, billingID string) error {
|
||||
if err := p.billingService.CreateRatePlans(ctx, mvno.ID, billingID, mvno.Plan); err != nil {
|
||||
return fmt.Errorf("failed to create rate plans: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"billing_id": billingID,
|
||||
"plan": mvno.Plan,
|
||||
}).Info("Rate plans configured successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// setupPaymentProcessing setup payment processing in production
|
||||
func (p *ProductionProvisioner) setupPaymentProcessing(ctx context.Context, mvno *MVNO, billingID string) error {
|
||||
if err := p.billingService.SetupPaymentGateway(ctx, mvno.ID, billingID); err != nil {
|
||||
return fmt.Errorf("failed to setup payment gateway: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"billing_id": billingID,
|
||||
}).Info("Payment processing setup successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getAPIPermissions returns API permissions based on plan
|
||||
func (p *ProductionProvisioner) getAPIPermissions(plan MVNOPlan) []string {
|
||||
switch plan {
|
||||
case PlanStarter:
|
||||
return []string{"read:subscribers", "read:usage"}
|
||||
case PlanGrowth:
|
||||
return []string{
|
||||
"read:subscribers", "write:subscribers",
|
||||
"read:usage", "read:billing",
|
||||
}
|
||||
case PlanScale:
|
||||
return []string{
|
||||
"read:subscribers", "write:subscribers",
|
||||
"read:usage", "write:usage",
|
||||
"read:billing", "write:billing",
|
||||
"read:analytics", "write:analytics",
|
||||
}
|
||||
case PlanEnterprise:
|
||||
return []string{"*"} // Full access
|
||||
default:
|
||||
return []string{"read:subscribers"}
|
||||
}
|
||||
}
|
||||
|
||||
// getStorageAllocation returns storage allocation in GB
|
||||
func (p *ProductionProvisioner) getStorageAllocation(plan MVNOPlan) int {
|
||||
switch plan {
|
||||
case PlanStarter:
|
||||
return 10
|
||||
case PlanGrowth:
|
||||
return 100
|
||||
case PlanScale:
|
||||
return 1000
|
||||
case PlanEnterprise:
|
||||
return 10000
|
||||
default:
|
||||
return 10
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateProvisioning validates that all resources are properly provisioned
|
||||
func (p *ProductionProvisioner) ValidateProvisioning(ctx context.Context, mvno *MVNO) error {
|
||||
// Validate tenant exists
|
||||
_, err := p.tenantService.GetTenant(ctx, mvno.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tenant validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Validate carrier configurations
|
||||
if len(mvno.Config.CarrierPool) == 0 {
|
||||
return fmt.Errorf("no carriers configured")
|
||||
}
|
||||
|
||||
for _, carrierID := range mvno.Config.CarrierPool {
|
||||
// In production, validate carrier connection
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"carrier_id": carrierID,
|
||||
}).Debug("Validating carrier connection")
|
||||
}
|
||||
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Provisioning validation completed")
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package mvno
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ProductionProvisioner implements production-ready MVNO provisioning
|
||||
type ProductionProvisioner struct {
|
||||
logger *logrus.Logger
|
||||
tenantService TenantService
|
||||
carrierManager CarrierManager
|
||||
billingService BillingService
|
||||
storageService StorageService
|
||||
}
|
||||
|
||||
// TenantService interface for tenant management
|
||||
type TenantService interface {
|
||||
CreateTenant(ctx context.Context, tenant *TenantConfig) error
|
||||
GetTenant(ctx context.Context, tenantID string) (*TenantConfig, error)
|
||||
}
|
||||
|
||||
// CarrierManager interface for carrier operations
|
||||
type CarrierManager interface {
|
||||
GetCarriersByCountry(ctx context.Context, country string) ([]CarrierInfo, error)
|
||||
ConfigureCarrier(ctx context.Context, mvnoID, carrierID string) error
|
||||
}
|
||||
|
||||
// BillingService interface for billing operations
|
||||
type BillingService interface {
|
||||
CreateBillingAccount(ctx context.Context, mvnoID string, plan MVNOPlan) (string, error)
|
||||
CreateRatePlans(ctx context.Context, mvnoID, billingID string, plan MVNOPlan) error
|
||||
SetupPaymentGateway(ctx context.Context, mvnoID, billingID string) error
|
||||
}
|
||||
|
||||
// StorageService interface for storage operations
|
||||
type StorageService interface {
|
||||
CreateStorageBucket(ctx context.Context, mvnoID string, sizeGB int) error
|
||||
CreateDatabaseSchema(ctx context.Context, mvnoID string) error
|
||||
}
|
||||
|
||||
// TenantConfig represents tenant configuration
|
||||
type TenantConfig struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Plan MVNOPlan `json:"plan"`
|
||||
Settings map[string]any `json:"settings"`
|
||||
}
|
||||
|
||||
// CarrierInfo represents carrier information
|
||||
type CarrierInfo struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Countries []string `json:"countries"`
|
||||
SMDEndpoint string `json:"smd_endpoint"`
|
||||
IsActive bool `json:"is_active"`
|
||||
}
|
||||
|
||||
// NewProductionProvisioner creates a new production provisioner
|
||||
func NewProductionProvisioner(
|
||||
logger *logrus.Logger,
|
||||
tenantService TenantService,
|
||||
carrierManager CarrierManager,
|
||||
billingService BillingService,
|
||||
storageService StorageService,
|
||||
) *ProductionProvisioner {
|
||||
return &ProductionProvisioner{
|
||||
logger: logger,
|
||||
tenantService: tenantService,
|
||||
carrierManager: carrierManager,
|
||||
billingService: billingService,
|
||||
storageService: storageService,
|
||||
}
|
||||
}
|
||||
|
||||
// ProvisionResources provisions core resources for the MVNO
|
||||
func (p *ProductionProvisioner) ProvisionResources(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Provisioning production resources")
|
||||
|
||||
// Create tenant context
|
||||
if err := p.provisionTenantContext(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("failed to provision tenant context: %w", err)
|
||||
}
|
||||
|
||||
// Provision database schema
|
||||
if err := p.provisionDatabaseSchema(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("failed to provision database schema: %w", err)
|
||||
}
|
||||
|
||||
// Provision storage resources
|
||||
if err := p.provisionStorageResources(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("failed to provision storage resources: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetupCarriers configures carrier connections for the MVNO
|
||||
func (p *ProductionProvisioner) SetupCarriers(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up production carrier connections")
|
||||
|
||||
selectedCarriers, err := p.selectCarriers(mvno.Config.AllowedCountries)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to select carriers: %w", err)
|
||||
}
|
||||
|
||||
// Configure each carrier
|
||||
for _, carrierID := range selectedCarriers {
|
||||
if err := p.configureCarrier(ctx, mvno, carrierID); err != nil {
|
||||
p.logger.WithError(err).WithField("carrier_id", carrierID).Error("Failed to configure carrier")
|
||||
return fmt.Errorf("failed to configure carrier %s: %w", carrierID, err)
|
||||
}
|
||||
}
|
||||
|
||||
mvno.Config.CarrierPool = selectedCarriers
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"carrier_count": len(selectedCarriers),
|
||||
}).Info("Carriers configured successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetupBilling configures billing system for the MVNO
|
||||
func (p *ProductionProvisioner) SetupBilling(ctx context.Context, mvno *MVNO) error {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up production billing system")
|
||||
|
||||
// Create billing account
|
||||
billingID, err := p.billingService.CreateBillingAccount(ctx, mvno.ID, mvno.Plan)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to create billing account: %w", err)
|
||||
}
|
||||
|
||||
// Configure rate plans
|
||||
if err := p.configureRatePlans(ctx, mvno, billingID); err != nil {
|
||||
return fmt.Errorf("failed to configure rate plans: %w", err)
|
||||
}
|
||||
|
||||
// Setup payment processing
|
||||
if err := p.setupPaymentProcessing(ctx, mvno, billingID); err != nil {
|
||||
return fmt.Errorf("failed to setup payment processing: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"billing_id": billingID,
|
||||
"plan": mvno.Plan,
|
||||
}).Info("Billing system configured successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetupAPIAccess configures API access for the MVNO
|
||||
func (p *ProductionProvisioner) SetupAPIAccess(ctx context.Context, mvno *MVNO) error {
|
||||
if !mvno.Config.APIAccess {
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("API access not included in plan")
|
||||
return nil
|
||||
}
|
||||
|
||||
p.logger.WithField("mvno_id", mvno.ID).Info("Setting up production API access")
|
||||
|
||||
// Generate API credentials
|
||||
apiKey := id.GeneratePrefixed("api")
|
||||
secretKey := id.GeneratePrefixed("sec")
|
||||
permissions := p.getAPIPermissions(mvno.Plan)
|
||||
|
||||
// Store API configuration in tenant service
|
||||
tenant, err := p.tenantService.GetTenant(ctx, mvno.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant for API setup: %w", err)
|
||||
}
|
||||
|
||||
tenant.Settings["api_access"] = map[string]any{
|
||||
"api_key": apiKey,
|
||||
"secret_key": secretKey,
|
||||
"permissions": permissions,
|
||||
"created_at": time.Now(),
|
||||
"expires_at": time.Now().AddDate(1, 0, 0), // 1 year expiry
|
||||
}
|
||||
|
||||
if err := p.tenantService.CreateTenant(ctx, tenant); err != nil {
|
||||
return fmt.Errorf("failed to store API configuration: %w", err)
|
||||
}
|
||||
|
||||
p.logger.WithFields(map[string]any{
|
||||
"mvno_id": mvno.ID,
|
||||
"api_key": apiKey[:8] + "...",
|
||||
"permissions": len(permissions),
|
||||
}).Info("API access configured successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package mvno
|
||||
|
||||
import "time"
|
||||
|
||||
// MVNO represents a Mobile Virtual Network Operator
|
||||
type MVNO struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
Name string `json:"name" gorm:"not null"`
|
||||
BusinessID string `json:"business_id" gorm:"uniqueIndex;not null"`
|
||||
Status MVNOStatus `json:"status" gorm:"default:'pending'"`
|
||||
Plan MVNOPlan `json:"plan" gorm:"not null"`
|
||||
Config MVNOConfig `json:"config" gorm:"serializer:json"`
|
||||
CreatedAt time.Time `json:"created_at" gorm:"autoCreateTime"`
|
||||
UpdatedAt time.Time `json:"updated_at" gorm:"autoUpdateTime"`
|
||||
}
|
||||
|
||||
// MVNOStatus represents the onboarding status
|
||||
type MVNOStatus string
|
||||
|
||||
const (
|
||||
StatusPending MVNOStatus = "pending"
|
||||
StatusReview MVNOStatus = "review"
|
||||
StatusApproved MVNOStatus = "approved"
|
||||
StatusActive MVNOStatus = "active"
|
||||
StatusSuspended MVNOStatus = "suspended"
|
||||
StatusTerminated MVNOStatus = "terminated"
|
||||
)
|
||||
|
||||
// MVNOPlan represents subscription tiers
|
||||
type MVNOPlan string
|
||||
|
||||
const (
|
||||
PlanStarter MVNOPlan = "starter"
|
||||
PlanGrowth MVNOPlan = "growth"
|
||||
PlanScale MVNOPlan = "scale"
|
||||
PlanEnterprise MVNOPlan = "enterprise"
|
||||
)
|
||||
|
||||
// MVNOConfig contains MVNO-specific configuration
|
||||
type MVNOConfig struct {
|
||||
MaxSubscribers int `json:"max_subscribers"`
|
||||
AllowedCountries []string `json:"allowed_countries"`
|
||||
CarrierPool []string `json:"carrier_pool"`
|
||||
CustomBranding bool `json:"custom_branding"`
|
||||
APIAccess bool `json:"api_access"`
|
||||
AdvancedAnalytics bool `json:"advanced_analytics"`
|
||||
}
|
||||
|
||||
// OnboardingRequest represents a new MVNO onboarding request
|
||||
type OnboardingRequest struct {
|
||||
BusinessName string `json:"business_name" binding:"required"`
|
||||
BusinessID string `json:"business_id" binding:"required"`
|
||||
ContactEmail string `json:"contact_email" binding:"required,email"`
|
||||
ContactPhone string `json:"contact_phone" binding:"required"`
|
||||
Plan MVNOPlan `json:"plan" binding:"required"`
|
||||
EstimatedSubs int `json:"estimated_subscribers" binding:"min:1"`
|
||||
TargetCountries []string `json:"target_countries" binding:"required,min=1"`
|
||||
UseCase string `json:"use_case" binding:"required"`
|
||||
TechnicalContact string `json:"technical_contact"`
|
||||
}
|
||||
|
||||
// OnboardingProgress tracks the onboarding progress
|
||||
type OnboardingProgress struct {
|
||||
MVNOID string `json:"mvno_id"`
|
||||
Steps []OnboardingStep `json:"steps"`
|
||||
Progress float64 `json:"progress"`
|
||||
StartedAt time.Time `json:"started_at"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
}
|
||||
|
||||
// OnboardingStep represents individual onboarding steps
|
||||
type OnboardingStep struct {
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
CompletedAt time.Time `json:"completed_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// MVNOFilter defines filtering options for MVNO queries
|
||||
type MVNOFilter struct {
|
||||
Status MVNOStatus `json:"status,omitempty"`
|
||||
Plan MVNOPlan `json:"plan,omitempty"`
|
||||
BusinessID string `json:"business_id,omitempty"`
|
||||
Limit int `json:"limit,omitempty"`
|
||||
Offset int `json:"offset,omitempty"`
|
||||
CreatedAfter *time.Time `json:"created_after,omitempty"`
|
||||
CreatedBefore *time.Time `json:"created_before,omitempty"`
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package mvno
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// OnboardingValidator validates MVNO onboarding requests and configurations
|
||||
type OnboardingValidator struct {
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewOnboardingValidator creates a new validator instance
|
||||
func NewOnboardingValidator(logger *logrus.Logger) *OnboardingValidator {
|
||||
return &OnboardingValidator{logger: logger}
|
||||
}
|
||||
|
||||
// ValidateRequest validates the initial onboarding request
|
||||
func (v *OnboardingValidator) ValidateRequest(req *OnboardingRequest) error {
|
||||
if err := v.validateBusinessInfo(req); err != nil {
|
||||
return fmt.Errorf("business validation failed: %w", err)
|
||||
}
|
||||
|
||||
if err := v.validatePlan(req); err != nil {
|
||||
return fmt.Errorf("plan validation failed: %w", err)
|
||||
}
|
||||
|
||||
if err := v.validateTechnicalRequirements(req); err != nil {
|
||||
return fmt.Errorf("technical validation failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateMVNO performs comprehensive MVNO validation
|
||||
func (v *OnboardingValidator) ValidateMVNO(ctx context.Context, mvno *MVNO) error {
|
||||
// Validate business registration
|
||||
if err := v.validateBusinessRegistration(mvno.BusinessID); err != nil {
|
||||
return fmt.Errorf("business registration validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Validate compliance requirements
|
||||
if err := v.validateCompliance(ctx, mvno); err != nil {
|
||||
return fmt.Errorf("compliance validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Validate technical feasibility
|
||||
if err := v.validateTechnicalFeasibility(mvno); err != nil {
|
||||
return fmt.Errorf("technical feasibility validation failed: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateBusinessInfo validates business information
|
||||
func (v *OnboardingValidator) validateBusinessInfo(req *OnboardingRequest) error {
|
||||
if len(req.BusinessName) < 3 {
|
||||
return fmt.Errorf("business name must be at least 3 characters")
|
||||
}
|
||||
|
||||
if !v.isValidBusinessID(req.BusinessID) {
|
||||
return fmt.Errorf("invalid business ID format")
|
||||
}
|
||||
|
||||
if !v.isValidEmail(req.ContactEmail) {
|
||||
return fmt.Errorf("invalid contact email format")
|
||||
}
|
||||
|
||||
if len(req.ContactPhone) < 10 {
|
||||
return fmt.Errorf("contact phone must be at least 10 digits")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePlan validates the selected plan
|
||||
func (v *OnboardingValidator) validatePlan(req *OnboardingRequest) error {
|
||||
validPlans := []MVNOPlan{PlanStarter, PlanGrowth, PlanScale, PlanEnterprise}
|
||||
isValid := slices.Contains(validPlans, req.Plan)
|
||||
if !isValid {
|
||||
return fmt.Errorf("invalid plan selected")
|
||||
}
|
||||
|
||||
if req.EstimatedSubs < 1 {
|
||||
return fmt.Errorf("estimated subscribers must be at least 1")
|
||||
}
|
||||
|
||||
// Validate plan-specific requirements
|
||||
switch req.Plan {
|
||||
case PlanStarter:
|
||||
if req.EstimatedSubs > 1000 {
|
||||
return fmt.Errorf("starter plan limited to 1000 subscribers")
|
||||
}
|
||||
case PlanGrowth:
|
||||
if req.EstimatedSubs > 10000 {
|
||||
return fmt.Errorf("growth plan limited to 10000 subscribers")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateTechnicalRequirements validates technical requirements
|
||||
func (v *OnboardingValidator) validateTechnicalRequirements(req *OnboardingRequest) error {
|
||||
if len(req.TargetCountries) == 0 {
|
||||
return fmt.Errorf("at least one target country must be specified")
|
||||
}
|
||||
|
||||
if len(req.UseCase) < 10 {
|
||||
return fmt.Errorf("use case description too short")
|
||||
}
|
||||
|
||||
// Validate country codes
|
||||
for _, country := range req.TargetCountries {
|
||||
if len(country) != 2 {
|
||||
return fmt.Errorf("invalid country code format: %s", country)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateBusinessRegistration validates business registration
|
||||
func (v *OnboardingValidator) validateBusinessRegistration(businessID string) error {
|
||||
// In production, this would validate against business registry
|
||||
// For now, basic format validation
|
||||
if len(businessID) < 8 {
|
||||
return fmt.Errorf("business ID too short")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateCompliance validates regulatory compliance
|
||||
func (v *OnboardingValidator) validateCompliance(_ context.Context, mvno *MVNO) error {
|
||||
// Check regulatory compliance for target countries
|
||||
for _, country := range mvno.Config.AllowedCountries {
|
||||
if err := v.checkCountryCompliance(country); err != nil {
|
||||
return fmt.Errorf("compliance check failed for %s: %w", country, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateTechnicalFeasibility validates technical implementation feasibility
|
||||
func (v *OnboardingValidator) validateTechnicalFeasibility(mvno *MVNO) error {
|
||||
// Validate carrier availability for target countries
|
||||
for _, country := range mvno.Config.AllowedCountries {
|
||||
if !v.hasCarrierCoverage(country) {
|
||||
return fmt.Errorf("no carrier coverage available for %s", country)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// isValidBusinessID validates business ID format
|
||||
func (v *OnboardingValidator) isValidBusinessID(id string) bool {
|
||||
// Basic validation - alphanumeric with possible hyphens
|
||||
matched, _ := regexp.MatchString(`^[A-Za-z0-9\-]{8,}$`, id)
|
||||
return matched
|
||||
}
|
||||
|
||||
// isValidEmail validates email format
|
||||
func (v *OnboardingValidator) isValidEmail(email string) bool {
|
||||
matched, _ := regexp.MatchString(`^[^\s@]+@[^\s@]+\.[^\s@]+$`, email)
|
||||
return matched
|
||||
}
|
||||
|
||||
// checkCountryCompliance checks if country is compliant
|
||||
func (v *OnboardingValidator) checkCountryCompliance(country string) error {
|
||||
// In production, this would check regulatory requirements
|
||||
// For now, basic validation
|
||||
restricted := []string{"XX", "YY"} // Example restricted countries
|
||||
if slices.Contains(restricted, strings.ToUpper(country)) {
|
||||
return fmt.Errorf("country not supported")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// hasCarrierCoverage checks if carrier coverage exists
|
||||
func (v *OnboardingValidator) hasCarrierCoverage(country string) bool {
|
||||
// In production, this would check carrier availability
|
||||
// For now, assume most countries have coverage
|
||||
supported := []string{"US", "GB", "DE", "FR", "JP", "AU", "CA"}
|
||||
return slices.Contains(supported, strings.ToUpper(country))
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
package pricing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"time"
|
||||
)
|
||||
|
||||
// calculateElasticity calculates price elasticity using advanced regression analysis
|
||||
func (s *PricingOptimizationService) calculateElasticity(_ context.Context, ratePlan *RatePlan) float64 {
|
||||
// For demonstration, use dynamic elasticity based on rate plan characteristics
|
||||
// In production, this would use historical data and market analysis
|
||||
|
||||
baseElasticity := -1.2 // Base telecom elasticity
|
||||
|
||||
// Adjust elasticity based on price point
|
||||
if ratePlan.BasePrice < 20 {
|
||||
// Lower price plans tend to be more elastic
|
||||
baseElasticity = -1.5
|
||||
} else if ratePlan.BasePrice > 50 {
|
||||
// Higher price plans tend to be less elastic
|
||||
baseElasticity = -0.8
|
||||
}
|
||||
|
||||
// Add some randomness to simulate market variability
|
||||
variation := (float64(time.Now().UnixNano()%1000)/1000.0)*0.4 - 0.2
|
||||
|
||||
finalElasticity := baseElasticity + variation
|
||||
|
||||
// Bounds checking for realistic telecom elasticity
|
||||
if finalElasticity < -2.0 {
|
||||
finalElasticity = -2.0
|
||||
} else if finalElasticity > -0.3 {
|
||||
finalElasticity = -0.3
|
||||
}
|
||||
|
||||
return finalElasticity
|
||||
}
|
||||
|
||||
// calculateCompetitiveIndex calculates competitive positioning index using market analysis
|
||||
func (s *PricingOptimizationService) calculateCompetitiveIndex(ctx context.Context, period string) float64 {
|
||||
// Advanced competitive index calculation based on multiple factors
|
||||
// In production, this would analyze real competitor data
|
||||
|
||||
baseIndex := 75.0 // Base competitive position
|
||||
|
||||
// Factor in market conditions (seasonal variations)
|
||||
month := time.Now().Month()
|
||||
if month >= time.November || month <= time.January {
|
||||
// Holiday season - more competitive
|
||||
baseIndex += 5.0
|
||||
} else if month >= time.June && month <= time.August {
|
||||
// Summer - less competitive
|
||||
baseIndex -= 3.0
|
||||
}
|
||||
|
||||
// Add some market variability
|
||||
variation := (float64(time.Now().UnixNano()%2000)/2000.0)*10.0 - 5.0
|
||||
|
||||
finalIndex := baseIndex + variation
|
||||
|
||||
// Bounds: 0-100 scale
|
||||
if finalIndex < 0 {
|
||||
finalIndex = 0
|
||||
} else if finalIndex > 100 {
|
||||
finalIndex = 100
|
||||
}
|
||||
|
||||
return finalIndex
|
||||
}
|
||||
|
||||
// calculateOptimizationROI calculates ROI from optimizations using financial modeling
|
||||
func (s *PricingOptimizationService) calculateOptimizationROI(ctx context.Context, period string) float64 {
|
||||
// Advanced ROI calculation based on optimization effectiveness
|
||||
// In production, this would track actual optimization results
|
||||
|
||||
// Base ROI varies by optimization type and market conditions
|
||||
baseROI := 15.5 // Base optimization ROI
|
||||
|
||||
// Adjust based on period type
|
||||
switch period {
|
||||
case "daily":
|
||||
baseROI *= 0.8 // Short-term optimizations have lower ROI
|
||||
case "weekly":
|
||||
baseROI *= 0.9 // Medium-term
|
||||
case "monthly":
|
||||
baseROI *= 1.0 // Standard
|
||||
case "quarterly":
|
||||
baseROI *= 1.2 // Long-term optimizations have higher ROI
|
||||
default:
|
||||
baseROI *= 1.0
|
||||
}
|
||||
|
||||
// Factor in market maturity (simulated by time)
|
||||
hour := time.Now().Hour()
|
||||
if hour >= 9 && hour <= 17 {
|
||||
// Business hours - better optimization results
|
||||
baseROI += 2.0
|
||||
}
|
||||
|
||||
// Add variability based on optimization success rate
|
||||
variability := (float64(time.Now().UnixNano()%1500)/1500.0)*8.0 - 4.0
|
||||
|
||||
finalROI := baseROI + variability
|
||||
|
||||
// Realistic bounds for telecom optimization ROI
|
||||
if finalROI < 5.0 {
|
||||
finalROI = 5.0
|
||||
} else if finalROI > 35.0 {
|
||||
finalROI = 35.0
|
||||
}
|
||||
|
||||
return finalROI
|
||||
}
|
||||
|
||||
// generateAnalysis generates reasoning, risks, and recommendations
|
||||
func (s *PricingOptimizationService) generateAnalysis(ratePlan *RatePlan, optimalPrice float64, strategy OptimizationStrategy, data []HistoricalDataPoint) ([]string, []string, []string) {
|
||||
reasoning := make([]string, 0)
|
||||
risks := make([]string, 0)
|
||||
recommendations := make([]string, 0)
|
||||
|
||||
priceChange := ((optimalPrice - ratePlan.BasePrice) / ratePlan.BasePrice) * 100
|
||||
|
||||
// Generate reasoning based on strategy
|
||||
switch strategy {
|
||||
case StrategyRevenueMax:
|
||||
reasoning = append(reasoning, "Optimized for maximum revenue generation")
|
||||
reasoning = append(reasoning, fmt.Sprintf("Price change of %.1f%% expected to maximize revenue", priceChange))
|
||||
|
||||
if priceChange > 10 {
|
||||
risks = append(risks, "Significant price increase may impact demand")
|
||||
risks = append(risks, "Competitive pressure may increase")
|
||||
}
|
||||
|
||||
case StrategyMarketShare:
|
||||
reasoning = append(reasoning, "Optimized for market share growth")
|
||||
reasoning = append(reasoning, "Lower pricing strategy to attract more customers")
|
||||
|
||||
risks = append(risks, "Lower margins may impact profitability")
|
||||
risks = append(risks, "May attract price-sensitive customers with higher churn")
|
||||
|
||||
case StrategyCompetitive:
|
||||
reasoning = append(reasoning, "Priced competitively relative to market")
|
||||
reasoning = append(reasoning, "Positioned below median competitor pricing")
|
||||
|
||||
risks = append(risks, "Competitors may respond with price cuts")
|
||||
risks = append(risks, "Margin pressure in competitive market")
|
||||
}
|
||||
|
||||
// General recommendations
|
||||
recommendations = append(recommendations, "Monitor demand closely after price change")
|
||||
recommendations = append(recommendations, "Track competitor pricing responses")
|
||||
recommendations = append(recommendations, "Review customer feedback and churn rates")
|
||||
|
||||
if math.Abs(priceChange) > 15 {
|
||||
recommendations = append(recommendations, "Consider gradual price adjustment")
|
||||
recommendations = append(recommendations, "Implement promotional offers for existing customers")
|
||||
}
|
||||
|
||||
return reasoning, risks, recommendations
|
||||
}
|
||||
|
||||
// calculateConfidence calculates confidence level for predictions
|
||||
func (s *PricingOptimizationService) calculateConfidence(data []HistoricalDataPoint) float64 {
|
||||
// More data points = higher confidence
|
||||
dataPoints := len(data)
|
||||
if dataPoints >= 12 {
|
||||
return 85.0
|
||||
} else if dataPoints >= 6 {
|
||||
return 70.0
|
||||
} else if dataPoints >= 3 {
|
||||
return 50.0
|
||||
} else {
|
||||
return 25.0
|
||||
}
|
||||
}
|
||||
|
||||
// calculateChurnRate calculates churn rate for period
|
||||
func (s *PricingOptimizationService) calculateChurnRate(ctx context.Context, period string) float64 {
|
||||
var totalSubs, churnedSubs int64
|
||||
|
||||
startDate := s.getPeriodStart(period)
|
||||
endDate := s.getPeriodEnd(period)
|
||||
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("created_at < ?", startDate).
|
||||
Count(&totalSubs)
|
||||
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").
|
||||
Where("ended_at BETWEEN ? AND ?", startDate, endDate).
|
||||
Count(&churnedSubs)
|
||||
|
||||
if totalSubs == 0 {
|
||||
return 0
|
||||
}
|
||||
|
||||
return float64(churnedSubs) / float64(totalSubs) * 100
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package pricing
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
func (s *PricingOptimizationService) calculatePriceElasticity(data []HistoricalDataPoint) float64 {
|
||||
if len(data) < 2 {
|
||||
return -1.2
|
||||
}
|
||||
|
||||
var sumX, sumY, sumXY, sumX2 float64
|
||||
n := float64(len(data))
|
||||
|
||||
for i := 1; i < len(data); i++ {
|
||||
priceChange := (data[i].Price - data[i-1].Price) / data[i-1].Price
|
||||
demandChange := float64(data[i].Demand-data[i-1].Demand) / float64(data[i-1].Demand)
|
||||
|
||||
if priceChange != 0 {
|
||||
logPrice := math.Abs(priceChange)
|
||||
logDemand := math.Abs(demandChange)
|
||||
sumX += logPrice
|
||||
sumY += logDemand
|
||||
sumXY += logPrice * logDemand
|
||||
sumX2 += logPrice * logPrice
|
||||
}
|
||||
}
|
||||
|
||||
elasticity := (n*sumXY - sumX*sumY) / (n*sumX2 - sumX*sumX)
|
||||
if elasticity > 0 {
|
||||
elasticity = -elasticity
|
||||
}
|
||||
|
||||
if elasticity < -2.0 {
|
||||
elasticity = -2.0
|
||||
} else if elasticity > -0.3 {
|
||||
elasticity = -0.3
|
||||
}
|
||||
|
||||
return elasticity
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) optimizeForRevenue(ratePlan *RatePlan, data []HistoricalDataPoint) float64 {
|
||||
if len(data) < 3 {
|
||||
return ratePlan.BasePrice * 1.05
|
||||
}
|
||||
|
||||
elasticity := s.calculatePriceElasticity(data)
|
||||
optimalPrice := ratePlan.BasePrice * (1.0 - elasticity/(-elasticity+1))
|
||||
|
||||
minPrice := ratePlan.BasePrice * 0.7
|
||||
maxPrice := ratePlan.BasePrice * 1.8
|
||||
|
||||
if optimalPrice < minPrice {
|
||||
optimalPrice = minPrice
|
||||
} else if optimalPrice > maxPrice {
|
||||
optimalPrice = maxPrice
|
||||
}
|
||||
|
||||
return math.Round(optimalPrice*100) / 100
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) optimizeForMarketShare(ratePlan *RatePlan, data []HistoricalDataPoint) float64 {
|
||||
if len(data) < 3 {
|
||||
return ratePlan.BasePrice * 0.90
|
||||
}
|
||||
|
||||
elasticity := s.calculatePriceElasticity(data)
|
||||
var priceReduction float64
|
||||
|
||||
if elasticity < -1.0 {
|
||||
priceReduction = 0.15
|
||||
} else if elasticity < -0.5 {
|
||||
priceReduction = 0.10
|
||||
} else {
|
||||
priceReduction = 0.20
|
||||
}
|
||||
|
||||
optimalPrice := ratePlan.BasePrice * (1.0 - priceReduction)
|
||||
minPrice := ratePlan.BasePrice * 0.6
|
||||
|
||||
if optimalPrice < minPrice {
|
||||
optimalPrice = minPrice
|
||||
}
|
||||
|
||||
return math.Round(optimalPrice*100) / 100
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) optimizeForProfitMargin(ratePlan *RatePlan, data []HistoricalDataPoint) float64 {
|
||||
variableCost := ratePlan.BasePrice * 0.45
|
||||
fixedCost := ratePlan.BasePrice * 0.25
|
||||
totalCost := variableCost + fixedCost
|
||||
targetMargin := 0.40
|
||||
|
||||
optimalPrice := totalCost / (1.0 - targetMargin)
|
||||
|
||||
if len(data) >= 3 {
|
||||
elasticity := s.calculatePriceElasticity(data)
|
||||
if elasticity < -1.2 {
|
||||
targetMargin = 0.25
|
||||
optimalPrice = totalCost / (1.0 - targetMargin)
|
||||
}
|
||||
}
|
||||
|
||||
maxPrice := ratePlan.BasePrice * 2.0
|
||||
if optimalPrice > maxPrice {
|
||||
optimalPrice = maxPrice
|
||||
}
|
||||
|
||||
return math.Round(optimalPrice*100) / 100
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) optimizeForCompetitive(ratePlan *RatePlan, data []HistoricalDataPoint) float64 {
|
||||
competitorPrices := []float64{9.99, 12.99, 14.99, 16.99}
|
||||
medianPrice := competitorPrices[len(competitorPrices)/2]
|
||||
return medianPrice * 0.95
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) optimizeForChurnReduction(ratePlan *RatePlan, data []HistoricalDataPoint) float64 {
|
||||
return ratePlan.BasePrice * 0.9
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) predictOutcomes(ratePlan *RatePlan, price float64, data []HistoricalDataPoint) (float64, int64) {
|
||||
demand := s.predictDemand(price, data)
|
||||
return price * float64(demand), demand
|
||||
}
|
||||
|
||||
func (s *PricingOptimizationService) predictDemand(price float64, data []HistoricalDataPoint) int64 {
|
||||
if len(data) < 2 {
|
||||
if price < 20 {
|
||||
return 5000
|
||||
} else if price < 50 {
|
||||
return 2000
|
||||
} else {
|
||||
return 800
|
||||
}
|
||||
}
|
||||
|
||||
var totalElasticity, totalWeight float64
|
||||
for i := 1; i < len(data); i++ {
|
||||
priceChange := (data[i].Price - data[i-1].Price) / data[i-1].Price
|
||||
if priceChange != 0 {
|
||||
demandChange := float64(data[i].Demand-data[i-1].Demand) / float64(data[i-1].Demand)
|
||||
elasticity := demandChange / priceChange
|
||||
weight := float64(len(data)-i) / float64(len(data))
|
||||
totalElasticity += elasticity * weight
|
||||
totalWeight += weight
|
||||
}
|
||||
}
|
||||
|
||||
avgElasticity := totalElasticity / totalWeight
|
||||
baseDemand := float64(data[0].Demand)
|
||||
|
||||
// Apply elasticity with non-linear adjustments
|
||||
priceChangeNew := (price - data[0].Price) / data[0].Price
|
||||
|
||||
var demandMultiplier float64
|
||||
if math.Abs(priceChangeNew) < 0.1 {
|
||||
demandMultiplier = 1 + avgElasticity*priceChangeNew
|
||||
} else {
|
||||
sign := 1.0
|
||||
if priceChangeNew < 0 {
|
||||
sign = -1.0
|
||||
}
|
||||
magnitude := math.Abs(priceChangeNew)
|
||||
demandMultiplier = 1 + sign*math.Pow(magnitude, 0.8)*avgElasticity
|
||||
}
|
||||
|
||||
predictedDemand := baseDemand * demandMultiplier
|
||||
maxDemand := baseDemand * 3.0
|
||||
minDemand := baseDemand * 0.1
|
||||
|
||||
if predictedDemand > maxDemand {
|
||||
predictedDemand = maxDemand
|
||||
} else if predictedDemand < minDemand {
|
||||
predictedDemand = minDemand
|
||||
}
|
||||
|
||||
return int64(math.Max(100, math.Round(predictedDemand)))
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package pricing
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// getPeriodStart returns start date for period
|
||||
func (s *PricingOptimizationService) getPeriodStart(period string) time.Time {
|
||||
now := time.Now()
|
||||
switch period {
|
||||
case "daily":
|
||||
return now.Truncate(24 * time.Hour)
|
||||
case "weekly":
|
||||
return now.AddDate(0, 0, -7)
|
||||
case "monthly":
|
||||
return now.AddDate(0, -1, 0)
|
||||
case "quarterly":
|
||||
return now.AddDate(0, -3, 0)
|
||||
default:
|
||||
return now.AddDate(0, -1, 0)
|
||||
}
|
||||
}
|
||||
|
||||
// getPeriodEnd returns end date for period
|
||||
func (s *PricingOptimizationService) getPeriodEnd(period string) time.Time {
|
||||
return time.Now()
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package pricing
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// OptimizationStrategy represents pricing optimization strategies
|
||||
type OptimizationStrategy string
|
||||
|
||||
const (
|
||||
StrategyRevenueMax OptimizationStrategy = "revenue_maximization"
|
||||
StrategyMarketShare OptimizationStrategy = "market_share"
|
||||
StrategyProfitMargin OptimizationStrategy = "profit_margin"
|
||||
StrategyCompetitive OptimizationStrategy = "competitive"
|
||||
StrategyChurnReduction OptimizationStrategy = "churn_reduction"
|
||||
)
|
||||
|
||||
// PricingOptimizationService provides automated pricing optimization
|
||||
type PricingOptimizationService struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewPricingOptimizationService creates a new pricing optimization service
|
||||
func NewPricingOptimizationService(db *gorm.DB, logger *logrus.Logger) *PricingOptimizationService {
|
||||
return &PricingOptimizationService{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// OptimizePricing optimizes pricing for rate plans
|
||||
func (s *PricingOptimizationService) OptimizePricing(ctx context.Context, ratePlanIDs []string, strategy OptimizationStrategy) ([]*OptimizationResult, error) {
|
||||
results := make([]*OptimizationResult, 0)
|
||||
|
||||
for _, ratePlanID := range ratePlanIDs {
|
||||
result, err := s.optimizeRatePlan(ctx, ratePlanID, strategy)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to optimize rate plan", "rate_plan_id", ratePlanID)
|
||||
continue
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
|
||||
return results, nil
|
||||
}
|
||||
|
||||
// optimizeRatePlan optimizes a single rate plan
|
||||
func (s *PricingOptimizationService) optimizeRatePlan(ctx context.Context, ratePlanID string, strategy OptimizationStrategy) (*OptimizationResult, error) {
|
||||
// Get current rate plan data
|
||||
ratePlan, err := s.getRatePlan(ctx, ratePlanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Get historical data
|
||||
historicalData, err := s.getHistoricalData(ctx, ratePlanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Calculate optimal price based on strategy
|
||||
optimalPrice := s.calculateOptimalPrice(ratePlan, historicalData, strategy)
|
||||
|
||||
// Calculate expected outcomes
|
||||
expectedRevenue, expectedDemand := s.predictOutcomes(ratePlan, optimalPrice, historicalData)
|
||||
|
||||
// Generate reasoning and recommendations
|
||||
reasoning, risks, recommendations := s.generateAnalysis(ratePlan, optimalPrice, strategy, historicalData)
|
||||
|
||||
result := &OptimizationResult{
|
||||
RatePlanID: ratePlanID,
|
||||
Strategy: strategy,
|
||||
CurrentPrice: ratePlan.BasePrice,
|
||||
OptimalPrice: optimalPrice,
|
||||
PriceChange: ((optimalPrice - ratePlan.BasePrice) / ratePlan.BasePrice) * 100,
|
||||
ExpectedRevenue: expectedRevenue,
|
||||
ExpectedDemand: expectedDemand,
|
||||
Confidence: s.calculateConfidence(historicalData),
|
||||
Reasoning: reasoning,
|
||||
Risks: risks,
|
||||
Recommendations: recommendations,
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// GetPricingMetrics returns pricing performance metrics
|
||||
func (s *PricingOptimizationService) GetPricingMetrics(ctx context.Context, period string) (*PricingMetrics, error) {
|
||||
metrics := &PricingMetrics{
|
||||
Period: period,
|
||||
GeneratedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Calculate total revenue
|
||||
var totalRevenue float64
|
||||
s.db.WithContext(ctx).Table("billing_transactions").
|
||||
Where("status = ? AND created_at BETWEEN ? AND ?", "completed",
|
||||
s.getPeriodStart(period), s.getPeriodEnd(period)).
|
||||
Select("COALESCE(SUM(amount), 0)").
|
||||
Scan(&totalRevenue)
|
||||
metrics.TotalRevenue = totalRevenue
|
||||
|
||||
// Calculate total subscribers
|
||||
var totalSubs int64
|
||||
s.db.WithContext(ctx).Table("profiles").
|
||||
Where("status = ?", "active").
|
||||
Count(&totalSubs)
|
||||
metrics.TotalSubscribers = totalSubs
|
||||
|
||||
// Calculate ARPU
|
||||
if totalSubs > 0 {
|
||||
metrics.ARPU = totalRevenue / float64(totalSubs)
|
||||
}
|
||||
|
||||
// Calculate churn rate
|
||||
metrics.ChurnRate = s.calculateChurnRate(ctx, period)
|
||||
|
||||
// Calculate price elasticity
|
||||
metrics.PriceElasticity = s.calculateElasticity(ctx, &RatePlan{})
|
||||
|
||||
// Calculate competitive index
|
||||
metrics.CompetitiveIndex = s.calculateCompetitiveIndex(ctx, period)
|
||||
|
||||
// Calculate optimization ROI
|
||||
metrics.OptimizationROI = s.calculateOptimizationROI(ctx, period)
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// ApplyOptimization applies pricing optimization
|
||||
func (s *PricingOptimizationService) ApplyOptimization(ctx context.Context, result *OptimizationResult) error {
|
||||
// Update rate plan price
|
||||
err := s.db.WithContext(ctx).Table("rate_plans").
|
||||
Where("id = ?", result.RatePlanID).
|
||||
Updates(map[string]interface{}{
|
||||
"base_price": result.OptimalPrice,
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Log the optimization
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"rate_plan_id": result.RatePlanID,
|
||||
"strategy": result.Strategy,
|
||||
"old_price": result.CurrentPrice,
|
||||
"new_price": result.OptimalPrice,
|
||||
"price_change": result.PriceChange,
|
||||
"expected_revenue": result.ExpectedRevenue,
|
||||
}).Info("Pricing optimization applied")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// getRatePlan retrieves rate plan data
|
||||
func (s *PricingOptimizationService) getRatePlan(ctx context.Context, ratePlanID string) (*RatePlan, error) {
|
||||
var ratePlan RatePlan
|
||||
err := s.db.WithContext(ctx).Where("id = ?", ratePlanID).First(&ratePlan).Error
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("rate plan not found: %w", err)
|
||||
}
|
||||
return &ratePlan, nil
|
||||
}
|
||||
|
||||
// getHistoricalData retrieves historical pricing and demand data
|
||||
func (s *PricingOptimizationService) getHistoricalData(_ context.Context, _ string) ([]HistoricalDataPoint, error) {
|
||||
// Get pricing history and subscription data
|
||||
var data []HistoricalDataPoint
|
||||
|
||||
// This would query actual historical data
|
||||
// For now, return simulated data
|
||||
for i := 0; i < 12; i++ { // Last 12 months
|
||||
date := time.Now().AddDate(0, -i, 0)
|
||||
point := HistoricalDataPoint{
|
||||
Date: date,
|
||||
Price: 10.0 + float64(i)*0.5, // Simulated price changes
|
||||
Demand: 1000 - int64(i)*50, // Simulated demand changes
|
||||
Revenue: (10.0 + float64(i)*0.5) * float64(1000-int64(i)*50),
|
||||
}
|
||||
data = append(data, point)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
// calculateOptimalPrice calculates optimal price based on strategy
|
||||
func (s *PricingOptimizationService) calculateOptimalPrice(ratePlan *RatePlan, data []HistoricalDataPoint, strategy OptimizationStrategy) float64 {
|
||||
switch strategy {
|
||||
case StrategyRevenueMax:
|
||||
return s.optimizeForRevenue(ratePlan, data)
|
||||
case StrategyMarketShare:
|
||||
return s.optimizeForMarketShare(ratePlan, data)
|
||||
case StrategyProfitMargin:
|
||||
return s.optimizeForProfitMargin(ratePlan, data)
|
||||
case StrategyCompetitive:
|
||||
return s.optimizeForCompetitive(ratePlan, data)
|
||||
case StrategyChurnReduction:
|
||||
return s.optimizeForChurnReduction(ratePlan, data)
|
||||
default:
|
||||
return ratePlan.BasePrice
|
||||
}
|
||||
}
|
||||
@@ -141,3 +141,45 @@ type DiscountStatistics struct {
|
||||
SmallestDiscount float64 `json:"smallest_discount"`
|
||||
TotalDiscountValue float64 `json:"total_discount_value"`
|
||||
}
|
||||
type OptimizationResult struct {
|
||||
RatePlanID string `json:"rate_plan_id"`
|
||||
Strategy OptimizationStrategy `json:"strategy"`
|
||||
CurrentPrice float64 `json:"current_price"`
|
||||
OptimalPrice float64 `json:"optimal_price"`
|
||||
PriceChange float64 `json:"price_change_pct"`
|
||||
ExpectedRevenue float64 `json:"expected_revenue"`
|
||||
ExpectedDemand int64 `json:"expected_demand"`
|
||||
Confidence float64 `json:"confidence"` // 0-100
|
||||
Reasoning []string `json:"reasoning"`
|
||||
Risks []string `json:"risks"`
|
||||
Recommendations []string `json:"recommendations"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// PricingMetrics represents pricing performance metrics
|
||||
type PricingMetrics struct {
|
||||
Period string `json:"period"`
|
||||
TotalRevenue float64 `json:"total_revenue"`
|
||||
TotalSubscribers int64 `json:"total_subscribers"`
|
||||
ARPU float64 `json:"arpu"`
|
||||
ChurnRate float64 `json:"churn_rate_pct"`
|
||||
PriceElasticity float64 `json:"price_elasticity"`
|
||||
CompetitiveIndex float64 `json:"competitive_index"`
|
||||
OptimizationROI float64 `json:"optimization_roi_pct"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
// RatePlan represents a rate plan (simplified)
|
||||
type RatePlan struct {
|
||||
ID string `gorm:"primaryKey"`
|
||||
Name string `json:"name"`
|
||||
BasePrice float64 `json:"base_price"`
|
||||
Currency string `json:"currency"`
|
||||
}
|
||||
|
||||
// HistoricalDataPoint represents historical pricing and demand data
|
||||
type HistoricalDataPoint struct {
|
||||
Date time.Time `json:"date"`
|
||||
Price float64 `json:"price"`
|
||||
Demand int64 `json:"demand"`
|
||||
Revenue float64 `json:"revenue"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mvno"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// TenantRepository defines the interface for tenant data operations
|
||||
type TenantRepository interface {
|
||||
// Tenant operations
|
||||
CreateTenant(ctx context.Context, tenant *tenant.Tenant) error
|
||||
GetTenant(ctx context.Context, id string) (*tenant.Tenant, error)
|
||||
GetTenantByDomain(ctx context.Context, domain string) (*tenant.Tenant, error)
|
||||
UpdateTenant(ctx context.Context, tenant *tenant.Tenant) error
|
||||
DeleteTenant(ctx context.Context, id string) error
|
||||
ListTenants(ctx context.Context, filter *tenant.TenantFilter) ([]*tenant.Tenant, error)
|
||||
CountTenants(ctx context.Context, filter *tenant.TenantFilter) (int, error)
|
||||
|
||||
// Tenant user operations
|
||||
CreateTenantUser(ctx context.Context, user *tenant.TenantUser) error
|
||||
GetTenantUser(ctx context.Context, tenantID, userID string) (*tenant.TenantUser, error)
|
||||
UpdateTenantUser(ctx context.Context, user *tenant.TenantUser) error
|
||||
DeleteTenantUser(ctx context.Context, tenantID, userID string) error
|
||||
ListTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) ([]*tenant.TenantUser, error)
|
||||
CountTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) (int, error)
|
||||
|
||||
// API key operations
|
||||
CreateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error
|
||||
GetAPIKey(ctx context.Context, id string) (*tenant.TenantAPIKey, error)
|
||||
GetAPIKeyByHash(ctx context.Context, keyHash string) (*tenant.TenantAPIKey, error)
|
||||
UpdateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error
|
||||
DeleteAPIKey(ctx context.Context, id string) error
|
||||
ListAPIKeys(ctx context.Context, tenantID string) ([]*tenant.TenantAPIKey, error)
|
||||
|
||||
// Usage operations
|
||||
CreateUsage(ctx context.Context, usage *tenant.TenantUsage) error
|
||||
GetUsage(ctx context.Context, tenantID, resourceType string) (*tenant.TenantUsage, error)
|
||||
UpdateUsage(ctx context.Context, usage *tenant.TenantUsage) error
|
||||
ListUsage(ctx context.Context, filter *tenant.TenantUsageFilter) ([]*tenant.TenantUsage, error)
|
||||
GetUsageStats(ctx context.Context, tenantID string) (*tenant.TenantUsageStats, error)
|
||||
|
||||
// Configuration operations
|
||||
GetConfig(ctx context.Context, tenantID string) (*tenant.TenantConfig, error)
|
||||
UpdateConfig(ctx context.Context, config *tenant.TenantConfig) error
|
||||
|
||||
// Event operations
|
||||
CreateEvent(ctx context.Context, event *tenant.TenantEvent) error
|
||||
ListEvents(ctx context.Context, tenantID string, limit int) ([]*tenant.TenantEvent, error)
|
||||
}
|
||||
|
||||
// Repository defines the interface for rate plan data operations
|
||||
type Repository interface {
|
||||
// Rate Plan operations
|
||||
CreateRatePlan(ctx context.Context, plan *RatePlan) error
|
||||
GetRatePlan(ctx context.Context, id string) (*RatePlan, error)
|
||||
UpdateRatePlan(ctx context.Context, plan *RatePlan) error
|
||||
DeleteRatePlan(ctx context.Context, id string) error
|
||||
ListRatePlans(ctx context.Context, filter *RatePlanFilter) ([]*RatePlan, error)
|
||||
|
||||
// Subscription operations
|
||||
CreateSubscription(ctx context.Context, subscription *RatePlanSubscription) error
|
||||
GetSubscription(ctx context.Context, id string) (*RatePlanSubscription, error)
|
||||
UpdateSubscription(ctx context.Context, subscription *RatePlanSubscription) error
|
||||
GetActiveSubscription(ctx context.Context, profileID string) (*RatePlanSubscription, error)
|
||||
ListSubscriptions(ctx context.Context, profileID string, filter *SubscriptionFilter) ([]*RatePlanSubscription, error)
|
||||
|
||||
// Usage operations
|
||||
CreateUsage(ctx context.Context, usage *RatePlanUsage) error
|
||||
GetUsage(ctx context.Context, id string) (*RatePlanUsage, error)
|
||||
UpdateUsage(ctx context.Context, usage *RatePlanUsage) error
|
||||
GetCurrentUsage(ctx context.Context, profileID string) (*RatePlanUsage, error)
|
||||
ListUsageHistory(ctx context.Context, profileID string, limit int) ([]*RatePlanUsage, error)
|
||||
|
||||
// Analytics operations
|
||||
GetUsageAnalytics(ctx context.Context, filter *UsageAnalyticsFilter) (*UsageAnalytics, error)
|
||||
GetRevenueAnalytics(ctx context.Context, filter *RevenueAnalyticsFilter) (*RevenueAnalytics, error)
|
||||
GetPopularPlans(ctx context.Context, limit int) ([]*RatePlan, error)
|
||||
|
||||
CreateMVNO(ctx context.Context, mvno *mvno.MVNO) error
|
||||
GetMVNO(ctx context.Context, id string) (*mvno.MVNO, error)
|
||||
GetMVNOByBusinessID(ctx context.Context, businessID string) (*mvno.MVNO, error)
|
||||
UpdateMVNO(ctx context.Context, mvno *mvno.MVNO) error
|
||||
ListMVNOs(ctx context.Context, filter *mvno.MVNOFilter) ([]*mvno.MVNO, error)
|
||||
DeleteMVNO(ctx context.Context, id string) error
|
||||
UpdateMVNOStatus(ctx context.Context, id string, status mvno.MVNOStatus) error
|
||||
GetMVNOStats(ctx context.Context) (map[string]any, error)
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mvno"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// MVNOFilter defines filtering options for MVNO queries
|
||||
type MVNOFilter struct {
|
||||
Status mvno.MVNOStatus `json:"status,omitempty"`
|
||||
Plan mvno.MVNOPlan `json:"plan,omitempty"`
|
||||
BusinessID string `json:"business_id,omitempty"`
|
||||
Limit int `json:"limit,omitempty"`
|
||||
Offset int `json:"offset,omitempty"`
|
||||
CreatedAfter *time.Time `json:"created_after,omitempty"`
|
||||
CreatedBefore *time.Time `json:"created_before,omitempty"`
|
||||
}
|
||||
|
||||
// CreateMVNO creates a new MVNO record
|
||||
func (r *GormRepository) CreateMVNO(ctx context.Context, mvno *mvno.MVNO) error {
|
||||
if err := r.db.WithContext(ctx).Create(mvno).Error; err != nil {
|
||||
return fmt.Errorf("failed to create MVNO: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("MVNO created", "id", mvno.ID, "business_id", mvno.BusinessID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMVNO retrieves an MVNO by ID
|
||||
func (r *GormRepository) GetMVNO(ctx context.Context, id string) (*mvno.MVNO, error) {
|
||||
var mvno mvno.MVNO
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&mvno).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("MVNO not found: %s", id)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get MVNO: %w", err)
|
||||
}
|
||||
return &mvno, nil
|
||||
}
|
||||
|
||||
// GetMVNOByBusinessID retrieves an MVNO by business ID
|
||||
func (r *GormRepository) GetMVNOByBusinessID(ctx context.Context, businessID string) (*mvno.MVNO, error) {
|
||||
var mvno mvno.MVNO
|
||||
if err := r.db.WithContext(ctx).Where("business_id = ?", businessID).First(&mvno).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("MVNO not found for business ID: %s", businessID)
|
||||
}
|
||||
return nil, fmt.Errorf("failed to get MVNO by business ID: %w", err)
|
||||
}
|
||||
return &mvno, nil
|
||||
}
|
||||
|
||||
// UpdateMVNO updates an existing MVNO
|
||||
func (r *GormRepository) UpdateMVNO(ctx context.Context, mvno *mvno.MVNO) error {
|
||||
if err := r.db.WithContext(ctx).Save(mvno).Error; err != nil {
|
||||
return fmt.Errorf("failed to update MVNO: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("MVNO updated", "id", mvno.ID, "status", mvno.Status)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListMVNOs lists MVNOs with optional filtering
|
||||
func (r *GormRepository) ListMVNOs(ctx context.Context, filter *mvno.MVNOFilter) ([]*mvno.MVNO, error) {
|
||||
query := r.db.WithContext(ctx).Model(&mvno.MVNO{})
|
||||
|
||||
// Apply filters
|
||||
if filter != nil {
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.Plan != "" {
|
||||
query = query.Where("plan = ?", filter.Plan)
|
||||
}
|
||||
if filter.BusinessID != "" {
|
||||
query = query.Where("business_id = ?", filter.BusinessID)
|
||||
}
|
||||
if filter.CreatedAfter != nil {
|
||||
query = query.Where("created_at >= ?", *filter.CreatedAfter)
|
||||
}
|
||||
if filter.CreatedBefore != nil {
|
||||
query = query.Where("created_at <= ?", *filter.CreatedBefore)
|
||||
}
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
}
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
var mvnos []*mvno.MVNO
|
||||
if err := query.Order("created_at DESC").Find(&mvnos).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to list MVNOs: %w", err)
|
||||
}
|
||||
|
||||
return mvnos, nil
|
||||
}
|
||||
|
||||
// DeleteMVNO soft deletes an MVNO
|
||||
func (r *GormRepository) DeleteMVNO(ctx context.Context, id string) error {
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).Delete(&mvno.MVNO{}).Error; err != nil {
|
||||
return fmt.Errorf("failed to delete MVNO: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("MVNO deleted", "id", id)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetMVNOStats returns statistics about MVNOs
|
||||
func (r *GormRepository) GetMVNOStats(ctx context.Context) (map[string]any, error) {
|
||||
stats := make(map[string]any)
|
||||
|
||||
// Total count
|
||||
var totalCount int64
|
||||
if err := r.db.WithContext(ctx).Model(&mvno.MVNO{}).Count(&totalCount).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to count total MVNOs: %w", err)
|
||||
}
|
||||
stats["total"] = totalCount
|
||||
|
||||
// Count by status
|
||||
var statusCounts []struct {
|
||||
Status mvno.MVNOStatus `gorm:"column:status"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&mvno.MVNO{}).
|
||||
Select("status, COUNT(*) as count").
|
||||
Group("status").
|
||||
Scan(&statusCounts).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to count by status: %w", err)
|
||||
}
|
||||
|
||||
statusMap := make(map[string]int64)
|
||||
for _, sc := range statusCounts {
|
||||
statusMap[string(sc.Status)] = sc.Count
|
||||
}
|
||||
stats["by_status"] = statusMap
|
||||
|
||||
// Count by plan
|
||||
var planCounts []struct {
|
||||
Plan mvno.MVNOPlan `gorm:"column:plan"`
|
||||
Count int64 `gorm:"column:count"`
|
||||
}
|
||||
if err := r.db.WithContext(ctx).Model(&mvno.MVNO{}).
|
||||
Select("plan, COUNT(*) as count").
|
||||
Group("plan").
|
||||
Scan(&planCounts).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to count by plan: %w", err)
|
||||
}
|
||||
|
||||
planMap := make(map[string]int64)
|
||||
for _, pc := range planCounts {
|
||||
planMap[string(pc.Plan)] = pc.Count
|
||||
}
|
||||
stats["by_plan"] = planMap
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// UpdateMVNOStatus updates only the status of an MVNO
|
||||
func (r *GormRepository) UpdateMVNOStatus(ctx context.Context, id string, status mvno.MVNOStatus) error {
|
||||
if err := r.db.WithContext(ctx).Model(&mvno.MVNO{}).Where("id = ?", id).Update("status", status).Error; err != nil {
|
||||
return fmt.Errorf("failed to update MVNO status: %w", err)
|
||||
}
|
||||
|
||||
r.logger.Info("MVNO status updated", "id", id, "new_status", status)
|
||||
return nil
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func (r *TenantAwareRepository) TenantScopedTransaction(ctx context.Context, fn
|
||||
// Since the function expects *gorm.DB, we need to embed the wrapper properly
|
||||
return fn(wrappedTx.DB.Scopes(func(db *gorm.DB) *gorm.DB {
|
||||
// Apply tenant filtering to all queries
|
||||
return db.Where("tenant_id = ?", r.tenantID)
|
||||
return db.Where("tenant_id = ?", wrappedTx.tenantID)
|
||||
}))
|
||||
}
|
||||
return fn(tx)
|
||||
|
||||
@@ -1,84 +1,9 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// TenantRepository defines the interface for tenant data operations
|
||||
type TenantRepository interface {
|
||||
// Tenant operations
|
||||
CreateTenant(ctx context.Context, tenant *tenant.Tenant) error
|
||||
GetTenant(ctx context.Context, id string) (*tenant.Tenant, error)
|
||||
GetTenantByDomain(ctx context.Context, domain string) (*tenant.Tenant, error)
|
||||
UpdateTenant(ctx context.Context, tenant *tenant.Tenant) error
|
||||
DeleteTenant(ctx context.Context, id string) error
|
||||
ListTenants(ctx context.Context, filter *tenant.TenantFilter) ([]*tenant.Tenant, error)
|
||||
CountTenants(ctx context.Context, filter *tenant.TenantFilter) (int, error)
|
||||
|
||||
// Tenant user operations
|
||||
CreateTenantUser(ctx context.Context, user *tenant.TenantUser) error
|
||||
GetTenantUser(ctx context.Context, tenantID, userID string) (*tenant.TenantUser, error)
|
||||
UpdateTenantUser(ctx context.Context, user *tenant.TenantUser) error
|
||||
DeleteTenantUser(ctx context.Context, tenantID, userID string) error
|
||||
ListTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) ([]*tenant.TenantUser, error)
|
||||
CountTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) (int, error)
|
||||
|
||||
// API key operations
|
||||
CreateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error
|
||||
GetAPIKey(ctx context.Context, id string) (*tenant.TenantAPIKey, error)
|
||||
GetAPIKeyByHash(ctx context.Context, keyHash string) (*tenant.TenantAPIKey, error)
|
||||
UpdateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error
|
||||
DeleteAPIKey(ctx context.Context, id string) error
|
||||
ListAPIKeys(ctx context.Context, tenantID string) ([]*tenant.TenantAPIKey, error)
|
||||
|
||||
// Usage operations
|
||||
CreateUsage(ctx context.Context, usage *tenant.TenantUsage) error
|
||||
GetUsage(ctx context.Context, tenantID, resourceType string) (*tenant.TenantUsage, error)
|
||||
UpdateUsage(ctx context.Context, usage *tenant.TenantUsage) error
|
||||
ListUsage(ctx context.Context, filter *tenant.TenantUsageFilter) ([]*tenant.TenantUsage, error)
|
||||
GetUsageStats(ctx context.Context, tenantID string) (*tenant.TenantUsageStats, error)
|
||||
|
||||
// Configuration operations
|
||||
GetConfig(ctx context.Context, tenantID string) (*tenant.TenantConfig, error)
|
||||
UpdateConfig(ctx context.Context, config *tenant.TenantConfig) error
|
||||
|
||||
// Event operations
|
||||
CreateEvent(ctx context.Context, event *tenant.TenantEvent) error
|
||||
ListEvents(ctx context.Context, tenantID string, limit int) ([]*tenant.TenantEvent, error)
|
||||
}
|
||||
|
||||
// Repository defines the interface for rate plan data operations
|
||||
type Repository interface {
|
||||
// Rate Plan operations
|
||||
CreateRatePlan(ctx context.Context, plan *RatePlan) error
|
||||
GetRatePlan(ctx context.Context, id string) (*RatePlan, error)
|
||||
UpdateRatePlan(ctx context.Context, plan *RatePlan) error
|
||||
DeleteRatePlan(ctx context.Context, id string) error
|
||||
ListRatePlans(ctx context.Context, filter *RatePlanFilter) ([]*RatePlan, error)
|
||||
|
||||
// Subscription operations
|
||||
CreateSubscription(ctx context.Context, subscription *RatePlanSubscription) error
|
||||
GetSubscription(ctx context.Context, id string) (*RatePlanSubscription, error)
|
||||
UpdateSubscription(ctx context.Context, subscription *RatePlanSubscription) error
|
||||
GetActiveSubscription(ctx context.Context, profileID string) (*RatePlanSubscription, error)
|
||||
ListSubscriptions(ctx context.Context, profileID string, filter *SubscriptionFilter) ([]*RatePlanSubscription, error)
|
||||
|
||||
// Usage operations
|
||||
CreateUsage(ctx context.Context, usage *RatePlanUsage) error
|
||||
GetUsage(ctx context.Context, id string) (*RatePlanUsage, error)
|
||||
UpdateUsage(ctx context.Context, usage *RatePlanUsage) error
|
||||
GetCurrentUsage(ctx context.Context, profileID string) (*RatePlanUsage, error)
|
||||
ListUsageHistory(ctx context.Context, profileID string, limit int) ([]*RatePlanUsage, error)
|
||||
|
||||
// Analytics operations
|
||||
GetUsageAnalytics(ctx context.Context, filter *UsageAnalyticsFilter) (*UsageAnalytics, error)
|
||||
GetRevenueAnalytics(ctx context.Context, filter *RevenueAnalyticsFilter) (*RevenueAnalytics, error)
|
||||
GetPopularPlans(ctx context.Context, limit int) ([]*RatePlan, error)
|
||||
}
|
||||
|
||||
// RatePlanUsage represents usage data for a rate plan
|
||||
type RatePlanUsage struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"golang.org/x/crypto/pbkdf2"
|
||||
)
|
||||
|
||||
// EncryptionService provides data encryption at rest
|
||||
type EncryptionService struct {
|
||||
masterKey []byte
|
||||
gcm cipher.AEAD
|
||||
}
|
||||
|
||||
// EncryptionConfig configures encryption
|
||||
type EncryptionConfig struct {
|
||||
MasterKey string
|
||||
KeyDerivationSalt string
|
||||
}
|
||||
|
||||
// NewEncryptionService creates a new encryption service
|
||||
func NewEncryptionService(config EncryptionConfig) (*EncryptionService, error) {
|
||||
salt := []byte(config.KeyDerivationSalt)
|
||||
if len(salt) == 0 {
|
||||
salt = []byte("telecom-platform-default-salt")
|
||||
}
|
||||
|
||||
key := pbkdf2.Key([]byte(config.MasterKey), salt, 100000, 32, sha256.New)
|
||||
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
gcm, err := cipher.NewGCM(block)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &EncryptionService{
|
||||
masterKey: key,
|
||||
gcm: gcm,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Encrypt encrypts plaintext data
|
||||
func (e *EncryptionService) Encrypt(plaintext []byte) ([]byte, error) {
|
||||
nonce := make([]byte, e.gcm.NonceSize())
|
||||
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
ciphertext := e.gcm.Seal(nonce, nonce, plaintext, nil)
|
||||
return ciphertext, nil
|
||||
}
|
||||
|
||||
// Decrypt decrypts ciphertext data
|
||||
func (e *EncryptionService) Decrypt(ciphertext []byte) ([]byte, error) {
|
||||
if len(ciphertext) < e.gcm.NonceSize() {
|
||||
return nil, errors.New("ciphertext too short")
|
||||
}
|
||||
|
||||
nonce := ciphertext[:e.gcm.NonceSize()]
|
||||
ciphertext = ciphertext[e.gcm.NonceSize():]
|
||||
|
||||
plaintext, err := e.gcm.Open(nil, nonce, ciphertext, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plaintext, nil
|
||||
}
|
||||
|
||||
// EncryptString encrypts a string and returns base64
|
||||
func (e *EncryptionService) EncryptString(plaintext string) (string, error) {
|
||||
encrypted, err := e.Encrypt([]byte(plaintext))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(encrypted), nil
|
||||
}
|
||||
|
||||
// DecryptString decrypts a base64 string
|
||||
func (e *EncryptionService) DecryptString(ciphertext string) (string, error) {
|
||||
data, err := base64.StdEncoding.DecodeString(ciphertext)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
decrypted, err := e.Decrypt(data)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(decrypted), nil
|
||||
}
|
||||
|
||||
// FieldEncryptor provides field-level encryption for sensitive data
|
||||
type FieldEncryptor struct {
|
||||
service *EncryptionService
|
||||
fields map[string]bool
|
||||
}
|
||||
|
||||
// NewFieldEncryptor creates a field encryptor
|
||||
func NewFieldEncryptor(service *EncryptionService, sensitiveFields []string) *FieldEncryptor {
|
||||
fields := make(map[string]bool)
|
||||
for _, f := range sensitiveFields {
|
||||
fields[f] = true
|
||||
}
|
||||
return &FieldEncryptor{
|
||||
service: service,
|
||||
fields: fields,
|
||||
}
|
||||
}
|
||||
|
||||
// IsSensitive checks if a field is sensitive
|
||||
func (fe *FieldEncryptor) IsSensitive(field string) bool {
|
||||
return fe.fields[field]
|
||||
}
|
||||
|
||||
// EncryptField encrypts a field value if sensitive
|
||||
func (fe *FieldEncryptor) EncryptField(field, value string) (string, error) {
|
||||
if !fe.IsSensitive(field) {
|
||||
return value, nil
|
||||
}
|
||||
return fe.service.EncryptString(value)
|
||||
}
|
||||
|
||||
// DecryptField decrypts a field value if sensitive
|
||||
func (fe *FieldEncryptor) DecryptField(field, value string) (string, error) {
|
||||
if !fe.IsSensitive(field) {
|
||||
return value, nil
|
||||
}
|
||||
return fe.service.DecryptString(value)
|
||||
}
|
||||
|
||||
// DefaultSensitiveFields returns commonly sensitive fields
|
||||
func DefaultSensitiveFields() []string {
|
||||
return []string{
|
||||
"ssn", "social_security_number",
|
||||
"credit_card", "card_number", "cvv",
|
||||
"password", "secret", "api_key",
|
||||
"phone", "email", "address",
|
||||
"date_of_birth", "dob",
|
||||
"bank_account", "routing_number",
|
||||
"iccid", "imsi", "msisdn",
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"math"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// FraudDetectionService provides fraud detection capabilities
|
||||
type FraudDetectionService struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
patterns []FraudPattern
|
||||
alerts []*FraudAlert
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewFraudDetectionService creates a new fraud detection service
|
||||
func NewFraudDetectionService(db *gorm.DB, logger *logrus.Logger, cfg FraudConfig) *FraudDetectionService {
|
||||
svc := &FraudDetectionService{
|
||||
db: db,
|
||||
logger: logger,
|
||||
patterns: DefaultFraudPatterns(),
|
||||
alerts: make([]*FraudAlert, 0),
|
||||
}
|
||||
go svc.cleanupAlerts(cfg.AlertRetentionDays)
|
||||
return svc
|
||||
}
|
||||
|
||||
// AnalyzeTransaction analyzes a transaction for fraud
|
||||
func (s *FraudDetectionService) AnalyzeTransaction(ctx context.Context, tx map[string]interface{}) (*FraudAlert, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
alert := &FraudAlert{
|
||||
ID: fmt.Sprintf("fraud-%d", time.Now().UnixNano()),
|
||||
Timestamp: time.Now(),
|
||||
Status: "new",
|
||||
Metadata: make(map[string]any),
|
||||
}
|
||||
|
||||
if id, ok := tx["profile_id"].(string); ok {
|
||||
alert.ProfileID = id
|
||||
}
|
||||
if ip, ok := tx["ip_address"].(string); ok {
|
||||
alert.IPAddress = ip
|
||||
}
|
||||
|
||||
score, evidence := s.evaluatePatterns(ctx, tx)
|
||||
alert.RiskScore = math.Min(100, score)
|
||||
alert.Evidence = evidence
|
||||
alert.Severity = SeverityFromScore(alert.RiskScore)
|
||||
alert.Type = s.detectType(evidence)
|
||||
alert.Description = fmt.Sprintf("%s %s fraud detected", alert.Severity, alert.Type)
|
||||
|
||||
if alert.RiskScore >= 80 {
|
||||
alert.Actions = append(alert.Actions, "auto_blocked")
|
||||
s.blockProfile(ctx, alert.ProfileID)
|
||||
} else if alert.RiskScore >= 60 {
|
||||
alert.Actions = append(alert.Actions, "flagged_for_review")
|
||||
}
|
||||
|
||||
s.alerts = append(s.alerts, alert)
|
||||
s.logger.WithField("alert_id", alert.ID).WithField("risk_score", alert.RiskScore).Warn("Fraud detected")
|
||||
|
||||
return alert, nil
|
||||
}
|
||||
|
||||
// GetFraudAlerts retrieves fraud alerts
|
||||
func (s *FraudDetectionService) GetFraudAlerts(_ context.Context, filter FraudAlertFilter) ([]*FraudAlert, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
var result []*FraudAlert
|
||||
for _, a := range s.alerts {
|
||||
if s.matchesFilter(a, filter) {
|
||||
result = append(result, a)
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// UpdateAlertStatus updates the status of a fraud alert
|
||||
func (s *FraudDetectionService) UpdateAlertStatus(_ context.Context, alertID, status string, actions []string) error {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
for _, a := range s.alerts {
|
||||
if a.ID == alertID {
|
||||
a.Status = status
|
||||
a.Actions = append(a.Actions, actions...)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("alert not found: %s", alertID)
|
||||
}
|
||||
|
||||
// GetFraudMetrics returns fraud detection metrics
|
||||
func (s *FraudDetectionService) GetFraudMetrics(_ context.Context, period string) (*FraudMetrics, error) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
start, end := fraudPeriodDates(period)
|
||||
m := &FraudMetrics{Period: period, GeneratedAt: time.Now(), ByType: make(map[FraudType]int64), BySeverity: make(map[FraudSeverity]int64)}
|
||||
|
||||
for _, a := range s.alerts {
|
||||
if a.Timestamp.After(start) && a.Timestamp.Before(end) {
|
||||
m.TotalAlerts++
|
||||
m.ByType[a.Type]++
|
||||
m.BySeverity[a.Severity]++
|
||||
switch a.Status {
|
||||
case "resolved":
|
||||
m.ResolvedAlerts++
|
||||
case "false_positive":
|
||||
m.FalsePositives++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if m.TotalAlerts > 0 {
|
||||
m.ResolutionRate = float64(m.ResolvedAlerts) / float64(m.TotalAlerts) * 100
|
||||
m.FalsePositiveRate = float64(m.FalsePositives) / float64(m.TotalAlerts) * 100
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) evaluatePatterns(ctx context.Context, tx map[string]interface{}) (float64, []string) {
|
||||
var score float64
|
||||
var evidence []string
|
||||
|
||||
profileID, _ := tx["profile_id"].(string)
|
||||
if profileID == "" {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
for _, p := range s.patterns {
|
||||
if !p.Enabled {
|
||||
continue
|
||||
}
|
||||
ps, ev := s.checkPattern(ctx, profileID, p)
|
||||
if ps > 0 {
|
||||
score += ps * p.Weight
|
||||
evidence = append(evidence, ev...)
|
||||
}
|
||||
}
|
||||
return score, evidence
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) checkPattern(ctx context.Context, profileID string, p FraudPattern) (float64, []string) {
|
||||
var count int64
|
||||
|
||||
switch p.ID {
|
||||
case "multiple_subs":
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").Where("profile_id = ? AND status = ?", profileID, "active").Count(&count)
|
||||
if count > int64(p.Threshold) {
|
||||
return float64(count) * 20, []string{fmt.Sprintf("%d active subscriptions", count)}
|
||||
}
|
||||
case "rapid_sub":
|
||||
s.db.WithContext(ctx).Table("rate_plan_subscriptions").Where("profile_id = ? AND created_at > ?", profileID, time.Now().Add(-time.Hour)).Count(&count)
|
||||
if count > int64(p.Threshold) {
|
||||
return float64(count) * 15, []string{fmt.Sprintf("%d subscriptions in last hour", count)}
|
||||
}
|
||||
case "payment_fail":
|
||||
s.db.WithContext(ctx).Table("billing_transactions").Where("profile_id = ? AND status = ? AND created_at > ?", profileID, "failed", time.Now().Add(-24*time.Hour)).Count(&count)
|
||||
if count > int64(p.Threshold) {
|
||||
return float64(count) * 25, []string{fmt.Sprintf("%d payment failures", count)}
|
||||
}
|
||||
case "sim_swap":
|
||||
s.db.WithContext(ctx).Table("profiles").Where("id = ? AND updated_at > ?", profileID, time.Now().Add(-time.Hour)).Count(&count)
|
||||
if count > 2 {
|
||||
return 80, []string{"possible SIM swap detected"}
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) detectType(evidence []string) FraudType {
|
||||
for _, e := range evidence {
|
||||
if contains(e, "subscription") {
|
||||
return FraudTypeSubscriptionFraud
|
||||
}
|
||||
if contains(e, "payment") {
|
||||
return FraudTypePaymentFraud
|
||||
}
|
||||
if contains(e, "SIM") {
|
||||
return FraudTypeSIMSwap
|
||||
}
|
||||
}
|
||||
return FraudTypeSubscriptionFraud
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) blockProfile(ctx context.Context, profileID string) {
|
||||
s.db.WithContext(ctx).Table("profiles").Where("id = ?", profileID).Updates(map[string]interface{}{"status": "blocked", "blocked_at": time.Now()})
|
||||
s.logger.WithField("profile_id", profileID).Warn("Profile blocked for fraud")
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) matchesFilter(a *FraudAlert, f FraudAlertFilter) bool {
|
||||
if f.Type != "" && a.Type != f.Type {
|
||||
return false
|
||||
}
|
||||
if f.Severity != "" && a.Severity != f.Severity {
|
||||
return false
|
||||
}
|
||||
if f.Status != "" && a.Status != f.Status {
|
||||
return false
|
||||
}
|
||||
if f.FromDate != nil && a.Timestamp.Before(*f.FromDate) {
|
||||
return false
|
||||
}
|
||||
if f.ToDate != nil && a.Timestamp.After(*f.ToDate) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *FraudDetectionService) cleanupAlerts(days int) {
|
||||
ticker := time.NewTicker(24 * time.Hour)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
s.mu.Lock()
|
||||
cutoff := time.Now().AddDate(0, 0, -days)
|
||||
var filtered []*FraudAlert
|
||||
for _, a := range s.alerts {
|
||||
if a.Timestamp.After(cutoff) {
|
||||
filtered = append(filtered, a)
|
||||
}
|
||||
}
|
||||
s.alerts = filtered
|
||||
s.mu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func fraudPeriodDates(period string) (time.Time, time.Time) {
|
||||
now := time.Now()
|
||||
switch period {
|
||||
case "daily":
|
||||
return now.Truncate(24 * time.Hour), now
|
||||
case "weekly":
|
||||
return now.AddDate(0, 0, -7), now
|
||||
case "monthly":
|
||||
return now.AddDate(0, -1, 0), now
|
||||
default:
|
||||
return now.AddDate(0, -1, 0), now
|
||||
}
|
||||
}
|
||||
|
||||
func contains(s, substr string) bool {
|
||||
return len(s) >= len(substr) && (s == substr || len(s) > 0 && containsAt(s, substr))
|
||||
}
|
||||
|
||||
func containsAt(s, substr string) bool {
|
||||
for i := 0; i <= len(s)-len(substr); i++ {
|
||||
if s[i:i+len(substr)] == substr {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package security
|
||||
|
||||
import "time"
|
||||
|
||||
// FraudType represents different types of fraud
|
||||
type FraudType string
|
||||
|
||||
const (
|
||||
FraudTypeAccountTakeover FraudType = "account_takeover"
|
||||
FraudTypeSubscriptionFraud FraudType = "subscription_fraud"
|
||||
FraudTypePaymentFraud FraudType = "payment_fraud"
|
||||
FraudTypeUsageAnomaly FraudType = "usage_anomaly"
|
||||
FraudTypeSIMSwap FraudType = "sim_swap"
|
||||
)
|
||||
|
||||
// FraudSeverity represents the severity of fraud detection
|
||||
type FraudSeverity string
|
||||
|
||||
const (
|
||||
FraudSeverityLow FraudSeverity = "low"
|
||||
FraudSeverityMedium FraudSeverity = "medium"
|
||||
FraudSeverityHigh FraudSeverity = "high"
|
||||
FraudSeverityCritical FraudSeverity = "critical"
|
||||
)
|
||||
|
||||
// FraudAlert represents a fraud detection alert
|
||||
type FraudAlert struct {
|
||||
ID string `json:"id"`
|
||||
Type FraudType `json:"type"`
|
||||
Severity FraudSeverity `json:"severity"`
|
||||
ProfileID string `json:"profile_id"`
|
||||
Description string `json:"description"`
|
||||
RiskScore float64 `json:"risk_score"`
|
||||
Evidence []string `json:"evidence"`
|
||||
IPAddress string `json:"ip_address"`
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Status string `json:"status"`
|
||||
Actions []string `json:"actions_taken"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
}
|
||||
|
||||
// FraudPattern represents a fraud detection pattern
|
||||
type FraudPattern struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type FraudType `json:"type"`
|
||||
Threshold float64 `json:"threshold"`
|
||||
Weight float64 `json:"weight"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// FraudMetrics represents fraud detection metrics
|
||||
type FraudMetrics struct {
|
||||
Period string `json:"period"`
|
||||
TotalAlerts int64 `json:"total_alerts"`
|
||||
ResolvedAlerts int64 `json:"resolved_alerts"`
|
||||
FalsePositives int64 `json:"false_positives"`
|
||||
ResolutionRate float64 `json:"resolution_rate_pct"`
|
||||
FalsePositiveRate float64 `json:"false_positive_rate_pct"`
|
||||
ByType map[FraudType]int64 `json:"by_type"`
|
||||
BySeverity map[FraudSeverity]int64 `json:"by_severity"`
|
||||
GeneratedAt time.Time `json:"generated_at"`
|
||||
}
|
||||
|
||||
// FraudAlertFilter filters fraud alerts
|
||||
type FraudAlertFilter struct {
|
||||
Type FraudType `json:"type,omitempty"`
|
||||
Severity FraudSeverity `json:"severity,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
FromDate *time.Time `json:"from_date,omitempty"`
|
||||
ToDate *time.Time `json:"to_date,omitempty"`
|
||||
}
|
||||
|
||||
// FraudConfig configures the fraud detection service
|
||||
type FraudConfig struct {
|
||||
EnableMLModels bool
|
||||
AlertRetentionDays int
|
||||
AutoBlockThreshold float64
|
||||
}
|
||||
|
||||
// DefaultFraudPatterns returns standard fraud detection patterns
|
||||
func DefaultFraudPatterns() []FraudPattern {
|
||||
return []FraudPattern{
|
||||
{ID: "multiple_subs", Name: "Multiple Subscriptions", Type: FraudTypeSubscriptionFraud, Threshold: 3, Weight: 0.3, Enabled: true},
|
||||
{ID: "rapid_sub", Name: "Rapid Subscription", Type: FraudTypeSubscriptionFraud, Threshold: 5, Weight: 0.4, Enabled: true},
|
||||
{ID: "unusual_loc", Name: "Unusual Location", Type: FraudTypeAccountTakeover, Threshold: 0.8, Weight: 0.5, Enabled: true},
|
||||
{ID: "usage_spike", Name: "Usage Spike", Type: FraudTypeUsageAnomaly, Threshold: 1000, Weight: 0.3, Enabled: true},
|
||||
{ID: "payment_fail", Name: "Payment Failures", Type: FraudTypePaymentFraud, Threshold: 3, Weight: 0.6, Enabled: true},
|
||||
{ID: "sim_swap", Name: "SIM Swap", Type: FraudTypeSIMSwap, Threshold: 0.7, Weight: 0.8, Enabled: true},
|
||||
}
|
||||
}
|
||||
|
||||
// SeverityFromScore determines severity from risk score
|
||||
func SeverityFromScore(score float64) FraudSeverity {
|
||||
switch {
|
||||
case score >= 80:
|
||||
return FraudSeverityCritical
|
||||
case score >= 60:
|
||||
return FraudSeverityHigh
|
||||
case score >= 40:
|
||||
return FraudSeverityMedium
|
||||
default:
|
||||
return FraudSeverityLow
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package security
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// ThreatLevel represents severity of detected threats
|
||||
type ThreatLevel string
|
||||
|
||||
const (
|
||||
ThreatLevelLow ThreatLevel = "low"
|
||||
ThreatLevelMedium ThreatLevel = "medium"
|
||||
ThreatLevelHigh ThreatLevel = "high"
|
||||
ThreatLevelCritical ThreatLevel = "critical"
|
||||
)
|
||||
|
||||
// ThreatType represents types of security threats
|
||||
type ThreatType string
|
||||
|
||||
const (
|
||||
ThreatTypeBruteForce ThreatType = "brute_force"
|
||||
ThreatTypeRateLimitAbuse ThreatType = "rate_limit_abuse"
|
||||
ThreatTypeSQLInjection ThreatType = "sql_injection"
|
||||
ThreatTypeXSS ThreatType = "xss"
|
||||
ThreatTypeUnauthorized ThreatType = "unauthorized_access"
|
||||
ThreatTypeDataExfil ThreatType = "data_exfiltration"
|
||||
ThreatTypeAnomalous ThreatType = "anomalous_behavior"
|
||||
)
|
||||
|
||||
// ThreatEvent represents a detected security threat
|
||||
type ThreatEvent struct {
|
||||
ID string `json:"id"`
|
||||
TenantID string `json:"tenant_id"`
|
||||
Type ThreatType `json:"type"`
|
||||
Level ThreatLevel `json:"level"`
|
||||
Source string `json:"source"`
|
||||
Target string `json:"target"`
|
||||
Description string `json:"description"`
|
||||
Metadata map[string]any `json:"metadata"`
|
||||
DetectedAt time.Time `json:"detected_at"`
|
||||
Mitigated bool `json:"mitigated"`
|
||||
MitigatedAt *time.Time `json:"mitigated_at"`
|
||||
}
|
||||
|
||||
// ThreatDetector provides threat detection capabilities
|
||||
type ThreatDetector struct {
|
||||
logger *logrus.Logger
|
||||
rules []DetectionRule
|
||||
events []*ThreatEvent
|
||||
ipTracker map[string]*IPActivity
|
||||
mu sync.RWMutex
|
||||
alertHandler func(*ThreatEvent)
|
||||
}
|
||||
|
||||
// IPActivity tracks activity per IP
|
||||
type IPActivity struct {
|
||||
IP string
|
||||
FailedLogins int
|
||||
RequestCount int
|
||||
LastRequest time.Time
|
||||
FirstSeen time.Time
|
||||
SuspiciousCount int
|
||||
}
|
||||
|
||||
// DetectionRule defines a threat detection rule
|
||||
type DetectionRule struct {
|
||||
ID string
|
||||
Name string
|
||||
Type ThreatType
|
||||
Threshold int
|
||||
Window time.Duration
|
||||
Level ThreatLevel
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// ThreatDetectorConfig configures the threat detector
|
||||
type ThreatDetectorConfig struct {
|
||||
MaxFailedLogins int
|
||||
RateLimitThreshold int
|
||||
AlertHandler func(*ThreatEvent)
|
||||
}
|
||||
|
||||
// DefaultThreatDetectorConfig returns default configuration
|
||||
func DefaultThreatDetectorConfig() ThreatDetectorConfig {
|
||||
return ThreatDetectorConfig{
|
||||
MaxFailedLogins: 5,
|
||||
RateLimitThreshold: 1000,
|
||||
}
|
||||
}
|
||||
|
||||
// NewThreatDetector creates a new threat detector
|
||||
func NewThreatDetector(logger *logrus.Logger, config ThreatDetectorConfig) *ThreatDetector {
|
||||
td := &ThreatDetector{
|
||||
logger: logger,
|
||||
ipTracker: make(map[string]*IPActivity),
|
||||
alertHandler: config.AlertHandler,
|
||||
rules: defaultRules(config),
|
||||
}
|
||||
go td.cleanupLoop()
|
||||
return td
|
||||
}
|
||||
|
||||
func defaultRules(config ThreatDetectorConfig) []DetectionRule {
|
||||
return []DetectionRule{
|
||||
{
|
||||
ID: "brute_force_login",
|
||||
Name: "Brute Force Login Detection",
|
||||
Type: ThreatTypeBruteForce,
|
||||
Threshold: config.MaxFailedLogins,
|
||||
Window: 5 * time.Minute,
|
||||
Level: ThreatLevelHigh,
|
||||
Enabled: true,
|
||||
},
|
||||
{
|
||||
ID: "rate_limit_abuse",
|
||||
Name: "Rate Limit Abuse Detection",
|
||||
Type: ThreatTypeRateLimitAbuse,
|
||||
Threshold: config.RateLimitThreshold,
|
||||
Window: time.Minute,
|
||||
Level: ThreatLevelMedium,
|
||||
Enabled: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// RecordRequest records an API request for analysis
|
||||
func (td *ThreatDetector) RecordRequest(ctx context.Context, ip, path, method string) {
|
||||
td.mu.Lock()
|
||||
defer td.mu.Unlock()
|
||||
|
||||
activity, exists := td.ipTracker[ip]
|
||||
if !exists {
|
||||
activity = &IPActivity{
|
||||
IP: ip,
|
||||
FirstSeen: time.Now(),
|
||||
}
|
||||
td.ipTracker[ip] = activity
|
||||
}
|
||||
|
||||
activity.RequestCount++
|
||||
activity.LastRequest = time.Now()
|
||||
|
||||
// Check rate limit rule
|
||||
for _, rule := range td.rules {
|
||||
if rule.Type == ThreatTypeRateLimitAbuse && rule.Enabled {
|
||||
if activity.RequestCount > rule.Threshold {
|
||||
td.raiseAlert(&ThreatEvent{
|
||||
Type: ThreatTypeRateLimitAbuse,
|
||||
Level: rule.Level,
|
||||
Source: ip,
|
||||
Target: path,
|
||||
Description: "Rate limit threshold exceeded",
|
||||
DetectedAt: time.Now(),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RecordFailedLogin records a failed login attempt
|
||||
func (td *ThreatDetector) RecordFailedLogin(ctx context.Context, ip, userID string) {
|
||||
td.mu.Lock()
|
||||
defer td.mu.Unlock()
|
||||
|
||||
activity, exists := td.ipTracker[ip]
|
||||
if !exists {
|
||||
activity = &IPActivity{
|
||||
IP: ip,
|
||||
FirstSeen: time.Now(),
|
||||
}
|
||||
td.ipTracker[ip] = activity
|
||||
}
|
||||
|
||||
activity.FailedLogins++
|
||||
activity.LastRequest = time.Now()
|
||||
|
||||
// Check brute force rule
|
||||
for _, rule := range td.rules {
|
||||
if rule.Type == ThreatTypeBruteForce && rule.Enabled {
|
||||
if activity.FailedLogins >= rule.Threshold {
|
||||
td.raiseAlert(&ThreatEvent{
|
||||
Type: ThreatTypeBruteForce,
|
||||
Level: rule.Level,
|
||||
Source: ip,
|
||||
Target: userID,
|
||||
Description: "Multiple failed login attempts detected",
|
||||
DetectedAt: time.Now(),
|
||||
Metadata: map[string]any{"attempts": activity.FailedLogins},
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// DetectSQLInjection checks for SQL injection patterns
|
||||
func (td *ThreatDetector) DetectSQLInjection(_ context.Context, ip, input string) bool {
|
||||
patterns := []string{
|
||||
"'--", "'; DROP", "1=1", "OR 1=1", "UNION SELECT",
|
||||
"'; DELETE", "'; UPDATE", "'; INSERT",
|
||||
}
|
||||
|
||||
for _, pattern := range patterns {
|
||||
if containsIgnoreCase(input, pattern) {
|
||||
td.raiseAlert(&ThreatEvent{
|
||||
Type: ThreatTypeSQLInjection,
|
||||
Level: ThreatLevelCritical,
|
||||
Source: ip,
|
||||
Description: "SQL injection attempt detected",
|
||||
DetectedAt: time.Now(),
|
||||
Metadata: map[string]any{"pattern": pattern},
|
||||
})
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func containsIgnoreCase(s, substr string) bool {
|
||||
return len(s) >= len(substr) // Simplified check
|
||||
}
|
||||
|
||||
func (td *ThreatDetector) raiseAlert(event *ThreatEvent) {
|
||||
td.events = append(td.events, event)
|
||||
|
||||
td.logger.WithFields(logrus.Fields{
|
||||
"type": event.Type,
|
||||
"level": event.Level,
|
||||
"source": event.Source,
|
||||
}).Warn("Security threat detected")
|
||||
|
||||
if td.alertHandler != nil {
|
||||
td.alertHandler(event)
|
||||
}
|
||||
}
|
||||
|
||||
// GetRecentEvents returns recent threat events
|
||||
func (td *ThreatDetector) GetRecentEvents(limit int) []*ThreatEvent {
|
||||
td.mu.RLock()
|
||||
defer td.mu.RUnlock()
|
||||
|
||||
if len(td.events) <= limit {
|
||||
return td.events
|
||||
}
|
||||
return td.events[len(td.events)-limit:]
|
||||
}
|
||||
|
||||
// GetIPActivity returns activity for an IP
|
||||
func (td *ThreatDetector) GetIPActivity(ip string) *IPActivity {
|
||||
td.mu.RLock()
|
||||
defer td.mu.RUnlock()
|
||||
return td.ipTracker[ip]
|
||||
}
|
||||
|
||||
// BlockIP marks an IP as blocked
|
||||
func (td *ThreatDetector) BlockIP(ip string) {
|
||||
td.mu.Lock()
|
||||
defer td.mu.Unlock()
|
||||
|
||||
if activity, exists := td.ipTracker[ip]; exists {
|
||||
activity.SuspiciousCount = 999
|
||||
}
|
||||
}
|
||||
|
||||
// IsBlocked checks if an IP is blocked
|
||||
func (td *ThreatDetector) IsBlocked(ip string) bool {
|
||||
td.mu.RLock()
|
||||
defer td.mu.RUnlock()
|
||||
|
||||
if activity, exists := td.ipTracker[ip]; exists {
|
||||
return activity.SuspiciousCount >= 999
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (td *ThreatDetector) cleanupLoop() {
|
||||
ticker := time.NewTicker(10 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
|
||||
for range ticker.C {
|
||||
td.cleanup()
|
||||
}
|
||||
}
|
||||
|
||||
func (td *ThreatDetector) cleanup() {
|
||||
td.mu.Lock()
|
||||
defer td.mu.Unlock()
|
||||
|
||||
cutoff := time.Now().Add(-time.Hour)
|
||||
for ip, activity := range td.ipTracker {
|
||||
if activity.LastRequest.Before(cutoff) && activity.SuspiciousCount < 999 {
|
||||
delete(td.ipTracker, ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/mvno"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// OnboardingService handles MVNO onboarding process
|
||||
type OnboardingService struct {
|
||||
logger *logrus.Logger
|
||||
validator *mvno.OnboardingValidator
|
||||
provisioner *mvno.ProductionProvisioner
|
||||
monitor *mvno.OnboardingMonitor
|
||||
}
|
||||
|
||||
// NewOnboardingService creates a new onboarding service
|
||||
func NewOnboardingService(logger *logrus.Logger) *OnboardingService {
|
||||
return &OnboardingService{
|
||||
logger: logger,
|
||||
validator: mvno.NewOnboardingValidator(logger),
|
||||
monitor: mvno.NewOnboardingMonitor(logger),
|
||||
// Note: ProductionProvisioner will be initialized with real services in main.go
|
||||
}
|
||||
}
|
||||
|
||||
// StartOnboarding initiates the MVNO onboarding process
|
||||
func (s *OnboardingService) StartOnboarding(ctx context.Context, req *mvno.OnboardingRequest) (*mvno.MVNO, error) {
|
||||
// Validate the onboarding request
|
||||
if err := s.validator.ValidateRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Create MVNO record
|
||||
mvnoRecord := &mvno.MVNO{
|
||||
ID: id.GeneratePrefixed("mvno"),
|
||||
BusinessID: req.BusinessID,
|
||||
Name: req.BusinessName,
|
||||
Status: mvno.StatusPending,
|
||||
Plan: req.Plan,
|
||||
Config: mvno.MVNOConfig{
|
||||
MaxSubscribers: s.getMaxSubscribersForPlan(req.Plan),
|
||||
AllowedCountries: req.TargetCountries,
|
||||
CustomBranding: req.Plan != mvno.PlanStarter,
|
||||
APIAccess: req.Plan != mvno.PlanStarter,
|
||||
AdvancedAnalytics: req.Plan == mvno.PlanScale || req.Plan == mvno.PlanEnterprise,
|
||||
},
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Start onboarding progress tracking
|
||||
progress := &mvno.OnboardingProgress{
|
||||
MVNOID: mvnoRecord.ID,
|
||||
Steps: s.getOnboardingSteps(),
|
||||
Progress: 0.0,
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"mvno_id": mvnoRecord.ID,
|
||||
"business_id": req.BusinessID,
|
||||
"plan": req.Plan,
|
||||
}).Info("Starting MVNO onboarding")
|
||||
|
||||
// Execute onboarding steps asynchronously
|
||||
go s.executeOnboarding(ctx, mvnoRecord, progress)
|
||||
|
||||
return mvnoRecord, nil
|
||||
}
|
||||
|
||||
// executeOnboarding runs all onboarding steps
|
||||
func (s *OnboardingService) executeOnboarding(ctx context.Context, mvno *mvno.MVNO, progress *mvno.OnboardingProgress) {
|
||||
for i, step := range progress.Steps {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
s.logger.WithField("mvno_id", mvno.ID).Error("Onboarding cancelled")
|
||||
return
|
||||
default:
|
||||
}
|
||||
|
||||
step.Status = "running"
|
||||
s.monitor.UpdateProgress(mvno.ID, progress)
|
||||
|
||||
if err := s.executeStep(ctx, mvno, &step); err != nil {
|
||||
step.Status = "failed"
|
||||
step.Error = err.Error()
|
||||
s.logger.WithError(err).WithField("step", step.Name).Error("Step failed")
|
||||
break
|
||||
}
|
||||
|
||||
step.Status = "completed"
|
||||
step.CompletedAt = time.Now()
|
||||
progress.Progress = float64(i+1) / float64(len(progress.Steps)) * 100
|
||||
|
||||
s.monitor.UpdateProgress(mvno.ID, progress)
|
||||
}
|
||||
|
||||
if progress.Progress == 100.0 {
|
||||
mvno.Status = "active"
|
||||
progress.CompletedAt = time.Now()
|
||||
s.logger.WithField("mvno_id", mvno.ID).Info("Onboarding completed")
|
||||
}
|
||||
}
|
||||
|
||||
// executeStep executes a single onboarding step
|
||||
func (s *OnboardingService) executeStep(ctx context.Context, mvno *mvno.MVNO, step *mvno.OnboardingStep) error {
|
||||
switch step.Name {
|
||||
case "validation":
|
||||
return s.validator.ValidateMVNO(ctx, mvno)
|
||||
case "provisioning":
|
||||
return s.provisioner.ProvisionResources(ctx, mvno)
|
||||
case "carrier_setup":
|
||||
return s.provisioner.SetupCarriers(ctx, mvno)
|
||||
case "billing_setup":
|
||||
return s.provisioner.SetupBilling(ctx, mvno)
|
||||
case "api_access":
|
||||
return s.provisioner.SetupAPIAccess(ctx, mvno)
|
||||
default:
|
||||
return fmt.Errorf("unknown step: %s", step.Name)
|
||||
}
|
||||
}
|
||||
|
||||
// getOnboardingSteps returns the standard onboarding workflow
|
||||
func (s *OnboardingService) getOnboardingSteps() []mvno.OnboardingStep {
|
||||
return []mvno.OnboardingStep{
|
||||
{Name: "validation", Status: "pending"},
|
||||
{Name: "provisioning", Status: "pending"},
|
||||
{Name: "carrier_setup", Status: "pending"},
|
||||
{Name: "billing_setup", Status: "pending"},
|
||||
{Name: "api_access", Status: "pending"},
|
||||
}
|
||||
}
|
||||
|
||||
// getMaxSubscribersForPlan returns subscriber limits per plan
|
||||
func (s *OnboardingService) getMaxSubscribersForPlan(plan mvno.MVNOPlan) int {
|
||||
switch plan {
|
||||
case mvno.PlanStarter:
|
||||
return 1000
|
||||
case mvno.PlanGrowth:
|
||||
return 10000
|
||||
case mvno.PlanScale:
|
||||
return 100000
|
||||
case mvno.PlanEnterprise:
|
||||
return -1 // Unlimited
|
||||
default:
|
||||
return 1000
|
||||
}
|
||||
}
|
||||
@@ -172,8 +172,8 @@ func (pi *PricingIntegration) GetPricingEffectiveness(ctx context.Context, tenan
|
||||
ActiveRules: analytics.ActiveRules,
|
||||
TotalRatePlans: ratePlanAnalytics.TotalRatePlans,
|
||||
PlansWithPricing: ratePlanAnalytics.PlansWithPricing,
|
||||
AverageDiscountRate: analytics.DiscountStats.AverageDiscount,
|
||||
TotalSavings: analytics.DiscountStats.TotalDiscountValue,
|
||||
AverageDiscountRate: ratePlanAnalytics.AverageDiscount,
|
||||
TotalSavings: ratePlanAnalytics.TotalSavings,
|
||||
RulesByType: analytics.RulesByType,
|
||||
ConversionImprovement: ratePlanAnalytics.ConversionRate,
|
||||
GeneratedAt: id.GetCurrentTime(),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
)
|
||||
|
||||
// RatePlanAdapter adapts services.Service to implement rateplan.Service interface
|
||||
type RatePlanAdapter struct {
|
||||
service *Service
|
||||
}
|
||||
|
||||
// NewRatePlanAdapter creates a new rate plan adapter
|
||||
func NewRatePlanAdapter(service *Service) rateplan.Service {
|
||||
return &RatePlanAdapter{service: service}
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) CreateRatePlan(ctx context.Context, plan *rateplan.RatePlan) (*rateplan.RatePlan, error) {
|
||||
result, err := a.service.CreateRatePlan(ctx, toRepoPlan(plan))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlan(result), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetRatePlan(ctx context.Context, id string) (*rateplan.RatePlan, error) {
|
||||
plan, err := a.service.GetRatePlan(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlan(plan), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) UpdateRatePlan(ctx context.Context, plan *rateplan.RatePlan) (*rateplan.RatePlan, error) {
|
||||
result, err := a.service.UpdateRatePlan(ctx, toRepoPlan(plan))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlan(result), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) DeleteRatePlan(ctx context.Context, id string) error {
|
||||
return a.service.DeleteRatePlan(ctx, id)
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) ListRatePlans(ctx context.Context, filter *rateplan.RatePlanFilter) ([]*rateplan.RatePlan, error) {
|
||||
repoFilter := &repository.RatePlanFilter{
|
||||
CarrierID: filter.CarrierID,
|
||||
Region: filter.Region,
|
||||
PlanType: repository.PlanType(filter.PlanType),
|
||||
IsActive: filter.IsActive,
|
||||
MinPrice: filter.MinPrice,
|
||||
MaxPrice: filter.MaxPrice,
|
||||
Limit: filter.Limit,
|
||||
Offset: filter.Offset,
|
||||
}
|
||||
plans, err := a.service.ListRatePlans(ctx, repoFilter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSlice(plans), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) SearchRatePlans(ctx context.Context, criteria rateplan.SearchCriteria) ([]*rateplan.RatePlan, error) {
|
||||
filter := &rateplan.RatePlanFilter{
|
||||
CarrierID: criteria.CarrierID,
|
||||
Region: criteria.Region,
|
||||
PlanType: criteria.PlanType,
|
||||
}
|
||||
return a.ListRatePlans(ctx, filter)
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetPopularPlans(ctx context.Context, limit int) ([]*rateplan.RatePlan, error) {
|
||||
plans, err := a.service.GetPopularPlans(ctx, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSlice(plans), nil
|
||||
}
|
||||
|
||||
// Conversion helpers
|
||||
|
||||
func toRepoPlan(p *rateplan.RatePlan) *repository.RatePlan {
|
||||
return &repository.RatePlan{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Description: p.Description,
|
||||
CarrierID: p.CarrierID,
|
||||
Region: p.Region,
|
||||
PlanType: repository.PlanType(p.PlanType),
|
||||
BasePrice: p.BasePrice,
|
||||
BillingCycle: repository.BillingCycle(p.BillingCycle),
|
||||
ValidFrom: p.ValidFrom,
|
||||
ValidTo: p.ValidTo,
|
||||
IsActive: p.IsActive,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UpdatedAt: p.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func toRatePlan(p *repository.RatePlan) *rateplan.RatePlan {
|
||||
return &rateplan.RatePlan{
|
||||
ID: p.ID,
|
||||
Name: p.Name,
|
||||
Description: p.Description,
|
||||
CarrierID: p.CarrierID,
|
||||
Region: p.Region,
|
||||
PlanType: rateplan.PlanType(p.PlanType),
|
||||
BasePrice: p.BasePrice,
|
||||
BillingCycle: rateplan.BillingCycle(p.BillingCycle),
|
||||
ValidFrom: p.ValidFrom,
|
||||
ValidTo: p.ValidTo,
|
||||
IsActive: p.IsActive,
|
||||
CreatedAt: p.CreatedAt,
|
||||
UpdatedAt: p.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func toRatePlanSlice(plans []*repository.RatePlan) []*rateplan.RatePlan {
|
||||
result := make([]*rateplan.RatePlan, len(plans))
|
||||
for i, p := range plans {
|
||||
result[i] = toRatePlan(p)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func toRatePlanSub(s *repository.RatePlanSubscription) *rateplan.RatePlanSubscription {
|
||||
return &rateplan.RatePlanSubscription{
|
||||
ID: s.ID,
|
||||
ProfileID: s.ProfileID,
|
||||
RatePlanID: s.RatePlanID,
|
||||
Status: rateplan.SubscriptionStatus(s.Status),
|
||||
CreatedAt: s.CreatedAt,
|
||||
UpdatedAt: s.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func convertRepoUsage(u *repository.RatePlanUsage) *rateplan.RatePlanUsage {
|
||||
return &rateplan.RatePlanUsage{
|
||||
ID: u.ID,
|
||||
RatePlanID: u.RatePlanID,
|
||||
ProfileID: u.ProfileID,
|
||||
CycleStart: u.CycleStart,
|
||||
CycleEnd: u.CycleEnd,
|
||||
DataUsed: u.DataUsed,
|
||||
VoiceUsed: u.VoiceUsed,
|
||||
SMSUsed: u.SMSUsed,
|
||||
LastUpdated: u.LastUpdated,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
)
|
||||
|
||||
func (a *RatePlanAdapter) SubscribeToPlan(ctx context.Context, req *rateplan.SubscribeRequest) (*rateplan.RatePlanSubscription, error) {
|
||||
repoReq := &repository.SubscribeRequest{
|
||||
ProfileID: req.ProfileID,
|
||||
RatePlanID: req.RatePlanID,
|
||||
}
|
||||
subscription, err := a.service.SubscribeToPlan(ctx, repoReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSub(subscription), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetSubscription(ctx context.Context, id string) (*rateplan.RatePlanSubscription, error) {
|
||||
subscription, err := a.service.GetSubscription(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSub(subscription), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) UpdateSubscription(ctx context.Context, subscription *rateplan.RatePlanSubscription) (*rateplan.RatePlanSubscription, error) {
|
||||
repoSub := &repository.RatePlanSubscription{
|
||||
ID: subscription.ID,
|
||||
ProfileID: subscription.ProfileID,
|
||||
RatePlanID: subscription.RatePlanID,
|
||||
Status: repository.SubscriptionStatus(subscription.Status),
|
||||
CreatedAt: subscription.CreatedAt,
|
||||
UpdatedAt: subscription.UpdatedAt,
|
||||
}
|
||||
result, err := a.service.UpdateSubscription(ctx, repoSub)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSub(result), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) CancelSubscription(ctx context.Context, subscriptionID string, reason string) error {
|
||||
return a.service.CancelSubscription(ctx, subscriptionID, reason)
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetActiveSubscription(ctx context.Context, profileID string) (*rateplan.RatePlanSubscription, error) {
|
||||
subscription, err := a.service.GetActiveSubscription(ctx, profileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return toRatePlanSub(subscription), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) ListSubscriptions(ctx context.Context, profileID string, filter *rateplan.SubscriptionFilter) ([]*rateplan.RatePlanSubscription, error) {
|
||||
repoFilter := &repository.SubscriptionFilter{
|
||||
Status: repository.SubscriptionStatus(filter.Status),
|
||||
Limit: filter.Limit,
|
||||
Offset: filter.Offset,
|
||||
}
|
||||
subscriptions, err := a.service.ListSubscriptions(ctx, profileID, repoFilter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*rateplan.RatePlanSubscription, len(subscriptions))
|
||||
for i, sub := range subscriptions {
|
||||
result[i] = toRatePlanSub(sub)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) RecordUsage(ctx context.Context, req *rateplan.RecordUsageRequest) (*rateplan.RatePlanUsage, error) {
|
||||
repoReq := &repository.RecordUsageRequest{
|
||||
ProfileID: req.ProfileID,
|
||||
DataUsed: req.DataUsed,
|
||||
VoiceUsed: req.VoiceUsed,
|
||||
SMSUsed: req.SMSUsed,
|
||||
}
|
||||
usage, err := a.service.RecordUsage(ctx, repoReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return convertRepoUsage(usage), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetUsage(ctx context.Context, profileID string) (*rateplan.RatePlanUsage, error) {
|
||||
usage, err := a.service.GetUsage(ctx, profileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return convertRepoUsage(usage), nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetUsageHistory(ctx context.Context, profileID string, limit int) ([]*rateplan.RatePlanUsage, error) {
|
||||
usageHistory, err := a.service.GetUsageHistory(ctx, profileID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result := make([]*rateplan.RatePlanUsage, len(usageHistory))
|
||||
for i, u := range usageHistory {
|
||||
result[i] = convertRepoUsage(u)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) CalculateCost(ctx context.Context, req *rateplan.CalculateCostRequest) (*rateplan.RatePlanCostCalculation, error) {
|
||||
repoReq := &repository.CalculateCostRequest{
|
||||
RatePlanID: req.RatePlanID,
|
||||
DataUsed: req.DataUsed,
|
||||
VoiceUsed: req.VoiceUsed,
|
||||
SMSUsed: req.SMSUsed,
|
||||
AppliedDiscounts: req.AppliedDiscounts,
|
||||
}
|
||||
calc, err := a.service.CalculateCost(ctx, repoReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rateplan.RatePlanCostCalculation{
|
||||
RatePlanID: calc.RatePlanID,
|
||||
BaseCost: calc.BaseCost,
|
||||
OverageCost: calc.OverageCost,
|
||||
DiscountCost: calc.DiscountCost,
|
||||
TotalCost: calc.TotalCost,
|
||||
Currency: calc.Currency,
|
||||
Breakdown: calc.Breakdown,
|
||||
CalculatedAt: calc.CalculatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetUsageAnalytics(ctx context.Context, filter *rateplan.UsageAnalyticsFilter) (*rateplan.UsageAnalytics, error) {
|
||||
repoFilter := &repository.UsageAnalyticsFilter{
|
||||
RatePlanID: filter.RatePlanID,
|
||||
CarrierID: filter.CarrierID,
|
||||
Region: filter.Region,
|
||||
StartDate: filter.StartDate,
|
||||
EndDate: filter.EndDate,
|
||||
GroupBy: filter.GroupBy,
|
||||
}
|
||||
analytics, err := a.service.GetUsageAnalytics(ctx, repoFilter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rateplan.UsageAnalytics{
|
||||
TotalDataUsed: analytics.TotalDataUsed,
|
||||
TotalVoiceUsed: analytics.TotalVoiceUsed,
|
||||
TotalSMSUsed: analytics.TotalSMSUsed,
|
||||
ActiveUsers: analytics.ActiveUsers,
|
||||
AverageUsage: analytics.AverageUsage,
|
||||
UsageByPlan: analytics.UsageByPlan,
|
||||
UsageByRegion: analytics.UsageByRegion,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a *RatePlanAdapter) GetRevenueAnalytics(ctx context.Context, filter *rateplan.RevenueAnalyticsFilter) (*rateplan.RevenueAnalytics, error) {
|
||||
repoFilter := &repository.RevenueAnalyticsFilter{
|
||||
RatePlanID: filter.RatePlanID,
|
||||
CarrierID: filter.CarrierID,
|
||||
Region: filter.Region,
|
||||
StartDate: filter.StartDate,
|
||||
EndDate: filter.EndDate,
|
||||
GroupBy: filter.GroupBy,
|
||||
}
|
||||
analytics, err := a.service.GetRevenueAnalytics(ctx, repoFilter)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &rateplan.RevenueAnalytics{
|
||||
TotalRevenue: analytics.TotalRevenue,
|
||||
RevenueByPlan: analytics.RevenueByPlan,
|
||||
RevenueByCarrier: analytics.RevenueByCarrier,
|
||||
RevenueByRegion: analytics.RevenueByRegion,
|
||||
AverageRevenue: analytics.AverageRevenue,
|
||||
}, nil
|
||||
}
|
||||
@@ -13,15 +13,16 @@ import (
|
||||
|
||||
type RatePlanCurrencyIntegrator struct {
|
||||
billingService currency.BillingService
|
||||
exchangeService *currency.ExchangeRateService
|
||||
exchangeService currency.ExchangeRateService
|
||||
ratePlanService rateplan.Service
|
||||
logger *logrus.Logger
|
||||
baseCurrency string
|
||||
}
|
||||
|
||||
// NewRatePlanCurrencyIntegrator creates a new rate plan currency integrator
|
||||
func NewRatePlanCurrencyIntegrator(
|
||||
billingService currency.BillingService,
|
||||
exchangeService *currency.ExchangeRateService,
|
||||
exchangeService currency.ExchangeRateService,
|
||||
ratePlanService rateplan.Service,
|
||||
logger *logrus.Logger,
|
||||
baseCurrency string,
|
||||
@@ -35,22 +36,24 @@ func NewRatePlanCurrencyIntegrator(
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeToPlanWithCurrency subscribes to a rate plan with currency conversion
|
||||
func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.Context, profileID string, planID string, targetCurrency string) (*rateplan.RatePlanSubscription, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Convert price to requested currency if needed
|
||||
subscriptionPrice := plan.BasePrice
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversionReq := ¤cy.CurrencyConversionRequest{
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, ¤cy.CurrencyConversionRequest{
|
||||
Amount: plan.BasePrice,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
}
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, conversionReq)
|
||||
})
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).Error("Failed to convert rate plan price")
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
@@ -59,19 +62,18 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
metadata := map[string]any{
|
||||
"original_currency": plan.Currency,
|
||||
"subscription_currency": targetCurrency,
|
||||
"original_price": plan.BasePrice,
|
||||
"subscription_price": subscriptionPrice,
|
||||
"exchange_rate": exchangeRate,
|
||||
}
|
||||
|
||||
// Create subscription request with currency information
|
||||
subscribeReq := &rateplan.SubscribeRequest{
|
||||
ProfileID: profileID,
|
||||
RatePlanID: planID,
|
||||
AutoRenew: true,
|
||||
Metadata: metadata,
|
||||
Metadata: map[string]any{
|
||||
"original_currency": plan.Currency,
|
||||
"subscription_currency": targetCurrency,
|
||||
"original_price": plan.BasePrice,
|
||||
"subscription_price": subscriptionPrice,
|
||||
"exchange_rate": exchangeRate,
|
||||
},
|
||||
}
|
||||
|
||||
createdSubscription, err := rpci.ratePlanService.SubscribeToPlan(ctx, subscribeReq)
|
||||
@@ -79,6 +81,7 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
return nil, fmt.Errorf("failed to create subscription: %w", err)
|
||||
}
|
||||
|
||||
// Process initial billing
|
||||
billingReq := ¤cy.BillingRequest{
|
||||
ProfileID: profileID,
|
||||
SubscriptionID: createdSubscription.ID,
|
||||
@@ -104,14 +107,18 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
return createdSubscription, nil
|
||||
}
|
||||
|
||||
// CalculatePlanCostInCurrency calculates the cost of a rate plan in a specific currency
|
||||
func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.Context, planID string, targetCurrency string, usageData *rateplan.RatePlanUsage) (*currency.BillingSummary, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Calculate base cost
|
||||
baseCost := plan.BasePrice
|
||||
|
||||
// Add overage costs if usage data is provided
|
||||
if usageData != nil {
|
||||
overageCost, err := rpci.calculateOverageCost(ctx, plan, usageData)
|
||||
if err != nil {
|
||||
@@ -121,16 +128,12 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to requested currency
|
||||
convertedCost := baseCost
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversionReq := ¤cy.CurrencyConversionRequest{
|
||||
Amount: baseCost,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
}
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, conversionReq)
|
||||
conversion, err := rpci.exchangeService.ConvertAmount(ctx, baseCost, plan.Currency, targetCurrency)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
}
|
||||
@@ -138,6 +141,7 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
// Create billing summary
|
||||
summary := ¤cy.BillingSummary{
|
||||
ProfileID: usageData.ProfileID,
|
||||
TotalAmount: convertedCost,
|
||||
@@ -160,13 +164,11 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
|
||||
// Check for context cancellation before calculation
|
||||
if err := ctx.Err(); err != nil {
|
||||
return 0.0, fmt.Errorf("overage calculation cancelled: %w", err)
|
||||
}
|
||||
// calculateOverageCost calculates overage costs for usage
|
||||
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(_ context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
|
||||
overageCost := 0.0
|
||||
|
||||
// Calculate data overage
|
||||
if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount {
|
||||
dataOverage := usage.DataUsed - plan.DataAllowance.Amount
|
||||
if plan.OverageRates != nil {
|
||||
@@ -174,6 +176,7 @@ func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate voice overage
|
||||
if plan.VoiceAllowance != nil && usage.VoiceUsed > plan.VoiceAllowance.Minutes {
|
||||
voiceOverage := usage.VoiceUsed - plan.VoiceAllowance.Minutes
|
||||
if plan.OverageRates != nil {
|
||||
@@ -181,6 +184,7 @@ func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate SMS overage
|
||||
if plan.SMSAllowance != nil && usage.SMSUsed > plan.SMSAllowance.Messages {
|
||||
smsOverage := usage.SMSUsed - plan.SMSAllowance.Messages
|
||||
if plan.OverageRates != nil {
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/handlers"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/smdp"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
@@ -13,27 +12,17 @@ import (
|
||||
// SelectionService provides high-level carrier selection operations
|
||||
type SelectionService struct {
|
||||
manager *smdp.SMDPManager
|
||||
handler *handlers.SelectionHandler
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewSelectionService creates a new selection service
|
||||
func NewSelectionService(manager *smdp.SMDPManager) *SelectionService {
|
||||
logger := logrus.New()
|
||||
logger.SetLevel(logrus.InfoLevel)
|
||||
|
||||
func NewSelectionService(manager *smdp.SMDPManager, logger *logrus.Logger) *SelectionService {
|
||||
return &SelectionService{
|
||||
manager: manager,
|
||||
handler: handlers.NewSelectionHandler(manager),
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// GetHandler returns the selection handler for API registration
|
||||
func (s *SelectionService) GetHandler() *handlers.SelectionHandler {
|
||||
return s.handler
|
||||
}
|
||||
|
||||
// IntelligentCarrierSelection performs intelligent carrier selection with comprehensive criteria
|
||||
func (s *SelectionService) IntelligentCarrierSelection(ctx context.Context, request *IntelligentSelectionRequest) (*IntelligentSelectionResponse, error) {
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
|
||||
@@ -154,18 +154,3 @@ func (m *SMDPManager) updateCarrierMetrics(carrierID string, success bool, respo
|
||||
|
||||
carrier.Metrics.RequestRate = float64(carrier.Metrics.TotalRequests) / time.Since(time.Now().Add(-time.Minute)).Seconds()
|
||||
}
|
||||
|
||||
func (m *SMDPManager) getHighestPriorityCarrier(carriers []*Carrier) *Carrier {
|
||||
if len(carriers) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
highestPriority := carriers[0]
|
||||
for _, carrier := range carriers {
|
||||
if carrier.Priority > highestPriority.Priority {
|
||||
highestPriority = carrier
|
||||
}
|
||||
}
|
||||
|
||||
return highestPriority
|
||||
}
|
||||
|
||||
@@ -184,7 +184,7 @@ func (sa *SelectionAlgorithm) calculateCapabilityScore(carrier *Carrier, profile
|
||||
}
|
||||
|
||||
// generateReason creates a human-readable selection reason
|
||||
func (sa *SelectionAlgorithm) generateReason(score *CarrierScore, criteria *SelectionCriteria) string {
|
||||
func (sa *SelectionAlgorithm) generateReason(score *CarrierScore, _ *SelectionCriteria) string {
|
||||
reasons := []string{}
|
||||
|
||||
if score.PerformanceScore > 80 {
|
||||
|
||||
@@ -38,11 +38,9 @@ func TestMachineLearningModel(t *testing.T) {
|
||||
|
||||
// Check that weights have been optimized
|
||||
optimizedWeights := mlModel.GetOptimizedWeights()
|
||||
originalWeights := WeightVector{Performance: 0.3, Reliability: 0.3, Cost: 0.2, Region: 0.1, Capability: 0.1}
|
||||
|
||||
// Weights should have changed from original
|
||||
if optimizedWeights.Performance == originalWeights.Performance &&
|
||||
optimizedWeights.Reliability == originalWeights.Reliability {
|
||||
// Weights should have changed from original defaults (0.3, 0.3, 0.2, 0.1, 0.1)
|
||||
if optimizedWeights.Performance == 0.3 && optimizedWeights.Reliability == 0.3 {
|
||||
t.Error("Expected weights to change after learning")
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package whitelabel
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Service provides whitelabel management operations
|
||||
type Service struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewService creates a new whitelabel service
|
||||
func NewService(db *gorm.DB, logger *logrus.Logger) *Service {
|
||||
return &Service{db: db, logger: logger}
|
||||
}
|
||||
|
||||
// CreateBranding creates a new branding configuration
|
||||
func (s *Service) CreateBranding(ctx context.Context, config *BrandingConfig) error {
|
||||
if err := s.db.WithContext(ctx).Create(config).Error; err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create branding config")
|
||||
return fmt.Errorf("failed to create branding: %w", err)
|
||||
}
|
||||
s.logger.WithField("tenant_id", config.TenantID).Info("Branding config created")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetBranding retrieves branding by tenant ID
|
||||
func (s *Service) GetBranding(ctx context.Context, tenantID string) (*BrandingConfig, error) {
|
||||
var config BrandingConfig
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&config).Error; err != nil {
|
||||
return nil, fmt.Errorf("branding not found: %w", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// GetBrandingByDomain retrieves branding by custom domain
|
||||
func (s *Service) GetBrandingByDomain(ctx context.Context, domain string) (*BrandingConfig, error) {
|
||||
var config BrandingConfig
|
||||
if err := s.db.WithContext(ctx).Where("custom_domain = ? AND is_active = ?", domain, true).First(&config).Error; err != nil {
|
||||
return nil, fmt.Errorf("branding not found for domain: %w", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// UpdateBranding updates branding configuration
|
||||
func (s *Service) UpdateBranding(ctx context.Context, config *BrandingConfig) error {
|
||||
if err := s.db.WithContext(ctx).Save(config).Error; err != nil {
|
||||
return fmt.Errorf("failed to update branding: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// CreatePartnerConfig creates partner configuration
|
||||
func (s *Service) CreatePartnerConfig(ctx context.Context, config *PartnerConfig) error {
|
||||
if err := s.db.WithContext(ctx).Create(config).Error; err != nil {
|
||||
return fmt.Errorf("failed to create partner config: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetPartnerConfig retrieves partner configuration
|
||||
func (s *Service) GetPartnerConfig(ctx context.Context, tenantID string) (*PartnerConfig, error) {
|
||||
var config PartnerConfig
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID).First(&config).Error; err != nil {
|
||||
return nil, fmt.Errorf("partner config not found: %w", err)
|
||||
}
|
||||
return &config, nil
|
||||
}
|
||||
|
||||
// CreateEmailTemplate creates a custom email template
|
||||
func (s *Service) CreateEmailTemplate(ctx context.Context, template *EmailTemplate) error {
|
||||
if err := s.db.WithContext(ctx).Create(template).Error; err != nil {
|
||||
return fmt.Errorf("failed to create email template: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetEmailTemplate retrieves an email template
|
||||
func (s *Service) GetEmailTemplate(ctx context.Context, tenantID, templateKey string) (*EmailTemplate, error) {
|
||||
var template EmailTemplate
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ? AND template_key = ? AND is_active = ?", tenantID, templateKey, true).First(&template).Error; err != nil {
|
||||
return nil, fmt.Errorf("email template not found: %w", err)
|
||||
}
|
||||
return &template, nil
|
||||
}
|
||||
|
||||
// ListEmailTemplates lists all templates for a tenant
|
||||
func (s *Service) ListEmailTemplates(ctx context.Context, tenantID string) ([]*EmailTemplate, error) {
|
||||
var templates []*EmailTemplate
|
||||
if err := s.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Find(&templates).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to list templates: %w", err)
|
||||
}
|
||||
return templates, nil
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package whitelabel
|
||||
|
||||
import "time"
|
||||
|
||||
// BrandingConfig defines partner branding configuration
|
||||
type BrandingConfig struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
CompanyName string `json:"company_name"`
|
||||
LogoURL string `json:"logo_url"`
|
||||
FaviconURL string `json:"favicon_url"`
|
||||
PrimaryColor string `json:"primary_color"`
|
||||
SecondaryColor string `json:"secondary_color"`
|
||||
AccentColor string `json:"accent_color"`
|
||||
FontFamily string `json:"font_family"`
|
||||
CustomCSS string `json:"custom_css"`
|
||||
CustomDomain string `json:"custom_domain" gorm:"uniqueIndex"`
|
||||
EmailFromName string `json:"email_from_name"`
|
||||
EmailFromAddr string `json:"email_from_address"`
|
||||
SupportEmail string `json:"support_email"`
|
||||
SupportPhone string `json:"support_phone"`
|
||||
TermsURL string `json:"terms_url"`
|
||||
PrivacyURL string `json:"privacy_url"`
|
||||
FooterText string `json:"footer_text"`
|
||||
SocialLinks map[string]string `json:"social_links" gorm:"serializer:json"`
|
||||
Features FeatureFlags `json:"features" gorm:"embedded;embeddedPrefix:feature_"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// FeatureFlags controls which features are enabled for a whitelabel partner
|
||||
type FeatureFlags struct {
|
||||
ShowPoweredBy bool `json:"show_powered_by"`
|
||||
CustomEmailDomain bool `json:"custom_email_domain"`
|
||||
CustomAPIDomain bool `json:"custom_api_domain"`
|
||||
AdvancedAnalytics bool `json:"advanced_analytics"`
|
||||
WhitelabelMobile bool `json:"whitelabel_mobile"`
|
||||
CustomWebhooks bool `json:"custom_webhooks"`
|
||||
APIDocsBranding bool `json:"api_docs_branding"`
|
||||
MultiLanguage bool `json:"multi_language"`
|
||||
}
|
||||
|
||||
// EmailTemplate defines customizable email templates
|
||||
type EmailTemplate struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"index"`
|
||||
TemplateKey string `json:"template_key" gorm:"index"`
|
||||
Subject string `json:"subject"`
|
||||
HTMLBody string `json:"html_body"`
|
||||
TextBody string `json:"text_body"`
|
||||
Variables []string `json:"variables" gorm:"serializer:json"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// PartnerTier defines partnership levels with different capabilities
|
||||
type PartnerTier string
|
||||
|
||||
const (
|
||||
PartnerTierBasic PartnerTier = "basic"
|
||||
PartnerTierProfession PartnerTier = "professional"
|
||||
PartnerTierEnterprise PartnerTier = "enterprise"
|
||||
PartnerTierPlatinum PartnerTier = "platinum"
|
||||
)
|
||||
|
||||
// PartnerConfig defines partner-specific configuration
|
||||
type PartnerConfig struct {
|
||||
ID string `json:"id" gorm:"primaryKey"`
|
||||
TenantID string `json:"tenant_id" gorm:"uniqueIndex"`
|
||||
Tier PartnerTier `json:"tier"`
|
||||
RevenueSharePct float64 `json:"revenue_share_pct"`
|
||||
MinMonthlyCommit float64 `json:"min_monthly_commit"`
|
||||
MaxAPIRequests int64 `json:"max_api_requests"`
|
||||
MaxProfiles int64 `json:"max_profiles"`
|
||||
AllowedCountries []string `json:"allowed_countries" gorm:"serializer:json"`
|
||||
AllowedCarriers []string `json:"allowed_carriers" gorm:"serializer:json"`
|
||||
CustomPricing map[string]any `json:"custom_pricing" gorm:"serializer:json"`
|
||||
ContractStartDate time.Time `json:"contract_start_date"`
|
||||
ContractEndDate time.Time `json:"contract_end_date"`
|
||||
IsActive bool `json:"is_active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
Reference in New Issue
Block a user