Files
telecom-platform/apps/carrier-connector/internal/services/analytics_service.go
T
NutcaseandGitHub 7614476e4f Multi-Currency Support for International Billing (#64)
* 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
2026-05-02 01:28:15 +03:00

245 lines
7.4 KiB
Go

package services
import (
"context"
"fmt"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/currency"
"github.com/sirupsen/logrus"
)
// AnalyticsServiceImpl handles currency analytics operations
type AnalyticsServiceImpl struct {
repository currency.Repository
logger *logrus.Logger
}
// NewAnalyticsService creates a new analytics service
func NewAnalyticsService(repository currency.Repository, logger *logrus.Logger) *AnalyticsServiceImpl {
return &AnalyticsServiceImpl{
repository: repository,
logger: logger,
}
}
// GetRevenueByCurrency calculates revenue breakdown by currency
func (s *AnalyticsServiceImpl) GetRevenueByCurrency(ctx context.Context, filter *currency.TransactionFilter) (map[string]float64, error) {
if filter == nil {
filter = &currency.TransactionFilter{}
}
filter.Status = currency.TransactionStatusCompleted
transactions, err := s.repository.ListTransactions(ctx, filter)
if err != nil {
s.logger.WithError(err).Error("Failed to get transactions for revenue analysis")
return nil, fmt.Errorf("failed to get transactions: %w", err)
}
revenueByCurrency := make(map[string]float64)
for _, tx := range transactions {
if tx.Type == currency.TransactionTypeSubscription || tx.Type == currency.TransactionTypeUsage || tx.Type == currency.TransactionTypeOverage {
revenueByCurrency[tx.Currency] += tx.Amount
}
}
return revenueByCurrency, nil
}
// GetTransactionVolumeByCurrency calculates transaction volume by currency
func (s *AnalyticsServiceImpl) GetTransactionVolumeByCurrency(ctx context.Context, filter *currency.TransactionFilter) (map[string]int64, error) {
if filter == nil {
filter = &currency.TransactionFilter{}
}
transactions, err := s.repository.ListTransactions(ctx, filter)
if err != nil {
s.logger.WithError(err).Error("Failed to get transactions for volume analysis")
return nil, fmt.Errorf("failed to get transactions: %w", err)
}
volumeByCurrency := make(map[string]int64)
for _, tx := range transactions {
volumeByCurrency[tx.Currency]++
}
return volumeByCurrency, nil
}
// GetExchangeRateTrends retrieves exchange rate trends for a currency pair
func (s *AnalyticsServiceImpl) GetExchangeRateTrends(ctx context.Context, fromCurrency, toCurrency string, days int) ([]*currency.ExchangeRate, error) {
filter := &currency.ExchangeRateFilter{
FromCurrency: fromCurrency,
ToCurrency: toCurrency,
IsValid: &[]bool{false}[0], // Include historical rates
Limit: days,
SortBy: "valid_from",
SortOrder: "desc",
}
rates, err := s.repository.ListExchangeRates(ctx, filter)
if err != nil {
s.logger.WithError(err).Error("Failed to get exchange rate trends")
return nil, fmt.Errorf("failed to get exchange rate trends: %w", err)
}
return rates, nil
}
// GetCurrencyUsageStats retrieves currency usage statistics
func (s *AnalyticsServiceImpl) GetCurrencyUsageStats(ctx context.Context) (*currency.CurrencyUsageStats, error) {
// Get total currencies
totalCurrencies, err := s.repository.CountCurrencies(ctx, &currency.CurrencyFilter{})
if err != nil {
return nil, fmt.Errorf("failed to count currencies: %w", err)
}
// Get active currencies
activeCurrencies, err := s.repository.CountCurrencies(ctx, &currency.CurrencyFilter{
IsActive: &[]bool{true}[0],
})
if err != nil {
return nil, fmt.Errorf("failed to count active currencies: %w", err)
}
// Get total transactions
totalTransactions, err := s.repository.CountTransactions(ctx, &currency.TransactionFilter{})
if err != nil {
return nil, fmt.Errorf("failed to count transactions: %w", err)
}
// Get total volume
transactions, err := s.repository.ListTransactions(ctx, &currency.TransactionFilter{
Status: currency.TransactionStatusCompleted,
})
if err != nil {
return nil, fmt.Errorf("failed to get transactions for volume: %w", err)
}
totalVolume := 0.0
currencyDistribution := make(map[string]int64)
for _, tx := range transactions {
totalVolume += tx.BaseAmount
currencyDistribution[tx.Currency]++
}
// Find most used currency
mostUsedCurrency := ""
maxCount := int64(0)
for currency, count := range currencyDistribution {
if count > maxCount {
maxCount = count
mostUsedCurrency = currency
}
}
// Get exchange rate count (using ListExchangeRates for now since CountExchangeRates doesn't exist)
exchangeRates, err := s.repository.ListExchangeRates(ctx, &currency.ExchangeRateFilter{})
if err != nil {
return nil, fmt.Errorf("failed to count exchange rates: %w", err)
}
return &currency.CurrencyUsageStats{
TotalCurrencies: totalCurrencies,
ActiveCurrencies: activeCurrencies,
TotalTransactions: int64(totalTransactions),
TotalVolume: totalVolume,
MostUsedCurrency: mostUsedCurrency,
CurrencyDistribution: currencyDistribution,
ExchangeRateCount: len(exchangeRates),
LastUpdated: time.Now(),
}, nil
}
// GetMonthlyRevenueTrends calculates monthly revenue trends
func (s *AnalyticsServiceImpl) GetMonthlyRevenueTrends(ctx context.Context, months int) (map[string]float64, error) {
endDate := time.Now()
startDate := endDate.AddDate(0, -months, 0)
filter := &currency.TransactionFilter{
Status: currency.TransactionStatusCompleted,
FromDate: &startDate,
ToDate: &endDate,
}
transactions, err := s.repository.ListTransactions(ctx, filter)
if err != nil {
s.logger.WithError(err).Error("Failed to get transactions for monthly trends")
return nil, fmt.Errorf("failed to get transactions: %w", err)
}
monthlyRevenue := make(map[string]float64)
for _, tx := range transactions {
monthKey := tx.CreatedAt.Format("2006-01")
monthlyRevenue[monthKey] += tx.BaseAmount
}
return monthlyRevenue, nil
}
// GetTopCurrenciesByRevenue returns top currencies by revenue
func (s *AnalyticsServiceImpl) GetTopCurrenciesByRevenue(ctx context.Context, limit int) ([]*currency.CurrencyRevenue, error) {
revenueByCurrency, err := s.GetRevenueByCurrency(ctx, &currency.TransactionFilter{
Status: currency.TransactionStatusCompleted,
})
if err != nil {
return nil, err
}
// Convert to slice and sort
var currencyRevenues []*currency.CurrencyRevenue
for currCode, revenue := range revenueByCurrency {
currencyRevenues = append(currencyRevenues, &currency.CurrencyRevenue{
Currency: currCode,
Revenue: revenue,
})
}
// Simple sort (in production, use proper sorting)
if len(currencyRevenues) > limit {
currencyRevenues = currencyRevenues[:limit]
}
return currencyRevenues, nil
}
// GetTransactionTypeAnalytics returns analytics by transaction type
func (s *AnalyticsServiceImpl) GetTransactionTypeAnalytics(ctx context.Context, filter *currency.TransactionFilter) (map[string]*currency.TransactionTypeStats, error) {
if filter == nil {
filter = &currency.TransactionFilter{}
}
transactions, err := s.repository.ListTransactions(ctx, filter)
if err != nil {
s.logger.WithError(err).Error("Failed to get transactions for type analytics")
return nil, fmt.Errorf("failed to get transactions: %w", err)
}
typeStats := make(map[string]*currency.TransactionTypeStats)
for _, tx := range transactions {
typeKey := string(tx.Type)
if _, exists := typeStats[typeKey]; !exists {
typeStats[typeKey] = &currency.TransactionTypeStats{
Type: tx.Type,
Count: 0,
Amount: 0.0,
Currency: tx.Currency,
}
}
stats := typeStats[typeKey]
stats.Count++
stats.Amount += tx.BaseAmount
}
return typeStats, nil
}