New features#66
Merged
Merged
Conversation
- Rename internal/handler directory to internal/handlers - Update handler import path in main.go and routes.go
…erations - 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
…zation 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
…ile 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
…ecking, 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
…to multi-carriersm-DP+
…ndations, 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
…, 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
…p, 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
…plified 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
…nnecessary 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
…ng 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
…ier 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
…to new-features
…o suffix - Rename ListProfilesHandlerWithRepo to ListProfilesHandler - Rename GetProfileHandlerWithRepo to GetProfileHandler - Rename DeleteProfileHandlerWithRepo to DeleteProfileHandler
… 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
…y, 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
…dpoints, 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
…owances, 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
…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
…ate 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
…d 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
…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
- 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
…iption 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
…ing, 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
…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
…nization - 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
…to new-features
…gional 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
… 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
…rganization 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
…t 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
…urrency, 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,
…th 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
…ytics 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
…ice 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
… 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
…d 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.
…ement - 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
…t 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
…ricing 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
…ts 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
…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
…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
…dd 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
…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
…olation 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
…s, 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
…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
…ble 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
…wnstream 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
…t 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
…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
…or 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
…racking, 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
- 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
…ementation - 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
No description provided.