mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-12-02 00:38:46 +00:00
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:
@@ -11,19 +11,17 @@ import (
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
|
||||
)
|
||||
|
||||
// RatePlanCurrencyIntegrator integrates currency system with rate plans
|
||||
type RatePlanCurrencyIntegrator struct {
|
||||
billingService currency.BillingService
|
||||
exchangeService *ExchangeRateService
|
||||
exchangeService *currency.ExchangeRateService
|
||||
ratePlanService rateplan.Service
|
||||
logger *logrus.Logger
|
||||
baseCurrency string
|
||||
}
|
||||
|
||||
// NewRatePlanCurrencyIntegrator creates a new rate plan currency integrator
|
||||
func NewRatePlanCurrencyIntegrator(
|
||||
billingService currency.BillingService,
|
||||
exchangeService *ExchangeRateService,
|
||||
exchangeService *currency.ExchangeRateService,
|
||||
ratePlanService rateplan.Service,
|
||||
logger *logrus.Logger,
|
||||
baseCurrency string,
|
||||
@@ -37,20 +35,22 @@ func NewRatePlanCurrencyIntegrator(
|
||||
}
|
||||
}
|
||||
|
||||
// SubscribeToPlanWithCurrency subscribes to a rate plan with currency conversion
|
||||
func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.Context, profileID string, planID string, targetCurrency string) (*rateplan.RatePlanSubscription, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Convert price to requested currency if needed
|
||||
subscriptionPrice := plan.BasePrice
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversion, err := rpci.exchangeService.ConvertAmount(ctx, plan.BasePrice, plan.Currency, targetCurrency)
|
||||
conversionReq := ¤cy.CurrencyConversionRequest{
|
||||
Amount: plan.BasePrice,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
}
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, conversionReq)
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).Error("Failed to convert rate plan price")
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
@@ -59,13 +59,12 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
// Create subscription with currency information
|
||||
subscription := &rateplan.RatePlanSubscription{
|
||||
ProfileID: profileID,
|
||||
RatePlanID: planID,
|
||||
Status: rateplan.SubscriptionStatusActive,
|
||||
StartedAt: time.Now(),
|
||||
Metadata: map[string]interface{}{
|
||||
Metadata: map[string]any{
|
||||
"original_currency": plan.Currency,
|
||||
"subscription_currency": targetCurrency,
|
||||
"original_price": plan.BasePrice,
|
||||
@@ -76,7 +75,6 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Create subscription request
|
||||
subscribeReq := &rateplan.SubscribeRequest{
|
||||
ProfileID: profileID,
|
||||
RatePlanID: planID,
|
||||
@@ -89,7 +87,6 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
return nil, fmt.Errorf("failed to create subscription: %w", err)
|
||||
}
|
||||
|
||||
// Process initial billing
|
||||
billingReq := ¤cy.BillingRequest{
|
||||
ProfileID: profileID,
|
||||
SubscriptionID: createdSubscription.ID,
|
||||
@@ -115,18 +112,14 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
|
||||
return createdSubscription, nil
|
||||
}
|
||||
|
||||
// CalculatePlanCostInCurrency calculates the cost of a rate plan in a specific currency
|
||||
func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.Context, planID string, targetCurrency string, usageData *rateplan.RatePlanUsage) (*currency.BillingSummary, error) {
|
||||
// Get the rate plan
|
||||
plan, err := rpci.ratePlanService.GetRatePlan(ctx, planID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
// Calculate base cost
|
||||
baseCost := plan.BasePrice
|
||||
|
||||
// Add overage costs if usage data is provided
|
||||
if usageData != nil {
|
||||
overageCost, err := rpci.calculateOverageCost(ctx, plan, usageData)
|
||||
if err != nil {
|
||||
@@ -136,12 +129,16 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
}
|
||||
}
|
||||
|
||||
// Convert to requested currency
|
||||
convertedCost := baseCost
|
||||
exchangeRate := 1.0
|
||||
|
||||
if targetCurrency != plan.Currency {
|
||||
conversion, err := rpci.exchangeService.ConvertAmount(ctx, baseCost, plan.Currency, targetCurrency)
|
||||
conversionReq := ¤cy.CurrencyConversionRequest{
|
||||
Amount: baseCost,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
}
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, conversionReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("currency conversion failed: %w", err)
|
||||
}
|
||||
@@ -149,7 +146,6 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
exchangeRate = conversion.ExchangeRate
|
||||
}
|
||||
|
||||
// Create billing summary
|
||||
summary := ¤cy.BillingSummary{
|
||||
ProfileID: usageData.ProfileID,
|
||||
TotalAmount: convertedCost,
|
||||
@@ -159,7 +155,7 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
TransactionCount: 1,
|
||||
FromDate: time.Now().AddDate(0, -1, 0),
|
||||
ToDate: time.Now(),
|
||||
Breakdown: map[string]interface{}{
|
||||
Breakdown: map[string]any{
|
||||
"plan_id": planID,
|
||||
"plan_name": plan.Name,
|
||||
"base_cost": plan.BasePrice,
|
||||
@@ -171,3 +167,30 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
|
||||
|
||||
return summary, nil
|
||||
}
|
||||
|
||||
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
|
||||
overageCost := 0.0
|
||||
|
||||
if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount {
|
||||
dataOverage := usage.DataUsed - plan.DataAllowance.Amount
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(dataOverage) * plan.OverageRates.DataRate
|
||||
}
|
||||
}
|
||||
|
||||
if plan.VoiceAllowance != nil && usage.VoiceUsed > plan.VoiceAllowance.Minutes {
|
||||
voiceOverage := usage.VoiceUsed - plan.VoiceAllowance.Minutes
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(voiceOverage) * plan.OverageRates.VoiceRate
|
||||
}
|
||||
}
|
||||
|
||||
if plan.SMSAllowance != nil && usage.SMSUsed > plan.SMSAllowance.Messages {
|
||||
smsOverage := usage.SMSUsed - plan.SMSAllowance.Messages
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(smsOverage) * plan.OverageRates.SMSRate
|
||||
}
|
||||
}
|
||||
|
||||
return overageCost, nil
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/currency"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
|
||||
)
|
||||
|
||||
@@ -21,7 +22,12 @@ func (rpci *RatePlanCurrencyIntegrator) GetPlansInCurrency(ctx context.Context,
|
||||
// Convert prices to target currency
|
||||
for _, plan := range plans {
|
||||
if plan.Currency != targetCurrency {
|
||||
conversion, err := rpci.exchangeService.ConvertAmount(ctx, plan.BasePrice, plan.Currency, targetCurrency)
|
||||
conversionReq := ¤cy.CurrencyConversionRequest{
|
||||
Amount: plan.BasePrice,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: targetCurrency,
|
||||
}
|
||||
conversion, err := rpci.billingService.ConvertAmount(ctx, conversionReq)
|
||||
if err != nil {
|
||||
rpci.logger.WithError(err).WithFields(logrus.Fields{
|
||||
"plan_id": plan.ID,
|
||||
@@ -33,7 +39,7 @@ func (rpci *RatePlanCurrencyIntegrator) GetPlansInCurrency(ctx context.Context,
|
||||
|
||||
// Store original price and update with converted price
|
||||
if plan.Metadata == nil {
|
||||
plan.Metadata = make(map[string]interface{})
|
||||
plan.Metadata = make(map[string]any)
|
||||
}
|
||||
plan.Metadata["original_price"] = plan.BasePrice
|
||||
plan.Metadata["original_currency"] = plan.Currency
|
||||
@@ -60,7 +66,11 @@ func (rpci *RatePlanCurrencyIntegrator) UpdatePlanCurrency(ctx context.Context,
|
||||
}
|
||||
|
||||
// Convert all monetary values to new currency
|
||||
convertedPrice, err := rpci.exchangeService.ConvertAmount(ctx, plan.BasePrice, plan.Currency, newCurrency)
|
||||
convertedPrice, err := rpci.billingService.ConvertAmount(ctx, ¤cy.CurrencyConversionRequest{
|
||||
Amount: plan.BasePrice,
|
||||
FromCurrency: plan.Currency,
|
||||
ToCurrency: newCurrency,
|
||||
})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to convert base price: %w", err)
|
||||
}
|
||||
@@ -71,9 +81,9 @@ func (rpci *RatePlanCurrencyIntegrator) UpdatePlanCurrency(ctx context.Context,
|
||||
|
||||
// Store conversion information in metadata
|
||||
if plan.Metadata == nil {
|
||||
plan.Metadata = make(map[string]interface{})
|
||||
plan.Metadata = make(map[string]any)
|
||||
}
|
||||
plan.Metadata["currency_conversion"] = map[string]interface{}{
|
||||
plan.Metadata["currency_conversion"] = map[string]any{
|
||||
"from_currency": plan.Metadata["original_currency"],
|
||||
"to_currency": newCurrency,
|
||||
"exchange_rate": convertedPrice.ExchangeRate,
|
||||
@@ -99,37 +109,6 @@ func (rpci *RatePlanCurrencyIntegrator) UpdatePlanCurrency(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
// calculateOverageCost calculates overage costs for usage
|
||||
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
|
||||
overageCost := 0.0
|
||||
|
||||
// Calculate data overage
|
||||
if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount {
|
||||
dataOverage := usage.DataUsed - plan.DataAllowance.Amount
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(dataOverage) * plan.OverageRates.DataRate
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate voice overage
|
||||
if plan.VoiceAllowance != nil && usage.VoiceUsed > plan.VoiceAllowance.Minutes {
|
||||
voiceOverage := usage.VoiceUsed - plan.VoiceAllowance.Minutes
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(voiceOverage) * plan.OverageRates.VoiceRate
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate SMS overage
|
||||
if plan.SMSAllowance != nil && usage.SMSUsed > plan.SMSAllowance.Messages {
|
||||
smsOverage := usage.SMSUsed - plan.SMSAllowance.Messages
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(smsOverage) * plan.OverageRates.SMSRate
|
||||
}
|
||||
}
|
||||
|
||||
return overageCost, nil
|
||||
}
|
||||
|
||||
// GetCurrencyUsageForPlan gets currency usage statistics for a specific rate plan
|
||||
func (rpci *RatePlanCurrencyIntegrator) GetCurrencyUsageForPlan(ctx context.Context, planID string) (map[string]int64, error) {
|
||||
// Get all subscriptions for this plan
|
||||
|
||||
@@ -187,7 +187,7 @@ func (s *Service) CalculateCost(ctx context.Context, req *repository.CalculateCo
|
||||
DiscountCost: discountCost,
|
||||
TotalCost: totalCost,
|
||||
Currency: plan.Currency,
|
||||
Breakdown: map[string]interface{}{
|
||||
Breakdown: map[string]any{
|
||||
"base_cost": baseCost,
|
||||
"overage_cost": overageCost,
|
||||
"discount_cost": discountCost,
|
||||
|
||||
@@ -3,8 +3,7 @@ package services
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/repository"
|
||||
)
|
||||
|
||||
func (s *Service) validateRatePlan(plan *repository.RatePlan) error {
|
||||
|
||||
@@ -101,7 +101,7 @@ func (s *Service) CancelSubscription(ctx context.Context, subscriptionID string,
|
||||
subscription.UpdatedAt = now
|
||||
|
||||
if subscription.Metadata == nil {
|
||||
subscription.Metadata = make(map[string]interface{})
|
||||
subscription.Metadata = make(map[string]any)
|
||||
}
|
||||
subscription.Metadata["cancellation_reason"] = reason
|
||||
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// GetTenantMetrics retrieves tenant metrics
|
||||
func (s *TenantServiceImpl) GetTenantMetrics(ctx context.Context, tenantID string) (*tenant.TenantMetrics, error) {
|
||||
// Get usage stats
|
||||
usageStats, err := s.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get usage stats: %w", err)
|
||||
}
|
||||
|
||||
// Get recent events
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, 100)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
// Calculate metrics
|
||||
metrics := &tenant.TenantMetrics{
|
||||
TenantID: tenantID,
|
||||
ActiveUsers: usageStats.ActiveUsers,
|
||||
StorageUsed: 0, // Would be calculated from actual storage usage
|
||||
HealthScore: 100.0,
|
||||
Alerts: []string{},
|
||||
}
|
||||
|
||||
// Calculate last activity
|
||||
if len(events) > 0 {
|
||||
metrics.LastActivity = events[0].Timestamp
|
||||
}
|
||||
|
||||
// Calculate error rate and response time from events
|
||||
errorCount := 0
|
||||
totalRequests := 0
|
||||
var totalResponseTime time.Duration
|
||||
|
||||
for _, event := range events {
|
||||
if event.EventType == "api_request" {
|
||||
totalRequests++
|
||||
if statusCode, exists := event.EventData["status_code"]; exists {
|
||||
if code, ok := statusCode.(float64); ok && code >= 400 {
|
||||
errorCount++
|
||||
}
|
||||
}
|
||||
if responseTime, exists := event.EventData["response_time"]; exists {
|
||||
if rt, ok := responseTime.(float64); ok {
|
||||
totalResponseTime += time.Duration(rt) * time.Millisecond
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if totalRequests > 0 {
|
||||
metrics.ErrorRate = float64(errorCount) / float64(totalRequests) * 100
|
||||
metrics.ResponseTime = float64(totalResponseTime) / float64(totalRequests) / float64(time.Millisecond)
|
||||
}
|
||||
|
||||
// Check for alerts
|
||||
for resourceType, quotaStatus := range usageStats.QuotaStatus {
|
||||
if quotaStatus.Critical {
|
||||
metrics.Alerts = append(metrics.Alerts, fmt.Sprintf("Critical: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
metrics.HealthScore -= 20
|
||||
} else if quotaStatus.Warning {
|
||||
metrics.Alerts = append(metrics.Alerts, fmt.Sprintf("Warning: %s quota at %.1f%%", resourceType, quotaStatus.Percent))
|
||||
metrics.HealthScore -= 10
|
||||
}
|
||||
}
|
||||
|
||||
return metrics, nil
|
||||
}
|
||||
|
||||
// GetTenantEvents retrieves tenant events
|
||||
func (s *TenantServiceImpl) GetTenantEvents(ctx context.Context, tenantID string, limit int) ([]*tenant.TenantEvent, error) {
|
||||
events, err := s.repository.ListEvents(ctx, tenantID, limit)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant events: %w", err)
|
||||
}
|
||||
|
||||
return events, nil
|
||||
}
|
||||
|
||||
// LogTenantEvent logs a tenant event
|
||||
func (s *TenantServiceImpl) LogTenantEvent(ctx context.Context, event *tenant.TenantEvent) error {
|
||||
if err := s.repository.CreateEvent(ctx, event); err != nil {
|
||||
return fmt.Errorf("failed to create tenant event: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantDashboard returns dashboard data for a tenant
|
||||
func (s *TenantServiceImpl) GetTenantDashboard(ctx context.Context, tenantID string) (*tenant.TenantDashboard, error) {
|
||||
// TODO: Implement proper dashboard when type conversion issues are resolved
|
||||
// For now, return a basic dashboard
|
||||
dashboard := &tenant.TenantDashboard{
|
||||
TenantID: tenantID,
|
||||
UsageStats: nil,
|
||||
Metrics: nil,
|
||||
RecentEvents: nil,
|
||||
QuotaStatus: nil,
|
||||
LastUpdated: time.Now(),
|
||||
}
|
||||
|
||||
return dashboard, nil
|
||||
}
|
||||
|
||||
// GetUsageAnalytics returns detailed usage analytics for a tenant
|
||||
func (s *TenantServiceImpl) GetUsageAnalytics(ctx context.Context, tenantID string, timeRange string) (*tenant.TenantUsageAnalytics, error) {
|
||||
// TODO: Implement proper usage analytics when type conversion issues are resolved
|
||||
// For now, return basic analytics
|
||||
startDate, endDate := s.parseTimeRange(timeRange)
|
||||
|
||||
analytics := &tenant.TenantUsageAnalytics{
|
||||
TenantID: tenantID,
|
||||
TimeRange: timeRange,
|
||||
StartDate: startDate,
|
||||
EndDate: endDate,
|
||||
UsageByType: make(map[string]*tenant.ResourceUsageAnalytics),
|
||||
Trends: make(map[string][]*tenant.UsageTrend),
|
||||
Peaks: make(map[string]*tenant.UsagePeak),
|
||||
}
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetPerformanceAnalytics returns performance analytics for a tenant
|
||||
func (s *TenantServiceImpl) GetPerformanceAnalytics(ctx context.Context, tenantID string, timeRange string) (*tenant.TenantPerformanceAnalytics, error) {
|
||||
// TODO: Implement proper performance analytics when type conversion issues are resolved
|
||||
// For now, return basic analytics
|
||||
startDate, endDate := s.parseTimeRange(timeRange)
|
||||
|
||||
analytics := &tenant.TenantPerformanceAnalytics{
|
||||
TenantID: tenantID,
|
||||
TimeRange: timeRange,
|
||||
StartDate: startDate,
|
||||
EndDate: endDate,
|
||||
APIPerformance: &tenant.APIPerformance{},
|
||||
ResourcePerformance: make(map[string]*tenant.ResourcePerformance),
|
||||
Errors: []*tenant.ErrorEvent{},
|
||||
SlowQueries: []*tenant.SlowQuery{},
|
||||
}
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func (s *TenantServiceImpl) parseTimeRange(timeRange string) (time.Time, time.Time) {
|
||||
now := time.Now()
|
||||
|
||||
switch timeRange {
|
||||
case "1h":
|
||||
return now.Add(-1 * time.Hour), now
|
||||
case "24h":
|
||||
return now.Add(-24 * time.Hour), now
|
||||
case "7d":
|
||||
return now.Add(-7 * 24 * time.Hour), now
|
||||
case "30d":
|
||||
return now.Add(-30 * 24 * time.Hour), now
|
||||
case "90d":
|
||||
return now.Add(-90 * 24 * time.Hour), now
|
||||
default:
|
||||
return now.Add(-24 * time.Hour), now
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) parseAPIRequestEvent(event *tenant.TenantEvent) *tenant.APIRequestEvent {
|
||||
// Implementation depends on event structure
|
||||
return &tenant.APIRequestEvent{
|
||||
Timestamp: event.Timestamp,
|
||||
Endpoint: "",
|
||||
Method: "",
|
||||
StatusCode: 200,
|
||||
ResponseTime: 0,
|
||||
UserID: event.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) parseErrorEvent(event *tenant.TenantEvent) *tenant.ErrorEvent {
|
||||
// Implementation depends on event structure
|
||||
return &tenant.ErrorEvent{
|
||||
Timestamp: event.Timestamp,
|
||||
Error: "",
|
||||
Context: event.EventData,
|
||||
UserID: event.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) parseSlowQueryEvent(event *tenant.TenantEvent) *tenant.SlowQuery {
|
||||
// Implementation depends on event structure
|
||||
return &tenant.SlowQuery{
|
||||
Timestamp: event.Timestamp,
|
||||
Query: "",
|
||||
Duration: 0,
|
||||
Context: event.EventData,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) calculateAPIPerformance(requests []*tenant.APIRequestEvent) *tenant.APIPerformance {
|
||||
// Implementation would calculate performance metrics
|
||||
return &tenant.APIPerformance{
|
||||
TotalRequests: len(requests),
|
||||
AverageResponseTime: 0,
|
||||
P95ResponseTime: 0,
|
||||
ErrorRate: 0,
|
||||
RequestsPerSecond: 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// CreateAPIKey creates a new API key for a tenant
|
||||
func (s *TenantServiceImpl) CreateAPIKey(ctx context.Context, tenantID string, req *tenant.CreateAPIKeyRequest) (*tenant.TenantAPIKey, string, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateAPIKeyRequest(req); err != nil {
|
||||
return nil, "", fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Generate API key
|
||||
apiKey := s.generateAPIKey()
|
||||
keyHash, err := s.hashAPIKey(apiKey)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("failed to hash API key: %w", err)
|
||||
}
|
||||
|
||||
// Create API key record
|
||||
apiKeyRecord := &tenant.TenantAPIKey{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: tenantID,
|
||||
Name: req.Name,
|
||||
KeyHash: keyHash,
|
||||
KeyPrefix: apiKey[:8],
|
||||
Permissions: req.Permissions,
|
||||
RateLimit: req.RateLimit,
|
||||
ExpiresAt: req.ExpiresAt,
|
||||
Status: tenant.APIKeyStatusActive,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Save API key
|
||||
if err := s.repository.CreateAPIKey(ctx, apiKeyRecord); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create API key")
|
||||
return nil, "", fmt.Errorf("failed to create API key: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"key_id": apiKeyRecord.ID,
|
||||
"name": req.Name,
|
||||
}).Info("API key created successfully")
|
||||
|
||||
return apiKeyRecord, apiKey, nil
|
||||
}
|
||||
|
||||
// GetAPIKey retrieves an API key by ID
|
||||
func (s *TenantServiceImpl) GetAPIKey(ctx context.Context, id string) (*tenant.TenantAPIKey, error) {
|
||||
apiKey, err := s.repository.GetAPIKey(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("key_id", id).Error("Failed to get API key")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// UpdateAPIKey updates an API key
|
||||
func (s *TenantServiceImpl) UpdateAPIKey(ctx context.Context, id string, req *tenant.UpdateAPIKeyRequest) (*tenant.TenantAPIKey, error) {
|
||||
// Get existing API key
|
||||
apiKey, err := s.repository.GetAPIKey(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Name != nil {
|
||||
apiKey.Name = *req.Name
|
||||
}
|
||||
if req.Permissions != nil {
|
||||
apiKey.Permissions = req.Permissions
|
||||
}
|
||||
if req.RateLimit != nil {
|
||||
apiKey.RateLimit = *req.RateLimit
|
||||
}
|
||||
if req.ExpiresAt != nil {
|
||||
apiKey.ExpiresAt = req.ExpiresAt
|
||||
}
|
||||
if req.Status != nil {
|
||||
apiKey.Status = *req.Status
|
||||
}
|
||||
|
||||
apiKey.UpdatedAt = time.Now()
|
||||
|
||||
// Save API key
|
||||
if err := s.repository.UpdateAPIKey(ctx, apiKey); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update API key")
|
||||
return nil, fmt.Errorf("failed to update API key: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("key_id", id).Info("API key updated successfully")
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// DeleteAPIKey deletes an API key
|
||||
func (s *TenantServiceImpl) DeleteAPIKey(ctx context.Context, id string) error {
|
||||
// Delete API key
|
||||
if err := s.repository.DeleteAPIKey(ctx, id); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to delete API key")
|
||||
return fmt.Errorf("failed to delete API key: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("key_id", id).Info("API key deleted successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAPIKeys lists API keys for a tenant
|
||||
func (s *TenantServiceImpl) ListAPIKeys(ctx context.Context, tenantID string) ([]*tenant.TenantAPIKey, error) {
|
||||
apiKeys, err := s.repository.ListAPIKeys(ctx, tenantID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("tenant_id", tenantID).Error("Failed to list API keys")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return apiKeys, nil
|
||||
}
|
||||
|
||||
// ValidateAPIKey validates an API key and returns the key record
|
||||
func (s *TenantServiceImpl) ValidateAPIKey(ctx context.Context, key string) (*tenant.TenantAPIKey, error) {
|
||||
// Hash the provided key
|
||||
keyHash, err := s.hashAPIKey(key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to hash API key: %w", err)
|
||||
}
|
||||
|
||||
// Look up API key by hash
|
||||
apiKey, err := s.repository.GetAPIKeyByHash(ctx, keyHash)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Check if key is active
|
||||
if apiKey.Status != tenant.APIKeyStatusActive {
|
||||
return nil, errors.New("API key is not active")
|
||||
}
|
||||
|
||||
// Check if key has expired
|
||||
if apiKey.ExpiresAt != nil && time.Now().After(*apiKey.ExpiresAt) {
|
||||
return nil, errors.New("API key has expired")
|
||||
}
|
||||
|
||||
// Update last used timestamp
|
||||
now := time.Now()
|
||||
apiKey.LastUsed = &now
|
||||
if err := s.repository.UpdateAPIKey(ctx, apiKey); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update API key last used")
|
||||
}
|
||||
|
||||
return apiKey, nil
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
func (s *TenantServiceImpl) validateCreateAPIKeyRequest(req *tenant.CreateAPIKeyRequest) error {
|
||||
if req.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) generateAPIKey() string {
|
||||
bytes := make([]byte, 32)
|
||||
if _, err := rand.Read(bytes); err != nil {
|
||||
// Fallback to less secure method if crypto/rand fails
|
||||
return uuid.New().String()
|
||||
}
|
||||
return "tk_" + hex.EncodeToString(bytes)
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) hashAPIKey(key string) (string, error) {
|
||||
// For now, use simple hash - in production, use bcrypt or similar
|
||||
return fmt.Sprintf("%x", key), nil
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// GetTenantConfig retrieves tenant configuration
|
||||
func (s *TenantServiceImpl) GetTenantConfig(ctx context.Context, tenantID string) (*tenant.TenantConfig, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// UpdateTenantConfig updates tenant configuration
|
||||
func (s *TenantServiceImpl) UpdateTenantConfig(ctx context.Context, tenantID string, config *tenant.TenantConfig) error {
|
||||
config.TenantID = tenantID
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to update tenant config: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant config updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantSettings retrieves tenant settings
|
||||
func (s *TenantServiceImpl) GetTenantSettings(ctx context.Context, tenantID string) (*tenant.TenantSettings, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config.Settings, nil
|
||||
}
|
||||
|
||||
// UpdateTenantSettings updates tenant settings
|
||||
func (s *TenantServiceImpl) UpdateTenantSettings(ctx context.Context, tenantID string, settings *tenant.TenantSettings) error {
|
||||
// Get current config
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Update settings
|
||||
config.Settings = settings
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to update tenant settings: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant settings updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantFeatures retrieves tenant features
|
||||
func (s *TenantServiceImpl) GetTenantFeatures(ctx context.Context, tenantID string) (map[string]bool, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config.Features, nil
|
||||
}
|
||||
|
||||
// UpdateTenantFeatures updates tenant features
|
||||
func (s *TenantServiceImpl) UpdateTenantFeatures(ctx context.Context, tenantID string, features map[string]bool) error {
|
||||
// Get current config
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Update features
|
||||
config.Features = features
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to update tenant features: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant features updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetTenantQuotas retrieves tenant quotas
|
||||
func (s *TenantServiceImpl) GetTenantQuotas(ctx context.Context, tenantID string) ([]tenant.ResourceQuota, error) {
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
return config.Quotas, nil
|
||||
}
|
||||
|
||||
// UpdateTenantQuotas updates tenant quotas
|
||||
func (s *TenantServiceImpl) UpdateTenantQuotas(ctx context.Context, tenantID string, quotas []tenant.ResourceQuota) error {
|
||||
// Get current config
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Update quotas
|
||||
config.Quotas = quotas
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to update tenant quotas: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant quotas updated successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateTenantConfig validates tenant configuration
|
||||
func (s *TenantServiceImpl) ValidateTenantConfig(ctx context.Context, config *tenant.TenantConfig) error {
|
||||
if config.TenantID == "" {
|
||||
return fmt.Errorf("tenant ID is required")
|
||||
}
|
||||
|
||||
if config.Settings == nil {
|
||||
return fmt.Errorf("settings are required")
|
||||
}
|
||||
|
||||
if config.Quotas == nil {
|
||||
return fmt.Errorf("quotas are required")
|
||||
}
|
||||
|
||||
if config.Features == nil {
|
||||
return fmt.Errorf("features are required")
|
||||
}
|
||||
|
||||
// Validate quotas
|
||||
for _, quota := range config.Quotas {
|
||||
if quota.ResourceType == "" {
|
||||
return fmt.Errorf("quota resource type is required")
|
||||
}
|
||||
if quota.Limit < -1 {
|
||||
return fmt.Errorf("quota limit must be -1 (unlimited) or greater")
|
||||
}
|
||||
if quota.Period == "" {
|
||||
return fmt.Errorf("quota period is required")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ResetTenantConfig resets tenant configuration to defaults
|
||||
func (s *TenantServiceImpl) ResetTenantConfig(ctx context.Context, tenantID string) error {
|
||||
// Get tenant to determine plan
|
||||
tenant, err := s.repository.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant: %w", err)
|
||||
}
|
||||
|
||||
// Create default config based on plan
|
||||
config := s.convertTenantConfig(tenantID, tenant.Settings, tenant.Plan)
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
return fmt.Errorf("failed to reset tenant config: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenantID).Info("Tenant config reset to defaults successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
func (s *TenantServiceImpl) convertTenantConfig(tenantID string, settings *tenant.TenantSettings, plan tenant.TenantPlan) *tenant.TenantConfig {
|
||||
return &tenant.TenantConfig{
|
||||
TenantID: tenantID,
|
||||
Config: make(map[string]any),
|
||||
Settings: settings,
|
||||
Quotas: s.getDefaultQuotas(plan),
|
||||
Features: s.getDefaultFeatures(plan),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// TenantServiceImpl implements the tenant service interface
|
||||
type TenantServiceImpl struct {
|
||||
repository tenant.Repository
|
||||
rateLimiter tenant.RateLimiter
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewTenantService creates a new tenant service
|
||||
func NewTenantService(
|
||||
repository tenant.Repository,
|
||||
rateLimiter tenant.RateLimiter,
|
||||
logger *logrus.Logger,
|
||||
) tenant.Service {
|
||||
return &TenantServiceImpl{
|
||||
repository: repository,
|
||||
rateLimiter: rateLimiter,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
// CreateTenant creates a new tenant
|
||||
func (s *TenantServiceImpl) CreateTenant(ctx context.Context, req *tenant.CreateTenantRequest) (*tenant.Tenant, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateTenantRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Check if domain already exists
|
||||
existing, err := s.repository.GetTenantByDomain(ctx, req.Domain)
|
||||
if err == nil && existing != nil {
|
||||
return nil, errors.New("domain already exists")
|
||||
}
|
||||
|
||||
// Create tenant
|
||||
newTenant := &tenant.Tenant{
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Domain: req.Domain,
|
||||
Status: tenant.TenantStatusActive,
|
||||
Plan: req.Plan,
|
||||
MaxUsers: req.MaxUsers,
|
||||
MaxProfiles: req.MaxProfiles,
|
||||
MaxCarriers: req.MaxCarriers,
|
||||
Settings: req.Settings,
|
||||
Metadata: req.Metadata,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Set default settings if not provided
|
||||
if newTenant.Settings == nil {
|
||||
newTenant.Settings = s.getDefaultSettings(req.Plan)
|
||||
}
|
||||
|
||||
// Save tenant
|
||||
if err := s.repository.CreateTenant(ctx, newTenant); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant")
|
||||
return nil, fmt.Errorf("failed to create tenant: %w", err)
|
||||
}
|
||||
|
||||
// Create initial configuration
|
||||
config := &tenant.TenantConfig{
|
||||
TenantID: newTenant.ID,
|
||||
Config: make(map[string]any),
|
||||
Settings: newTenant.Settings,
|
||||
Quotas: s.getDefaultQuotas(req.Plan),
|
||||
Features: s.getDefaultFeatures(req.Plan),
|
||||
}
|
||||
|
||||
if err := s.repository.UpdateConfig(ctx, config); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant config")
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": newTenant.ID,
|
||||
"name": newTenant.Name,
|
||||
"domain": newTenant.Domain,
|
||||
}).Info("Tenant created successfully")
|
||||
|
||||
return newTenant, nil
|
||||
}
|
||||
|
||||
// GetTenant retrieves a tenant by ID
|
||||
func (s *TenantServiceImpl) GetTenant(ctx context.Context, id string) (*tenant.Tenant, error) {
|
||||
tenant, err := s.repository.GetTenant(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("tenant_id", id).Error("Failed to get tenant")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// GetTenantByDomain retrieves a tenant by domain
|
||||
func (s *TenantServiceImpl) GetTenantByDomain(ctx context.Context, domain string) (*tenant.Tenant, error) {
|
||||
tenant, err := s.repository.GetTenantByDomain(ctx, domain)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("domain", domain).Error("Failed to get tenant by domain")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// UpdateTenant updates an existing tenant
|
||||
func (s *TenantServiceImpl) UpdateTenant(ctx context.Context, id string, req *tenant.UpdateTenantRequest) (*tenant.Tenant, error) {
|
||||
// Get existing tenant
|
||||
tenant, err := s.repository.GetTenant(ctx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Name != nil {
|
||||
tenant.Name = *req.Name
|
||||
}
|
||||
if req.Status != nil {
|
||||
tenant.Status = *req.Status
|
||||
}
|
||||
if req.Plan != nil {
|
||||
tenant.Plan = *req.Plan
|
||||
}
|
||||
if req.MaxUsers != nil {
|
||||
tenant.MaxUsers = *req.MaxUsers
|
||||
}
|
||||
if req.MaxProfiles != nil {
|
||||
tenant.MaxProfiles = *req.MaxProfiles
|
||||
}
|
||||
if req.MaxCarriers != nil {
|
||||
tenant.MaxCarriers = *req.MaxCarriers
|
||||
}
|
||||
if req.Settings != nil {
|
||||
tenant.Settings = req.Settings
|
||||
}
|
||||
if req.Metadata != nil {
|
||||
tenant.Metadata = req.Metadata
|
||||
}
|
||||
|
||||
tenant.UpdatedAt = time.Now()
|
||||
|
||||
// Save tenant
|
||||
if err := s.repository.UpdateTenant(ctx, tenant); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update tenant")
|
||||
return nil, fmt.Errorf("failed to update tenant: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", tenant.ID).Info("Tenant updated successfully")
|
||||
|
||||
return tenant, nil
|
||||
}
|
||||
|
||||
// DeleteTenant deletes a tenant
|
||||
func (s *TenantServiceImpl) DeleteTenant(ctx context.Context, id string) error {
|
||||
// Delete tenant
|
||||
if err := s.repository.DeleteTenant(ctx, id); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to delete tenant")
|
||||
return fmt.Errorf("failed to delete tenant: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithField("tenant_id", id).Info("Tenant deleted successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTenants lists tenants with filtering
|
||||
func (s *TenantServiceImpl) ListTenants(ctx context.Context, filter *tenant.TenantFilter) ([]*tenant.Tenant, error) {
|
||||
tenants, err := s.repository.ListTenants(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list tenants")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return tenants, nil
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
func (s *TenantServiceImpl) validateCreateTenantRequest(req *tenant.CreateTenantRequest) error {
|
||||
if req.Name == "" {
|
||||
return errors.New("name is required")
|
||||
}
|
||||
if req.Domain == "" {
|
||||
return errors.New("domain is required")
|
||||
}
|
||||
if req.Plan == "" {
|
||||
return errors.New("plan is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) getDefaultSettings(plan tenant.TenantPlan) *tenant.TenantSettings {
|
||||
settings := &tenant.TenantSettings{
|
||||
DefaultCurrency: "USD",
|
||||
SupportedCurrencies: []string{"USD", "EUR", "GBP"},
|
||||
APIRateLimitPerMinute: 60,
|
||||
APIRateLimitPerHour: 1000,
|
||||
SessionTimeout: 120, // 2 hours
|
||||
DataRetentionDays: 90,
|
||||
ComplianceRegions: []string{"US", "EU"},
|
||||
}
|
||||
|
||||
switch plan {
|
||||
case tenant.TenantPlanFree:
|
||||
settings.EnableMultiCurrency = false
|
||||
settings.EnableAdvancedAnalytics = false
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = false
|
||||
settings.Require2FA = false
|
||||
case tenant.TenantPlanBasic:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = false
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = false
|
||||
settings.Require2FA = false
|
||||
case tenant.TenantPlanPro:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = true
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = true
|
||||
settings.Require2FA = true
|
||||
case tenant.TenantPlanEnterprise:
|
||||
settings.EnableMultiCurrency = true
|
||||
settings.EnableAdvancedAnalytics = true
|
||||
settings.EnableAPIAccess = true
|
||||
settings.EnableWebhooks = true
|
||||
settings.Require2FA = true
|
||||
settings.APIRateLimitPerMinute = 1000
|
||||
settings.APIRateLimitPerHour = 10000
|
||||
}
|
||||
|
||||
return settings
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) getDefaultQuotas(plan tenant.TenantPlan) []tenant.ResourceQuota {
|
||||
quotas := []tenant.ResourceQuota{}
|
||||
|
||||
switch plan {
|
||||
case tenant.TenantPlanFree:
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "users", Limit: 5, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "profiles", Limit: 100, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "carriers", Limit: 3, Period: "monthly"})
|
||||
case tenant.TenantPlanBasic:
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "users", Limit: 25, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "profiles", Limit: 1000, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "carriers", Limit: 10, Period: "monthly"})
|
||||
case tenant.TenantPlanPro:
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "users", Limit: 100, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "profiles", Limit: 10000, Period: "monthly"})
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "carriers", Limit: 50, Period: "monthly"})
|
||||
case tenant.TenantPlanEnterprise:
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "users", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "profiles", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
quotas = append(quotas, tenant.ResourceQuota{ResourceType: "carriers", Limit: -1, Period: "monthly"}) // Unlimited
|
||||
}
|
||||
|
||||
return quotas
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) getDefaultFeatures(plan tenant.TenantPlan) map[string]bool {
|
||||
features := map[string]bool{
|
||||
"multi_currency": false,
|
||||
"advanced_analytics": false,
|
||||
"api_access": true,
|
||||
"webhooks": false,
|
||||
"custom_branding": false,
|
||||
"priority_support": false,
|
||||
}
|
||||
|
||||
switch plan {
|
||||
case tenant.TenantPlanBasic:
|
||||
features["multi_currency"] = true
|
||||
case tenant.TenantPlanPro:
|
||||
features["multi_currency"] = true
|
||||
features["advanced_analytics"] = true
|
||||
features["webhooks"] = true
|
||||
features["custom_branding"] = true
|
||||
case tenant.TenantPlanEnterprise:
|
||||
features["multi_currency"] = true
|
||||
features["advanced_analytics"] = true
|
||||
features["webhooks"] = true
|
||||
features["custom_branding"] = true
|
||||
features["priority_support"] = true
|
||||
}
|
||||
|
||||
return features
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// CheckQuota checks if tenant has sufficient quota for a resource
|
||||
func (s *TenantServiceImpl) CheckQuota(ctx context.Context, tenantID, resourceType string, amount int) error {
|
||||
// Get current usage
|
||||
usage, err := s.repository.GetUsage(ctx, tenantID, resourceType)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get usage: %w", err)
|
||||
}
|
||||
|
||||
// Get quota limits
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get tenant config: %w", err)
|
||||
}
|
||||
|
||||
// Find quota for resource type
|
||||
var quotaLimit int
|
||||
for _, quota := range config.Quotas {
|
||||
if quota.ResourceType == resourceType {
|
||||
quotaLimit = quota.Limit
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Check if quota is exceeded
|
||||
if quotaLimit >= 0 && usage.QuotaUsed+amount > quotaLimit {
|
||||
return fmt.Errorf("quota exceeded for resource %s: %d/%d", resourceType, usage.QuotaUsed+amount, quotaLimit)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsageStats retrieves usage statistics for a tenant
|
||||
func (s *TenantServiceImpl) GetUsageStats(ctx context.Context, tenantID string) (*tenant.TenantUsageStats, error) {
|
||||
// Get all usage records
|
||||
usageRecords, err := s.repository.ListUsage(ctx, &tenant.TenantUsageFilter{TenantID: tenantID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list usage: %w", err)
|
||||
}
|
||||
|
||||
// Calculate stats
|
||||
stats := &tenant.TenantUsageStats{
|
||||
TenantID: tenantID,
|
||||
TotalUsers: 0,
|
||||
ActiveUsers: 0,
|
||||
TotalProfiles: 0,
|
||||
ActiveProfiles: 0,
|
||||
TotalCarriers: 0,
|
||||
ActiveCarriers: 0,
|
||||
APIRequests: 0,
|
||||
StorageUsed: 0,
|
||||
LastActivity: time.Time{},
|
||||
ResourceBreakdown: make(map[string]int64),
|
||||
QuotaStatus: make(map[string]tenant.QuotaStatus),
|
||||
}
|
||||
|
||||
// Get tenant config for quotas
|
||||
config, err := s.repository.GetConfig(ctx, tenantID)
|
||||
if err == nil {
|
||||
for _, quota := range config.Quotas {
|
||||
// Find current usage for this resource
|
||||
var currentUsage int
|
||||
for _, usage := range usageRecords {
|
||||
if usage.ResourceType == quota.ResourceType {
|
||||
currentUsage = usage.QuotaUsed
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate quota status
|
||||
percent := float64(currentUsage) / float64(quota.Limit) * 100
|
||||
status := tenant.QuotaStatus{
|
||||
Used: currentUsage,
|
||||
Limit: quota.Limit,
|
||||
Remaining: quota.Limit - currentUsage,
|
||||
Percent: percent,
|
||||
Warning: percent >= 80,
|
||||
Critical: percent >= 95,
|
||||
}
|
||||
stats.QuotaStatus[quota.ResourceType] = status
|
||||
}
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
// UpdateUsage updates resource usage for a tenant
|
||||
func (s *TenantServiceImpl) UpdateUsage(ctx context.Context, tenantID, resourceType string, amount int) error {
|
||||
// Create usage record
|
||||
usage := &tenant.TenantUsage{
|
||||
ID: fmt.Sprintf("usage_%d", time.Now().UnixNano()),
|
||||
TenantID: tenantID,
|
||||
ResourceType: resourceType,
|
||||
QuotaUsed: amount,
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Update usage
|
||||
if err := s.repository.UpdateUsage(ctx, usage); err != nil {
|
||||
return fmt.Errorf("failed to update usage: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetQuotaStatus retrieves quota status for all resources
|
||||
func (s *TenantServiceImpl) GetQuotaStatus(ctx context.Context, tenantID string) (map[string]tenant.QuotaStatus, error) {
|
||||
// Get usage stats
|
||||
stats, err := s.GetUsageStats(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return stats.QuotaStatus, nil
|
||||
}
|
||||
|
||||
// CheckRateLimit checks rate limit for tenant
|
||||
func (s *TenantServiceImpl) CheckRateLimit(ctx context.Context, tenantCtx *tenant.TenantContext, endpoint string) error {
|
||||
// Use rate limiter to check if request is allowed
|
||||
key := fmt.Sprintf("%s:%s", tenantCtx.TenantID, endpoint)
|
||||
|
||||
if !s.rateLimiter.Allow(ctx, tenantCtx.TenantID, key) {
|
||||
return fmt.Errorf("rate limit exceeded")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecordAPIUsage records API usage for a tenant
|
||||
func (s *TenantServiceImpl) RecordAPIUsage(ctx context.Context, tenantID, endpoint string, statusCode int, responseTime time.Duration) error {
|
||||
// Create usage record
|
||||
usage := &tenant.TenantUsage{
|
||||
ID: fmt.Sprintf("api_%d", time.Now().UnixNano()),
|
||||
TenantID: tenantID,
|
||||
ResourceType: "api_calls",
|
||||
QuotaUsed: 1,
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Update usage
|
||||
if err := s.repository.UpdateUsage(ctx, usage); err != nil {
|
||||
return fmt.Errorf("failed to record API usage: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateResourceAccess validates access to a specific resource
|
||||
func (s *TenantServiceImpl) ValidateResourceAccess(ctx context.Context, tenantID, resourceType, resourceID string) error {
|
||||
// Get tenant
|
||||
tenant, err := s.repository.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("tenant not found: %w", err)
|
||||
}
|
||||
|
||||
// Check tenant status
|
||||
if tenant.Status != "active" {
|
||||
return fmt.Errorf("tenant is not active")
|
||||
}
|
||||
|
||||
// Check resource access based on type
|
||||
switch resourceType {
|
||||
case "profiles", "carriers", "users":
|
||||
// These resources belong to the tenant, so basic tenant validation is sufficient
|
||||
return nil
|
||||
default:
|
||||
// Unknown resource type, deny access
|
||||
return fmt.Errorf("access denied: unknown resource type")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
)
|
||||
|
||||
// HasPermission checks if user has permission
|
||||
func (s *TenantServiceImpl) HasPermission(ctx context.Context, tenantID, userID, permission string) (bool, error) {
|
||||
// Get tenant user
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
// Simple permission check based on role
|
||||
switch user.Role {
|
||||
case tenant.TenantRoleOwner, tenant.TenantRoleAdmin:
|
||||
return true, nil
|
||||
case tenant.TenantRoleManager:
|
||||
return permission != "delete", nil
|
||||
case tenant.TenantRoleUser:
|
||||
return permission == "read", nil
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) validateCreateTenantUserRequest(req *tenant.CreateTenantUserRequest) error {
|
||||
if req.TenantID == "" {
|
||||
return errors.New("tenant ID is required")
|
||||
}
|
||||
if req.UserID == "" {
|
||||
return errors.New("user ID is required")
|
||||
}
|
||||
if req.Email == "" {
|
||||
return errors.New("email is required")
|
||||
}
|
||||
if req.Role == "" {
|
||||
return errors.New("role is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *TenantServiceImpl) convertTenantSettings(settings *tenant.TenantSettings) *tenant.TenantSettings {
|
||||
if settings == nil {
|
||||
return &tenant.TenantSettings{}
|
||||
}
|
||||
|
||||
return &tenant.TenantSettings{
|
||||
DefaultCurrency: settings.DefaultCurrency,
|
||||
SupportedCurrencies: settings.SupportedCurrencies,
|
||||
EnableMultiCurrency: settings.EnableMultiCurrency,
|
||||
EnableAdvancedAnalytics: settings.EnableAdvancedAnalytics,
|
||||
EnableAPIAccess: settings.EnableAPIAccess,
|
||||
EnableWebhooks: settings.EnableWebhooks,
|
||||
Require2FA: settings.Require2FA,
|
||||
SessionTimeout: settings.SessionTimeout,
|
||||
DataRetentionDays: settings.DataRetentionDays,
|
||||
ComplianceRegions: settings.ComplianceRegions,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/tenant"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// AddUserToTenant adds a user to a tenant
|
||||
func (s *TenantServiceImpl) AddUserToTenant(ctx context.Context, req *tenant.CreateTenantUserRequest) (*tenant.TenantUser, error) {
|
||||
// Validate request
|
||||
if err := s.validateCreateTenantUserRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
existing, err := s.repository.GetTenantUser(ctx, req.TenantID, req.UserID)
|
||||
if err == nil && existing != nil {
|
||||
return nil, errors.New("user already exists in tenant")
|
||||
}
|
||||
|
||||
// Create tenant user
|
||||
tenantUser := &tenant.TenantUser{
|
||||
ID: uuid.New().String(),
|
||||
TenantID: req.TenantID,
|
||||
UserID: req.UserID,
|
||||
Email: req.Email,
|
||||
Role: req.Role,
|
||||
Status: tenant.TenantUserStatusActive,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
}
|
||||
|
||||
// Save tenant user
|
||||
if err := s.repository.CreateTenantUser(ctx, tenantUser); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create tenant user")
|
||||
return nil, fmt.Errorf("failed to add user to tenant: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": req.TenantID,
|
||||
"user_id": req.UserID,
|
||||
"role": req.Role,
|
||||
}).Info("User added to tenant successfully")
|
||||
|
||||
return tenantUser, nil
|
||||
}
|
||||
|
||||
// GetTenantUser retrieves a tenant user
|
||||
func (s *TenantServiceImpl) GetTenantUser(ctx context.Context, tenantID, userID string) (*tenant.TenantUser, error) {
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Error("Failed to get tenant user")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// UpdateTenantUser updates a tenant user
|
||||
func (s *TenantServiceImpl) UpdateTenantUser(ctx context.Context, tenantID, userID string, req *tenant.UpdateTenantUserRequest) (*tenant.TenantUser, error) {
|
||||
// Get existing user
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply updates
|
||||
if req.Role != nil {
|
||||
user.Role = *req.Role
|
||||
}
|
||||
if req.Status != nil {
|
||||
user.Status = *req.Status
|
||||
}
|
||||
|
||||
user.UpdatedAt = time.Now()
|
||||
|
||||
// Save user
|
||||
if err := s.repository.UpdateTenantUser(ctx, user); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update tenant user")
|
||||
return nil, fmt.Errorf("failed to update tenant user: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Info("Tenant user updated successfully")
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// RemoveUserFromTenant removes a user from a tenant
|
||||
func (s *TenantServiceImpl) RemoveUserFromTenant(ctx context.Context, tenantID, userID string) error {
|
||||
// Delete tenant user
|
||||
if err := s.repository.DeleteTenantUser(ctx, tenantID, userID); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to remove user from tenant")
|
||||
return fmt.Errorf("failed to remove user from tenant: %w", err)
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"tenant_id": tenantID,
|
||||
"user_id": userID,
|
||||
}).Info("User removed from tenant successfully")
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListTenantUsers lists tenant users with filtering
|
||||
func (s *TenantServiceImpl) ListTenantUsers(ctx context.Context, filter *tenant.TenantUserFilter) ([]*tenant.TenantUser, error) {
|
||||
users, err := s.repository.ListTenantUsers(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list tenant users")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// ValidateTenantAccess validates tenant access
|
||||
func (s *TenantServiceImpl) ValidateTenantAccess(ctx context.Context, tenantID, userID string) (*tenant.TenantContext, error) {
|
||||
// Get tenant
|
||||
tenantRecord, err := s.repository.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tenant not found: %w", err)
|
||||
}
|
||||
|
||||
// Check tenant status
|
||||
if tenantRecord.Status != "active" {
|
||||
return nil, fmt.Errorf("tenant is not active")
|
||||
}
|
||||
|
||||
// Get user
|
||||
user, err := s.repository.GetTenantUser(ctx, tenantID, userID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("user not found in tenant: %w", err)
|
||||
}
|
||||
|
||||
// Check user status
|
||||
if user.Status != "active" {
|
||||
return nil, fmt.Errorf("user is not active")
|
||||
}
|
||||
|
||||
// Create context
|
||||
tenantCtx := &tenant.TenantContext{
|
||||
TenantID: tenantID,
|
||||
TenantName: tenantRecord.Name,
|
||||
Plan: tenantRecord.Plan,
|
||||
UserID: userID,
|
||||
UserRole: user.Role,
|
||||
Settings: tenantRecord.Settings,
|
||||
Metadata: tenantRecord.Metadata,
|
||||
}
|
||||
|
||||
return tenantCtx, nil
|
||||
}
|
||||
|
||||
// GetTenantContext retrieves tenant context
|
||||
func (s *TenantServiceImpl) GetTenantContext(ctx context.Context, tenantID string) (*tenant.TenantContext, error) {
|
||||
// Get tenant
|
||||
tenantRecord, err := s.repository.GetTenant(ctx, tenantID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("tenant not found: %w", err)
|
||||
}
|
||||
|
||||
// Create context with basic tenant info
|
||||
tenantCtx := &tenant.TenantContext{
|
||||
TenantID: tenantID,
|
||||
TenantName: tenantRecord.Name,
|
||||
Plan: tenantRecord.Plan,
|
||||
UserID: "",
|
||||
Settings: tenantRecord.Settings,
|
||||
Metadata: tenantRecord.Metadata,
|
||||
}
|
||||
|
||||
return tenantCtx, nil
|
||||
}
|
||||
Reference in New Issue
Block a user