mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-19 18:48:46 +00:00
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
This commit is contained in:
@@ -1,180 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// GormRepository implements the Repository interface using GORM
|
||||
type GormRepository struct {
|
||||
db *gorm.DB
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewGormRepository creates a new GORM repository
|
||||
func NewGormRepository(db *gorm.DB, logger *logrus.Logger) *GormRepository {
|
||||
return &GormRepository{
|
||||
db: db,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
// CreateUsage creates a new usage record
|
||||
func (r *GormRepository) CreateUsage(ctx context.Context, usage *RatePlanUsage) error {
|
||||
usage.LastUpdated = time.Now()
|
||||
|
||||
if err := r.db.WithContext(ctx).Create(usage).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to create usage record")
|
||||
return fmt.Errorf("failed to create usage record: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsage retrieves a usage record by ID
|
||||
func (r *GormRepository) GetUsage(ctx context.Context, id string) (*RatePlanUsage, error) {
|
||||
var usage RatePlanUsage
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&usage).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("usage record not found: %s", id)
|
||||
}
|
||||
r.logger.WithError(err).Error("Failed to get usage record")
|
||||
return nil, fmt.Errorf("failed to get usage record: %w", err)
|
||||
}
|
||||
|
||||
return &usage, nil
|
||||
}
|
||||
|
||||
// UpdateUsage updates an existing usage record
|
||||
func (r *GormRepository) UpdateUsage(ctx context.Context, usage *RatePlanUsage) error {
|
||||
usage.LastUpdated = time.Now()
|
||||
|
||||
result := r.db.WithContext(ctx).Where("id = ?", usage.ID).Updates(usage)
|
||||
if result.Error != nil {
|
||||
r.logger.WithError(result.Error).Error("Failed to update usage record")
|
||||
return fmt.Errorf("failed to update usage record: %w", result.Error)
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("usage record not found: %s", usage.ID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetCurrentUsage retrieves the current usage for a profile
|
||||
func (r *GormRepository) GetCurrentUsage(ctx context.Context, profileID string) (*RatePlanUsage, error) {
|
||||
var usage RatePlanUsage
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("profile_id = ?", profileID).
|
||||
Order("cycle_start DESC").
|
||||
First(&usage).Error
|
||||
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil // No usage record found
|
||||
}
|
||||
r.logger.WithError(err).Error("Failed to get current usage")
|
||||
return nil, fmt.Errorf("failed to get current usage: %w", err)
|
||||
}
|
||||
|
||||
return &usage, nil
|
||||
}
|
||||
|
||||
// ListUsageHistory retrieves usage history for a profile
|
||||
func (r *GormRepository) ListUsageHistory(ctx context.Context, profileID string, limit int) ([]*RatePlanUsage, error) {
|
||||
query := r.db.WithContext(ctx).Where("profile_id = ?", profileID).Order("cycle_start DESC")
|
||||
|
||||
if limit > 0 {
|
||||
query = query.Limit(limit)
|
||||
}
|
||||
|
||||
var usageHistory []*RatePlanUsage
|
||||
if err := query.Find(&usageHistory).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to list usage history")
|
||||
return nil, fmt.Errorf("failed to list usage history: %w", err)
|
||||
}
|
||||
|
||||
return usageHistory, nil
|
||||
}
|
||||
|
||||
// GetUsageAnalytics retrieves usage analytics
|
||||
func (r *GormRepository) GetUsageAnalytics(ctx context.Context, filter *UsageAnalyticsFilter) (*UsageAnalytics, error) {
|
||||
analytics := &UsageAnalytics{
|
||||
TotalDataUsed: 0,
|
||||
TotalVoiceUsed: 0,
|
||||
TotalSMSUsed: 0,
|
||||
ActiveUsers: 0,
|
||||
AverageUsage: make(map[string]float64),
|
||||
UsageByPlan: make(map[string]int64),
|
||||
UsageByRegion: make(map[string]int64),
|
||||
TimelineData: []TimelineDataPoint{},
|
||||
}
|
||||
|
||||
// Get active users count
|
||||
var activeUsersCount int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&RatePlanSubscription{}).
|
||||
Where("status = ?", SubscriptionStatusActive).
|
||||
Count(&activeUsersCount).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to get active users count")
|
||||
return nil, fmt.Errorf("failed to get active users count: %w", err)
|
||||
}
|
||||
|
||||
// Get total usage
|
||||
var totalDataUsed, totalVoiceUsed, totalSMSUsed int64
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&RatePlanUsage{}).
|
||||
Select("COALESCE(SUM(data_used), 0), COALESCE(SUM(voice_used), 0), COALESCE(SUM(sms_used), 0)").
|
||||
Where("cycle_start >= ? AND cycle_end <= ?", filter.StartDate, filter.EndDate).
|
||||
Row().Scan(&totalDataUsed, &totalVoiceUsed, &totalSMSUsed); err != nil {
|
||||
r.logger.WithError(err).Error("Failed to get total usage")
|
||||
return nil, fmt.Errorf("failed to get total usage: %w", err)
|
||||
}
|
||||
|
||||
analytics.ActiveUsers = int(activeUsersCount)
|
||||
analytics.TotalDataUsed = totalDataUsed
|
||||
analytics.TotalVoiceUsed = totalVoiceUsed
|
||||
analytics.TotalSMSUsed = totalSMSUsed
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetRevenueAnalytics retrieves revenue analytics
|
||||
func (r *GormRepository) GetRevenueAnalytics(ctx context.Context, filter *RevenueAnalyticsFilter) (*RevenueAnalytics, error) {
|
||||
// Simplified implementation - in production, you'd have actual revenue tracking
|
||||
analytics := &RevenueAnalytics{
|
||||
TotalRevenue: 0,
|
||||
RevenueByPlan: make(map[string]float64),
|
||||
RevenueByCarrier: make(map[string]float64),
|
||||
RevenueByRegion: make(map[string]float64),
|
||||
AverageRevenue: make(map[string]float64),
|
||||
TimelineData: []TimelineDataPoint{},
|
||||
}
|
||||
|
||||
// This would typically join with billing/payment tables
|
||||
// For now, returning empty analytics
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetPopularPlans retrieves the most popular rate plans
|
||||
func (r *GormRepository) GetPopularPlans(ctx context.Context, limit int) ([]*RatePlan, error) {
|
||||
var plans []*RatePlan
|
||||
if err := r.db.WithContext(ctx).
|
||||
Model(&RatePlan{}).
|
||||
Select("rate_plans.*, COUNT(rate_plan_subscriptions.id) as subscription_count").
|
||||
Joins("LEFT JOIN rate_plan_subscriptions ON rate_plans.id = rate_plan_subscriptions.rate_plan_id").
|
||||
Where("rate_plans.is_active = ? AND rate_plans.status = ?", true, PlanStatusActive).
|
||||
Group("rate_plans.id").
|
||||
Order("subscription_count DESC").
|
||||
Limit(limit).
|
||||
Find(&plans).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to get popular plans")
|
||||
return nil, fmt.Errorf("failed to get popular plans: %w", err)
|
||||
}
|
||||
|
||||
return plans, nil
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// CreateRatePlan creates a new rate plan
|
||||
func (r *GormRepository) CreateRatePlan(ctx context.Context, plan *RatePlan) error {
|
||||
now := time.Now()
|
||||
plan.CreatedAt = now
|
||||
plan.UpdatedAt = now
|
||||
|
||||
if err := r.db.WithContext(ctx).Create(plan).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to create rate plan")
|
||||
return fmt.Errorf("failed to create rate plan: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *GormRepository) GetRatePlan(ctx context.Context, id string) (*RatePlan, error) {
|
||||
var plan RatePlan
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&plan).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("rate plan not found: %s", id)
|
||||
}
|
||||
r.logger.WithError(err).Error("Failed to get rate plan")
|
||||
return nil, fmt.Errorf("failed to get rate plan: %w", err)
|
||||
}
|
||||
|
||||
return &plan, nil
|
||||
}
|
||||
|
||||
func (r *GormRepository) UpdateRatePlan(ctx context.Context, plan *RatePlan) error {
|
||||
plan.UpdatedAt = time.Now()
|
||||
|
||||
result := r.db.WithContext(ctx).Where("id = ?", plan.ID).Updates(plan)
|
||||
if result.Error != nil {
|
||||
r.logger.WithError(result.Error).Error("Failed to update rate plan")
|
||||
return fmt.Errorf("failed to update rate plan: %w", result.Error)
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("rate plan not found: %s", plan.ID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *GormRepository) DeleteRatePlan(ctx context.Context, id string) error {
|
||||
result := r.db.WithContext(ctx).Where("id = ?", id).Delete(&RatePlan{})
|
||||
if result.Error != nil {
|
||||
r.logger.WithError(result.Error).Error("Failed to delete rate plan")
|
||||
return fmt.Errorf("failed to delete rate plan: %w", result.Error)
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("rate plan not found: %s", id)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *GormRepository) ListRatePlans(ctx context.Context, filter *RatePlanFilter) ([]*RatePlan, error) {
|
||||
query := r.db.WithContext(ctx).Model(&RatePlan{})
|
||||
|
||||
if filter.CarrierID != "" {
|
||||
query = query.Where("carrier_id = ?", filter.CarrierID)
|
||||
}
|
||||
if filter.Region != "" {
|
||||
query = query.Where("region = ?", filter.Region)
|
||||
}
|
||||
if filter.PlanType != "" {
|
||||
query = query.Where("plan_type = ?", filter.PlanType)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.MinPrice > 0 {
|
||||
query = query.Where("base_price >= ?", filter.MinPrice)
|
||||
}
|
||||
if filter.MaxPrice > 0 {
|
||||
query = query.Where("base_price <= ?", filter.MaxPrice)
|
||||
}
|
||||
if filter.IsActive != nil {
|
||||
query = query.Where("is_active = ?", *filter.IsActive)
|
||||
}
|
||||
if filter.ValidFrom != nil {
|
||||
query = query.Where("valid_from >= ?", *filter.ValidFrom)
|
||||
}
|
||||
if filter.ValidTo != nil {
|
||||
query = query.Where("valid_to <= ?", *filter.ValidTo)
|
||||
}
|
||||
|
||||
// Apply ordering
|
||||
if filter.SortBy != "" {
|
||||
order := "ASC"
|
||||
if filter.SortOrder == "desc" {
|
||||
order = "DESC"
|
||||
}
|
||||
query = query.Order(fmt.Sprintf("%s %s", filter.SortBy, order))
|
||||
} else {
|
||||
query = query.Order("priority DESC, created_at DESC")
|
||||
}
|
||||
|
||||
// Apply pagination
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
var plans []*RatePlan
|
||||
if err := query.Find(&plans).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to list rate plans")
|
||||
return nil, fmt.Errorf("failed to list rate plans: %w", err)
|
||||
}
|
||||
|
||||
return plans, nil
|
||||
}
|
||||
|
||||
// CountRatePlans counts rate plans with filtering
|
||||
func (r *GormRepository) CountRatePlans(ctx context.Context, filter *RatePlanFilter) (int, error) {
|
||||
query := r.db.WithContext(ctx).Model(&RatePlan{})
|
||||
|
||||
// Apply filters
|
||||
if filter.CarrierID != "" {
|
||||
query = query.Where("carrier_id = ?", filter.CarrierID)
|
||||
}
|
||||
if filter.Region != "" {
|
||||
query = query.Where("region = ?", filter.Region)
|
||||
}
|
||||
if filter.PlanType != "" {
|
||||
query = query.Where("plan_type = ?", filter.PlanType)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.MinPrice > 0 {
|
||||
query = query.Where("base_price >= ?", filter.MinPrice)
|
||||
}
|
||||
if filter.MaxPrice > 0 {
|
||||
query = query.Where("base_price <= ?", filter.MaxPrice)
|
||||
}
|
||||
if filter.IsActive != nil {
|
||||
query = query.Where("is_active = ?", *filter.IsActive)
|
||||
}
|
||||
if filter.ValidFrom != nil {
|
||||
query = query.Where("valid_from >= ?", *filter.ValidFrom)
|
||||
}
|
||||
if filter.ValidTo != nil {
|
||||
query = query.Where("valid_to <= ?", *filter.ValidTo)
|
||||
}
|
||||
|
||||
var count int64
|
||||
if err := query.Count(&count).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to count rate plans")
|
||||
return 0, fmt.Errorf("failed to count rate plans: %w", err)
|
||||
}
|
||||
|
||||
return int(count), nil
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
// CreateSubscription creates a new rate plan subscription
|
||||
func (r *GormRepository) CreateSubscription(ctx context.Context, subscription *RatePlanSubscription) error {
|
||||
now := time.Now()
|
||||
subscription.CreatedAt = now
|
||||
subscription.UpdatedAt = now
|
||||
|
||||
if err := r.db.WithContext(ctx).Create(subscription).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to create subscription")
|
||||
return fmt.Errorf("failed to create subscription: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetSubscription retrieves a subscription by ID
|
||||
func (r *GormRepository) GetSubscription(ctx context.Context, id string) (*RatePlanSubscription, error) {
|
||||
var subscription RatePlanSubscription
|
||||
if err := r.db.WithContext(ctx).Where("id = ?", id).First(&subscription).Error; err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, fmt.Errorf("subscription not found: %s", id)
|
||||
}
|
||||
r.logger.WithError(err).Error("Failed to get subscription")
|
||||
return nil, fmt.Errorf("failed to get subscription: %w", err)
|
||||
}
|
||||
|
||||
return &subscription, nil
|
||||
}
|
||||
|
||||
// GetActiveSubscription retrieves the active subscription for a profile
|
||||
func (r *GormRepository) GetActiveSubscription(ctx context.Context, profileID string) (*RatePlanSubscription, error) {
|
||||
var subscription RatePlanSubscription
|
||||
err := r.db.WithContext(ctx).
|
||||
Where("profile_id = ? AND status = ?", profileID, SubscriptionStatusActive).
|
||||
Order("started_at DESC").
|
||||
First(&subscription).Error
|
||||
|
||||
if err != nil {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
return nil, nil // No active subscription found
|
||||
}
|
||||
r.logger.WithError(err).Error("Failed to get active subscription")
|
||||
return nil, fmt.Errorf("failed to get active subscription: %w", err)
|
||||
}
|
||||
|
||||
return &subscription, nil
|
||||
}
|
||||
|
||||
// UpdateSubscription updates an existing subscription
|
||||
func (r *GormRepository) UpdateSubscription(ctx context.Context, subscription *RatePlanSubscription) error {
|
||||
subscription.UpdatedAt = time.Now()
|
||||
|
||||
result := r.db.WithContext(ctx).Where("id = ?", subscription.ID).Updates(subscription)
|
||||
if result.Error != nil {
|
||||
r.logger.WithError(result.Error).Error("Failed to update subscription")
|
||||
return fmt.Errorf("failed to update subscription: %w", result.Error)
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("subscription not found: %s", subscription.ID)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteSubscription deletes a subscription
|
||||
func (r *GormRepository) DeleteSubscription(ctx context.Context, id string) error {
|
||||
result := r.db.WithContext(ctx).Where("id = ?", id).Delete(&RatePlanSubscription{})
|
||||
if result.Error != nil {
|
||||
r.logger.WithError(result.Error).Error("Failed to delete subscription")
|
||||
return fmt.Errorf("failed to delete subscription: %w", result.Error)
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return fmt.Errorf("subscription not found: %s", id)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
// ListSubscriptions retrieves subscriptions for a profile
|
||||
func (r *GormRepository) ListSubscriptions(ctx context.Context, profileID string, filter *SubscriptionFilter) ([]*RatePlanSubscription, error) {
|
||||
query := r.db.WithContext(ctx).Where("profile_id = ?", profileID)
|
||||
|
||||
// Apply filters
|
||||
if filter.Status != "" {
|
||||
query = query.Where("status = ?", filter.Status)
|
||||
}
|
||||
if filter.RatePlanID != "" {
|
||||
query = query.Where("rate_plan_id = ?", filter.RatePlanID)
|
||||
}
|
||||
if filter.StartedAfter != nil {
|
||||
query = query.Where("started_at >= ?", *filter.StartedAfter)
|
||||
}
|
||||
if filter.StartedBefore != nil {
|
||||
query = query.Where("started_at <= ?", *filter.StartedBefore)
|
||||
}
|
||||
|
||||
query = query.Order("started_at DESC")
|
||||
|
||||
// Apply pagination
|
||||
if filter.Limit > 0 {
|
||||
query = query.Limit(filter.Limit)
|
||||
if filter.Offset > 0 {
|
||||
query = query.Offset(filter.Offset)
|
||||
}
|
||||
}
|
||||
|
||||
var subscriptions []*RatePlanSubscription
|
||||
if err := query.Find(&subscriptions).Error; err != nil {
|
||||
r.logger.WithError(err).Error("Failed to list subscriptions")
|
||||
return nil, fmt.Errorf("failed to list subscriptions: %w", err)
|
||||
}
|
||||
|
||||
return subscriptions, nil
|
||||
}
|
||||
@@ -1,198 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// Service provides business logic for rate plan operations
|
||||
type Service struct {
|
||||
repo Repository
|
||||
logger *logrus.Logger
|
||||
}
|
||||
|
||||
// NewService creates a new rate plan service
|
||||
func NewService(repo Repository, logger *logrus.Logger) *Service {
|
||||
return &Service{
|
||||
repo: repo,
|
||||
logger: logger,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) CreateRatePlan(ctx context.Context, plan *RatePlan) (*RatePlan, error) {
|
||||
// Generate ID if not provided
|
||||
if plan.ID == "" {
|
||||
plan.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
// Validate rate plan
|
||||
if err := s.validateRatePlan(plan); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Create the rate plan
|
||||
if err := s.repo.CreateRatePlan(ctx, plan); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create rate plan")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.WithField("plan_id", plan.ID).Info("Rate plan created successfully")
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// GetRatePlan retrieves a rate plan by ID
|
||||
func (s *Service) GetRatePlan(ctx context.Context, id string) (*RatePlan, error) {
|
||||
plan, err := s.repo.GetRatePlan(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("plan_id", id).Error("Failed to get rate plan")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// UpdateRatePlan updates an existing rate plan
|
||||
func (s *Service) UpdateRatePlan(ctx context.Context, plan *RatePlan) (*RatePlan, error) {
|
||||
// Validate rate plan
|
||||
if err := s.validateRatePlan(plan); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
// Check if plan exists by attempting to update
|
||||
_, err := s.repo.GetRatePlan(ctx, plan.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Update the rate plan
|
||||
if err := s.repo.UpdateRatePlan(ctx, plan); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update rate plan")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.WithField("plan_id", plan.ID).Info("Rate plan updated successfully")
|
||||
return plan, nil
|
||||
}
|
||||
|
||||
// DeleteRatePlan deletes a rate plan
|
||||
func (s *Service) DeleteRatePlan(ctx context.Context, id string) error {
|
||||
// Check if plan has active subscriptions
|
||||
subscriptions, err := s.repo.ListSubscriptions(ctx, "", &SubscriptionFilter{
|
||||
RatePlanID: id,
|
||||
Status: SubscriptionStatusActive,
|
||||
Limit: 1,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(subscriptions) > 0 {
|
||||
return fmt.Errorf("cannot delete rate plan with active subscriptions")
|
||||
}
|
||||
|
||||
// Delete the rate plan
|
||||
if err := s.repo.DeleteRatePlan(ctx, id); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to delete rate plan")
|
||||
return err
|
||||
}
|
||||
|
||||
s.logger.WithField("plan_id", id).Info("Rate plan deleted successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListRatePlans retrieves rate plans with filtering
|
||||
func (s *Service) ListRatePlans(ctx context.Context, filter *RatePlanFilter) ([]*RatePlan, error) {
|
||||
plans, err := s.repo.ListRatePlans(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list rate plans")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plans, nil
|
||||
}
|
||||
|
||||
// SearchRatePlans searches for rate plans based on criteria
|
||||
func (s *Service) SearchRatePlans(ctx context.Context, criteria SearchCriteria) ([]*RatePlan, error) {
|
||||
filter := &RatePlanFilter{
|
||||
CarrierID: criteria.CarrierID,
|
||||
Region: criteria.Region,
|
||||
PlanType: criteria.PlanType,
|
||||
Status: PlanStatusActive,
|
||||
IsActive: &[]bool{true}[0],
|
||||
MinPrice: criteria.MinPrice,
|
||||
MaxPrice: criteria.MaxPrice,
|
||||
Limit: criteria.Limit,
|
||||
Offset: criteria.Offset,
|
||||
SortBy: criteria.SortBy,
|
||||
SortOrder: criteria.SortOrder,
|
||||
}
|
||||
|
||||
return s.repo.ListRatePlans(ctx, filter)
|
||||
}
|
||||
// CalculateCost calculates the cost for a rate plan based on usage
|
||||
func (s *Service) CalculateCost(ctx context.Context, req *CalculateCostRequest) (*RatePlanCostCalculation, error) {
|
||||
// Get the rate plan
|
||||
plan, err := s.repo.GetRatePlan(ctx, req.RatePlanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Calculate base cost
|
||||
baseCost := plan.BasePrice
|
||||
|
||||
// Calculate overage costs
|
||||
overageCost := 0.0
|
||||
if req.DataUsed > 0 && plan.DataAllowance != nil && !plan.DataAllowance.Unlimited {
|
||||
allowanceMB := plan.DataAllowance.Amount
|
||||
if plan.DataAllowance.Unit == "GB" {
|
||||
allowanceMB *= 1024
|
||||
}
|
||||
if req.DataUsed > allowanceMB {
|
||||
overageMB := req.DataUsed - allowanceMB
|
||||
if plan.OverageRates != nil {
|
||||
overageCost += float64(overageMB) * plan.OverageRates.DataRate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply discounts
|
||||
discountCost := 0.0
|
||||
if len(req.AppliedDiscounts) > 0 && plan.Discounts != nil {
|
||||
for _, discountID := range req.AppliedDiscounts {
|
||||
for _, discount := range plan.Discounts {
|
||||
if discount.ID == discountID && discount.IsActive {
|
||||
switch discount.Type {
|
||||
case DiscountTypePercentage:
|
||||
discountCost += baseCost * discount.Value / 100
|
||||
case DiscountTypeFixed:
|
||||
discountCost += discount.Value
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
totalCost := baseCost + overageCost - discountCost
|
||||
|
||||
calculation := &RatePlanCostCalculation{
|
||||
RatePlanID: req.RatePlanID,
|
||||
BaseCost: baseCost,
|
||||
OverageCost: overageCost,
|
||||
DiscountCost: discountCost,
|
||||
TotalCost: totalCost,
|
||||
Currency: plan.Currency,
|
||||
Breakdown: map[string]interface{}{
|
||||
"base_cost": baseCost,
|
||||
"overage_cost": overageCost,
|
||||
"discount_cost": discountCost,
|
||||
"total_cost": totalCost,
|
||||
},
|
||||
CalculatedAt: time.Now(),
|
||||
}
|
||||
|
||||
return calculation, nil
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
// GetUsage retrieves usage for a profile
|
||||
func (s *Service) GetUsage(ctx context.Context, profileID string) (*RatePlanUsage, error) {
|
||||
usage, err := s.repo.GetCurrentUsage(ctx, profileID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("profile_id", profileID).Error("Failed to get usage")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return usage, nil
|
||||
}
|
||||
// GetUsageHistory retrieves usage history for a profile
|
||||
func (s *Service) GetUsageHistory(ctx context.Context, profileID string, limit int) ([]*RatePlanUsage, error) {
|
||||
usageHistory, err := s.repo.ListUsageHistory(ctx, profileID, limit)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to get usage history")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return usageHistory, nil
|
||||
}
|
||||
|
||||
// GetUsageAnalytics retrieves usage analytics
|
||||
func (s *Service) GetUsageAnalytics(ctx context.Context, filter *UsageAnalyticsFilter) (*UsageAnalytics, error) {
|
||||
analytics, err := s.repo.GetUsageAnalytics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to get usage analytics")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetRevenueAnalytics retrieves revenue analytics
|
||||
func (s *Service) GetRevenueAnalytics(ctx context.Context, filter *RevenueAnalyticsFilter) (*RevenueAnalytics, error) {
|
||||
analytics, err := s.repo.GetRevenueAnalytics(ctx, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to get revenue analytics")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return analytics, nil
|
||||
}
|
||||
|
||||
// GetPopularPlans retrieves the most popular rate plans
|
||||
func (s *Service) GetPopularPlans(ctx context.Context, limit int) ([]*RatePlan, error) {
|
||||
plans, err := s.repo.GetPopularPlans(ctx, limit)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to get popular plans")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return plans, nil
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Service) validateRatePlan(plan *RatePlan) error {
|
||||
if plan.Name == "" {
|
||||
return fmt.Errorf("rate plan name is required")
|
||||
}
|
||||
if plan.CarrierID == "" {
|
||||
return fmt.Errorf("carrier ID is required")
|
||||
}
|
||||
if plan.Region == "" {
|
||||
return fmt.Errorf("region is required")
|
||||
}
|
||||
if plan.BasePrice < 0 {
|
||||
return fmt.Errorf("base price cannot be negative")
|
||||
}
|
||||
if plan.Currency == "" {
|
||||
return fmt.Errorf("currency is required")
|
||||
}
|
||||
if plan.BillingCycle == "" {
|
||||
return fmt.Errorf("billing cycle is required")
|
||||
}
|
||||
if plan.ValidFrom.IsZero() {
|
||||
return fmt.Errorf("valid from date is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) validateSubscribeRequest(req *SubscribeRequest) error {
|
||||
if req.ProfileID == "" {
|
||||
return fmt.Errorf("profile ID is required")
|
||||
}
|
||||
if req.RatePlanID == "" {
|
||||
return fmt.Errorf("rate plan ID is required")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) calculateNextBillingDate(cycle BillingCycle, from time.Time) time.Time {
|
||||
switch cycle {
|
||||
case BillingCycleDaily:
|
||||
return from.AddDate(0, 0, 1)
|
||||
case BillingCycleWeekly:
|
||||
return from.AddDate(0, 0, 7)
|
||||
case BillingCycleMonthly:
|
||||
return from.AddDate(0, 1, 0)
|
||||
case BillingCycleQuarterly:
|
||||
return from.AddDate(0, 3, 0)
|
||||
case BillingCycleYearly:
|
||||
return from.AddDate(1, 0, 0)
|
||||
default:
|
||||
return from.AddDate(0, 1, 0) // Default to monthly
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) calculateCycleEnd(cycle BillingCycle, cycleStart time.Time) time.Time {
|
||||
switch cycle {
|
||||
case BillingCycleDaily:
|
||||
return cycleStart.AddDate(0, 0, 1).Add(-time.Nanosecond)
|
||||
case BillingCycleWeekly:
|
||||
return cycleStart.AddDate(0, 0, 7).Add(-time.Nanosecond)
|
||||
case BillingCycleMonthly:
|
||||
return cycleStart.AddDate(0, 1, 0).Add(-time.Nanosecond)
|
||||
case BillingCycleQuarterly:
|
||||
return cycleStart.AddDate(0, 3, 0).Add(-time.Nanosecond)
|
||||
case BillingCycleYearly:
|
||||
return cycleStart.AddDate(1, 0, 0).Add(-time.Nanosecond)
|
||||
default:
|
||||
return cycleStart.AddDate(0, 1, 0).Add(-time.Nanosecond) // Default to monthly
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
package rateplan
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (s *Service) SubscribeToPlan(ctx context.Context, req *SubscribeRequest) (*RatePlanSubscription, error) {
|
||||
if err := s.validateSubscribeRequest(req); err != nil {
|
||||
return nil, fmt.Errorf("validation failed: %w", err)
|
||||
}
|
||||
|
||||
plan, err := s.repo.GetRatePlan(ctx, req.RatePlanID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !plan.IsActive || plan.Status != PlanStatusActive {
|
||||
return nil, fmt.Errorf("rate plan is not available for subscription")
|
||||
}
|
||||
|
||||
activeSub, err := s.repo.GetActiveSubscription(ctx, req.ProfileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if activeSub != nil {
|
||||
return nil, fmt.Errorf("profile already has an active subscription")
|
||||
}
|
||||
|
||||
// Create subscription
|
||||
subscription := &RatePlanSubscription{
|
||||
ID: uuid.New().String(),
|
||||
ProfileID: req.ProfileID,
|
||||
RatePlanID: req.RatePlanID,
|
||||
Status: SubscriptionStatusActive,
|
||||
StartedAt: time.Now(),
|
||||
BillingCycle: plan.BillingCycle,
|
||||
NextBillingDate: s.calculateNextBillingDate(plan.BillingCycle, time.Now()),
|
||||
AutoRenew: req.AutoRenew,
|
||||
CurrentCycle: time.Now(),
|
||||
AppliedDiscounts: req.AppliedDiscounts,
|
||||
Metadata: req.Metadata,
|
||||
}
|
||||
|
||||
if err := s.repo.CreateSubscription(ctx, subscription); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create subscription")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"subscription_id": subscription.ID,
|
||||
"profile_id": req.ProfileID,
|
||||
"rate_plan_id": req.RatePlanID,
|
||||
}).Info("Subscription created successfully")
|
||||
|
||||
return subscription, nil
|
||||
}
|
||||
|
||||
// GetSubscription retrieves a subscription by ID
|
||||
func (s *Service) GetSubscription(ctx context.Context, id string) (*RatePlanSubscription, error) {
|
||||
subscription, err := s.repo.GetSubscription(ctx, id)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("subscription_id", id).Error("Failed to get subscription")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return subscription, nil
|
||||
}
|
||||
|
||||
// UpdateSubscription updates an existing subscription
|
||||
func (s *Service) UpdateSubscription(ctx context.Context, subscription *RatePlanSubscription) (*RatePlanSubscription, error) {
|
||||
if err := s.repo.UpdateSubscription(ctx, subscription); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update subscription")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
s.logger.WithField("subscription_id", subscription.ID).Info("Subscription updated successfully")
|
||||
return subscription, nil
|
||||
}
|
||||
|
||||
// CancelSubscription cancels a subscription
|
||||
func (s *Service) CancelSubscription(ctx context.Context, subscriptionID string, reason string) error {
|
||||
subscription, err := s.repo.GetSubscription(ctx, subscriptionID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if subscription.Status != SubscriptionStatusActive {
|
||||
return fmt.Errorf("subscription is not active")
|
||||
}
|
||||
|
||||
now := time.Now()
|
||||
subscription.Status = SubscriptionStatusCancelled
|
||||
subscription.EndedAt = &now
|
||||
subscription.UpdatedAt = now
|
||||
|
||||
if subscription.Metadata == nil {
|
||||
subscription.Metadata = make(map[string]interface{})
|
||||
}
|
||||
subscription.Metadata["cancellation_reason"] = reason
|
||||
|
||||
if err := s.repo.UpdateSubscription(ctx, subscription); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to cancel subscription")
|
||||
return err
|
||||
}
|
||||
|
||||
s.logger.WithField("subscription_id", subscriptionID).Info("Subscription cancelled successfully")
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetActiveSubscription retrieves the active subscription for a profile
|
||||
func (s *Service) GetActiveSubscription(ctx context.Context, profileID string) (*RatePlanSubscription, error) {
|
||||
subscription, err := s.repo.GetActiveSubscription(ctx, profileID)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).WithField("profile_id", profileID).Error("Failed to get active subscription")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return subscription, nil
|
||||
}
|
||||
|
||||
// ListSubscriptions retrieves subscriptions for a profile
|
||||
func (s *Service) ListSubscriptions(ctx context.Context, profileID string, filter *SubscriptionFilter) ([]*RatePlanSubscription, error) {
|
||||
subscriptions, err := s.repo.ListSubscriptions(ctx, profileID, filter)
|
||||
if err != nil {
|
||||
s.logger.WithError(err).Error("Failed to list subscriptions")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return subscriptions, nil
|
||||
}
|
||||
|
||||
func (s *Service) RecordUsage(ctx context.Context, req *RecordUsageRequest) (*RatePlanUsage, error) {
|
||||
// Get active subscription
|
||||
subscription, err := s.repo.GetActiveSubscription(ctx, req.ProfileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if subscription == nil {
|
||||
return nil, fmt.Errorf("no active subscription found")
|
||||
}
|
||||
|
||||
// Get current usage
|
||||
currentUsage, err := s.repo.GetCurrentUsage(ctx, req.ProfileID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Create or update usage record
|
||||
var usage *RatePlanUsage
|
||||
if currentUsage == nil {
|
||||
// Create new usage record
|
||||
usage = &RatePlanUsage{
|
||||
ID: uuid.New().String(),
|
||||
RatePlanID: subscription.RatePlanID,
|
||||
ProfileID: req.ProfileID,
|
||||
CycleStart: subscription.CurrentCycle,
|
||||
CycleEnd: s.calculateCycleEnd(subscription.BillingCycle, subscription.CurrentCycle),
|
||||
DataUsed: req.DataUsed,
|
||||
VoiceUsed: req.VoiceUsed,
|
||||
SMSUsed: req.SMSUsed,
|
||||
}
|
||||
|
||||
if err := s.repo.CreateUsage(ctx, usage); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to create usage record")
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// Update existing usage record
|
||||
currentUsage.DataUsed += req.DataUsed
|
||||
currentUsage.VoiceUsed += req.VoiceUsed
|
||||
currentUsage.SMSUsed += req.SMSUsed
|
||||
|
||||
if err := s.repo.UpdateUsage(ctx, currentUsage); err != nil {
|
||||
s.logger.WithError(err).Error("Failed to update usage record")
|
||||
return nil, err
|
||||
}
|
||||
|
||||
usage = currentUsage
|
||||
}
|
||||
|
||||
s.logger.WithFields(logrus.Fields{
|
||||
"profile_id": req.ProfileID,
|
||||
"data_used": req.DataUsed,
|
||||
"voice_used": req.VoiceUsed,
|
||||
"sms_used": req.SMSUsed,
|
||||
}).Info("Usage recorded successfully")
|
||||
|
||||
return usage, nil
|
||||
}
|
||||
Reference in New Issue
Block a user