- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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.
- 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
- 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
- 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
- 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{}
- Add logrus import and logger initialization in NewSelectionIntegration
- Pass logger instance to NewSelectionService constructor
- Replace selectionService.GetHandler() with direct handlers.NewSelectionHandler(manager) call
- Move OnboardingProgress struct definition before OnboardingStep for logical ordering
- Add MVNOFilter struct with status, plan, business_id, limit, offset, and date range filtering fields
- 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
- 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
- Replace if-else chain with switch statement for step.Status evaluation in monitor.go
- Maintain completed and failed case handling with cleaner control flow
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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,
- 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
- 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
- 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)
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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
- 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)