New features (#65)

* 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,
This commit is contained in:
Nutcase
2026-05-02 03:24:14 +03:00
committed by GitHub
parent 7614476e4f
commit 2b738b0216
40 changed files with 4956 additions and 452 deletions
@@ -102,7 +102,7 @@ func (r *GormRepository) transactionToModel(transaction *currency.Transaction) *
// modelToTransaction converts database model to transaction domain model
func (r *GormRepository) modelToTransaction(model *currency.TransactionModel) (*currency.Transaction, error) {
var metadata map[string]interface{}
var metadata map[string]any
if model.Metadata != "" {
if err := json.Unmarshal([]byte(model.Metadata), &metadata); err != nil {
return nil, fmt.Errorf("failed to parse metadata: %w", err)
@@ -0,0 +1,115 @@
package repository
import (
"context"
"fmt"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
"gorm.io/gorm"
)
// TenantAwareRepository provides tenant isolation for existing repositories
type TenantAwareRepository struct {
db *gorm.DB
tenantID string
}
// NewTenantAwareRepository creates a new tenant-aware repository
func NewTenantAwareRepository(db *gorm.DB, tenantID string) *TenantAwareRepository {
return &TenantAwareRepository{
db: db,
tenantID: tenantID,
}
}
// WithTenant creates a new tenant-aware repository instance
func (r *TenantAwareRepository) WithTenant(tenantID string) *TenantAwareRepository {
return &TenantAwareRepository{
db: r.db,
tenantID: tenantID,
}
}
// GetTenantID returns the current tenant ID
func (r *TenantAwareRepository) GetTenantID() string {
return r.tenantID
}
// ValidateTenant validates that the tenant exists and is active
func (r *TenantAwareRepository) ValidateTenant(ctx context.Context) error {
if r.tenantID == "" {
return fmt.Errorf("tenant ID is required")
}
var tenantRecord tenant.Tenant
err := r.db.WithContext(ctx).Where("id = ? AND status = ?", r.tenantID, tenant.TenantStatusActive).First(&tenantRecord).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return fmt.Errorf("tenant not found or inactive")
}
return fmt.Errorf("failed to validate tenant: %w", err)
}
return nil
}
// TenantScopedQuery creates a query scoped to the current tenant
func (r *TenantAwareRepository) TenantScopedQuery(ctx context.Context, model any) *gorm.DB {
query := r.db.WithContext(ctx).Model(model)
if r.tenantID != "" {
query = query.Where("tenant_id = ?", r.tenantID)
}
return query
}
// TenantScopedTransaction creates a transaction scoped to the current tenant
func (r *TenantAwareRepository) TenantScopedTransaction(ctx context.Context, fn func(*gorm.DB) error) error {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Apply tenant filtering to all operations within the transaction
if r.tenantID != "" {
// This would need to be implemented based on specific requirements
// For now, we'll rely on the tenant-scoped queries within the transaction
}
return fn(tx)
})
}
// ValidateResourceAccess validates that a resource belongs to a tenant
func (v *TenantResourceValidator) ValidateResourceAccess(ctx context.Context, tenantID, resourceType, resourceID string) error {
switch resourceType {
case "profile":
return v.validateProfileAccess(ctx, tenantID, resourceID)
case "rateplan":
return v.validateRatePlanAccess(ctx, tenantID, resourceID)
case "carrier":
return v.validateCarrierAccess(ctx, tenantID, resourceID)
case "subscription":
return v.validateSubscriptionAccess(ctx, tenantID, resourceID)
default:
return fmt.Errorf("unsupported resource type: %s", resourceType)
}
}
func (v *TenantResourceValidator) validateProfileAccess(ctx context.Context, tenantID, profileID string) error {
// This would check if the profile belongs to the tenant
// Implementation depends on the actual profile schema
return nil
}
func (v *TenantResourceValidator) validateRatePlanAccess(ctx context.Context, tenantID, ratePlanID string) error {
// This would check if the rate plan belongs to the tenant
// Implementation depends on the actual rate plan schema
return nil
}
func (v *TenantResourceValidator) validateCarrierAccess(ctx context.Context, tenantID, carrierID string) error {
// This would check if the carrier belongs to the tenant
// Implementation depends on the actual carrier schema
return nil
}
func (v *TenantResourceValidator) validateSubscriptionAccess(ctx context.Context, tenantID, subscriptionID string) error {
// This would check if the subscription belongs to the tenant
// Implementation depends on the actual subscription schema
return nil
}
@@ -0,0 +1,186 @@
package repository
import (
"context"
"encoding/json"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
)
// GetUsageStats retrieves usage statistics for a tenant
func (r *GormTenantRepository) GetUsageStats(ctx context.Context, tenantID string) (*tenant.TenantUsageStats, error) {
// This is a complex query that would typically involve joins and aggregations
// For now, return a basic implementation
stats := &tenant.TenantUsageStats{
TenantID: tenantID,
ResourceBreakdown: make(map[string]int64),
QuotaStatus: make(map[string]tenant.QuotaStatus),
}
// Get all usage records for the tenant
usageRecords, err := r.ListUsage(ctx, &tenant.TenantUsageFilter{TenantID: tenantID})
if err != nil {
return nil, err
}
// Process usage records
for _, usage := range usageRecords {
stats.ResourceBreakdown[usage.ResourceType] = int64(usage.QuotaUsed)
stats.QuotaStatus[usage.ResourceType] = tenant.QuotaStatus{
Used: usage.QuotaUsed,
Limit: usage.QuotaLimit,
Remaining: usage.QuotaRemaining,
}
}
return stats, nil
}
// GetConfig retrieves tenant configuration
func (r *GormTenantRepository) GetConfig(ctx context.Context, tenantID string) (*tenant.TenantConfig, error) {
// Get tenant to extract settings
tenantRecord, err := r.GetTenant(ctx, tenantID)
if err != nil {
return nil, err
}
// Create basic config
config := &tenant.TenantConfig{
TenantID: tenantID,
Config: make(map[string]any),
Settings: tenantRecord.Settings,
Quotas: []tenant.ResourceQuota{},
Features: make(map[string]bool),
}
// Add default quotas based on plan
switch tenantRecord.Plan {
case tenant.TenantPlanFree:
config.Quotas = []tenant.ResourceQuota{
{ResourceType: "users", Limit: 5, Period: "monthly"},
{ResourceType: "profiles", Limit: 100, Period: "monthly"},
{ResourceType: "carriers", Limit: 3, Period: "monthly"},
}
case tenant.TenantPlanBasic:
config.Quotas = []tenant.ResourceQuota{
{ResourceType: "users", Limit: 25, Period: "monthly"},
{ResourceType: "profiles", Limit: 1000, Period: "monthly"},
{ResourceType: "carriers", Limit: 10, Period: "monthly"},
}
case tenant.TenantPlanPro:
config.Quotas = []tenant.ResourceQuota{
{ResourceType: "users", Limit: 100, Period: "monthly"},
{ResourceType: "profiles", Limit: 10000, Period: "monthly"},
{ResourceType: "carriers", Limit: 50, Period: "monthly"},
}
case tenant.TenantPlanEnterprise:
config.Quotas = []tenant.ResourceQuota{
{ResourceType: "users", Limit: -1, Period: "monthly"},
{ResourceType: "profiles", Limit: -1, Period: "monthly"},
{ResourceType: "carriers", Limit: -1, Period: "monthly"},
}
}
// Add default features based on plan
switch tenantRecord.Plan {
case tenant.TenantPlanFree:
config.Features = map[string]bool{
"multi_currency": false,
"advanced_analytics": false,
"api_access": true,
"webhooks": false,
}
case tenant.TenantPlanBasic:
config.Features = map[string]bool{
"multi_currency": true,
"advanced_analytics": false,
"api_access": true,
"webhooks": false,
}
case tenant.TenantPlanPro, tenant.TenantPlanEnterprise:
config.Features = map[string]bool{
"multi_currency": true,
"advanced_analytics": true,
"api_access": true,
"webhooks": true,
}
}
return config, nil
}
// UpdateConfig updates tenant configuration
func (r *GormTenantRepository) UpdateConfig(ctx context.Context, config *tenant.TenantConfig) error {
// Store configuration in tenant metadata or separate table
// For now, update tenant settings
tenantRecord, err := r.GetTenant(ctx, config.TenantID)
if err != nil {
return err
}
tenantRecord.Settings = config.Settings
tenantRecord.Metadata = config.Config
tenantRecord.UpdatedAt = time.Now()
return r.UpdateTenant(ctx, tenantRecord)
}
// CreateEvent creates a new tenant event
func (r *GormTenantRepository) CreateEvent(ctx context.Context, event *tenant.TenantEvent) error {
// Store events in a separate table or log system
// For now, we'll use a simple approach with JSON storage
eventData, err := json.Marshal(event)
if err != nil {
return err
}
// Create a simple event record (in a real implementation, this would be a proper table)
eventRecord := struct {
ID string `gorm:"primaryKey"`
TenantID string `gorm:"index"`
EventData string `gorm:"type:text"`
CreatedAt time.Time `gorm:"autoCreateTime"`
}{
ID: event.ID,
TenantID: event.TenantID,
EventData: string(eventData),
CreatedAt: event.Timestamp,
}
return r.db.WithContext(ctx).Table("tenant_events").Create(&eventRecord).Error
}
// ListEvents lists tenant events
func (r *GormTenantRepository) ListEvents(ctx context.Context, tenantID string, limit int) ([]*tenant.TenantEvent, error) {
// Query events from the events table
var eventRecords []struct {
ID string `gorm:"primaryKey"`
TenantID string `gorm:"index"`
EventData string `gorm:"type:text"`
CreatedAt time.Time `gorm:"autoCreateTime"`
}
query := r.db.WithContext(ctx).Table("tenant_events").Where("tenant_id = ?", tenantID)
if limit > 0 {
query = query.Limit(limit)
}
query = query.Order("created_at DESC")
err := query.Find(&eventRecords).Error
if err != nil {
return nil, err
}
// Unmarshal events
var events []*tenant.TenantEvent
for _, record := range eventRecords {
var event tenant.TenantEvent
if err := json.Unmarshal([]byte(record.EventData), &event); err != nil {
continue // Skip malformed events
}
events = append(events, &event)
}
return events, nil
}
@@ -0,0 +1,101 @@
package repository
import (
"context"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
)
// CreateAPIKey creates a new API key
func (r *GormTenantRepository) CreateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error {
return r.db.WithContext(ctx).Create(apiKey).Error
}
// GetAPIKey retrieves an API key by ID
func (r *GormTenantRepository) GetAPIKey(ctx context.Context, id string) (*tenant.TenantAPIKey, error) {
var apiKey tenant.TenantAPIKey
err := r.db.WithContext(ctx).Where("id = ?", id).First(&apiKey).Error
if err != nil {
return nil, err
}
return &apiKey, nil
}
// GetAPIKeyByHash retrieves an API key by hash
func (r *GormTenantRepository) GetAPIKeyByHash(ctx context.Context, keyHash string) (*tenant.TenantAPIKey, error) {
var apiKey tenant.TenantAPIKey
err := r.db.WithContext(ctx).Where("key_hash = ?", keyHash).First(&apiKey).Error
if err != nil {
return nil, err
}
return &apiKey, nil
}
// UpdateAPIKey updates an API key
func (r *GormTenantRepository) UpdateAPIKey(ctx context.Context, apiKey *tenant.TenantAPIKey) error {
return r.db.WithContext(ctx).Save(apiKey).Error
}
// DeleteAPIKey deletes an API key
func (r *GormTenantRepository) DeleteAPIKey(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Delete(&tenant.TenantAPIKey{}, "id = ?", id).Error
}
// ListAPIKeys lists API keys for a tenant
func (r *GormTenantRepository) ListAPIKeys(ctx context.Context, tenantID string) ([]*tenant.TenantAPIKey, error) {
var apiKeys []*tenant.TenantAPIKey
err := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID).Order("created_at DESC").Find(&apiKeys).Error
return apiKeys, err
}
// CreateUsage creates a new usage record
func (r *GormTenantRepository) CreateUsage(ctx context.Context, usage *tenant.TenantUsage) error {
return r.db.WithContext(ctx).Create(usage).Error
}
// GetUsage retrieves usage by tenant and resource type
func (r *GormTenantRepository) GetUsage(ctx context.Context, tenantID, resourceType string) (*tenant.TenantUsage, error) {
var usage tenant.TenantUsage
err := r.db.WithContext(ctx).Where("tenant_id = ? AND resource_type = ?", tenantID, resourceType).First(&usage).Error
if err != nil {
return nil, err
}
return &usage, nil
}
// UpdateUsage updates a usage record
func (r *GormTenantRepository) UpdateUsage(ctx context.Context, usage *tenant.TenantUsage) error {
return r.db.WithContext(ctx).Save(usage).Error
}
// ListUsage lists usage records with filtering
func (r *GormTenantRepository) ListUsage(ctx context.Context, filter *tenant.TenantUsageFilter) ([]*tenant.TenantUsage, error) {
query := r.db.WithContext(ctx).Model(&tenant.TenantUsage{})
// Apply filters
if filter.TenantID != "" {
query = query.Where("tenant_id = ?", filter.TenantID)
}
if filter.ResourceType != "" {
query = query.Where("resource_type = ?", filter.ResourceType)
}
if !filter.PeriodStart.IsZero() {
query = query.Where("period_start >= ?", filter.PeriodStart)
}
if !filter.PeriodEnd.IsZero() {
query = query.Where("period_end <= ?", filter.PeriodEnd)
}
// Apply pagination
if filter.Limit > 0 {
query = query.Limit(filter.Limit)
}
if filter.Offset > 0 {
query = query.Offset(filter.Offset)
}
var usage []*tenant.TenantUsage
err := query.Find(&usage).Error
return usage, err
}
@@ -0,0 +1,194 @@
package repository
import (
"context"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
"gorm.io/gorm"
)
type GormTenantRepository struct {
db *gorm.DB
}
func NewGormTenantRepository(db *gorm.DB) TenantRepository {
return &GormTenantRepository{db: db}
}
func (r *GormTenantRepository) CreateTenant(ctx context.Context, tenant *tenant.Tenant) error {
return r.db.WithContext(ctx).Create(tenant).Error
}
func (r *GormTenantRepository) GetTenant(ctx context.Context, id string) (*tenant.Tenant, error) {
var tenant tenant.Tenant
err := r.db.WithContext(ctx).Where("id = ?", id).First(&tenant).Error
if err != nil {
return nil, err
}
return &tenant, nil
}
// GetTenantByDomain retrieves a tenant by domain
func (r *GormTenantRepository) GetTenantByDomain(ctx context.Context, domain string) (*tenant.Tenant, error) {
var tenant tenant.Tenant
err := r.db.WithContext(ctx).Where("domain = ?", domain).First(&tenant).Error
if err != nil {
return nil, err
}
return &tenant, nil
}
// UpdateTenant updates an existing tenant
func (r *GormTenantRepository) UpdateTenant(ctx context.Context, tenant *tenant.Tenant) error {
return r.db.WithContext(ctx).Save(tenant).Error
}
// DeleteTenant deletes a tenant
func (r *GormTenantRepository) DeleteTenant(ctx context.Context, id string) error {
return r.db.WithContext(ctx).Delete(&tenant.Tenant{}, "id = ?", id).Error
}
// ListTenants lists tenants with filtering
func (r *GormTenantRepository) ListTenants(ctx context.Context, filter *tenant.TenantFilter) ([]*tenant.Tenant, error) {
query := r.db.WithContext(ctx).Model(&tenant.Tenant{})
if filter.ID != "" {
query = query.Where("id = ?", filter.ID)
}
if filter.Name != "" {
query = query.Where("name ILIKE ?", "%"+filter.Name+"%")
}
if filter.Domain != "" {
query = query.Where("domain ILIKE ?", "%"+filter.Domain+"%")
}
if filter.Status != "" {
query = query.Where("status = ?", filter.Status)
}
if filter.Plan != "" {
query = query.Where("plan = ?", filter.Plan)
}
// Apply sorting
if filter.SortBy != "" {
order := filter.SortBy
if filter.SortOrder == "desc" {
order += " DESC"
}
query = query.Order(order)
} else {
query = query.Order("created_at DESC")
}
// Apply pagination
if filter.Limit > 0 {
query = query.Limit(filter.Limit)
}
if filter.Offset > 0 {
query = query.Offset(filter.Offset)
}
var tenants []*tenant.Tenant
err := query.Find(&tenants).Error
return tenants, err
}
func (r *GormTenantRepository) CountTenants(ctx context.Context, filter *tenant.TenantFilter) (int, error) {
query := r.db.WithContext(ctx).Model(&tenant.Tenant{})
if filter.ID != "" {
query = query.Where("id = ?", filter.ID)
}
if filter.Name != "" {
query = query.Where("name ILIKE ?", "%"+filter.Name+"%")
}
if filter.Domain != "" {
query = query.Where("domain ILIKE ?", "%"+filter.Domain+"%")
}
if filter.Status != "" {
query = query.Where("status = ?", filter.Status)
}
if filter.Plan != "" {
query = query.Where("plan = ?", filter.Plan)
}
var count int64
err := query.Count(&count).Error
return int(count), err
}
func (r *GormTenantRepository) CreateTenantUser(ctx context.Context, user *tenant.TenantUser) error {
return r.db.WithContext(ctx).Create(user).Error
}
func (r *GormTenantRepository) GetTenantUser(ctx context.Context, tenantID, userID string) (*tenant.TenantUser, error) {
var user tenant.TenantUser
err := r.db.WithContext(ctx).Where("tenant_id = ? AND user_id = ?", tenantID, userID).First(&user).Error
if err != nil {
return nil, err
}
return &user, nil
}
func (r *GormTenantRepository) UpdateTenantUser(ctx context.Context, user *tenant.TenantUser) error {
return r.db.WithContext(ctx).Save(user).Error
}
func (r *GormTenantRepository) DeleteTenantUser(ctx context.Context, tenantID, userID string) error {
return r.db.WithContext(ctx).Delete(&tenant.TenantUser{}, "tenant_id = ? AND user_id = ?", tenantID, userID).Error
}
func (r *GormTenantRepository) ListTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) ([]*tenant.TenantUser, error) {
query := r.db.WithContext(ctx).Model(&tenant.TenantUser{})
if filter.TenantID != "" {
query = query.Where("tenant_id = ?", filter.TenantID)
}
if filter.UserID != "" {
query = query.Where("user_id = ?", filter.UserID)
}
if filter.Email != "" {
query = query.Where("email ILIKE ?", "%"+filter.Email+"%")
}
if filter.Role != "" {
query = query.Where("role = ?", filter.Role)
}
if filter.Status != "" {
query = query.Where("status = ?", filter.Status)
}
// Apply pagination
if filter.Limit > 0 {
query = query.Limit(filter.Limit)
}
if filter.Offset > 0 {
query = query.Offset(filter.Offset)
}
var users []*tenant.TenantUser
err := query.Find(&users).Error
return users, err
}
func (r *GormTenantRepository) CountTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) (int, error) {
query := r.db.WithContext(ctx).Model(&tenant.TenantUser{})
if filter.TenantID != "" {
query = query.Where("tenant_id = ?", filter.TenantID)
}
if filter.UserID != "" {
query = query.Where("user_id = ?", filter.UserID)
}
if filter.Email != "" {
query = query.Where("email ILIKE ?", "%"+filter.Email+"%")
}
if filter.Role != "" {
query = query.Where("role = ?", filter.Role)
}
if filter.Status != "" {
query = query.Where("status = ?", filter.Status)
}
var count int64
err := query.Count(&count).Error
return int(count), err
}
@@ -0,0 +1,60 @@
package repository
import (
"context"
"fmt"
"gorm.io/gorm"
)
// TenantAwareQuery adds tenant filtering to database queries
func (r *GormTenantRepository) TenantAwareQuery(ctx context.Context, model any, tenantID string) *gorm.DB {
query := r.db.WithContext(ctx).Model(model)
// Add tenant filter if the model has tenant_id field
if tenantID != "" {
query = query.Where("tenant_id = ?", tenantID)
}
return query
}
// EnsureTenantIsolation ensures that queries are tenant-isolated
func (r *GormTenantRepository) EnsureTenantIsolation(ctx context.Context, tenantID string) error {
if tenantID == "" {
return fmt.Errorf("tenant ID is required for tenant-isolated operations")
}
// Validate tenant exists
_, err := r.GetTenant(ctx, tenantID)
if err != nil {
return fmt.Errorf("invalid tenant ID: %w", err)
}
return nil
}
// GetTenantFromContext extracts tenant ID from context
func (r *GormTenantRepository) GetTenantFromContext(ctx context.Context) string {
if tenantID, ok := ctx.Value("tenant_id").(string); ok {
return tenantID
}
return ""
}
// WithTenantIsolation applies tenant isolation to a database operation
func (r *GormTenantRepository) WithTenantIsolation(ctx context.Context, operation func(*gorm.DB) error) error {
tenantID := r.GetTenantFromContext(ctx)
if tenantID == "" {
return fmt.Errorf("tenant ID not found in context")
}
// Validate tenant exists
if err := r.EnsureTenantIsolation(ctx, tenantID); err != nil {
return err
}
// Execute operation with tenant filtering
tx := r.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
return operation(tx)
}
@@ -0,0 +1,192 @@
package repository
import (
"context"
"fmt"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
"gorm.io/gorm"
)
func (r *TenantAwareRepository) CreateWithTenant(ctx context.Context, model any) error {
if err := r.ValidateTenant(ctx); err != nil {
return err
}
// Set tenant ID if the model has a TenantID field
if modelWithTenant, ok := model.(interface{ SetTenantID(string) }); ok {
modelWithTenant.SetTenantID(r.tenantID)
}
return r.db.WithContext(ctx).Create(model).Error
}
func (r *TenantAwareRepository) GetByTenantID(ctx context.Context, model any, id string) error {
if err := r.ValidateTenant(ctx); err != nil {
return err
}
return r.TenantScopedQuery(ctx, model).Where("id = ?", id).First(model).Error
}
func (r *TenantAwareRepository) UpdateWithTenant(ctx context.Context, model any) error {
if err := r.ValidateTenant(ctx); err != nil {
return err
}
return r.db.WithContext(ctx).Save(model).Error
}
func (r *TenantAwareRepository) DeleteWithTenant(ctx context.Context, model any, id string) error {
if err := r.ValidateTenant(ctx); err != nil {
return err
}
return r.TenantScopedQuery(ctx, model).Where("id = ?", id).Delete(model).Error
}
func (r *TenantAwareRepository) ListWithTenant(ctx context.Context, model any, results any, filters map[string]any) error {
if err := r.ValidateTenant(ctx); err != nil {
return err
}
query := r.TenantScopedQuery(ctx, model)
// Apply filters
for key, value := range filters {
query = query.Where(key+" = ?", value)
}
return query.Find(results).Error
}
func (r *TenantAwareRepository) CountWithTenant(ctx context.Context, model any, filters map[string]any) (int64, error) {
if err := r.ValidateTenant(ctx); err != nil {
return 0, err
}
query := r.TenantScopedQuery(ctx, model)
// Apply filters
for key, value := range filters {
query = query.Where(key+" = ?", value)
}
var count int64
err := query.Count(&count).Error
return count, err
}
type TenantAwareModel interface {
SetTenantID(tenantID string)
GetTenantID() string
}
type BaseTenantModel struct {
TenantID string `json:"tenant_id" gorm:"column:tenant_id;index;not null"`
}
func (m *BaseTenantModel) SetTenantID(tenantID string) {
m.TenantID = tenantID
}
func (m *BaseTenantModel) GetTenantID() string {
return m.TenantID
}
type TenantIsolationMiddleware struct {
db *gorm.DB
}
func NewTenantIsolationMiddleware(db *gorm.DB) *TenantIsolationMiddleware {
return &TenantIsolationMiddleware{db: db}
}
func (m *TenantIsolationMiddleware) WithTenantIsolation(ctx context.Context, tenantID string, operation func(*gorm.DB) error) error {
if tenantID == "" {
return fmt.Errorf("tenant ID is required for tenant-isolated operations")
}
var tenantRecord tenant.Tenant
err := m.db.WithContext(ctx).Where("id = ? AND status = ?", tenantID, tenant.TenantStatusActive).First(&tenantRecord).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return fmt.Errorf("tenant not found or inactive")
}
return fmt.Errorf("failed to validate tenant: %w", err)
}
tx := m.db.WithContext(ctx).Where("tenant_id = ?", tenantID)
return operation(tx)
}
func GetTenantFromContext(ctx context.Context) string {
if tenantID, ok := ctx.Value("tenant_id").(string); ok {
return tenantID
}
return ""
}
func SetTenantInContext(ctx context.Context, tenantID string) context.Context {
return context.WithValue(ctx, "tenant_id", tenantID)
}
type TenantQueryBuilder struct {
db *gorm.DB
tenantID string
query *gorm.DB
}
func NewTenantQueryBuilder(db *gorm.DB, tenantID string) *TenantQueryBuilder {
return &TenantQueryBuilder{
db: db,
tenantID: tenantID,
query: db.Where("tenant_id = ?", tenantID),
}
}
func (b *TenantQueryBuilder) Where(query string, args ...any) *TenantQueryBuilder {
b.query = b.query.Where(query, args...)
return b
}
func (b *TenantQueryBuilder) Order(value string) *TenantQueryBuilder {
b.query = b.query.Order(value)
return b
}
func (b *TenantQueryBuilder) Limit(limit int) *TenantQueryBuilder {
b.query = b.query.Limit(limit)
return b
}
func (b *TenantQueryBuilder) Offset(offset int) *TenantQueryBuilder {
b.query = b.query.Offset(offset)
return b
}
func (b *TenantQueryBuilder) Find(dest any) error {
return b.query.Find(dest).Error
}
func (b *TenantQueryBuilder) First(dest any) error {
return b.query.First(dest).Error
}
func (b *TenantQueryBuilder) Count() (int64, error) {
var count int64
err := b.query.Count(&count).Error
return count, err
}
func (b *TenantQueryBuilder) GetQuery() *gorm.DB {
return b.query
}
type TenantResourceValidator struct {
db *gorm.DB
}
func NewTenantResourceValidator(db *gorm.DB) *TenantResourceValidator {
return &TenantResourceValidator{db: db}
}
@@ -3,8 +3,53 @@ 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
@@ -54,20 +99,20 @@ func (RatePlanUsage) TableName() string {
// RatePlanSubscription represents a subscription to a rate plan
type RatePlanSubscription struct {
ID string `json:"id" gorm:"primaryKey"`
ProfileID string `json:"profile_id" gorm:"index"`
RatePlanID string `json:"rate_plan_id" gorm:"index"`
Status SubscriptionStatus `json:"status" gorm:"index"`
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
BillingCycle BillingCycle `json:"billing_cycle"`
NextBillingDate time.Time `json:"next_billing_date"`
AutoRenew bool `json:"auto_renew"`
CurrentCycle time.Time `json:"current_cycle"`
AppliedDiscounts []string `json:"applied_discounts,omitempty" gorm:"serializer:json"`
Metadata map[string]interface{} `json:"metadata,omitempty" gorm:"serializer:json"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id" gorm:"primaryKey"`
ProfileID string `json:"profile_id" gorm:"index"`
RatePlanID string `json:"rate_plan_id" gorm:"index"`
Status SubscriptionStatus `json:"status" gorm:"index"`
StartedAt time.Time `json:"started_at"`
EndedAt *time.Time `json:"ended_at,omitempty"`
BillingCycle BillingCycle `json:"billing_cycle"`
NextBillingDate time.Time `json:"next_billing_date"`
AutoRenew bool `json:"auto_renew"`
CurrentCycle time.Time `json:"current_cycle"`
AppliedDiscounts []string `json:"applied_discounts,omitempty" gorm:"serializer:json"`
Metadata map[string]any `json:"metadata,omitempty" gorm:"serializer:json"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName returns the table name for RatePlanSubscription
@@ -108,27 +153,27 @@ type SubscriptionFilter struct {
// RatePlan represents a rate plan
type RatePlan struct {
ID string `json:"id" gorm:"primaryKey"`
Name string `json:"name"`
Description string `json:"description"`
CarrierID string `json:"carrier_id" gorm:"index"`
Region string `json:"region" gorm:"index"`
PlanType PlanType `json:"plan_type"`
BasePrice float64 `json:"base_price"`
Currency string `json:"currency"`
BillingCycle BillingCycle `json:"billing_cycle"`
DataAllowance *DataAllowance `json:"data_allowance,omitempty" gorm:"serializer:json"`
VoiceAllowance *VoiceAllowance `json:"voice_allowance,omitempty" gorm:"serializer:json"`
SMSAllowance *SMSAllowance `json:"sms_allowance,omitempty" gorm:"serializer:json"`
OverageRates *OverageRates `json:"overage_rates,omitempty" gorm:"serializer:json"`
Discounts []*Discount `json:"discounts,omitempty" gorm:"serializer:json"`
ValidFrom time.Time `json:"valid_from"`
ValidTo *time.Time `json:"valid_to,omitempty"`
IsActive bool `json:"is_active"`
Status PlanStatus `json:"status"`
Metadata map[string]interface{} `json:"metadata,omitempty" gorm:"serializer:json"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID string `json:"id" gorm:"primaryKey"`
Name string `json:"name"`
Description string `json:"description"`
CarrierID string `json:"carrier_id" gorm:"index"`
Region string `json:"region" gorm:"index"`
PlanType PlanType `json:"plan_type"`
BasePrice float64 `json:"base_price"`
Currency string `json:"currency"`
BillingCycle BillingCycle `json:"billing_cycle"`
DataAllowance *DataAllowance `json:"data_allowance,omitempty" gorm:"serializer:json"`
VoiceAllowance *VoiceAllowance `json:"voice_allowance,omitempty" gorm:"serializer:json"`
SMSAllowance *SMSAllowance `json:"sms_allowance,omitempty" gorm:"serializer:json"`
OverageRates *OverageRates `json:"overage_rates,omitempty" gorm:"serializer:json"`
Discounts []*Discount `json:"discounts,omitempty" gorm:"serializer:json"`
ValidFrom time.Time `json:"valid_from"`
ValidTo *time.Time `json:"valid_to,omitempty"`
IsActive bool `json:"is_active"`
Status PlanStatus `json:"status"`
Metadata map[string]any `json:"metadata,omitempty" gorm:"serializer:json"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName returns the table name for RatePlan
@@ -278,11 +323,11 @@ type SearchCriteria struct {
// SubscribeRequest represents a request to subscribe to a rate plan
type SubscribeRequest struct {
ProfileID string `json:"profile_id"`
RatePlanID string `json:"rate_plan_id"`
AutoRenew bool `json:"auto_renew"`
AppliedDiscounts []string `json:"applied_discounts,omitempty"`
Metadata map[string]interface{} `json:"metadata,omitempty"`
ProfileID string `json:"profile_id"`
RatePlanID string `json:"rate_plan_id"`
AutoRenew bool `json:"auto_renew"`
AppliedDiscounts []string `json:"applied_discounts,omitempty"`
Metadata map[string]any `json:"metadata,omitempty"`
}
// RecordUsageRequest represents a request to record usage
@@ -304,12 +349,12 @@ type CalculateCostRequest struct {
// RatePlanCostCalculation represents the result of a cost calculation
type RatePlanCostCalculation struct {
RatePlanID string `json:"rate_plan_id"`
BaseCost float64 `json:"base_cost"`
OverageCost float64 `json:"overage_cost"`
DiscountCost float64 `json:"discount_cost"`
TotalCost float64 `json:"total_cost"`
Currency string `json:"currency"`
Breakdown map[string]interface{} `json:"breakdown"`
CalculatedAt time.Time `json:"calculated_at"`
RatePlanID string `json:"rate_plan_id"`
BaseCost float64 `json:"base_cost"`
OverageCost float64 `json:"overage_cost"`
DiscountCost float64 `json:"discount_cost"`
TotalCost float64 `json:"total_cost"`
Currency string `json:"currency"`
Breakdown map[string]any `json:"breakdown"`
CalculatedAt time.Time `json:"calculated_at"`
}