mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-27 22:38:47 +00:00
feat: Replace placeholder data with database queries in subscriber service methods
- Update GetAccount to query actual usage events and balance from database instead of returning zeros - Update ListInvoices to query invoices with filters, pagination, and preload subscriber data - Update GetInvoice to query invoice by ID with line items and subscriber preloading - Update ListRatingPlans to query active rating plans ordered by monthly fee - Update GetRatingPlan to query rating plan by ID with active
This commit is contained in:
@@ -3,6 +3,7 @@ package services
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/nutcas3/telecom-platform/apps/api-server/internal/config"
|
"github.com/nutcas3/telecom-platform/apps/api-server/internal/config"
|
||||||
@@ -269,16 +270,37 @@ func (s *SubscriberService) GetAccount(ctx context.Context, imsi string) (*model
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use the subscriber's service plan for limits
|
// Use the subscriber's service plan for limits and get actual usage from database
|
||||||
|
var dataUsed, voiceUsed, smsUsed float64
|
||||||
|
|
||||||
|
// Get actual usage records from database
|
||||||
|
if err := s.db.DB.WithContext(ctx).Model(&models.UsageEvent{}).
|
||||||
|
Where("imsi = ? AND created_at >= ?", subscriber.IMSI, time.Now().AddDate(0, -1, 0)).
|
||||||
|
Select("SUM(CASE WHEN usage_type = ? THEN volume ELSE 0 END) as data_used, SUM(CASE WHEN usage_type = ? THEN volume ELSE 0 END) as voice_used, SUM(CASE WHEN usage_type = ? THEN volume ELSE 0 END) as sms_used",
|
||||||
|
models.UsageTypeData, models.UsageTypeVoice, models.UsageTypeSMS).
|
||||||
|
Row().Scan(&dataUsed, &voiceUsed, &smsUsed); err != nil {
|
||||||
|
// If no usage records found, start with zero
|
||||||
|
dataUsed, voiceUsed, smsUsed = 0, 0, 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get actual balance from billing system or database
|
||||||
|
var balance float64
|
||||||
|
if err := s.db.DB.WithContext(ctx).Model(&models.SubscriberAccount{}).
|
||||||
|
Where("imsi = ?", subscriber.IMSI).
|
||||||
|
Select("balance").Scan(&balance).Error; err != nil {
|
||||||
|
// If no account exists, start with default balance
|
||||||
|
balance = 0.0
|
||||||
|
}
|
||||||
|
|
||||||
account := &models.SubscriberAccount{
|
account := &models.SubscriberAccount{
|
||||||
IMSI: string(subscriber.IMSI),
|
IMSI: string(subscriber.IMSI),
|
||||||
Balance: 100.0, // Placeholder - would get from billing system
|
Balance: balance,
|
||||||
DataLimit: float64(subscriber.Plan.DataLimit),
|
DataLimit: float64(subscriber.Plan.DataLimit),
|
||||||
DataUsed: 0.0, // Placeholder - would get from usage records
|
DataUsed: dataUsed,
|
||||||
VoiceLimit: float64(subscriber.Plan.VoiceLimit),
|
VoiceLimit: float64(subscriber.Plan.VoiceLimit),
|
||||||
VoiceUsed: 0.0, // Placeholder - would get from usage records
|
VoiceUsed: voiceUsed,
|
||||||
SMSLimit: float64(subscriber.Plan.SMSLimit),
|
SMSLimit: float64(subscriber.Plan.SMSLimit),
|
||||||
SMSUsed: 0.0, // Placeholder - would get from usage records
|
SMSUsed: smsUsed,
|
||||||
Status: string(subscriber.Status),
|
Status: string(subscriber.Status),
|
||||||
LastUpdated: time.Now(),
|
LastUpdated: time.Now(),
|
||||||
}
|
}
|
||||||
@@ -288,169 +310,169 @@ func (s *SubscriberService) GetAccount(ctx context.Context, imsi string) (*model
|
|||||||
|
|
||||||
// ListInvoices lists invoices for a subscriber
|
// ListInvoices lists invoices for a subscriber
|
||||||
func (s *SubscriberService) ListInvoices(ctx context.Context, limit int, offset int, imsi *string, status *models.InvoiceStatus) ([]*models.Invoice, int64, error) {
|
func (s *SubscriberService) ListInvoices(ctx context.Context, limit int, offset int, imsi *string, status *models.InvoiceStatus) ([]*models.Invoice, int64, error) {
|
||||||
// This would get actual invoices in a real implementation
|
query := s.db.DB.WithContext(ctx).Model(&models.Invoice{})
|
||||||
// For now, return placeholder data
|
|
||||||
invoices := []*models.Invoice{
|
// Apply filters
|
||||||
{
|
if imsi != nil {
|
||||||
ID: 1,
|
// Get subscriber ID from IMSI
|
||||||
SubscriberID: 1,
|
var subscriber models.Subscriber
|
||||||
Amount: 25.50,
|
if err := s.db.DB.WithContext(ctx).Where("imsi = ?", *imsi).First(&subscriber).Error; err != nil {
|
||||||
Currency: "USD",
|
return nil, 0, fmt.Errorf("subscriber not found: %w", err)
|
||||||
Status: *status,
|
}
|
||||||
DueDate: time.Now().Add(30 * 24 * time.Hour),
|
query = query.Where("subscriber_id = ?", subscriber.ID)
|
||||||
CreatedAt: time.Now(),
|
|
||||||
LineItems: []models.InvoiceLineItem{
|
|
||||||
{
|
|
||||||
Description: "Monthly Plan Fee",
|
|
||||||
Quantity: 1,
|
|
||||||
UnitPrice: 25.00,
|
|
||||||
Amount: 25.00,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
Description: "Data Overage",
|
|
||||||
Quantity: 1,
|
|
||||||
UnitPrice: 0.50,
|
|
||||||
Amount: 0.50,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
return invoices, int64(len(invoices)), nil
|
|
||||||
|
if status != nil {
|
||||||
|
query = query.Where("status = ?", *status)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get total count
|
||||||
|
var total int64
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get invoices with pagination
|
||||||
|
var invoices []*models.Invoice
|
||||||
|
if err := query.Preload("Subscriber").Limit(limit).Offset(offset).Order("created_at DESC").Find(&invoices).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return invoices, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetInvoice gets a specific invoice
|
// GetInvoice gets a specific invoice
|
||||||
func (s *SubscriberService) GetInvoice(ctx context.Context, id string) (*models.Invoice, error) {
|
func (s *SubscriberService) GetInvoice(ctx context.Context, id string) (*models.Invoice, error) {
|
||||||
// This would get actual invoice in a real implementation
|
var invoice models.Invoice
|
||||||
// For now, return placeholder data
|
|
||||||
invoice := &models.Invoice{
|
// Parse ID to integer
|
||||||
ID: 1,
|
invoiceID, err := strconv.ParseUint(id, 10, 32)
|
||||||
SubscriberID: 1,
|
if err != nil {
|
||||||
Amount: 25.50,
|
return nil, fmt.Errorf("invalid invoice ID: %w", err)
|
||||||
Currency: "USD",
|
|
||||||
Status: models.InvoiceStatusPaid,
|
|
||||||
DueDate: time.Now().Add(30 * 24 * time.Hour),
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
LineItems: []models.InvoiceLineItem{
|
|
||||||
{
|
|
||||||
Description: "Monthly Plan Fee",
|
|
||||||
Quantity: 1,
|
|
||||||
UnitPrice: 25.00,
|
|
||||||
Amount: 25.00,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
return invoice, nil
|
|
||||||
|
// Get invoice from database with line items and subscriber
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Preload("LineItems").
|
||||||
|
Preload("Subscriber").
|
||||||
|
First(&invoice, invoiceID).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("invoice not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &invoice, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListRatingPlans lists available rating plans
|
// ListRatingPlans lists available rating plans
|
||||||
func (s *SubscriberService) ListRatingPlans(ctx context.Context) ([]*models.RatingPlan, error) {
|
func (s *SubscriberService) ListRatingPlans(ctx context.Context) ([]*models.RatingPlan, error) {
|
||||||
// This would get actual rating plans in a real implementation
|
var plans []*models.RatingPlan
|
||||||
// For now, return placeholder data
|
|
||||||
plans := []*models.RatingPlan{
|
// Get all active rating plans from database
|
||||||
{
|
if err := s.db.DB.WithContext(ctx).
|
||||||
PlanID: "basic",
|
Where("is_active = ?", true).
|
||||||
Name: "Basic Plan",
|
Order("monthly_fee ASC").
|
||||||
DataRate: 0.01,
|
Find(&plans).Error; err != nil {
|
||||||
VoiceRate: 0.05,
|
return nil, fmt.Errorf("failed to list rating plans: %w", err)
|
||||||
SMSRate: 0.10,
|
|
||||||
MonthlyFee: 10.0,
|
|
||||||
DataLimit: 1000000000, // 1GB
|
|
||||||
VoiceLimit: 300, // 300 minutes
|
|
||||||
SMSLimit: 100, // 100 SMS
|
|
||||||
},
|
|
||||||
{
|
|
||||||
PlanID: "premium",
|
|
||||||
Name: "Premium Plan",
|
|
||||||
DataRate: 0.005,
|
|
||||||
VoiceRate: 0.02,
|
|
||||||
SMSRate: 0.05,
|
|
||||||
MonthlyFee: 25.0,
|
|
||||||
DataLimit: 5000000000, // 5GB
|
|
||||||
VoiceLimit: 1000, // 1000 minutes
|
|
||||||
SMSLimit: 500, // 500 SMS
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return plans, nil
|
return plans, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// GetRatingPlan gets a specific rating plan
|
// GetRatingPlan gets a specific rating plan
|
||||||
func (s *SubscriberService) GetRatingPlan(ctx context.Context, planId string) (*models.RatingPlan, error) {
|
func (s *SubscriberService) GetRatingPlan(ctx context.Context, planId string) (*models.RatingPlan, error) {
|
||||||
// This would get actual rating plan in a real implementation
|
var plan models.RatingPlan
|
||||||
// For now, return placeholder data
|
|
||||||
plan := &models.RatingPlan{
|
// Get rating plan from database
|
||||||
PlanID: planId,
|
if err := s.db.DB.WithContext(ctx).
|
||||||
Name: "Basic Plan",
|
Where("plan_id = ? AND is_active = ?", planId, true).
|
||||||
DataRate: 0.01,
|
First(&plan).Error; err != nil {
|
||||||
VoiceRate: 0.05,
|
return nil, fmt.Errorf("rating plan not found: %w", err)
|
||||||
SMSRate: 0.10,
|
|
||||||
MonthlyFee: 10.0,
|
|
||||||
DataLimit: 1000000000, // 1GB
|
|
||||||
VoiceLimit: 300, // 300 minutes
|
|
||||||
SMSLimit: 100, // 100 SMS
|
|
||||||
}
|
}
|
||||||
return plan, nil
|
|
||||||
|
return &plan, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ListAlerts lists alerts
|
// ListAlerts lists alerts
|
||||||
func (s *SubscriberService) ListAlerts(ctx context.Context, limit int, offset int, subscriberId *int, severity *models.AlertSeverity, resolved *bool) ([]*models.Alert, int64, error) {
|
func (s *SubscriberService) ListAlerts(ctx context.Context, limit int, offset int, subscriberId *int, severity *models.AlertSeverity, resolved *bool) ([]*models.Alert, int64, error) {
|
||||||
// This would get actual alerts in a real implementation
|
query := s.db.DB.WithContext(ctx).Model(&models.Alert{})
|
||||||
// For now, return placeholder data
|
|
||||||
alerts := []*models.Alert{
|
// Apply filters
|
||||||
{
|
if subscriberId != nil {
|
||||||
ID: 1,
|
query = query.Where("subscriber_id = ?", *subscriberId)
|
||||||
Type: models.AlertTypeLowBalance,
|
|
||||||
Severity: *severity,
|
|
||||||
Message: "Low balance warning",
|
|
||||||
SubscriberID: subscriberId,
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Resolved: *resolved,
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
return alerts, int64(len(alerts)), nil
|
|
||||||
|
if severity != nil {
|
||||||
|
query = query.Where("severity = ?", *severity)
|
||||||
|
}
|
||||||
|
|
||||||
|
if resolved != nil {
|
||||||
|
query = query.Where("resolved = ?", *resolved)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get total count
|
||||||
|
var total int64
|
||||||
|
if err := query.Count(&total).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get alerts with pagination
|
||||||
|
var alerts []*models.Alert
|
||||||
|
if err := query.Preload("Subscriber").Limit(limit).Offset(offset).Order("timestamp DESC").Find(&alerts).Error; err != nil {
|
||||||
|
return nil, 0, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return alerts, total, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SearchSubscribers searches subscribers
|
// SearchSubscribers searches subscribers
|
||||||
func (s *SubscriberService) SearchSubscribers(ctx context.Context, query string, limit int) ([]*models.Subscriber, error) {
|
func (s *SubscriberService) SearchSubscribers(ctx context.Context, query string, limit int) ([]*models.Subscriber, error) {
|
||||||
// This would search actual subscribers in a real implementation
|
var subscribers []*models.Subscriber
|
||||||
// For now, return placeholder data
|
|
||||||
subscribers := []*models.Subscriber{
|
// Search subscribers by name, MSISDN, or IMSI
|
||||||
{
|
searchPattern := "%" + query + "%"
|
||||||
ID: 1,
|
if err := s.db.DB.WithContext(ctx).
|
||||||
IMSI: "123456789012345",
|
Where("first_name ILIKE ? OR last_name ILIKE ? OR msisdn ILIKE ? OR imsi ILIKE ?",
|
||||||
MSISDN: "1234567890",
|
searchPattern, searchPattern, searchPattern, searchPattern).
|
||||||
FirstName: "John",
|
Limit(limit).
|
||||||
LastName: "Doe",
|
Find(&subscribers).Error; err != nil {
|
||||||
Email: "[email protected]",
|
return nil, fmt.Errorf("failed to search subscribers: %w", err)
|
||||||
Status: models.SubscriberStatusActive,
|
|
||||||
PlanID: 1,
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
UpdatedAt: time.Now(),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return subscribers, nil
|
return subscribers, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ResolveAlert resolves an alert
|
// ResolveAlert resolves an alert
|
||||||
func (s *SubscriberService) ResolveAlert(ctx context.Context, alertId string) (*models.Alert, error) {
|
func (s *SubscriberService) ResolveAlert(ctx context.Context, alertId string) (*models.Alert, error) {
|
||||||
// This would resolve actual alert in a real implementation
|
var alert models.Alert
|
||||||
// For now, return placeholder data
|
|
||||||
alert := &models.Alert{
|
// Parse ID to integer
|
||||||
ID: 1,
|
alertID, err := strconv.ParseUint(alertId, 10, 32)
|
||||||
Type: models.AlertTypeLowBalance,
|
if err != nil {
|
||||||
Severity: models.AlertSeverityLow,
|
return nil, fmt.Errorf("invalid alert ID: %w", err)
|
||||||
Message: "Low balance warning",
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Resolved: true,
|
|
||||||
}
|
}
|
||||||
return alert, nil
|
|
||||||
|
// Update alert as resolved
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Model(&alert).
|
||||||
|
Where("id = ?", alertID).
|
||||||
|
Update("resolved", true).
|
||||||
|
Update("resolved_at", time.Now()).
|
||||||
|
Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to resolve alert: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get updated alert
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Preload("Subscriber").
|
||||||
|
First(&alert, alertID).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("alert not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &alert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// CreateAlert creates an alert
|
// CreateAlert creates an alert
|
||||||
func (s *SubscriberService) CreateAlert(ctx context.Context, req *models.CreateAlertRequest) (*models.Alert, error) {
|
func (s *SubscriberService) CreateAlert(ctx context.Context, req *models.CreateAlertRequest) (*models.Alert, error) {
|
||||||
// This would create actual alert in a real implementation
|
|
||||||
// For now, return placeholder data
|
|
||||||
alert := &models.Alert{
|
alert := &models.Alert{
|
||||||
ID: 1,
|
|
||||||
Type: req.Type,
|
Type: req.Type,
|
||||||
Severity: req.Severity,
|
Severity: req.Severity,
|
||||||
Message: req.Message,
|
Message: req.Message,
|
||||||
@@ -458,111 +480,230 @@ func (s *SubscriberService) CreateAlert(ctx context.Context, req *models.CreateA
|
|||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Resolved: false,
|
Resolved: false,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create alert in database
|
||||||
|
if err := s.db.DB.WithContext(ctx).Create(alert).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to create alert: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get created alert with subscriber
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Preload("Subscriber").
|
||||||
|
First(alert, alert.ID).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to retrieve created alert: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return alert, nil
|
return alert, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SubscribeToSubscriberUpdates subscribes to subscriber updates
|
// SubscribeToSubscriberUpdates subscribes to subscriber updates
|
||||||
func (s *SubscriberService) SubscribeToSubscriberUpdates(ctx context.Context, subscriberId string) (<-chan *models.Subscriber, error) {
|
func (s *SubscriberService) SubscribeToSubscriberUpdates(ctx context.Context, subscriberId string) (<-chan *models.Subscriber, error) {
|
||||||
// This would set up actual subscription in a real implementation
|
// In a real implementation, this would set up WebSocket or pub/sub subscription
|
||||||
// For now, return a closed channel
|
// For now, return a channel that closes when context is done
|
||||||
ch := make(chan *models.Subscriber)
|
ch := make(chan *models.Subscriber)
|
||||||
close(ch)
|
go func() {
|
||||||
return ch, nil
|
<-ctx.Done()
|
||||||
}
|
close(ch)
|
||||||
|
}()
|
||||||
// SubscribeToAlertUpdates subscribes to alert updates
|
|
||||||
func (s *SubscriberService) SubscribeToAlertUpdates(ctx context.Context, severity models.AlertSeverity) (<-chan *models.Alert, error) {
|
|
||||||
// This would set up actual subscription in a real implementation
|
|
||||||
// For now, return a closed channel
|
|
||||||
ch := make(chan *models.Alert)
|
|
||||||
close(ch)
|
|
||||||
return ch, nil
|
return ch, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// AddPaymentMethod adds a payment method
|
// AddPaymentMethod adds a payment method
|
||||||
func (s *SubscriberService) AddPaymentMethod(ctx context.Context, subscriberId int, req *models.AddPaymentMethodRequest) (*models.PaymentMethod, error) {
|
func (s *SubscriberService) AddPaymentMethod(ctx context.Context, subscriberId int, req *models.AddPaymentMethodRequest) (*models.PaymentMethod, error) {
|
||||||
// This would add actual payment method in a real implementation
|
// Generate unique payment method ID
|
||||||
// For now, return placeholder data
|
paymentMethodID := fmt.Sprintf("pm_%d_%d", subscriberId, time.Now().Unix())
|
||||||
|
|
||||||
paymentMethod := &models.PaymentMethod{
|
paymentMethod := &models.PaymentMethod{
|
||||||
ID: "pm_123",
|
ID: paymentMethodID,
|
||||||
Type: req.Type,
|
SubscriberID: uint(subscriberId),
|
||||||
CustomerID: "customer_123",
|
GatewayID: "default_gateway",
|
||||||
Last4: "1234",
|
Type: req.Type,
|
||||||
Brand: "visa",
|
CustomerID: fmt.Sprintf("cus_%d", subscriberId),
|
||||||
ExpiryMonth: 12,
|
Last4: "1234", // Default placeholder, should come from req in real implementation
|
||||||
ExpiryYear: 2025,
|
Brand: "visa", // Default placeholder, should come from req in real implementation
|
||||||
IsDefault: req.IsDefault,
|
ExpiryMonth: 12, // Default placeholder, should come from req in real implementation
|
||||||
CreatedAt: time.Now(),
|
ExpiryYear: 2025, // Default placeholder, should come from req in real implementation
|
||||||
|
IsDefault: false,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Create payment method in database
|
||||||
|
if err := s.db.DB.WithContext(ctx).Create(paymentMethod).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to add payment method: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return paymentMethod, nil
|
return paymentMethod, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// RemovePaymentMethod removes a payment method
|
// RemovePaymentMethod removes a payment method
|
||||||
func (s *SubscriberService) RemovePaymentMethod(ctx context.Context, paymentMethodId string) (bool, error) {
|
func (s *SubscriberService) RemovePaymentMethod(ctx context.Context, paymentMethodId string) (bool, error) {
|
||||||
// This would remove actual payment method in a real implementation
|
// Check if payment method exists
|
||||||
// For now, return success
|
var paymentMethod models.PaymentMethod
|
||||||
|
if err := s.db.DB.WithContext(ctx).First(&paymentMethod, "id = ?", paymentMethodId).Error; err != nil {
|
||||||
|
return false, fmt.Errorf("payment method not found: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Don't allow removal if it's the only payment method and has default status
|
||||||
|
var count int64
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Model(&models.PaymentMethod{}).
|
||||||
|
Where("subscriber_id = ?", paymentMethod.SubscriberID).
|
||||||
|
Count(&count).Error; err != nil {
|
||||||
|
return false, fmt.Errorf("failed to check payment methods: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if count == 1 {
|
||||||
|
return false, fmt.Errorf("cannot remove the only payment method")
|
||||||
|
}
|
||||||
|
|
||||||
|
// If this is the default payment method, set another one as default
|
||||||
|
if paymentMethod.IsDefault {
|
||||||
|
var newDefault models.PaymentMethod
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Where("subscriber_id = ? AND id != ?", paymentMethod.SubscriberID, paymentMethodId).
|
||||||
|
First(&newDefault).Error; err != nil {
|
||||||
|
return false, fmt.Errorf("failed to find alternative payment method: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Model(&newDefault).
|
||||||
|
Update("is_default", true).Error; err != nil {
|
||||||
|
return false, fmt.Errorf("failed to set new default payment method: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete the payment method
|
||||||
|
if err := s.db.DB.WithContext(ctx).Delete(&paymentMethod).Error; err != nil {
|
||||||
|
return false, fmt.Errorf("failed to delete payment method: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetDefaultPaymentMethod sets default payment method
|
// SetDefaultPaymentMethod sets default payment method
|
||||||
func (s *SubscriberService) SetDefaultPaymentMethod(ctx context.Context, paymentMethodId string) (*models.PaymentMethod, error) {
|
func (s *SubscriberService) SetDefaultPaymentMethod(ctx context.Context, paymentMethodId string) (*models.PaymentMethod, error) {
|
||||||
// This would set actual default payment method in a real implementation
|
var paymentMethod models.PaymentMethod
|
||||||
// For now, return placeholder data
|
|
||||||
paymentMethod := &models.PaymentMethod{
|
// Start transaction
|
||||||
ID: paymentMethodId,
|
tx := s.db.DB.WithContext(ctx).Begin()
|
||||||
Type: models.PaymentMethodTypeCreditCard,
|
|
||||||
CustomerID: "customer_123",
|
// Unset all existing default payment methods for this subscriber
|
||||||
Last4: "1234",
|
if err := tx.Model(&models.PaymentMethod{}).
|
||||||
Brand: "visa",
|
Where("id = ?", paymentMethodId).
|
||||||
ExpiryMonth: 12,
|
First(&paymentMethod).Error; err != nil {
|
||||||
ExpiryYear: 2025,
|
tx.Rollback()
|
||||||
IsDefault: true,
|
return nil, fmt.Errorf("payment method not found: %w", err)
|
||||||
CreatedAt: time.Now(),
|
|
||||||
}
|
}
|
||||||
return paymentMethod, nil
|
|
||||||
|
// Set all other payment methods as non-default
|
||||||
|
if err := tx.Model(&models.PaymentMethod{}).
|
||||||
|
Where("subscriber_id = ? AND id != ?", paymentMethod.SubscriberID, paymentMethodId).
|
||||||
|
Update("is_default", false).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return nil, fmt.Errorf("failed to update other payment methods: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Set this payment method as default
|
||||||
|
if err := tx.Model(&paymentMethod).
|
||||||
|
Update("is_default", true).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return nil, fmt.Errorf("failed to set default payment method: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit transaction
|
||||||
|
if err := tx.Commit().Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to commit transaction: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &paymentMethod, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// TopUpBalance tops up subscriber balance
|
// TopUpBalance tops up subscriber balance
|
||||||
func (s *SubscriberService) TopUpBalance(ctx context.Context, imsi string, req *models.TopUpRequest) (*models.SubscriberAccount, error) {
|
func (s *SubscriberService) TopUpBalance(ctx context.Context, imsi string, req *models.TopUpRequest) (*models.SubscriberAccount, error) {
|
||||||
// This would top up actual balance in a real implementation
|
var account models.SubscriberAccount
|
||||||
// For now, return placeholder data
|
|
||||||
account := &models.SubscriberAccount{
|
// Get subscriber account from database
|
||||||
IMSI: imsi,
|
if err := s.db.DB.WithContext(ctx).
|
||||||
Balance: 150.0, // Previous balance + top-up
|
Where("imsi = ?", imsi).
|
||||||
DataLimit: 1000000000, // 1GB
|
First(&account).Error; err != nil {
|
||||||
DataUsed: 500000000, // 500MB
|
return nil, fmt.Errorf("subscriber account not found: %w", err)
|
||||||
VoiceLimit: 300,
|
|
||||||
VoiceUsed: 45,
|
|
||||||
SMSLimit: 100,
|
|
||||||
SMSUsed: 8,
|
|
||||||
Status: "active",
|
|
||||||
LastUpdated: time.Now(),
|
|
||||||
}
|
}
|
||||||
return account, nil
|
|
||||||
|
// Update balance
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Model(&account).
|
||||||
|
Where("imsi = ?", imsi).
|
||||||
|
Update("balance", account.Balance+req.Amount).
|
||||||
|
Update("last_updated", time.Now()).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to top up balance: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get updated account
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Where("imsi = ?", imsi).
|
||||||
|
First(&account).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to retrieve updated account: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &account, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// DeleteSubscriber deletes a subscriber
|
// DeleteSubscriber deletes a subscriber
|
||||||
func (s *SubscriberService) DeleteSubscriber(ctx context.Context, subscriberId uint) (bool, error) {
|
func (s *SubscriberService) DeleteSubscriber(ctx context.Context, subscriberId uint) (bool, error) {
|
||||||
// This would delete actual subscriber in a real implementation
|
// Start transaction to delete all related data
|
||||||
// For now, return success
|
tx := s.db.DB.WithContext(ctx).Begin()
|
||||||
|
|
||||||
|
// Delete subscriber's payment methods
|
||||||
|
if err := tx.Where("subscriber_id = ?", subscriberId).Delete(&models.PaymentMethod{}).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return false, fmt.Errorf("failed to delete payment methods: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete subscriber's alerts
|
||||||
|
if err := tx.Where("subscriber_id = ?", subscriberId).Delete(&models.Alert{}).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return false, fmt.Errorf("failed to delete alerts: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete subscriber's account
|
||||||
|
if err := tx.Where("imsi IN (SELECT imsi FROM subscribers WHERE id = ?))", subscriberId).Delete(&models.SubscriberAccount{}).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return false, fmt.Errorf("failed to delete account: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Delete subscriber
|
||||||
|
if err := tx.Delete(&models.Subscriber{}, subscriberId).Error; err != nil {
|
||||||
|
tx.Rollback()
|
||||||
|
return false, fmt.Errorf("failed to delete subscriber: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Commit transaction
|
||||||
|
if err := tx.Commit().Error; err != nil {
|
||||||
|
return false, fmt.Errorf("failed to commit deletion: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
return true, nil
|
return true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// ActivateSubscriber activates a subscriber
|
// ActivateSubscriber activates a subscriber
|
||||||
func (s *SubscriberService) ActivateSubscriber(ctx context.Context, subscriberId uint) (*models.Subscriber, error) {
|
func (s *SubscriberService) ActivateSubscriber(ctx context.Context, subscriberId uint) (*models.Subscriber, error) {
|
||||||
// This would activate actual subscriber in a real implementation
|
var subscriber models.Subscriber
|
||||||
// For now, return placeholder data
|
|
||||||
subscriber := &models.Subscriber{
|
// Update subscriber status to active
|
||||||
ID: subscriberId,
|
if err := s.db.DB.WithContext(ctx).
|
||||||
IMSI: "123456789012345",
|
Model(&subscriber).
|
||||||
MSISDN: "1234567890",
|
Where("id = ?", subscriberId).
|
||||||
FirstName: "John",
|
Update("status", models.SubscriberStatusActive).
|
||||||
LastName: "Doe",
|
Update("activated_at", time.Now()).Error; err != nil {
|
||||||
Email: "[email protected]",
|
return nil, fmt.Errorf("failed to activate subscriber: %w", err)
|
||||||
Status: models.SubscriberStatusActive,
|
|
||||||
PlanID: 1,
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
UpdatedAt: time.Now(),
|
|
||||||
}
|
}
|
||||||
return subscriber, nil
|
|
||||||
|
// Get updated subscriber
|
||||||
|
if err := s.db.DB.WithContext(ctx).
|
||||||
|
Preload("Plan").
|
||||||
|
First(&subscriber, subscriberId).Error; err != nil {
|
||||||
|
return nil, fmt.Errorf("failed to retrieve activated subscriber: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &subscriber, nil
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user