feat: Add analytics, security, and currency SDK modules with comprehensive API endpoints across Elixir and Go SDKs

- Add AnalyticsAPI with churn prediction (predict, metrics, at-risk), market analytics (metrics, competitors, opportunities), predictive maintenance (metrics, assets, alerts, predict), and pricing optimization (metrics, optimize, elasticity) endpoints
- Add SecurityAPI with fraud detection (analyze, alerts, update status, metrics, patterns) and SIM swap protection (verify, history) endpoints
- Add CurrencyAPI with currency conversion (convert, exchange rates, rate
This commit is contained in:
nutcas3
2026-05-03 13:29:44 +03:00
parent 12887765de
commit 9f51d6f20e
44 changed files with 3432 additions and 146 deletions
+92
View File
@@ -0,0 +1,92 @@
package telecom
import (
"context"
"fmt"
)
// AnalyticsAPI provides access to analytics endpoints
type AnalyticsAPI struct {
client *HTTPClient
}
// NewAnalyticsAPI creates a new AnalyticsAPI client
func NewAnalyticsAPI(client *HTTPClient) *AnalyticsAPI {
return &AnalyticsAPI{client: client}
}
// PredictChurn predicts churn risk for a specific profile
func (a *AnalyticsAPI) PredictChurn(ctx context.Context, profileID string) (*ChurnPrediction, error) {
var result ChurnPrediction
err := a.client.Post(ctx, "/api/v1/analytics/churn/predict", map[string]string{"profile_id": profileID}, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// GetChurnMetrics retrieves overall churn metrics
func (a *AnalyticsAPI) GetChurnMetrics(ctx context.Context, period string) (*ChurnMetrics, error) {
var result ChurnMetrics
err := a.client.Get(ctx, "/api/v1/analytics/churn/metrics", &result, map[string]string{"period": period})
if err != nil {
return nil, err
}
return &result, nil
}
// GetAtRiskCustomers retrieves customers at high risk of churn
func (a *AnalyticsAPI) GetAtRiskCustomers(ctx context.Context, riskLevel ChurnRiskLevel, limit int) ([]*ChurnPrediction, error) {
var result []*ChurnPrediction
err := a.client.Get(ctx, "/api/v1/analytics/churn/at-risk", &result, map[string]string{
"risk_level": string(riskLevel),
"limit": fmt.Sprintf("%d", limit),
})
if err != nil {
return nil, err
}
return result, nil
}
// GetMarketMetrics retrieves market penetration metrics
func (a *AnalyticsAPI) GetMarketMetrics(ctx context.Context, period string) (*MarketMetrics, error) {
var result MarketMetrics
err := a.client.Get(ctx, "/api/v1/analytics/market/metrics", &result, map[string]string{"period": period})
if err != nil {
return nil, err
}
return &result, nil
}
// GetPredictiveMaintenanceMetrics retrieves infrastructure health metrics
func (a *AnalyticsAPI) GetPredictiveMaintenanceMetrics(ctx context.Context, period string) (*PredictiveMaintenanceMetrics, error) {
var result PredictiveMaintenanceMetrics
err := a.client.Get(ctx, "/api/v1/analytics/maintenance/metrics", &result, map[string]string{"period": period})
if err != nil {
return nil, err
}
return &result, nil
}
// GetPricingMetrics retrieves pricing optimization metrics
func (a *AnalyticsAPI) GetPricingMetrics(ctx context.Context, period string) (*PricingMetrics, error) {
var result PricingMetrics
err := a.client.Get(ctx, "/api/v1/analytics/pricing/metrics", &result, map[string]string{"period": period})
if err != nil {
return nil, err
}
return &result, nil
}
// OptimizePrice performs pricing optimization for a rate plan
func (a *AnalyticsAPI) OptimizePrice(ctx context.Context, ratePlanID, strategy string) (*PricingOptimizationResult, error) {
var result PricingOptimizationResult
err := a.client.Post(ctx, "/api/v1/analytics/pricing/optimize", map[string]interface{}{
"rate_plan_id": ratePlanID,
"strategy": strategy,
}, &result)
if err != nil {
return nil, err
}
return &result, nil
}
+131
View File
@@ -0,0 +1,131 @@
package telecom
import (
"context"
"fmt"
)
// CurrencyAPI provides currency and billing operations
type CurrencyAPI struct {
client *HTTPClient
}
// NewCurrencyAPI creates a new currency API client
func NewCurrencyAPI(client *HTTPClient) *CurrencyAPI {
return &CurrencyAPI{client: client}
}
// ConvertRequest represents a currency conversion request
type ConvertRequest struct {
From string `json:"from"`
To string `json:"to"`
Amount float64 `json:"amount"`
}
// ConvertResponse represents a currency conversion response
type ConvertResponse struct {
From string `json:"from"`
To string `json:"to"`
Amount float64 `json:"amount"`
Converted float64 `json:"converted"`
Rate float64 `json:"rate"`
Timestamp string `json:"timestamp"`
}
// ExchangeRate represents an exchange rate
type ExchangeRate struct {
From string `json:"from"`
To string `json:"to"`
Rate float64 `json:"rate"`
Timestamp string `json:"timestamp"`
}
// BillingTransaction represents a billing transaction
type BillingTransaction struct {
ID string `json:"id"`
ProfileID string `json:"profile_id"`
Amount float64 `json:"amount"`
Currency string `json:"currency"`
Type string `json:"type"`
Status string `json:"status"`
Description string `json:"description"`
CreatedAt string `json:"created_at"`
}
// BillingSummary represents a billing summary
type BillingSummary struct {
ProfileID string `json:"profile_id"`
Period string `json:"period"`
TotalAmount float64 `json:"total_amount"`
Currency string `json:"currency"`
TransactionCount int `json:"transaction_count"`
Breakdown map[string]float64 `json:"breakdown"`
}
// Convert converts currency
func (c *CurrencyAPI) Convert(ctx context.Context, req *ConvertRequest) (*ConvertResponse, error) {
var result ConvertResponse
err := c.client.Post(ctx, "/api/v1/currency/convert", req, &result)
return &result, err
}
// GetExchangeRate gets the exchange rate between currencies
func (c *CurrencyAPI) GetExchangeRate(ctx context.Context, from, to string) (*ExchangeRate, error) {
var result ExchangeRate
err := c.client.Get(ctx, fmt.Sprintf("/api/v1/currency/exchange/%s/%s", from, to), &result)
return &result, err
}
// GetExchangeRateHistory gets exchange rate history
func (c *CurrencyAPI) GetExchangeRateHistory(ctx context.Context, from, to string, days int) ([]ExchangeRate, error) {
var result []ExchangeRate
err := c.client.Get(ctx, fmt.Sprintf("/api/v1/currency/exchange/%s/%s/history", from, to), &result, map[string]string{"days": fmt.Sprintf("%d", days)})
return result, err
}
// GetSupportedCurrencies gets list of supported currencies
func (c *CurrencyAPI) GetSupportedCurrencies(ctx context.Context) ([]string, error) {
var result []string
err := c.client.Get(ctx, "/api/v1/currency/currencies", &result)
return result, err
}
// RefreshExchangeRates refreshes exchange rates
func (c *CurrencyAPI) RefreshExchangeRates(ctx context.Context) error {
return c.client.Post(ctx, "/api/v1/currency/exchange/refresh", nil, nil)
}
// ProcessBilling processes a billing transaction
func (c *CurrencyAPI) ProcessBilling(ctx context.Context, billingData map[string]interface{}) (*BillingTransaction, error) {
var result BillingTransaction
err := c.client.Post(ctx, "/api/v1/currency/billing", billingData, &result)
return &result, err
}
// GetBillingHistory gets billing history for a profile
func (c *CurrencyAPI) GetBillingHistory(ctx context.Context, profileID string, limit int) ([]BillingTransaction, error) {
var result []BillingTransaction
err := c.client.Get(ctx, fmt.Sprintf("/api/v1/currency/billing/history/%s", profileID), &result, map[string]string{"limit": fmt.Sprintf("%d", limit)})
return result, err
}
// GetBillingSummary gets billing summary for a profile
func (c *CurrencyAPI) GetBillingSummary(ctx context.Context, profileID, period string) (*BillingSummary, error) {
var result BillingSummary
err := c.client.Get(ctx, fmt.Sprintf("/api/v1/currency/billing/summary/%s", profileID), &result, map[string]string{"period": period})
return &result, err
}
// ProcessRefund processes a refund
func (c *CurrencyAPI) ProcessRefund(ctx context.Context, transactionID, reason string) (*BillingTransaction, error) {
var result BillingTransaction
err := c.client.Post(ctx, fmt.Sprintf("/api/v1/currency/billing/refund/%s", transactionID), map[string]string{"reason": reason}, &result)
return &result, err
}
// GetBillingAnalytics gets billing analytics
func (c *CurrencyAPI) GetBillingAnalytics(ctx context.Context, period string) (map[string]interface{}, error) {
var result map[string]interface{}
err := c.client.Get(ctx, "/api/v1/currency/billing/analytics", &result, map[string]string{"period": period})
return result, err
}
-29
View File
@@ -1,29 +0,0 @@
package telecom
import (
"context"
)
// GraphQLAPI handles GraphQL API calls
type GraphQLAPI struct {
client *HTTPClient
}
// NewGraphQLAPI creates a new GraphQLAPI
func NewGraphQLAPI(client *HTTPClient) *GraphQLAPI {
return &GraphQLAPI{client: client}
}
// Execute executes a GraphQL query
func (g *GraphQLAPI) Execute(ctx context.Context, query string, variables map[string]interface{}) (map[string]interface{}, error) {
data := map[string]interface{}{
"query": query,
}
if variables != nil {
data["variables"] = variables
}
var result map[string]interface{}
err := g.client.Post(ctx, "/graphql", data, &result)
return result, err
}
+52
View File
@@ -0,0 +1,52 @@
package telecom
import "context"
// SecurityAPI provides access to security endpoints
type SecurityAPI struct {
client *HTTPClient
}
// NewSecurityAPI creates a new SecurityAPI client
func NewSecurityAPI(client *HTTPClient) *SecurityAPI {
return &SecurityAPI{client: client}
}
// AnalyzeTransaction analyzes a transaction for fraud
func (s *SecurityAPI) AnalyzeTransaction(ctx context.Context, transaction map[string]interface{}) (*FraudAlert, error) {
var result FraudAlert
err := s.client.Post(ctx, "/api/v1/security/fraud/analyze", transaction, &result)
if err != nil {
return nil, err
}
return &result, nil
}
// GetFraudAlerts retrieves fraud alerts
func (s *SecurityAPI) GetFraudAlerts(ctx context.Context, filter FraudAlertFilter) ([]*FraudAlert, error) {
var result []*FraudAlert
err := s.client.Post(ctx, "/api/v1/security/fraud/alerts", filter, &result)
if err != nil {
return nil, err
}
return result, nil
}
// UpdateAlertStatus updates the status of a fraud alert
func (s *SecurityAPI) UpdateAlertStatus(ctx context.Context, alertID, status string, actions []string) error {
req := map[string]interface{}{
"status": status,
"actions": actions,
}
return s.client.Put(ctx, "/api/v1/security/fraud/alerts/"+alertID, req, nil)
}
// GetFraudMetrics returns fraud detection metrics
func (s *SecurityAPI) GetFraudMetrics(ctx context.Context, period string) (*FraudMetrics, error) {
var result FraudMetrics
err := s.client.Get(ctx, "/api/v1/security/fraud/metrics", &result, map[string]string{"period": period})
if err != nil {
return nil, err
}
return &result, nil
}
+6 -2
View File
@@ -16,7 +16,9 @@ type Client struct {
Payments *PaymentAPI
RatingPlans *RatingPlanAPI
System *SystemAPI
GraphQL *GraphQLAPI
Analytics *AnalyticsAPI
Security *SecurityAPI
Currency *CurrencyAPI
}
// Config holds the SDK configuration
@@ -75,7 +77,9 @@ func NewClient(config *Config) (*Client, error) {
client.Payments = NewPaymentAPI(httpClient)
client.RatingPlans = NewRatingPlanAPI(httpClient)
client.System = NewSystemAPI(httpClient)
client.GraphQL = NewGraphQLAPI(httpClient)
client.Analytics = NewAnalyticsAPI(httpClient)
client.Security = NewSecurityAPI(httpClient)
client.Currency = NewCurrencyAPI(httpClient)
return client, nil
}
+234
View File
@@ -259,3 +259,237 @@ type GetSystemStatsRequest struct{}
// GetHealthStatusRequest represents a gRPC request to get health status
type GetHealthStatusRequest struct{}
// ChurnRiskLevel represents the risk level of customer churn
type ChurnRiskLevel string
const (
ChurnRiskLow ChurnRiskLevel = "low"
ChurnRiskMedium ChurnRiskLevel = "medium"
ChurnRiskHigh ChurnRiskLevel = "high"
ChurnRiskCritical ChurnRiskLevel = "critical"
)
// ChurnPrediction represents a churn prediction for a customer
type ChurnPrediction struct {
ProfileID string `json:"profile_id"`
RiskLevel ChurnRiskLevel `json:"risk_level"`
RiskScore float64 `json:"risk_score"`
PredictedChurnDate *time.Time `json:"predicted_churn_date,omitempty"`
Reasons []string `json:"reasons"`
Recommendations []string `json:"recommendations"`
LastUpdated time.Time `json:"last_updated"`
}
// ChurnMetrics represents churn analysis metrics
type ChurnMetrics struct {
Period string `json:"period"`
TotalSubscribers int64 `json:"total_subscribers"`
ChurnedSubscribers int64 `json:"churned_subscribers"`
ChurnRate float64 `json:"churn_rate"`
MonthlyChurnRate float64 `json:"monthly_churn_rate"`
AnnualChurnRate float64 `json:"annual_churn_rate"`
AverageTenure float64 `json:"average_tenure_days"`
RiskDistribution map[ChurnRiskLevel]int64 `json:"risk_distribution"`
GeneratedAt time.Time `json:"generated_at"`
}
// FraudType represents different types of fraud
type FraudType string
const (
FraudTypeAccountTakeover FraudType = "account_takeover"
FraudTypeSubscriptionFraud FraudType = "subscription_fraud"
FraudTypePaymentFraud FraudType = "payment_fraud"
FraudTypeUsageAnomaly FraudType = "usage_anomaly"
FraudTypeSIMSwap FraudType = "sim_swap"
)
// FraudSeverity represents the severity of fraud detection
type FraudSeverity string
const (
FraudSeverityLow FraudSeverity = "low"
FraudSeverityMedium FraudSeverity = "medium"
FraudSeverityHigh FraudSeverity = "high"
FraudSeverityCritical FraudSeverity = "critical"
)
// FraudAlert represents a fraud detection alert
type FraudAlert struct {
ID string `json:"id"`
Type FraudType `json:"type"`
Severity FraudSeverity `json:"severity"`
ProfileID string `json:"profile_id"`
Description string `json:"description"`
RiskScore float64 `json:"risk_score"`
Evidence []string `json:"evidence"`
IPAddress string `json:"ip_address"`
Timestamp time.Time `json:"timestamp"`
Status string `json:"status"`
Actions []string `json:"actions_taken"`
Metadata map[string]any `json:"metadata"`
}
// FraudMetrics represents fraud detection metrics
type FraudMetrics struct {
Period string `json:"period"`
TotalAlerts int64 `json:"total_alerts"`
ResolvedAlerts int64 `json:"resolved_alerts"`
FalsePositives int64 `json:"false_positives"`
ResolutionRate float64 `json:"resolution_rate_pct"`
FalsePositiveRate float64 `json:"false_positive_rate_pct"`
ByType map[FraudType]int64 `json:"by_type"`
BySeverity map[FraudSeverity]int64 `json:"by_severity"`
GeneratedAt time.Time `json:"generated_at"`
}
// FraudAlertFilter filters fraud alerts
type FraudAlertFilter struct {
Type FraudType `json:"type,omitempty"`
Severity FraudSeverity `json:"severity,omitempty"`
Status string `json:"status,omitempty"`
FromDate *time.Time `json:"from_date,omitempty"`
ToDate *time.Time `json:"to_date,omitempty"`
Limit int `json:"limit,omitempty"`
}
// MarketMetrics represents market penetration analysis
type MarketMetrics struct {
Period string `json:"period"`
TotalMarketSize int64 `json:"total_market_size"`
OurSubscribers int64 `json:"our_subscribers"`
MarketShare float64 `json:"market_share_pct"`
GrowthRate float64 `json:"growth_rate_pct"`
ByCountry map[string]CountryMetrics `json:"by_country"`
ByCarrier map[string]MarketCarrierMetrics `json:"by_carrier"`
ByDemographic map[string]DemoMetrics `json:"by_demographic"`
CompetitorAnalysis map[string]CompetitorMetrics `json:"competitor_analysis"`
MarketOpportunities []MarketOpportunity `json:"market_opportunities"`
GeneratedAt time.Time `json:"generated_at"`
}
// CountryMetrics represents metrics by country
type CountryMetrics struct {
Country string `json:"country"`
MarketSize int64 `json:"market_size"`
OurSubscribers int64 `json:"our_subscribers"`
MarketShare float64 `json:"market_share_pct"`
GrowthRate float64 `json:"growth_rate_pct"`
AverageRevenue float64 `json:"average_revenue"`
}
// MarketCarrierMetrics represents metrics by carrier
type MarketCarrierMetrics struct {
CarrierID string `json:"carrier_id"`
CarrierName string `json:"carrier_name"`
Subscribers int64 `json:"subscribers"`
MarketShare float64 `json:"market_share_pct"`
AverageRevenue float64 `json:"average_revenue"`
QualityScore float64 `json:"quality_score"`
}
// DemoMetrics represents metrics by demographic
type DemoMetrics struct {
Segment string `json:"segment"`
Subscribers int64 `json:"subscribers"`
MarketShare float64 `json:"market_share_pct"`
AverageRevenue float64 `json:"average_revenue"`
GrowthRate float64 `json:"growth_rate_pct"`
}
// CompetitorMetrics represents competitor analysis
type CompetitorMetrics struct {
Name string `json:"name"`
MarketShare float64 `json:"market_share_pct"`
Subscribers int64 `json:"subscribers"`
AveragePrice float64 `json:"average_price"`
Strengths []string `json:"strengths"`
Weaknesses []string `json:"weaknesses"`
}
// MarketOpportunity represents a market opportunity
type MarketOpportunity struct {
ID string `json:"id"`
Type string `json:"type"`
Description string `json:"description"`
PotentialSize int64 `json:"potential_size"`
Confidence float64 `json:"confidence"`
RequiredActions []string `json:"required_actions"`
}
// PredictiveMaintenanceMetrics represents infrastructure health metrics
type PredictiveMaintenanceMetrics struct {
Period string `json:"period"`
TotalAssets int64 `json:"total_assets"`
HealthyAssets int64 `json:"healthy_assets"`
AtRiskAssets int64 `json:"at_risk_assets"`
CriticalAssets int64 `json:"critical_assets"`
OverallHealthScore float64 `json:"overall_health_score"`
ByAssetType map[string]AssetTypeMetrics `json:"by_asset_type"`
PredictedFailures []PredictedFailure `json:"predicted_failures"`
MaintenanceSchedule []MaintenanceTask `json:"maintenance_schedule"`
GeneratedAt time.Time `json:"generated_at"`
}
// AssetTypeMetrics represents metrics by asset type
type AssetTypeMetrics struct {
AssetType string `json:"asset_type"`
Total int64 `json:"total"`
Healthy int64 `json:"healthy"`
AtRisk int64 `json:"at_risk"`
Critical int64 `json:"critical"`
HealthScore float64 `json:"health_score"`
}
// PredictedFailure represents a predicted failure
type PredictedFailure struct {
AssetID string `json:"asset_id"`
AssetType string `json:"asset_type"`
FailureType string `json:"failure_type"`
PredictedDate time.Time `json:"predicted_date"`
Confidence float64 `json:"confidence"`
RecommendedActions []string `json:"recommended_actions"`
}
// MaintenanceTask represents a scheduled maintenance task
type MaintenanceTask struct {
ID string `json:"id"`
AssetID string `json:"asset_id"`
TaskType string `json:"task_type"`
Priority string `json:"priority"`
ScheduledDate time.Time `json:"scheduled_date"`
EstimatedDuration int `json:"estimated_duration_minutes"`
Description string `json:"description"`
Status string `json:"status"`
}
// PricingOptimizationResult represents pricing optimization results
type PricingOptimizationResult struct {
RatePlanID string `json:"rate_plan_id"`
CurrentPrice float64 `json:"current_price"`
OptimalPrice float64 `json:"optimal_price"`
Strategy string `json:"strategy"`
ExpectedRevenue float64 `json:"expected_revenue"`
ExpectedDemand int64 `json:"expected_demand"`
PriceChange float64 `json:"price_change_pct"`
Reasoning []string `json:"reasoning"`
Risks []string `json:"risks"`
Recommendations []string `json:"recommendations"`
Confidence float64 `json:"confidence"`
GeneratedAt time.Time `json:"generated_at"`
}
// PricingMetrics represents pricing optimization metrics
type PricingMetrics struct {
Period string `json:"period"`
TotalRatePlans int64 `json:"total_rate_plans"`
OptimizedRatePlans int64 `json:"optimized_rate_plans"`
AveragePriceChange float64 `json:"average_price_change_pct"`
ExpectedRevenueImpact float64 `json:"expected_revenue_impact_pct"`
ChurnRateReduction float64 `json:"churn_rate_reduction_pct"`
PriceElasticity float64 `json:"price_elasticity"`
CompetitiveIndex float64 `json:"competitive_index"`
OptimizationROI float64 `json:"optimization_roi_pct"`
GeneratedAt time.Time `json:"generated_at"`
}