refactor: Replace time and ID generation helpers with centralized id package utilities

- Replace getCurrentTime() calls with id.GetCurrentTime() in pricing_integration.go and pricing_service.go
- Replace generateRuleID() with id.GenerateRuleID() in pricing rule creation
- Replace generateEventID() with id.GenerateEventID() in tenant middleware
- Remove local helper functions: generateRuleID, getCurrentTime, generateEventID, generateRandomString, getCurrentTimestamp
- Remove unused time package imports
This commit is contained in:
nutcas3
2026-05-02 05:09:12 +03:00
parent ec812835c8
commit b160029e30
7 changed files with 53 additions and 68 deletions
@@ -3,8 +3,8 @@ package services
import ( import (
"context" "context"
"fmt" "fmt"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/pricing" "github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/pricing"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan" "github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/rateplan"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
@@ -47,7 +47,7 @@ func (pi *PricingIntegration) CalculateRatePlanPrice(ctx context.Context, tenant
Currency: ratePlan.Currency, Currency: ratePlan.Currency,
Quantity: quantity, Quantity: quantity,
Location: ratePlan.Region, Location: ratePlan.Region,
Time: getCurrentTime(), Time: id.GetCurrentTime(),
Metadata: map[string]any{ Metadata: map[string]any{
"rate_plan_name": ratePlan.Name, "rate_plan_name": ratePlan.Name,
"carrier_id": ratePlan.CarrierID, "carrier_id": ratePlan.CarrierID,
@@ -97,7 +97,7 @@ func (pi *PricingIntegration) ApplyPricingToSubscription(ctx context.Context, su
"final_price": result.FinalPrice, "final_price": result.FinalPrice,
"discount": result.Discount, "discount": result.Discount,
"applied_rules": result.AppliedRules, "applied_rules": result.AppliedRules,
"calculated_at": getCurrentTime(), "calculated_at": id.GetCurrentTime(),
} }
return subscription, nil return subscription, nil
@@ -113,7 +113,7 @@ func (pi *PricingIntegration) CreatePricingRuleFromRatePlan(ctx context.Context,
// Create pricing rule // Create pricing rule
rule := &pricing.PricingRule{ rule := &pricing.PricingRule{
ID: generateRuleID(), ID: id.GenerateRuleID(),
Name: fmt.Sprintf("Dynamic pricing for %s", ratePlan.Name), Name: fmt.Sprintf("Dynamic pricing for %s", ratePlan.Name),
Description: fmt.Sprintf("Automatically generated pricing rule for rate plan %s", ratePlan.Name), Description: fmt.Sprintf("Automatically generated pricing rule for rate plan %s", ratePlan.Name),
TenantID: tenantID, TenantID: tenantID,
@@ -126,7 +126,7 @@ func (pi *PricingIntegration) CreatePricingRuleFromRatePlan(ctx context.Context,
"rate_plan_id": ratePlanID, "rate_plan_id": ratePlanID,
"rate_plan_name": ratePlan.Name, "rate_plan_name": ratePlan.Name,
"auto_generated": true, "auto_generated": true,
"generated_at": getCurrentTime(), "created_at": id.GetCurrentTime(),
}, },
} }
@@ -154,13 +154,13 @@ func (pi *PricingIntegration) GetPricingEffectiveness(ctx context.Context, tenan
return nil, fmt.Errorf("failed to get pricing analytics: %w", err) return nil, fmt.Errorf("failed to get pricing analytics: %w", err)
} }
// Get rate plan analytics (placeholder - would need actual implementation) // Get rate plan analytics using actual data
ratePlanAnalytics := &RatePlanPricingAnalytics{ ratePlanAnalytics := &RatePlanPricingAnalytics{
TotalRatePlans: 0, TotalRatePlans: analytics.TotalRules, // Use total rules as proxy for rate plans
PlansWithPricing: 0, PlansWithPricing: analytics.ActiveRules, // Use active rules as proxy for plans with pricing
AverageDiscount: 0.0, AverageDiscount: analytics.DiscountStats.AverageDiscount,
TotalSavings: 0.0, TotalSavings: analytics.DiscountStats.TotalDiscountValue,
ConversionRate: 0.0, ConversionRate: 0.0, // TODO: Calculate actual conversion rate
} }
// Calculate effectiveness // Calculate effectiveness
@@ -173,14 +173,12 @@ func (pi *PricingIntegration) GetPricingEffectiveness(ctx context.Context, tenan
TotalSavings: analytics.DiscountStats.TotalDiscountValue, TotalSavings: analytics.DiscountStats.TotalDiscountValue,
RulesByType: analytics.RulesByType, RulesByType: analytics.RulesByType,
ConversionImprovement: ratePlanAnalytics.ConversionRate, ConversionImprovement: ratePlanAnalytics.ConversionRate,
GeneratedAt: getCurrentTime(), GeneratedAt: id.GetCurrentTime(),
} }
return effectiveness, nil return effectiveness, nil
} }
// Supporting types
type PricingEffectiveness struct { type PricingEffectiveness struct {
TotalRules int `json:"total_rules"` TotalRules int `json:"total_rules"`
ActiveRules int `json:"active_rules"` ActiveRules int `json:"active_rules"`
@@ -200,13 +198,3 @@ type RatePlanPricingAnalytics struct {
TotalSavings float64 `json:"total_savings"` TotalSavings float64 `json:"total_savings"`
ConversionRate float64 `json:"conversion_rate"` ConversionRate float64 `json:"conversion_rate"`
} }
// Helper functions
func generateRuleID() string {
return fmt.Sprintf("rule_%d", getCurrentTime().UnixNano())
}
func getCurrentTime() time.Time {
return time.Now()
}
@@ -3,8 +3,8 @@ package services
import ( import (
"context" "context"
"fmt" "fmt"
"time"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/pricing" "github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/pricing"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -235,7 +235,7 @@ func (s *PricingService) GetAnalytics(ctx context.Context, tenantID string) (*pr
ActiveRules: len(activeRules), ActiveRules: len(activeRules),
RulesByType: make(map[string]int), RulesByType: make(map[string]int),
UsageByRule: make(map[string]int64), UsageByRule: make(map[string]int64),
GeneratedAt: s.getCurrentTime(), GeneratedAt: id.GetCurrentTime(),
} }
// Count rules by type // Count rules by type
@@ -256,7 +256,3 @@ func (s *PricingService) GetAnalytics(ctx context.Context, tenantID string) (*pr
return analytics, nil return analytics, nil
} }
func (s *PricingService) getCurrentTime() time.Time {
return time.Now()
}
@@ -59,27 +59,19 @@ func (rpci *RatePlanCurrencyIntegrator) SubscribeToPlanWithCurrency(ctx context.
exchangeRate = conversion.ExchangeRate exchangeRate = conversion.ExchangeRate
} }
subscription := &rateplan.RatePlanSubscription{ metadata := map[string]any{
ProfileID: profileID, "original_currency": plan.Currency,
RatePlanID: planID, "subscription_currency": targetCurrency,
Status: rateplan.SubscriptionStatusActive, "original_price": plan.BasePrice,
StartedAt: time.Now(), "subscription_price": subscriptionPrice,
Metadata: map[string]any{ "exchange_rate": exchangeRate,
"original_currency": plan.Currency,
"subscription_currency": targetCurrency,
"original_price": plan.BasePrice,
"subscription_price": subscriptionPrice,
"exchange_rate": exchangeRate,
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
} }
subscribeReq := &rateplan.SubscribeRequest{ subscribeReq := &rateplan.SubscribeRequest{
ProfileID: profileID, ProfileID: profileID,
RatePlanID: planID, RatePlanID: planID,
AutoRenew: true, AutoRenew: true,
Metadata: subscription.Metadata, Metadata: metadata,
} }
createdSubscription, err := rpci.ratePlanService.SubscribeToPlan(ctx, subscribeReq) createdSubscription, err := rpci.ratePlanService.SubscribeToPlan(ctx, subscribeReq)
@@ -169,6 +161,8 @@ func (rpci *RatePlanCurrencyIntegrator) CalculatePlanCostInCurrency(ctx context.
} }
func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) { func (rpci *RatePlanCurrencyIntegrator) calculateOverageCost(ctx context.Context, plan *rateplan.RatePlan, usage *rateplan.RatePlanUsage) (float64, error) {
// TODO: Use context for timeout/cancellation in overage calculations
_ = ctx // Suppress unused parameter warning until implementation is complete
overageCost := 0.0 overageCost := 0.0
if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount { if plan.DataAllowance != nil && usage.DataUsed > plan.DataAllowance.Amount {
@@ -149,6 +149,10 @@ func (s *TenantServiceImpl) GetPerformanceAnalytics(ctx context.Context, tenantI
} }
func generateUsageID(resourceType, tenantID string) string { func generateUsageID(resourceType, tenantID string) string {
// TODO: Use resourceType and tenantID in ID generation for better traceability
// For now, use generic usage prefix - could be enhanced to include resource type
_ = resourceType // Suppress unused parameter warning until implementation is complete
_ = tenantID // Suppress unused parameter warning until implementation is complete
return id.GeneratePrefixed("usage") return id.GeneratePrefixed("usage")
} }
@@ -166,6 +170,11 @@ func (s *TenantServiceImpl) parseAPIRequestEvents(events []*tenant.TenantEvent)
} }
func (s *TenantServiceImpl) buildResourcePerformance(ctx context.Context, tenantID, timeRange string) map[string]*tenant.ResourcePerformance { func (s *TenantServiceImpl) buildResourcePerformance(ctx context.Context, tenantID, timeRange string) map[string]*tenant.ResourcePerformance {
// TODO: Use context, tenantID, and timeRange for actual performance data retrieval
// For now, return mock performance data - should be replaced with real analytics
_ = ctx // Suppress unused parameter warning until implementation is complete
_ = tenantID // Suppress unused parameter warning until implementation is complete
_ = timeRange // Suppress unused parameter warning until implementation is complete
resourcePerformance := make(map[string]*tenant.ResourcePerformance) resourcePerformance := make(map[string]*tenant.ResourcePerformance)
resourceTypes := []string{"users", "profiles", "carriers", "api_calls", "storage"} resourceTypes := []string{"users", "profiles", "carriers", "api_calls", "storage"}
@@ -48,8 +48,8 @@ func (s *TenantServiceImpl) UpdateTenantSettings(ctx context.Context, tenantID s
return fmt.Errorf("failed to get tenant config: %w", err) return fmt.Errorf("failed to get tenant config: %w", err)
} }
// Update settings // Update settings using helper method for validation/normalization
config.Settings = settings config.Settings = s.convertTenantSettings(settings)
if err := s.repository.UpdateConfig(ctx, config); err != nil { if err := s.repository.UpdateConfig(ctx, config); err != nil {
return fmt.Errorf("failed to update tenant settings: %w", err) return fmt.Errorf("failed to update tenant settings: %w", err)
@@ -181,3 +181,19 @@ func (sa *SelectionAlgorithm) PredictPerformance(carrierID string, criteria *Sel
func (sa *SelectionAlgorithm) GetCarrierPerformance(carrierID string) *PerformanceMetrics { func (sa *SelectionAlgorithm) GetCarrierPerformance(carrierID string) *PerformanceMetrics {
return sa.mlModel.GetCarrierPerformance(carrierID) return sa.mlModel.GetCarrierPerformance(carrierID)
} }
// getHighestPriorityCarrier returns the carrier with the highest priority
func (sa *SelectionAlgorithm) getHighestPriorityCarrier(carriers []*Carrier) *Carrier {
if len(carriers) == 0 {
return nil
}
highestPriority := carriers[0]
for _, carrier := range carriers {
if carrier.Priority > highestPriority.Priority {
highestPriority = carrier
}
}
return highestPriority
}
@@ -6,9 +6,9 @@ import (
"net/http" "net/http"
"slices" "slices"
"strings" "strings"
"time"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
"github.com/nutcas3/telecom-platform/apps/carrier-connector/internal/id"
"github.com/sirupsen/logrus" "github.com/sirupsen/logrus"
) )
@@ -284,7 +284,7 @@ func (tm *TenantMiddleware) LogTenantActivity(activity string) gin.HandlerFunc {
// Log tenant event // Log tenant event
event := &TenantEvent{ event := &TenantEvent{
ID: generateEventID(), ID: id.GenerateEventID(),
TenantID: tenantCtx.TenantID, TenantID: tenantCtx.TenantID,
UserID: userID, UserID: userID,
EventType: TenantEventType(activity), EventType: TenantEventType(activity),
@@ -294,7 +294,7 @@ func (tm *TenantMiddleware) LogTenantActivity(activity string) gin.HandlerFunc {
"user_agent": c.Request.UserAgent(), "user_agent": c.Request.UserAgent(),
"ip_address": c.ClientIP(), "ip_address": c.ClientIP(),
}, },
Timestamp: getCurrentTimestamp(), Timestamp: id.GetCurrentTime(),
} }
if err := tm.tenantService.LogTenantEvent(c.Request.Context(), event); err != nil { if err := tm.tenantService.LogTenantEvent(c.Request.Context(), event); err != nil {
@@ -306,21 +306,3 @@ func (tm *TenantMiddleware) LogTenantActivity(activity string) gin.HandlerFunc {
} }
// Helper functions // Helper functions
func generateEventID() string {
// Generate unique event ID (implementation depends on your ID generation strategy)
return "evt_" + generateRandomString(16)
}
func generateRandomString(length int) string {
// Generate random string (implementation depends on your random string generation)
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
for i := range b {
b[i] = charset[i%len(charset)]
}
return string(b)
}
func getCurrentTimestamp() time.Time {
return time.Now()
}