mirror of
https://github.com/andwati/telecom-platform.git
synced 2026-11-29 07:18:47 +00:00
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:
@@ -57,7 +57,9 @@ defmodule TelecomSDK do
|
|||||||
payments = PaymentAPI.new(http_client)
|
payments = PaymentAPI.new(http_client)
|
||||||
rating_plans = RatingPlanAPI.new(http_client)
|
rating_plans = RatingPlanAPI.new(http_client)
|
||||||
system = SystemAPI.new(http_client)
|
system = SystemAPI.new(http_client)
|
||||||
graphql = GraphQLAPI.new(http_client)
|
analytics = AnalyticsAPI.new(http_client)
|
||||||
|
security = SecurityAPI.new(http_client)
|
||||||
|
currency = CurrencyAPI.new(http_client)
|
||||||
|
|
||||||
state = %{
|
state = %{
|
||||||
config: config,
|
config: config,
|
||||||
@@ -68,7 +70,9 @@ defmodule TelecomSDK do
|
|||||||
payments: payments,
|
payments: payments,
|
||||||
rating_plans: rating_plans,
|
rating_plans: rating_plans,
|
||||||
system: system,
|
system: system,
|
||||||
graphql: graphql
|
analytics: analytics,
|
||||||
|
security: security,
|
||||||
|
currency: currency
|
||||||
}
|
}
|
||||||
|
|
||||||
{:ok, state}
|
{:ok, state}
|
||||||
|
|||||||
@@ -0,0 +1,78 @@
|
|||||||
|
defmodule TelecomSDK.AnalyticsAPI do
|
||||||
|
@moduledoc """
|
||||||
|
Analytics API for churn prediction, market analysis, and pricing optimization
|
||||||
|
"""
|
||||||
|
|
||||||
|
defstruct [:http_client]
|
||||||
|
|
||||||
|
def new(http_client) do
|
||||||
|
%__MODULE__{http_client: http_client}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Churn Analysis
|
||||||
|
|
||||||
|
def predict_churn(%__MODULE__{http_client: client}, profile_id) do
|
||||||
|
body = %{profile_id: profile_id}
|
||||||
|
HTTPClient.post(client, "/api/v1/analytics/churn/predict", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_churn_metrics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/churn/metrics", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_at_risk_customers(%__MODULE__{http_client: client}, risk_level, limit \\ 100) do
|
||||||
|
body = %{risk_level: risk_level, limit: limit}
|
||||||
|
HTTPClient.post(client, "/api/v1/analytics/churn/at-risk", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
# Market Analytics
|
||||||
|
|
||||||
|
def get_market_metrics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/market/metrics", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_competitors(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/market/competitors", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_market_opportunities(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/market/opportunities", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Predictive Maintenance
|
||||||
|
|
||||||
|
def get_maintenance_metrics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/maintenance/metrics", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_assets_health(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/maintenance/assets", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_maintenance_alerts(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/maintenance/alerts", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
def predict_failure(%__MODULE__{http_client: client}, asset_id) do
|
||||||
|
HTTPClient.post(client, "/api/v1/analytics/maintenance/predict/#{asset_id}", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Pricing Optimization
|
||||||
|
|
||||||
|
def get_pricing_metrics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/pricing/metrics", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def optimize_pricing(%__MODULE__{http_client: client}, rate_plan_ids, strategy \\ "revenue_maximization") do
|
||||||
|
body = %{rate_plan_ids: rate_plan_ids, strategy: strategy}
|
||||||
|
HTTPClient.post(client, "/api/v1/analytics/pricing/optimize", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_price_elasticity(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/analytics/pricing/elasticity", %{})
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
defmodule TelecomSDK.CurrencyAPI do
|
||||||
|
@moduledoc """
|
||||||
|
Currency and Billing API
|
||||||
|
"""
|
||||||
|
|
||||||
|
defstruct [:http_client]
|
||||||
|
|
||||||
|
def new(http_client) do
|
||||||
|
%__MODULE__{http_client: http_client}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Currency Conversion
|
||||||
|
|
||||||
|
def convert(%__MODULE__{http_client: client}, from, to, amount) do
|
||||||
|
body = %{from: from, to: to, amount: amount}
|
||||||
|
HTTPClient.post(client, "/api/v1/currency/convert", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_exchange_rate(%__MODULE__{http_client: client}, from, to) do
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/exchange/#{from}/#{to}", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_exchange_rate_history(%__MODULE__{http_client: client}, from, to, days \\ 30) do
|
||||||
|
params = %{days: days}
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/exchange/#{from}/#{to}/history", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_supported_currencies(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/currencies", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
def refresh_exchange_rates(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.post(client, "/api/v1/currency/exchange/refresh", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Billing
|
||||||
|
|
||||||
|
def process_billing(%__MODULE__{http_client: client}, billing_data) do
|
||||||
|
HTTPClient.post(client, "/api/v1/currency/billing", billing_data)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_history(%__MODULE__{http_client: client}, profile_id, limit \\ 50) do
|
||||||
|
params = %{limit: limit}
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/billing/history/#{profile_id}", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_summary(%__MODULE__{http_client: client}, profile_id, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/billing/summary/#{profile_id}", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def process_refund(%__MODULE__{http_client: client}, transaction_id, reason) do
|
||||||
|
body = %{reason: reason}
|
||||||
|
HTTPClient.post(client, "/api/v1/currency/billing/refund/#{transaction_id}", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_analytics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/currency/billing/analytics", params)
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
defmodule TelecomSDK.GraphQLAPI do
|
|
||||||
@moduledoc """
|
|
||||||
API for GraphQL queries
|
|
||||||
"""
|
|
||||||
|
|
||||||
defstruct [:client]
|
|
||||||
|
|
||||||
def new(client) do
|
|
||||||
%__MODULE__{client: client}
|
|
||||||
end
|
|
||||||
|
|
||||||
def execute(api, query, variables \\ nil) do
|
|
||||||
request = %{query: query}
|
|
||||||
request = if variables, do: Map.put(request, :variables, variables), else: request
|
|
||||||
TelecomSDK.HTTPClient.post(api.client, "/graphql", request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
defmodule TelecomSDK.SecurityAPI do
|
||||||
|
@moduledoc """
|
||||||
|
Security API for fraud detection and SIM swap protection
|
||||||
|
"""
|
||||||
|
|
||||||
|
defstruct [:http_client]
|
||||||
|
|
||||||
|
def new(http_client) do
|
||||||
|
%__MODULE__{http_client: http_client}
|
||||||
|
end
|
||||||
|
|
||||||
|
# Fraud Detection
|
||||||
|
|
||||||
|
def analyze_transaction(%__MODULE__{http_client: client}, transaction) do
|
||||||
|
HTTPClient.post(client, "/api/v1/security/fraud/analyze", transaction)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_alerts(%__MODULE__{http_client: client}, filter \\ nil) do
|
||||||
|
body = if filter, do: filter, else: %{}
|
||||||
|
HTTPClient.post(client, "/api/v1/security/fraud/alerts", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def update_alert_status(%__MODULE__{http_client: client}, alert_id, status, actions \\ []) do
|
||||||
|
body = %{status: status, actions: actions}
|
||||||
|
HTTPClient.put(client, "/api/v1/security/fraud/alerts/#{alert_id}", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_metrics(%__MODULE__{http_client: client}, period \\ "monthly") do
|
||||||
|
params = %{period: period}
|
||||||
|
HTTPClient.get(client, "/api/v1/security/fraud/metrics", params)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_patterns(%__MODULE__{http_client: client}) do
|
||||||
|
HTTPClient.get(client, "/api/v1/security/fraud/patterns", %{})
|
||||||
|
end
|
||||||
|
|
||||||
|
# SIM Swap Protection
|
||||||
|
|
||||||
|
def verify_sim_swap(%__MODULE__{http_client: client}, profile_id, msisdn) do
|
||||||
|
body = %{profile_id: profile_id, msisdn: msisdn}
|
||||||
|
HTTPClient.post(client, "/api/v1/security/simswap/verify", body)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_sim_swap_history(%__MODULE__{http_client: client}, profile_id) do
|
||||||
|
HTTPClient.get(client, "/api/v1/security/simswap/history/#{profile_id}", %{})
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -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
|
|
||||||
}
|
|
||||||
@@ -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
@@ -16,7 +16,9 @@ type Client struct {
|
|||||||
Payments *PaymentAPI
|
Payments *PaymentAPI
|
||||||
RatingPlans *RatingPlanAPI
|
RatingPlans *RatingPlanAPI
|
||||||
System *SystemAPI
|
System *SystemAPI
|
||||||
GraphQL *GraphQLAPI
|
Analytics *AnalyticsAPI
|
||||||
|
Security *SecurityAPI
|
||||||
|
Currency *CurrencyAPI
|
||||||
}
|
}
|
||||||
|
|
||||||
// Config holds the SDK configuration
|
// Config holds the SDK configuration
|
||||||
@@ -75,7 +77,9 @@ func NewClient(config *Config) (*Client, error) {
|
|||||||
client.Payments = NewPaymentAPI(httpClient)
|
client.Payments = NewPaymentAPI(httpClient)
|
||||||
client.RatingPlans = NewRatingPlanAPI(httpClient)
|
client.RatingPlans = NewRatingPlanAPI(httpClient)
|
||||||
client.System = NewSystemAPI(httpClient)
|
client.System = NewSystemAPI(httpClient)
|
||||||
client.GraphQL = NewGraphQLAPI(httpClient)
|
client.Analytics = NewAnalyticsAPI(httpClient)
|
||||||
|
client.Security = NewSecurityAPI(httpClient)
|
||||||
|
client.Currency = NewCurrencyAPI(httpClient)
|
||||||
|
|
||||||
return client, nil
|
return client, nil
|
||||||
}
|
}
|
||||||
|
|||||||
+234
@@ -259,3 +259,237 @@ type GetSystemStatsRequest struct{}
|
|||||||
|
|
||||||
// GetHealthStatusRequest represents a gRPC request to get health status
|
// GetHealthStatusRequest represents a gRPC request to get health status
|
||||||
type GetHealthStatusRequest struct{}
|
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"`
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,201 @@
|
|||||||
|
package com.telecom
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
import kotlinx.serialization.json.JsonObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analytics API for churn prediction, market analysis, and pricing optimization
|
||||||
|
*/
|
||||||
|
class AnalyticsAPI(private val httpClient: HTTPClient) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Predict churn risk for a profile
|
||||||
|
*/
|
||||||
|
suspend fun predictChurn(profileId: String): ChurnPrediction {
|
||||||
|
return httpClient.post("/api/v1/analytics/churn/predict",
|
||||||
|
mapOf("profile_id" to profileId))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get churn metrics
|
||||||
|
*/
|
||||||
|
suspend fun getChurnMetrics(period: String = "monthly"): ChurnMetrics {
|
||||||
|
return httpClient.get("/api/v1/analytics/churn/metrics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get at-risk customers
|
||||||
|
*/
|
||||||
|
suspend fun getAtRiskCustomers(
|
||||||
|
riskLevel: ChurnRiskLevel,
|
||||||
|
limit: Int = 100
|
||||||
|
): List<ChurnPrediction> {
|
||||||
|
return httpClient.post("/api/v1/analytics/churn/at-risk",
|
||||||
|
mapOf(
|
||||||
|
"risk_level" to riskLevel.value,
|
||||||
|
"limit" to limit
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get market metrics
|
||||||
|
*/
|
||||||
|
suspend fun getMarketMetrics(period: String = "monthly"): MarketMetrics {
|
||||||
|
return httpClient.get("/api/v1/analytics/market/metrics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get competitor analysis
|
||||||
|
*/
|
||||||
|
suspend fun getCompetitors(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/analytics/market/competitors")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get market opportunities
|
||||||
|
*/
|
||||||
|
suspend fun getMarketOpportunities(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/analytics/market/opportunities")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get maintenance metrics
|
||||||
|
*/
|
||||||
|
suspend fun getMaintenanceMetrics(period: String = "monthly"): MaintenanceMetrics {
|
||||||
|
return httpClient.get("/api/v1/analytics/maintenance/metrics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get assets health
|
||||||
|
*/
|
||||||
|
suspend fun getAssetsHealth(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/analytics/maintenance/assets")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get maintenance alerts
|
||||||
|
*/
|
||||||
|
suspend fun getMaintenanceAlerts(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/analytics/maintenance/alerts")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Predict failure for an asset
|
||||||
|
*/
|
||||||
|
suspend fun predictFailure(assetId: String): JsonObject {
|
||||||
|
return httpClient.post("/api/v1/analytics/maintenance/predict/$assetId", emptyMap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get pricing metrics
|
||||||
|
*/
|
||||||
|
suspend fun getPricingMetrics(period: String = "monthly"): PricingMetrics {
|
||||||
|
return httpClient.get("/api/v1/analytics/pricing/metrics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optimize pricing for rate plans
|
||||||
|
*/
|
||||||
|
suspend fun optimizePricing(
|
||||||
|
ratePlanIds: List<String>,
|
||||||
|
strategy: String = "revenue_maximization"
|
||||||
|
): List<PricingOptimizationResult> {
|
||||||
|
return httpClient.post("/api/v1/analytics/pricing/optimize",
|
||||||
|
mapOf(
|
||||||
|
"rate_plan_ids" to ratePlanIds,
|
||||||
|
"strategy" to strategy
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get price elasticity data
|
||||||
|
*/
|
||||||
|
suspend fun getPriceElasticity(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/analytics/pricing/elasticity")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ChurnPrediction(
|
||||||
|
val profileId: String,
|
||||||
|
val riskLevel: String,
|
||||||
|
val riskScore: Double,
|
||||||
|
val predictedChurnDate: String? = null,
|
||||||
|
val reasons: List<String>,
|
||||||
|
val recommendations: List<String>,
|
||||||
|
val lastUpdated: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ChurnMetrics(
|
||||||
|
val period: String,
|
||||||
|
val totalSubscribers: Long,
|
||||||
|
val churnedSubscribers: Long,
|
||||||
|
val churnRate: Double,
|
||||||
|
val monthlyChurnRate: Double,
|
||||||
|
val annualChurnRate: Double,
|
||||||
|
val averageTenureDays: Double,
|
||||||
|
val riskDistribution: Map<String, Long>,
|
||||||
|
val generatedAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class MarketMetrics(
|
||||||
|
val period: String,
|
||||||
|
val totalMarketSize: Long,
|
||||||
|
val ourSubscribers: Long,
|
||||||
|
val marketShare: Double,
|
||||||
|
val growthRate: Double,
|
||||||
|
val byCountry: Map<String, JsonObject>,
|
||||||
|
val generatedAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class MaintenanceMetrics(
|
||||||
|
val period: String,
|
||||||
|
val totalAssets: Long,
|
||||||
|
val healthyAssets: Long,
|
||||||
|
val assetsNeedingAttention: Long,
|
||||||
|
val uptime: Double,
|
||||||
|
val meanTimeToFailure: Double,
|
||||||
|
val meanTimeToRepair: Double,
|
||||||
|
val generatedAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PricingMetrics(
|
||||||
|
val period: String,
|
||||||
|
val totalRevenue: Double,
|
||||||
|
val arpu: Double,
|
||||||
|
val priceElasticity: Double,
|
||||||
|
val competitiveIndex: Double,
|
||||||
|
val optimizationRoi: Double,
|
||||||
|
val generatedAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class PricingOptimizationResult(
|
||||||
|
val ratePlanId: String,
|
||||||
|
val strategy: String,
|
||||||
|
val currentPrice: Double,
|
||||||
|
val optimalPrice: Double,
|
||||||
|
val priceChangePct: Double,
|
||||||
|
val expectedRevenue: Double,
|
||||||
|
val expectedDemand: Double,
|
||||||
|
val confidence: Double,
|
||||||
|
val reasoning: List<String>,
|
||||||
|
val risks: List<String>,
|
||||||
|
val recommendations: List<String>
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class ChurnRiskLevel(val value: String) {
|
||||||
|
LOW("low"),
|
||||||
|
MEDIUM("medium"),
|
||||||
|
HIGH("high"),
|
||||||
|
CRITICAL("critical")
|
||||||
|
}
|
||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.telecom
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Currency and Billing API
|
||||||
|
*/
|
||||||
|
class CurrencyAPI(private val httpClient: HTTPClient) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert currency
|
||||||
|
*/
|
||||||
|
suspend fun convert(from: String, to: String, amount: Double): ConvertResponse {
|
||||||
|
return httpClient.post("/api/v1/currency/convert",
|
||||||
|
mapOf(
|
||||||
|
"from" to from,
|
||||||
|
"to" to to,
|
||||||
|
"amount" to amount
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get exchange rate between currencies
|
||||||
|
*/
|
||||||
|
suspend fun getExchangeRate(from: String, to: String): ExchangeRate {
|
||||||
|
return httpClient.get("/api/v1/currency/exchange/$from/$to")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get exchange rate history
|
||||||
|
*/
|
||||||
|
suspend fun getExchangeRateHistory(from: String, to: String, days: Int = 30): List<ExchangeRate> {
|
||||||
|
return httpClient.get("/api/v1/currency/exchange/$from/$to/history",
|
||||||
|
mapOf("days" to days))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get supported currencies
|
||||||
|
*/
|
||||||
|
suspend fun getSupportedCurrencies(): List<Currency> {
|
||||||
|
return httpClient.get("/api/v1/currency/currencies")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Refresh exchange rates
|
||||||
|
*/
|
||||||
|
suspend fun refreshExchangeRates(): JsonObject {
|
||||||
|
return httpClient.post("/api/v1/currency/exchange/refresh", emptyMap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process billing transaction
|
||||||
|
*/
|
||||||
|
suspend fun processBilling(billingData: Map<String, Any>): BillingTransaction {
|
||||||
|
return httpClient.post("/api/v1/currency/billing", billingData)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get billing history for a profile
|
||||||
|
*/
|
||||||
|
suspend fun getBillingHistory(profileId: String, limit: Int = 50): List<BillingTransaction> {
|
||||||
|
return httpClient.get("/api/v1/currency/billing/history/$profileId",
|
||||||
|
mapOf("limit" to limit))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get billing summary for a profile
|
||||||
|
*/
|
||||||
|
suspend fun getBillingSummary(profileId: String, period: String = "monthly"): BillingSummary {
|
||||||
|
return httpClient.get("/api/v1/currency/billing/summary/$profileId",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process refund
|
||||||
|
*/
|
||||||
|
suspend fun processRefund(transactionId: String, reason: String): BillingTransaction {
|
||||||
|
return httpClient.post("/api/v1/currency/billing/refund/$transactionId",
|
||||||
|
mapOf("reason" to reason))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get billing analytics
|
||||||
|
*/
|
||||||
|
suspend fun getBillingAnalytics(period: String = "monthly"): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/currency/billing/analytics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ConvertRequest(
|
||||||
|
val from: String,
|
||||||
|
val to: String,
|
||||||
|
val amount: Double
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ConvertResponse(
|
||||||
|
val from: String,
|
||||||
|
val to: String,
|
||||||
|
val amount: Double,
|
||||||
|
val converted: Double,
|
||||||
|
val rate: Double,
|
||||||
|
val timestamp: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class ExchangeRate(
|
||||||
|
val from: String,
|
||||||
|
val to: String,
|
||||||
|
val rate: Double,
|
||||||
|
val timestamp: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class Currency(
|
||||||
|
val code: String,
|
||||||
|
val name: String,
|
||||||
|
val symbol: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class BillingTransaction(
|
||||||
|
val id: String,
|
||||||
|
val profileId: String,
|
||||||
|
val amount: Double,
|
||||||
|
val currency: String,
|
||||||
|
val type: String,
|
||||||
|
val status: String,
|
||||||
|
val description: String,
|
||||||
|
val createdAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class BillingSummary(
|
||||||
|
val profileId: String,
|
||||||
|
val period: String,
|
||||||
|
val totalAmount: Double,
|
||||||
|
val currency: String,
|
||||||
|
val transactionCount: Int,
|
||||||
|
val breakdown: Map<String, Double>
|
||||||
|
)
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
package com.telecom
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API for GraphQL queries
|
|
||||||
*/
|
|
||||||
class GraphQLAPI(private val client: HTTPClient) {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Execute a GraphQL query
|
|
||||||
*/
|
|
||||||
suspend fun execute(query: String, variables: Map<String, Any>? = null): Map<String, Any> {
|
|
||||||
val request = GraphQLRequest(query, variables)
|
|
||||||
return client.post("/graphql", request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,134 @@
|
|||||||
|
package com.telecom
|
||||||
|
|
||||||
|
import kotlinx.serialization.Serializable
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Security API for fraud detection and SIM swap protection
|
||||||
|
*/
|
||||||
|
class SecurityAPI(private val httpClient: HTTPClient) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Analyze a transaction for fraud
|
||||||
|
*/
|
||||||
|
suspend fun analyzeTransaction(transaction: Map<String, Any>): FraudAlert? {
|
||||||
|
return httpClient.post("/api/v1/security/fraud/analyze", transaction)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get fraud alerts with filtering
|
||||||
|
*/
|
||||||
|
suspend fun getFraudAlerts(filter: FraudAlertFilter? = null): List<FraudAlert> {
|
||||||
|
val payload = filter?.let {
|
||||||
|
mapOf(
|
||||||
|
"type" to it.type,
|
||||||
|
"severity" to it.severity,
|
||||||
|
"status" to it.status,
|
||||||
|
"limit" to it.limit
|
||||||
|
).filterValues { it != null }
|
||||||
|
} ?: emptyMap()
|
||||||
|
|
||||||
|
return httpClient.post("/api/v1/security/fraud/alerts", payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Update fraud alert status
|
||||||
|
*/
|
||||||
|
suspend fun updateAlertStatus(
|
||||||
|
alertId: String,
|
||||||
|
status: String,
|
||||||
|
actions: List<String> = emptyList()
|
||||||
|
): JsonObject {
|
||||||
|
return httpClient.put("/api/v1/security/fraud/alerts/$alertId",
|
||||||
|
mapOf(
|
||||||
|
"status" to status,
|
||||||
|
"actions" to actions
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get fraud detection metrics
|
||||||
|
*/
|
||||||
|
suspend fun getFraudMetrics(period: String = "monthly"): FraudMetrics {
|
||||||
|
return httpClient.get("/api/v1/security/fraud/metrics",
|
||||||
|
mapOf("period" to period))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get detected fraud patterns
|
||||||
|
*/
|
||||||
|
suspend fun getFraudPatterns(): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/security/fraud/patterns")
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify SIM swap request
|
||||||
|
*/
|
||||||
|
suspend fun verifySIMSwap(profileId: String, msisdn: String): JsonObject {
|
||||||
|
return httpClient.post("/api/v1/security/simswap/verify",
|
||||||
|
mapOf(
|
||||||
|
"profile_id" to profileId,
|
||||||
|
"msisdn" to msisdn
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get SIM swap history for a profile
|
||||||
|
*/
|
||||||
|
suspend fun getSIMSwapHistory(profileId: String): JsonObject {
|
||||||
|
return httpClient.get("/api/v1/security/simswap/history/$profileId")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class FraudAlert(
|
||||||
|
val id: String,
|
||||||
|
val type: String,
|
||||||
|
val severity: String,
|
||||||
|
val profileId: String,
|
||||||
|
val description: String,
|
||||||
|
val riskScore: Double,
|
||||||
|
val evidence: List<String>,
|
||||||
|
val ipAddress: String,
|
||||||
|
val timestamp: String,
|
||||||
|
val status: String,
|
||||||
|
val actionsTaken: List<String>,
|
||||||
|
val metadata: Map<String, Any>
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class FraudMetrics(
|
||||||
|
val period: String,
|
||||||
|
val totalAlerts: Long,
|
||||||
|
val resolvedAlerts: Long,
|
||||||
|
val falsePositives: Long,
|
||||||
|
val resolutionRate: Double,
|
||||||
|
val falsePositiveRate: Double,
|
||||||
|
val byType: Map<String, Long>,
|
||||||
|
val bySeverity: Map<String, Long>,
|
||||||
|
val generatedAt: String
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
data class FraudAlertFilter(
|
||||||
|
val type: String? = null,
|
||||||
|
val severity: String? = null,
|
||||||
|
val status: String? = null,
|
||||||
|
val limit: Int = 50
|
||||||
|
)
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class FraudType(val value: String) {
|
||||||
|
ACCOUNT_TAKEOVER("account_takeover"),
|
||||||
|
SUBSCRIPTION_FRAUD("subscription_fraud"),
|
||||||
|
PAYMENT_FRAUD("payment_fraud"),
|
||||||
|
USAGE_ANOMALY("usage_anomaly"),
|
||||||
|
SIM_SWAP("sim_swap")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Serializable
|
||||||
|
enum class FraudSeverity(val value: String) {
|
||||||
|
LOW("low"),
|
||||||
|
MEDIUM("medium"),
|
||||||
|
HIGH("high"),
|
||||||
|
CRITICAL("critical")
|
||||||
|
}
|
||||||
@@ -17,7 +17,9 @@ class TelecomSDK private constructor(
|
|||||||
val payments: PaymentAPI
|
val payments: PaymentAPI
|
||||||
val ratingPlans: RatingPlanAPI
|
val ratingPlans: RatingPlanAPI
|
||||||
val system: SystemAPI
|
val system: SystemAPI
|
||||||
val graphql: GraphQLAPI
|
val analytics: AnalyticsAPI
|
||||||
|
val security: SecurityAPI
|
||||||
|
val currency: CurrencyAPI
|
||||||
|
|
||||||
companion object {
|
companion object {
|
||||||
/**
|
/**
|
||||||
@@ -33,9 +35,11 @@ class TelecomSDK private constructor(
|
|||||||
val payments = PaymentAPI(httpClient)
|
val payments = PaymentAPI(httpClient)
|
||||||
val ratingPlans = RatingPlanAPI(httpClient)
|
val ratingPlans = RatingPlanAPI(httpClient)
|
||||||
val system = SystemAPI(httpClient)
|
val system = SystemAPI(httpClient)
|
||||||
val graphql = GraphQLAPI(httpClient)
|
val analytics = AnalyticsAPI(httpClient)
|
||||||
|
val security = SecurityAPI(httpClient)
|
||||||
|
val currency = CurrencyAPI(httpClient)
|
||||||
|
|
||||||
return TelecomSDK(config, authProvider, httpClient, subscribers, usage, payments, ratingPlans, system, graphql)
|
return TelecomSDK(config, authProvider, httpClient, subscribers, usage, payments, ratingPlans, system, analytics, security, currency)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,7 +52,9 @@ class TelecomSDK private constructor(
|
|||||||
payments: PaymentAPI,
|
payments: PaymentAPI,
|
||||||
ratingPlans: RatingPlanAPI,
|
ratingPlans: RatingPlanAPI,
|
||||||
system: SystemAPI,
|
system: SystemAPI,
|
||||||
graphql: GraphQLAPI
|
analytics: AnalyticsAPI,
|
||||||
|
security: SecurityAPI,
|
||||||
|
currency: CurrencyAPI
|
||||||
) {
|
) {
|
||||||
this.config = config
|
this.config = config
|
||||||
this.authProvider = authProvider
|
this.authProvider = authProvider
|
||||||
@@ -58,7 +64,9 @@ class TelecomSDK private constructor(
|
|||||||
this.payments = payments
|
this.payments = payments
|
||||||
this.ratingPlans = ratingPlans
|
this.ratingPlans = ratingPlans
|
||||||
this.system = system
|
this.system = system
|
||||||
this.graphql = graphql
|
this.analytics = analytics
|
||||||
|
this.security = security
|
||||||
|
this.currency = currency
|
||||||
}
|
}
|
||||||
|
|
||||||
// Authentication methods
|
// Authentication methods
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ from .api import (
|
|||||||
SystemAPI,
|
SystemAPI,
|
||||||
GraphQLAPI,
|
GraphQLAPI,
|
||||||
)
|
)
|
||||||
|
from .analytics import AnalyticsAPI
|
||||||
|
from .security import SecurityAPI
|
||||||
|
from .currency import CurrencyAPI
|
||||||
from .websocket import WebSocketClient
|
from .websocket import WebSocketClient
|
||||||
from .types import (
|
from .types import (
|
||||||
Subscriber,
|
Subscriber,
|
||||||
@@ -21,6 +24,18 @@ from .types import (
|
|||||||
RatingPlan,
|
RatingPlan,
|
||||||
RealTimeUsage,
|
RealTimeUsage,
|
||||||
PaginatedResponse,
|
PaginatedResponse,
|
||||||
|
ChurnRiskLevel,
|
||||||
|
ChurnPrediction,
|
||||||
|
ChurnMetrics,
|
||||||
|
FraudType,
|
||||||
|
FraudSeverity,
|
||||||
|
FraudAlert,
|
||||||
|
FraudMetrics,
|
||||||
|
FraudAlertFilter,
|
||||||
|
MarketMetrics,
|
||||||
|
PredictiveMaintenanceMetrics,
|
||||||
|
PricingOptimizationResult,
|
||||||
|
PricingMetrics,
|
||||||
)
|
)
|
||||||
from .exceptions import (
|
from .exceptions import (
|
||||||
TelecomError,
|
TelecomError,
|
||||||
@@ -32,7 +47,7 @@ from .exceptions import (
|
|||||||
ServerError,
|
ServerError,
|
||||||
)
|
)
|
||||||
|
|
||||||
__version__ = "1.0.0"
|
__version__ = "2.0.0"
|
||||||
__all__ = [
|
__all__ = [
|
||||||
# Main SDK client
|
# Main SDK client
|
||||||
"TelecomSDK",
|
"TelecomSDK",
|
||||||
@@ -46,6 +61,9 @@ __all__ = [
|
|||||||
"RatingPlanAPI",
|
"RatingPlanAPI",
|
||||||
"SystemAPI",
|
"SystemAPI",
|
||||||
"GraphQLAPI",
|
"GraphQLAPI",
|
||||||
|
"AnalyticsAPI",
|
||||||
|
"SecurityAPI",
|
||||||
|
"CurrencyAPI",
|
||||||
# WebSocket
|
# WebSocket
|
||||||
"WebSocketClient",
|
"WebSocketClient",
|
||||||
# Types
|
# Types
|
||||||
@@ -59,6 +77,18 @@ __all__ = [
|
|||||||
"RatingPlan",
|
"RatingPlan",
|
||||||
"RealTimeUsage",
|
"RealTimeUsage",
|
||||||
"PaginatedResponse",
|
"PaginatedResponse",
|
||||||
|
"ChurnRiskLevel",
|
||||||
|
"ChurnPrediction",
|
||||||
|
"ChurnMetrics",
|
||||||
|
"FraudType",
|
||||||
|
"FraudSeverity",
|
||||||
|
"FraudAlert",
|
||||||
|
"FraudMetrics",
|
||||||
|
"FraudAlertFilter",
|
||||||
|
"MarketMetrics",
|
||||||
|
"PredictiveMaintenanceMetrics",
|
||||||
|
"PricingOptimizationResult",
|
||||||
|
"PricingMetrics",
|
||||||
# Exceptions
|
# Exceptions
|
||||||
"TelecomError",
|
"TelecomError",
|
||||||
"AuthenticationError",
|
"AuthenticationError",
|
||||||
|
|||||||
@@ -0,0 +1,92 @@
|
|||||||
|
"""Analytics API client for churn prediction, market analysis, and pricing optimization."""
|
||||||
|
|
||||||
|
from typing import List, Optional
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from .types import (
|
||||||
|
ChurnPrediction,
|
||||||
|
ChurnMetrics,
|
||||||
|
ChurnRiskLevel,
|
||||||
|
MarketMetrics,
|
||||||
|
PredictiveMaintenanceMetrics,
|
||||||
|
PricingOptimizationResult,
|
||||||
|
PricingMetrics,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class AnalyticsAPI:
|
||||||
|
"""Analytics API client for churn, market, maintenance, and pricing analytics."""
|
||||||
|
|
||||||
|
def __init__(self, client):
|
||||||
|
self._client = client
|
||||||
|
|
||||||
|
def predict_churn(self, profile_id: str) -> ChurnPrediction:
|
||||||
|
"""Predict churn risk for a profile."""
|
||||||
|
response = self._client.post("/api/v1/analytics/churn/predict", {"profile_id": profile_id})
|
||||||
|
return ChurnPrediction(**response)
|
||||||
|
|
||||||
|
def get_churn_metrics(self, period: str = "monthly") -> ChurnMetrics:
|
||||||
|
"""Get churn metrics for a period."""
|
||||||
|
response = self._client.get("/api/v1/analytics/churn/metrics", params={"period": period})
|
||||||
|
return ChurnMetrics(**response)
|
||||||
|
|
||||||
|
def get_at_risk_customers(
|
||||||
|
self, risk_level: ChurnRiskLevel, limit: int = 100
|
||||||
|
) -> List[ChurnPrediction]:
|
||||||
|
"""Get customers at risk of churning."""
|
||||||
|
response = self._client.get(
|
||||||
|
"/api/v1/analytics/churn/at-risk",
|
||||||
|
params={"risk_level": risk_level.value, "limit": str(limit)},
|
||||||
|
)
|
||||||
|
return [ChurnPrediction(**item) for item in response]
|
||||||
|
|
||||||
|
def get_market_metrics(self, period: str = "monthly") -> MarketMetrics:
|
||||||
|
"""Get market penetration metrics."""
|
||||||
|
response = self._client.get("/api/v1/analytics/market/metrics", params={"period": period})
|
||||||
|
return MarketMetrics(**response)
|
||||||
|
|
||||||
|
def get_competitors(self) -> dict:
|
||||||
|
"""Get competitor analysis."""
|
||||||
|
return self._client.get("/api/v1/analytics/market/competitors")
|
||||||
|
|
||||||
|
def get_market_opportunities(self) -> dict:
|
||||||
|
"""Get market opportunities."""
|
||||||
|
return self._client.get("/api/v1/analytics/market/opportunities")
|
||||||
|
|
||||||
|
def get_maintenance_metrics(self, period: str = "monthly") -> PredictiveMaintenanceMetrics:
|
||||||
|
"""Get predictive maintenance metrics."""
|
||||||
|
response = self._client.get(
|
||||||
|
"/api/v1/analytics/maintenance/metrics", params={"period": period}
|
||||||
|
)
|
||||||
|
return PredictiveMaintenanceMetrics(**response)
|
||||||
|
|
||||||
|
def get_assets_health(self) -> dict:
|
||||||
|
"""Get assets health status."""
|
||||||
|
return self._client.get("/api/v1/analytics/maintenance/assets")
|
||||||
|
|
||||||
|
def get_maintenance_alerts(self) -> dict:
|
||||||
|
"""Get maintenance alerts."""
|
||||||
|
return self._client.get("/api/v1/analytics/maintenance/alerts")
|
||||||
|
|
||||||
|
def predict_failure(self, asset_id: str) -> dict:
|
||||||
|
"""Predict failure for an asset."""
|
||||||
|
return self._client.post(f"/api/v1/analytics/maintenance/predict/{asset_id}", {})
|
||||||
|
|
||||||
|
def get_pricing_metrics(self, period: str = "monthly") -> PricingMetrics:
|
||||||
|
"""Get pricing optimization metrics."""
|
||||||
|
response = self._client.get("/api/v1/analytics/pricing/metrics", params={"period": period})
|
||||||
|
return PricingMetrics(**response)
|
||||||
|
|
||||||
|
def optimize_pricing(
|
||||||
|
self, rate_plan_ids: List[str], strategy: str = "revenue_maximization"
|
||||||
|
) -> List[PricingOptimizationResult]:
|
||||||
|
"""Optimize pricing for rate plans."""
|
||||||
|
response = self._client.post(
|
||||||
|
"/api/v1/analytics/pricing/optimize",
|
||||||
|
{"rate_plan_ids": rate_plan_ids, "strategy": strategy},
|
||||||
|
)
|
||||||
|
return [PricingOptimizationResult(**item) for item in response]
|
||||||
|
|
||||||
|
def get_price_elasticity(self) -> dict:
|
||||||
|
"""Get price elasticity data."""
|
||||||
|
return self._client.get("/api/v1/analytics/pricing/elasticity")
|
||||||
@@ -9,8 +9,10 @@ from .api import (
|
|||||||
PaymentAPI,
|
PaymentAPI,
|
||||||
RatingPlanAPI,
|
RatingPlanAPI,
|
||||||
SystemAPI,
|
SystemAPI,
|
||||||
GraphQLAPI,
|
|
||||||
)
|
)
|
||||||
|
from .analytics import AnalyticsAPI
|
||||||
|
from .security import SecurityAPI
|
||||||
|
from .currency import CurrencyAPI
|
||||||
from .websocket import WebSocketClient
|
from .websocket import WebSocketClient
|
||||||
from .types import (
|
from .types import (
|
||||||
Subscriber,
|
Subscriber,
|
||||||
@@ -99,7 +101,9 @@ class TelecomSDK:
|
|||||||
self.payments = PaymentAPI(self.api_client)
|
self.payments = PaymentAPI(self.api_client)
|
||||||
self.rating_plans = RatingPlanAPI(self.api_client)
|
self.rating_plans = RatingPlanAPI(self.api_client)
|
||||||
self.system = SystemAPI(self.api_client)
|
self.system = SystemAPI(self.api_client)
|
||||||
self.graphql = GraphQLAPI(self.api_client)
|
self.analytics = AnalyticsAPI(self.api_client)
|
||||||
|
self.security = SecurityAPI(self.api_client)
|
||||||
|
self.currency = CurrencyAPI(self.api_client)
|
||||||
|
|
||||||
async def __aenter__(self):
|
async def __aenter__(self):
|
||||||
"""Async context manager entry."""
|
"""Async context manager entry."""
|
||||||
|
|||||||
@@ -0,0 +1,68 @@
|
|||||||
|
"""Currency and Billing API client."""
|
||||||
|
|
||||||
|
from typing import List, Optional, Dict, Any
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
|
||||||
|
class CurrencyAPI:
|
||||||
|
"""Currency and Billing API client."""
|
||||||
|
|
||||||
|
def __init__(self, client):
|
||||||
|
self._client = client
|
||||||
|
|
||||||
|
def convert(self, from_currency: str, to_currency: str, amount: float) -> dict:
|
||||||
|
"""Convert currency."""
|
||||||
|
return self._client.post(
|
||||||
|
"/api/v1/currency/convert",
|
||||||
|
{"from": from_currency, "to": to_currency, "amount": amount},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_exchange_rate(self, from_currency: str, to_currency: str) -> dict:
|
||||||
|
"""Get exchange rate between currencies."""
|
||||||
|
return self._client.get(f"/api/v1/currency/exchange/{from_currency}/{to_currency}")
|
||||||
|
|
||||||
|
def get_exchange_rate_history(
|
||||||
|
self, from_currency: str, to_currency: str, days: int = 30
|
||||||
|
) -> dict:
|
||||||
|
"""Get exchange rate history."""
|
||||||
|
return self._client.get(
|
||||||
|
f"/api/v1/currency/exchange/{from_currency}/{to_currency}/history",
|
||||||
|
params={"days": str(days)},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_supported_currencies(self) -> dict:
|
||||||
|
"""Get list of supported currencies."""
|
||||||
|
return self._client.get("/api/v1/currency/currencies")
|
||||||
|
|
||||||
|
def refresh_exchange_rates(self) -> dict:
|
||||||
|
"""Refresh exchange rates from external sources."""
|
||||||
|
return self._client.post("/api/v1/currency/exchange/refresh", {})
|
||||||
|
|
||||||
|
def process_billing(self, billing_data: Dict[str, Any]) -> dict:
|
||||||
|
"""Process billing transaction."""
|
||||||
|
return self._client.post("/api/v1/currency/billing", billing_data)
|
||||||
|
|
||||||
|
def get_billing_history(self, profile_id: str, limit: int = 50) -> dict:
|
||||||
|
"""Get billing history for a profile."""
|
||||||
|
return self._client.get(
|
||||||
|
f"/api/v1/currency/billing/history/{profile_id}",
|
||||||
|
params={"limit": str(limit)},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_billing_summary(self, profile_id: str, period: str = "monthly") -> dict:
|
||||||
|
"""Get billing summary for a profile."""
|
||||||
|
return self._client.get(
|
||||||
|
f"/api/v1/currency/billing/summary/{profile_id}",
|
||||||
|
params={"period": period},
|
||||||
|
)
|
||||||
|
|
||||||
|
def process_refund(self, transaction_id: str, reason: str) -> dict:
|
||||||
|
"""Process a refund for a transaction."""
|
||||||
|
return self._client.post(
|
||||||
|
f"/api/v1/currency/billing/refund/{transaction_id}",
|
||||||
|
{"reason": reason},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_billing_analytics(self, period: str = "monthly") -> dict:
|
||||||
|
"""Get billing analytics."""
|
||||||
|
return self._client.get("/api/v1/currency/billing/analytics", params={"period": period})
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"""Security API client for fraud detection and SIM swap protection."""
|
||||||
|
|
||||||
|
from typing import List, Optional, Dict, Any
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
from .types import (
|
||||||
|
FraudAlert,
|
||||||
|
FraudMetrics,
|
||||||
|
FraudAlertFilter,
|
||||||
|
FraudType,
|
||||||
|
FraudSeverity,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class SecurityAPI:
|
||||||
|
"""Security API client for fraud detection and protection."""
|
||||||
|
|
||||||
|
def __init__(self, client):
|
||||||
|
self._client = client
|
||||||
|
|
||||||
|
def analyze_transaction(self, transaction: Dict[str, Any]) -> Optional[FraudAlert]:
|
||||||
|
"""Analyze a transaction for fraud."""
|
||||||
|
response = self._client.post("/api/v1/security/fraud/analyze", transaction)
|
||||||
|
if response and response.get("id"):
|
||||||
|
return FraudAlert(**response)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def get_fraud_alerts(self, filter: Optional[FraudAlertFilter] = None) -> List[FraudAlert]:
|
||||||
|
"""Get fraud alerts with optional filtering."""
|
||||||
|
payload = {}
|
||||||
|
if filter:
|
||||||
|
payload = filter.model_dump(exclude_none=True)
|
||||||
|
response = self._client.post("/api/v1/security/fraud/alerts", payload)
|
||||||
|
return [FraudAlert(**item) for item in response]
|
||||||
|
|
||||||
|
def update_alert_status(
|
||||||
|
self, alert_id: str, status: str, actions: Optional[List[str]] = None
|
||||||
|
) -> dict:
|
||||||
|
"""Update fraud alert status."""
|
||||||
|
payload = {"status": status}
|
||||||
|
if actions:
|
||||||
|
payload["actions"] = actions
|
||||||
|
return self._client.put(f"/api/v1/security/fraud/alerts/{alert_id}", payload)
|
||||||
|
|
||||||
|
def get_fraud_metrics(self, period: str = "monthly") -> FraudMetrics:
|
||||||
|
"""Get fraud detection metrics."""
|
||||||
|
response = self._client.get("/api/v1/security/fraud/metrics", params={"period": period})
|
||||||
|
return FraudMetrics(**response)
|
||||||
|
|
||||||
|
def get_fraud_patterns(self) -> dict:
|
||||||
|
"""Get detected fraud patterns."""
|
||||||
|
return self._client.get("/api/v1/security/fraud/patterns")
|
||||||
|
|
||||||
|
def verify_sim_swap(self, profile_id: str, msisdn: str) -> dict:
|
||||||
|
"""Verify SIM swap request."""
|
||||||
|
return self._client.post(
|
||||||
|
"/api/v1/security/simswap/verify",
|
||||||
|
{"profile_id": profile_id, "msisdn": msisdn},
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_sim_swap_history(self, profile_id: str) -> dict:
|
||||||
|
"""Get SIM swap history for a profile."""
|
||||||
|
return self._client.get(f"/api/v1/security/simswap/history/{profile_id}")
|
||||||
@@ -79,13 +79,11 @@ class HealthStatus(BaseModel):
|
|||||||
checks: Dict[str, Dict[str, Any]]
|
checks: Dict[str, Dict[str, Any]]
|
||||||
uptime: float = Field(ge=0.0)
|
uptime: float = Field(ge=0.0)
|
||||||
|
|
||||||
|
|
||||||
class WebSocketMessage(BaseModel):
|
class WebSocketMessage(BaseModel):
|
||||||
type: str
|
type: str
|
||||||
data: Dict[str, Any]
|
data: Dict[str, Any]
|
||||||
timestamp: datetime
|
timestamp: datetime
|
||||||
|
|
||||||
|
|
||||||
class UsageEvent(BaseModel):
|
class UsageEvent(BaseModel):
|
||||||
id: str
|
id: str
|
||||||
subscriber_id: str
|
subscriber_id: str
|
||||||
@@ -95,7 +93,6 @@ class UsageEvent(BaseModel):
|
|||||||
timestamp: datetime
|
timestamp: datetime
|
||||||
metadata: Optional[Dict[str, Any]] = None
|
metadata: Optional[Dict[str, Any]] = None
|
||||||
|
|
||||||
|
|
||||||
class RatingPlan(BaseModel):
|
class RatingPlan(BaseModel):
|
||||||
plan_id: str
|
plan_id: str
|
||||||
name: str
|
name: str
|
||||||
@@ -137,5 +134,212 @@ class PaginatedResponse(BaseModel):
|
|||||||
total: int = Field(ge=0)
|
total: int = Field(ge=0)
|
||||||
page: int = Field(ge=1)
|
page: int = Field(ge=1)
|
||||||
page_size: int = Field(ge=1, le=100)
|
page_size: int = Field(ge=1, le=100)
|
||||||
|
|
||||||
|
class ChurnRiskLevel(str, Enum):
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
CRITICAL = "critical"
|
||||||
|
|
||||||
|
|
||||||
|
class ChurnPrediction(BaseModel):
|
||||||
|
profile_id: str
|
||||||
|
risk_level: ChurnRiskLevel
|
||||||
|
risk_score: float = Field(ge=0.0, le=100.0)
|
||||||
|
predicted_churn_date: Optional[datetime] = None
|
||||||
|
reasons: List[str]
|
||||||
|
recommendations: List[str]
|
||||||
|
last_updated: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class ChurnMetrics(BaseModel):
|
||||||
|
period: str
|
||||||
|
total_subscribers: int = Field(ge=0)
|
||||||
|
churned_subscribers: int = Field(ge=0)
|
||||||
|
churn_rate: float = Field(ge=0.0)
|
||||||
|
monthly_churn_rate: float = Field(ge=0.0)
|
||||||
|
annual_churn_rate: float = Field(ge=0.0)
|
||||||
|
average_tenure_days: float = Field(ge=0.0)
|
||||||
|
risk_distribution: Dict[ChurnRiskLevel, int]
|
||||||
|
generated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class FraudType(str, Enum):
|
||||||
|
ACCOUNT_TAKEOVER = "account_takeover"
|
||||||
|
SUBSCRIPTION_FRAUD = "subscription_fraud"
|
||||||
|
PAYMENT_FRAUD = "payment_fraud"
|
||||||
|
USAGE_ANOMALY = "usage_anomaly"
|
||||||
|
SIM_SWAP = "sim_swap"
|
||||||
|
|
||||||
|
|
||||||
|
class FraudSeverity(str, Enum):
|
||||||
|
LOW = "low"
|
||||||
|
MEDIUM = "medium"
|
||||||
|
HIGH = "high"
|
||||||
|
CRITICAL = "critical"
|
||||||
|
|
||||||
|
|
||||||
|
class FraudAlert(BaseModel):
|
||||||
|
id: str
|
||||||
|
type: FraudType
|
||||||
|
severity: FraudSeverity
|
||||||
|
profile_id: str
|
||||||
|
description: str
|
||||||
|
risk_score: float = Field(ge=0.0, le=100.0)
|
||||||
|
evidence: List[str]
|
||||||
|
ip_address: str
|
||||||
|
timestamp: datetime
|
||||||
|
status: str
|
||||||
|
actions_taken: List[str]
|
||||||
|
metadata: Dict[str, Any]
|
||||||
|
|
||||||
|
|
||||||
|
class FraudMetrics(BaseModel):
|
||||||
|
period: str
|
||||||
|
total_alerts: int = Field(ge=0)
|
||||||
|
resolved_alerts: int = Field(ge=0)
|
||||||
|
false_positives: int = Field(ge=0)
|
||||||
|
resolution_rate_pct: float = Field(ge=0.0)
|
||||||
|
false_positive_rate_pct: float = Field(ge=0.0)
|
||||||
|
by_type: Dict[FraudType, int]
|
||||||
|
by_severity: Dict[FraudSeverity, int]
|
||||||
|
generated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class FraudAlertFilter(BaseModel):
|
||||||
|
type: Optional[FraudType] = None
|
||||||
|
severity: Optional[FraudSeverity] = None
|
||||||
|
status: Optional[str] = None
|
||||||
|
from_date: Optional[datetime] = None
|
||||||
|
to_date: Optional[datetime] = None
|
||||||
|
limit: Optional[int] = Field(None, ge=1, le=1000)
|
||||||
|
|
||||||
|
|
||||||
|
class MarketMetrics(BaseModel):
|
||||||
|
period: str
|
||||||
|
total_market_size: int = Field(ge=0)
|
||||||
|
our_subscribers: int = Field(ge=0)
|
||||||
|
market_share_pct: float = Field(ge=0.0)
|
||||||
|
growth_rate_pct: float = Field(ge=0.0)
|
||||||
|
by_country: Dict[str, "CountryMetrics"]
|
||||||
|
by_carrier: Dict[str, "MarketCarrierMetrics"]
|
||||||
|
by_demographic: Dict[str, "DemoMetrics"]
|
||||||
|
competitor_analysis: Dict[str, "CompetitorMetrics"]
|
||||||
|
market_opportunities: List["MarketOpportunity"]
|
||||||
|
generated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class CountryMetrics(BaseModel):
|
||||||
|
country: str
|
||||||
|
market_size: int = Field(ge=0)
|
||||||
|
our_subscribers: int = Field(ge=0)
|
||||||
|
market_share_pct: float = Field(ge=0.0)
|
||||||
|
growth_rate_pct: float = Field(ge=0.0)
|
||||||
|
average_revenue: float = Field(ge=0.0)
|
||||||
|
|
||||||
|
|
||||||
|
class MarketCarrierMetrics(BaseModel):
|
||||||
|
carrier_id: str
|
||||||
|
carrier_name: str
|
||||||
|
subscribers: int = Field(ge=0)
|
||||||
|
market_share_pct: float = Field(ge=0.0)
|
||||||
|
average_revenue: float = Field(ge=0.0)
|
||||||
|
quality_score: float = Field(ge=0.0, le=100.0)
|
||||||
|
|
||||||
|
|
||||||
|
class DemoMetrics(BaseModel):
|
||||||
|
segment: str
|
||||||
|
subscribers: int = Field(ge=0)
|
||||||
|
market_share_pct: float = Field(ge=0.0)
|
||||||
|
average_revenue: float = Field(ge=0.0)
|
||||||
|
growth_rate_pct: float = Field(ge=0.0)
|
||||||
|
|
||||||
|
|
||||||
|
class CompetitorMetrics(BaseModel):
|
||||||
|
name: str
|
||||||
|
market_share_pct: float = Field(ge=0.0)
|
||||||
|
subscribers: int = Field(ge=0)
|
||||||
|
average_price: float = Field(ge=0.0)
|
||||||
|
strengths: List[str]
|
||||||
|
weaknesses: List[str]
|
||||||
|
|
||||||
|
|
||||||
|
class MarketOpportunity(BaseModel):
|
||||||
|
id: str
|
||||||
|
type: str
|
||||||
|
description: str
|
||||||
|
potential_size: int = Field(ge=0)
|
||||||
|
confidence: float = Field(ge=0.0, le=100.0)
|
||||||
|
required_actions: List[str]
|
||||||
|
|
||||||
|
|
||||||
|
class PredictiveMaintenanceMetrics(BaseModel):
|
||||||
|
period: str
|
||||||
|
total_assets: int = Field(ge=0)
|
||||||
|
healthy_assets: int = Field(ge=0)
|
||||||
|
at_risk_assets: int = Field(ge=0)
|
||||||
|
critical_assets: int = Field(ge=0)
|
||||||
|
overall_health_score: float = Field(ge=0.0, le=100.0)
|
||||||
|
by_asset_type: Dict[str, "AssetTypeMetrics"]
|
||||||
|
predicted_failures: List["PredictedFailure"]
|
||||||
|
maintenance_schedule: List["MaintenanceTask"]
|
||||||
|
generated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class AssetTypeMetrics(BaseModel):
|
||||||
|
asset_type: str
|
||||||
|
total: int = Field(ge=0)
|
||||||
|
healthy: int = Field(ge=0)
|
||||||
|
at_risk: int = Field(ge=0)
|
||||||
|
critical: int = Field(ge=0)
|
||||||
|
health_score: float = Field(ge=0.0, le=100.0)
|
||||||
|
|
||||||
|
|
||||||
|
class PredictedFailure(BaseModel):
|
||||||
|
asset_id: str
|
||||||
|
asset_type: str
|
||||||
|
failure_type: str
|
||||||
|
predicted_date: datetime
|
||||||
|
confidence: float = Field(ge=0.0, le=100.0)
|
||||||
|
recommended_actions: List[str]
|
||||||
|
|
||||||
|
|
||||||
|
class MaintenanceTask(BaseModel):
|
||||||
|
id: str
|
||||||
|
asset_id: str
|
||||||
|
task_type: str
|
||||||
|
priority: str
|
||||||
|
scheduled_date: datetime
|
||||||
|
estimated_duration_minutes: int = Field(ge=0)
|
||||||
|
description: str
|
||||||
|
status: str
|
||||||
|
|
||||||
|
|
||||||
|
class PricingOptimizationResult(BaseModel):
|
||||||
|
rate_plan_id: str
|
||||||
|
current_price: float = Field(ge=0.0)
|
||||||
|
optimal_price: float = Field(ge=0.0)
|
||||||
|
strategy: str
|
||||||
|
expected_revenue: float = Field(ge=0.0)
|
||||||
|
expected_demand: int = Field(ge=0)
|
||||||
|
price_change_pct: float
|
||||||
|
reasoning: List[str]
|
||||||
|
risks: List[str]
|
||||||
|
recommendations: List[str]
|
||||||
|
confidence: float = Field(ge=0.0, le=100.0)
|
||||||
|
generated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class PricingMetrics(BaseModel):
|
||||||
|
period: str
|
||||||
|
total_rate_plans: int = Field(ge=0)
|
||||||
|
optimized_rate_plans: int = Field(ge=0)
|
||||||
|
average_price_change_pct: float
|
||||||
|
expected_revenue_impact_pct: float
|
||||||
|
churn_rate_reduction_pct: float
|
||||||
|
price_elasticity: float
|
||||||
|
competitive_index: float
|
||||||
|
optimization_roi_pct: float
|
||||||
|
generated_at: datetime
|
||||||
has_next: bool
|
has_next: bool
|
||||||
has_prev: bool
|
has_prev: bool
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ require_relative "telecom_sdk/usage_api"
|
|||||||
require_relative "telecom_sdk/payments_api"
|
require_relative "telecom_sdk/payments_api"
|
||||||
require_relative "telecom_sdk/rating_plans_api"
|
require_relative "telecom_sdk/rating_plans_api"
|
||||||
require_relative "telecom_sdk/system_api"
|
require_relative "telecom_sdk/system_api"
|
||||||
require_relative "telecom_sdk/graphql_api"
|
require_relative "telecom_sdk/analytics_api"
|
||||||
|
require_relative "telecom_sdk/security_api"
|
||||||
|
require_relative "telecom_sdk/currency_api"
|
||||||
|
|
||||||
module TelecomSDK
|
module TelecomSDK
|
||||||
class Error < StandardError; end
|
class Error < StandardError; end
|
||||||
@@ -22,7 +24,7 @@ module TelecomSDK
|
|||||||
class ServerError < Error; end
|
class ServerError < Error; end
|
||||||
|
|
||||||
class Client
|
class Client
|
||||||
attr_reader :config, :subscribers, :usage, :payments, :rating_plans, :system, :graphql
|
attr_reader :config, :subscribers, :usage, :payments, :rating_plans, :system, :analytics, :security, :currency
|
||||||
|
|
||||||
def initialize(config = {})
|
def initialize(config = {})
|
||||||
@config = Config.new(config)
|
@config = Config.new(config)
|
||||||
@@ -42,7 +44,9 @@ module TelecomSDK
|
|||||||
@payments = PaymentAPI.new(@http_client)
|
@payments = PaymentAPI.new(@http_client)
|
||||||
@rating_plans = RatingPlanAPI.new(@http_client)
|
@rating_plans = RatingPlanAPI.new(@http_client)
|
||||||
@system = SystemAPI.new(@http_client)
|
@system = SystemAPI.new(@http_client)
|
||||||
@graphql = GraphQLAPI.new(@http_client)
|
@analytics = AnalyticsAPI.new(@http_client)
|
||||||
|
@security = SecurityAPI.new(@http_client)
|
||||||
|
@currency = CurrencyAPI.new(@http_client)
|
||||||
end
|
end
|
||||||
|
|
||||||
# Authentication methods
|
# Authentication methods
|
||||||
|
|||||||
@@ -0,0 +1,73 @@
|
|||||||
|
module TelecomSDK
|
||||||
|
class AnalyticsAPI
|
||||||
|
def initialize(http_client)
|
||||||
|
@http_client = http_client
|
||||||
|
end
|
||||||
|
|
||||||
|
# Churn Analysis
|
||||||
|
|
||||||
|
def predict_churn(profile_id)
|
||||||
|
@http_client.post("/api/v1/analytics/churn/predict", { profile_id: profile_id })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_churn_metrics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/analytics/churn/metrics", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_at_risk_customers(risk_level:, limit: 100)
|
||||||
|
@http_client.post("/api/v1/analytics/churn/at-risk", {
|
||||||
|
risk_level: risk_level,
|
||||||
|
limit: limit
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Market Analytics
|
||||||
|
|
||||||
|
def get_market_metrics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/analytics/market/metrics", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_competitors
|
||||||
|
@http_client.get("/api/v1/analytics/market/competitors")
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_market_opportunities
|
||||||
|
@http_client.get("/api/v1/analytics/market/opportunities")
|
||||||
|
end
|
||||||
|
|
||||||
|
# Predictive Maintenance
|
||||||
|
|
||||||
|
def get_maintenance_metrics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/analytics/maintenance/metrics", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_assets_health
|
||||||
|
@http_client.get("/api/v1/analytics/maintenance/assets")
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_maintenance_alerts
|
||||||
|
@http_client.get("/api/v1/analytics/maintenance/alerts")
|
||||||
|
end
|
||||||
|
|
||||||
|
def predict_failure(asset_id)
|
||||||
|
@http_client.post("/api/v1/analytics/maintenance/predict/#{asset_id}", {})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Pricing Optimization
|
||||||
|
|
||||||
|
def get_pricing_metrics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/analytics/pricing/metrics", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def optimize_pricing(rate_plan_ids:, strategy: "revenue_maximization")
|
||||||
|
@http_client.post("/api/v1/analytics/pricing/optimize", {
|
||||||
|
rate_plan_ids: rate_plan_ids,
|
||||||
|
strategy: strategy
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_price_elasticity
|
||||||
|
@http_client.get("/api/v1/analytics/pricing/elasticity")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
module TelecomSDK
|
||||||
|
class CurrencyAPI
|
||||||
|
def initialize(http_client)
|
||||||
|
@http_client = http_client
|
||||||
|
end
|
||||||
|
|
||||||
|
# Currency Conversion
|
||||||
|
|
||||||
|
def convert(from:, to:, amount:)
|
||||||
|
@http_client.post("/api/v1/currency/convert", {
|
||||||
|
from: from,
|
||||||
|
to: to,
|
||||||
|
amount: amount
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_exchange_rate(from:, to:)
|
||||||
|
@http_client.get("/api/v1/currency/exchange/#{from}/#{to}")
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_exchange_rate_history(from:, to:, days: 30)
|
||||||
|
@http_client.get("/api/v1/currency/exchange/#{from}/#{to}/history", { days: days })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_supported_currencies
|
||||||
|
@http_client.get("/api/v1/currency/currencies")
|
||||||
|
end
|
||||||
|
|
||||||
|
def refresh_exchange_rates
|
||||||
|
@http_client.post("/api/v1/currency/exchange/refresh", {})
|
||||||
|
end
|
||||||
|
|
||||||
|
# Billing
|
||||||
|
|
||||||
|
def process_billing(billing_data)
|
||||||
|
@http_client.post("/api/v1/currency/billing", billing_data)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_history(profile_id:, limit: 50)
|
||||||
|
@http_client.get("/api/v1/currency/billing/history/#{profile_id}", { limit: limit })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_summary(profile_id:, period: "monthly")
|
||||||
|
@http_client.get("/api/v1/currency/billing/summary/#{profile_id}", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def process_refund(transaction_id:, reason:)
|
||||||
|
@http_client.post("/api/v1/currency/billing/refund/#{transaction_id}", { reason: reason })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_billing_analytics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/currency/billing/analytics", { period: period })
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
module TelecomSDK
|
|
||||||
# API for GraphQL queries
|
|
||||||
class GraphQLAPI
|
|
||||||
def initialize(client)
|
|
||||||
@client = client
|
|
||||||
end
|
|
||||||
|
|
||||||
def execute(query, variables = nil)
|
|
||||||
request = { query: query }
|
|
||||||
request[:variables] = variables if variables
|
|
||||||
@client.post("/graphql", request)
|
|
||||||
end
|
|
||||||
end
|
|
||||||
end
|
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
module TelecomSDK
|
||||||
|
class SecurityAPI
|
||||||
|
def initialize(http_client)
|
||||||
|
@http_client = http_client
|
||||||
|
end
|
||||||
|
|
||||||
|
# Fraud Detection
|
||||||
|
|
||||||
|
def analyze_transaction(transaction)
|
||||||
|
@http_client.post("/api/v1/security/fraud/analyze", transaction)
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_alerts(filter: nil)
|
||||||
|
payload = filter&.compact || {}
|
||||||
|
@http_client.post("/api/v1/security/fraud/alerts", payload)
|
||||||
|
end
|
||||||
|
|
||||||
|
def update_alert_status(alert_id:, status:, actions: [])
|
||||||
|
@http_client.put("/api/v1/security/fraud/alerts/#{alert_id}", {
|
||||||
|
status: status,
|
||||||
|
actions: actions
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_metrics(period: "monthly")
|
||||||
|
@http_client.get("/api/v1/security/fraud/metrics", { period: period })
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_fraud_patterns
|
||||||
|
@http_client.get("/api/v1/security/fraud/patterns")
|
||||||
|
end
|
||||||
|
|
||||||
|
# SIM Swap Protection
|
||||||
|
|
||||||
|
def verify_sim_swap(profile_id:, msisdn:)
|
||||||
|
@http_client.post("/api/v1/security/simswap/verify", {
|
||||||
|
profile_id: profile_id,
|
||||||
|
msisdn: msisdn
|
||||||
|
})
|
||||||
|
end
|
||||||
|
|
||||||
|
def get_sim_swap_history(profile_id)
|
||||||
|
@http_client.get("/api/v1/security/simswap/history/#{profile_id}")
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
use crate::client::HTTPClient;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Analytics API for churn prediction, market analysis, and pricing optimization
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct AnalyticsAPI {
|
||||||
|
client: HTTPClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AnalyticsAPI {
|
||||||
|
pub fn new(client: HTTPClient) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Churn Analysis
|
||||||
|
|
||||||
|
/// Predict churn risk for a profile
|
||||||
|
pub async fn predict_churn(&self, profile_id: &str) -> Result<ChurnPrediction, crate::error::TelecomError> {
|
||||||
|
let body = serde_json::json!({ "profile_id": profile_id });
|
||||||
|
self.client.post("/api/v1/analytics/churn/predict", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get churn metrics
|
||||||
|
pub async fn get_churn_metrics(&self, period: Option<&str>) -> Result<ChurnMetrics, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/analytics/churn/metrics", ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get at-risk customers
|
||||||
|
pub async fn get_at_risk_customers(
|
||||||
|
&self,
|
||||||
|
risk_level: ChurnRiskLevel,
|
||||||
|
limit: Option<u32>,
|
||||||
|
) -> Result<Vec<ChurnPrediction>, crate::error::TelecomError> {
|
||||||
|
let mut body = serde_json::json!({ "risk_level": risk_level });
|
||||||
|
if let Some(l) = limit {
|
||||||
|
body["limit"] = serde_json::Value::Number(l.into());
|
||||||
|
}
|
||||||
|
self.client.post("/api/v1/analytics/churn/at-risk", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Market Analytics
|
||||||
|
|
||||||
|
/// Get market metrics
|
||||||
|
pub async fn get_market_metrics(&self, period: Option<&str>) -> Result<MarketMetrics, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/analytics/market/metrics", ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get competitor analysis
|
||||||
|
pub async fn get_competitors(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/analytics/market/competitors", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get market opportunities
|
||||||
|
pub async fn get_market_opportunities(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/analytics/market/opportunities", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Predictive Maintenance
|
||||||
|
|
||||||
|
/// Get maintenance metrics
|
||||||
|
pub async fn get_maintenance_metrics(&self, period: Option<&str>) -> Result<MaintenanceMetrics, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/analytics/maintenance/metrics", ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get assets health
|
||||||
|
pub async fn get_assets_health(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/analytics/maintenance/assets", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get maintenance alerts
|
||||||
|
pub async fn get_maintenance_alerts(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/analytics/maintenance/alerts", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Predict failure for an asset
|
||||||
|
pub async fn predict_failure(&self, asset_id: &str) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.post(&format!("/api/v1/analytics/maintenance/predict/{}", asset_id), &serde_json::Value::Null).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pricing Optimization
|
||||||
|
|
||||||
|
/// Get pricing metrics
|
||||||
|
pub async fn get_pricing_metrics(&self, period: Option<&str>) -> Result<PricingMetrics, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/analytics/pricing/metrics", ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Optimize pricing for rate plans
|
||||||
|
pub async fn optimize_pricing(
|
||||||
|
&self,
|
||||||
|
rate_plan_ids: Vec<String>,
|
||||||
|
strategy: Option<&str>,
|
||||||
|
) -> Result<Vec<PricingOptimizationResult>, crate::error::TelecomError> {
|
||||||
|
let mut body = serde_json::json!({ "rate_plan_ids": rate_plan_ids });
|
||||||
|
if let Some(s) = strategy {
|
||||||
|
body["strategy"] = serde_json::Value::String(s.to_string());
|
||||||
|
}
|
||||||
|
self.client.post("/api/v1/analytics/pricing/optimize", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get price elasticity data
|
||||||
|
pub async fn get_price_elasticity(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/analytics/pricing/elasticity", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Analytics Types
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ChurnPrediction {
|
||||||
|
pub profile_id: String,
|
||||||
|
pub risk_level: String,
|
||||||
|
pub risk_score: f64,
|
||||||
|
pub predicted_churn_date: Option<String>,
|
||||||
|
pub reasons: Vec<String>,
|
||||||
|
pub recommendations: Vec<String>,
|
||||||
|
pub last_updated: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ChurnMetrics {
|
||||||
|
pub period: String,
|
||||||
|
pub total_subscribers: i64,
|
||||||
|
pub churned_subscribers: i64,
|
||||||
|
pub churn_rate: f64,
|
||||||
|
pub monthly_churn_rate: f64,
|
||||||
|
pub annual_churn_rate: f64,
|
||||||
|
pub average_tenure_days: f64,
|
||||||
|
pub risk_distribution: HashMap<String, i64>,
|
||||||
|
pub generated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MarketMetrics {
|
||||||
|
pub period: String,
|
||||||
|
pub total_market_size: i64,
|
||||||
|
pub our_subscribers: i64,
|
||||||
|
pub market_share: f64,
|
||||||
|
pub growth_rate: f64,
|
||||||
|
pub by_country: HashMap<String, serde_json::Value>,
|
||||||
|
pub generated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct MaintenanceMetrics {
|
||||||
|
pub period: String,
|
||||||
|
pub total_assets: i64,
|
||||||
|
pub healthy_assets: i64,
|
||||||
|
pub assets_needing_attention: i64,
|
||||||
|
pub uptime: f64,
|
||||||
|
pub mean_time_to_failure: f64,
|
||||||
|
pub mean_time_to_repair: f64,
|
||||||
|
pub generated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PricingMetrics {
|
||||||
|
pub period: String,
|
||||||
|
pub total_revenue: f64,
|
||||||
|
pub arpu: f64,
|
||||||
|
pub price_elasticity: f64,
|
||||||
|
pub competitive_index: f64,
|
||||||
|
pub optimization_roi: f64,
|
||||||
|
pub generated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct PricingOptimizationResult {
|
||||||
|
pub rate_plan_id: String,
|
||||||
|
pub strategy: String,
|
||||||
|
pub current_price: f64,
|
||||||
|
pub optimal_price: f64,
|
||||||
|
pub price_change_pct: f64,
|
||||||
|
pub expected_revenue: f64,
|
||||||
|
pub expected_demand: f64,
|
||||||
|
pub confidence: f64,
|
||||||
|
pub reasoning: Vec<String>,
|
||||||
|
pub risks: Vec<String>,
|
||||||
|
pub recommendations: Vec<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum ChurnRiskLevel {
|
||||||
|
Low,
|
||||||
|
Medium,
|
||||||
|
High,
|
||||||
|
Critical,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AsRef<str> for ChurnRiskLevel {
|
||||||
|
fn as_ref(&self) -> &str {
|
||||||
|
match self {
|
||||||
|
ChurnRiskLevel::Low => "low",
|
||||||
|
ChurnRiskLevel::Medium => "medium",
|
||||||
|
ChurnRiskLevel::High => "high",
|
||||||
|
ChurnRiskLevel::Critical => "critical",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,178 @@
|
|||||||
|
use crate::client::HTTPClient;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Currency and Billing API
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct CurrencyAPI {
|
||||||
|
client: HTTPClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl CurrencyAPI {
|
||||||
|
pub fn new(client: HTTPClient) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Currency Conversion
|
||||||
|
|
||||||
|
/// Convert currency
|
||||||
|
pub async fn convert(
|
||||||
|
&self,
|
||||||
|
from: &str,
|
||||||
|
to: &str,
|
||||||
|
amount: f64,
|
||||||
|
) -> Result<ConvertResponse, crate::error::TelecomError> {
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"from": from,
|
||||||
|
"to": to,
|
||||||
|
"amount": amount
|
||||||
|
});
|
||||||
|
self.client.post("/api/v1/currency/convert", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get exchange rate between currencies
|
||||||
|
pub async fn get_exchange_rate(&self, from: &str, to: &str) -> Result<ExchangeRate, crate::error::TelecomError> {
|
||||||
|
self.client.get(&format!("/api/v1/currency/exchange/{}/{}", from, to), &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get exchange rate history
|
||||||
|
pub async fn get_exchange_rate_history(
|
||||||
|
&self,
|
||||||
|
from: &str,
|
||||||
|
to: &str,
|
||||||
|
days: Option<u32>,
|
||||||
|
) -> Result<Vec<ExchangeRate>, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(d) = days {
|
||||||
|
params.insert("days".to_string(), d.to_string());
|
||||||
|
}
|
||||||
|
self.client.get(&format!("/api/v1/currency/exchange/{}/{}", from, to), ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get supported currencies
|
||||||
|
pub async fn get_supported_currencies(&self) -> Result<Vec<Currency>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/currency/currencies", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refresh exchange rates
|
||||||
|
pub async fn refresh_exchange_rates(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.post("/api/v1/currency/exchange/refresh", &serde_json::Value::Null).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// Billing
|
||||||
|
|
||||||
|
/// Process billing transaction
|
||||||
|
pub async fn process_billing(
|
||||||
|
&self,
|
||||||
|
billing_data: &serde_json::Value,
|
||||||
|
) -> Result<BillingTransaction, crate::error::TelecomError> {
|
||||||
|
self.client.post("/api/v1/currency/billing", billing_data).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing history for a profile
|
||||||
|
pub async fn get_billing_history(
|
||||||
|
&self,
|
||||||
|
profile_id: &str,
|
||||||
|
limit: Option<u32>,
|
||||||
|
) -> Result<Vec<BillingTransaction>, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(l) = limit {
|
||||||
|
params.insert("limit".to_string(), l.to_string());
|
||||||
|
}
|
||||||
|
self.client.get(&format!("/api/v1/currency/billing/history/{}", profile_id), ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing summary for a profile
|
||||||
|
pub async fn get_billing_summary(
|
||||||
|
&self,
|
||||||
|
profile_id: &str,
|
||||||
|
period: Option<&str>,
|
||||||
|
) -> Result<BillingSummary, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get(&format!("/api/v1/currency/billing/summary/{}", profile_id), ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process refund
|
||||||
|
pub async fn process_refund(
|
||||||
|
&self,
|
||||||
|
transaction_id: &str,
|
||||||
|
reason: &str,
|
||||||
|
) -> Result<BillingTransaction, crate::error::TelecomError> {
|
||||||
|
let body = serde_json::json!({ "reason": reason });
|
||||||
|
self.client.post(&format!("/api/v1/currency/billing/refund/{}", transaction_id), &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing analytics
|
||||||
|
pub async fn get_billing_analytics(&self, period: Option<&str>) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/currency/billing/analytics", ¶ms).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Currency Types
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ConvertRequest {
|
||||||
|
pub from: String,
|
||||||
|
pub to: String,
|
||||||
|
pub amount: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ConvertResponse {
|
||||||
|
pub from: String,
|
||||||
|
pub to: String,
|
||||||
|
pub amount: f64,
|
||||||
|
pub converted: f64,
|
||||||
|
pub rate: f64,
|
||||||
|
pub timestamp: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct ExchangeRate {
|
||||||
|
pub from: String,
|
||||||
|
pub to: String,
|
||||||
|
pub rate: f64,
|
||||||
|
pub timestamp: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct Currency {
|
||||||
|
pub code: String,
|
||||||
|
pub name: String,
|
||||||
|
pub symbol: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct BillingTransaction {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(rename = "profile_id")]
|
||||||
|
pub profile_id: String,
|
||||||
|
pub amount: f64,
|
||||||
|
pub currency: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub transaction_type: String,
|
||||||
|
pub status: String,
|
||||||
|
pub description: String,
|
||||||
|
#[serde(rename = "created_at")]
|
||||||
|
pub created_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct BillingSummary {
|
||||||
|
#[serde(rename = "profile_id")]
|
||||||
|
pub profile_id: String,
|
||||||
|
pub period: String,
|
||||||
|
#[serde(rename = "total_amount")]
|
||||||
|
pub total_amount: f64,
|
||||||
|
pub currency: String,
|
||||||
|
#[serde(rename = "transaction_count")]
|
||||||
|
pub transaction_count: u32,
|
||||||
|
pub breakdown: HashMap<String, f64>,
|
||||||
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
use crate::client::HTTPClient;
|
|
||||||
use crate::error::TelecomError;
|
|
||||||
use crate::types::GraphQLRequest;
|
|
||||||
use std::collections::HashMap;
|
|
||||||
|
|
||||||
pub struct GraphQLAPI {
|
|
||||||
client: HTTPClient,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl GraphQLAPI {
|
|
||||||
pub fn new(client: HTTPClient) -> Self {
|
|
||||||
Self { client }
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn execute(
|
|
||||||
&self,
|
|
||||||
query: String,
|
|
||||||
variables: Option<HashMap<String, serde_json::Value>>,
|
|
||||||
) -> Result<HashMap<String, serde_json::Value>, TelecomError> {
|
|
||||||
let req = GraphQLRequest { query, variables };
|
|
||||||
self.client.post("/graphql", Some(&req)).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,13 +1,17 @@
|
|||||||
pub mod graphql;
|
pub mod analytics;
|
||||||
|
pub mod currency;
|
||||||
pub mod payments;
|
pub mod payments;
|
||||||
pub mod rating_plans;
|
pub mod rating_plans;
|
||||||
|
pub mod security;
|
||||||
pub mod subscribers;
|
pub mod subscribers;
|
||||||
pub mod system;
|
pub mod system;
|
||||||
pub mod usage;
|
pub mod usage;
|
||||||
|
|
||||||
pub use graphql::GraphQLAPI;
|
pub use analytics::AnalyticsAPI;
|
||||||
|
pub use currency::CurrencyAPI;
|
||||||
pub use payments::PaymentAPI;
|
pub use payments::PaymentAPI;
|
||||||
pub use rating_plans::RatingPlanAPI;
|
pub use rating_plans::RatingPlanAPI;
|
||||||
|
pub use security::SecurityAPI;
|
||||||
pub use subscribers::SubscriberAPI;
|
pub use subscribers::SubscriberAPI;
|
||||||
pub use system::SystemAPI;
|
pub use system::SystemAPI;
|
||||||
pub use usage::UsageAPI;
|
pub use usage::UsageAPI;
|
||||||
|
|||||||
@@ -0,0 +1,180 @@
|
|||||||
|
use crate::client::HTTPClient;
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
/// Security API for fraud detection and SIM swap protection
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct SecurityAPI {
|
||||||
|
client: HTTPClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SecurityAPI {
|
||||||
|
pub fn new(client: HTTPClient) -> Self {
|
||||||
|
Self { client }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fraud Detection
|
||||||
|
|
||||||
|
/// Analyze a transaction for fraud
|
||||||
|
pub async fn analyze_transaction(
|
||||||
|
&self,
|
||||||
|
transaction: &serde_json::Value,
|
||||||
|
) -> Result<Option<FraudAlert>, crate::error::TelecomError> {
|
||||||
|
match self.client.post("/api/v1/security/fraud/analyze", transaction).await {
|
||||||
|
Ok(alert) => Ok(Some(alert)),
|
||||||
|
Err(crate::error::TelecomError::APIError(404, _)) => Ok(None),
|
||||||
|
Err(e) => Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get fraud alerts with filtering
|
||||||
|
pub async fn get_fraud_alerts(
|
||||||
|
&self,
|
||||||
|
filter: Option<FraudAlertFilter>,
|
||||||
|
) -> Result<Vec<FraudAlert>, crate::error::TelecomError> {
|
||||||
|
let body = if let Some(f) = filter {
|
||||||
|
serde_json::to_value(f).unwrap_or_default()
|
||||||
|
} else {
|
||||||
|
serde_json::Value::Null
|
||||||
|
};
|
||||||
|
self.client.post("/api/v1/security/fraud/alerts", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update fraud alert status
|
||||||
|
pub async fn update_alert_status(
|
||||||
|
&self,
|
||||||
|
alert_id: &str,
|
||||||
|
status: &str,
|
||||||
|
actions: Vec<String>,
|
||||||
|
) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"status": status,
|
||||||
|
"actions": actions
|
||||||
|
});
|
||||||
|
self.client.put(&format!("/api/v1/security/fraud/alerts/{}", alert_id), &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get fraud detection metrics
|
||||||
|
pub async fn get_fraud_metrics(&self, period: Option<&str>) -> Result<FraudMetrics, crate::error::TelecomError> {
|
||||||
|
let mut params = HashMap::new();
|
||||||
|
if let Some(p) = period {
|
||||||
|
params.insert("period".to_string(), p.to_string());
|
||||||
|
}
|
||||||
|
self.client.get("/api/v1/security/fraud/metrics", ¶ms).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get detected fraud patterns
|
||||||
|
pub async fn get_fraud_patterns(&self) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get("/api/v1/security/fraud/patterns", &HashMap::new()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
// SIM Swap Protection
|
||||||
|
|
||||||
|
/// Verify SIM swap request
|
||||||
|
pub async fn verify_sim_swap(
|
||||||
|
&self,
|
||||||
|
profile_id: &str,
|
||||||
|
msisdn: &str,
|
||||||
|
) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
let body = serde_json::json!({
|
||||||
|
"profile_id": profile_id,
|
||||||
|
"msisdn": msisdn
|
||||||
|
});
|
||||||
|
self.client.post("/api/v1/security/simswap/verify", &body).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get SIM swap history for a profile
|
||||||
|
pub async fn get_sim_swap_history(&self, profile_id: &str) -> Result<HashMap<String, serde_json::Value>, crate::error::TelecomError> {
|
||||||
|
self.client.get(&format!("/api/v1/security/simswap/history/{}", profile_id), &HashMap::new()).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Security Types
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FraudAlert {
|
||||||
|
pub id: String,
|
||||||
|
#[serde(rename = "type")]
|
||||||
|
pub alert_type: String,
|
||||||
|
pub severity: String,
|
||||||
|
#[serde(rename = "profile_id")]
|
||||||
|
pub profile_id: String,
|
||||||
|
pub description: String,
|
||||||
|
#[serde(rename = "risk_score")]
|
||||||
|
pub risk_score: f64,
|
||||||
|
pub evidence: Vec<String>,
|
||||||
|
#[serde(rename = "ip_address")]
|
||||||
|
pub ip_address: String,
|
||||||
|
pub timestamp: String,
|
||||||
|
pub status: String,
|
||||||
|
#[serde(rename = "actions_taken")]
|
||||||
|
pub actions_taken: Vec<String>,
|
||||||
|
pub metadata: HashMap<String, serde_json::Value>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FraudMetrics {
|
||||||
|
pub period: String,
|
||||||
|
#[serde(rename = "total_alerts")]
|
||||||
|
pub total_alerts: i64,
|
||||||
|
#[serde(rename = "resolved_alerts")]
|
||||||
|
pub resolved_alerts: i64,
|
||||||
|
#[serde(rename = "false_positives")]
|
||||||
|
pub false_positives: i64,
|
||||||
|
#[serde(rename = "resolution_rate")]
|
||||||
|
pub resolution_rate: f64,
|
||||||
|
#[serde(rename = "false_positive_rate")]
|
||||||
|
pub false_positive_rate: f64,
|
||||||
|
#[serde(rename = "by_type")]
|
||||||
|
pub by_type: HashMap<String, i64>,
|
||||||
|
#[serde(rename = "by_severity")]
|
||||||
|
pub by_severity: HashMap<String, i64>,
|
||||||
|
#[serde(rename = "generated_at")]
|
||||||
|
pub generated_at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
pub struct FraudAlertFilter {
|
||||||
|
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
|
||||||
|
pub alert_type: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub severity: Option<String>,
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub status: Option<String>,
|
||||||
|
#[serde(default = "default_limit")]
|
||||||
|
pub limit: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn default_limit() -> u32 {
|
||||||
|
50
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for FraudAlertFilter {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
alert_type: None,
|
||||||
|
severity: None,
|
||||||
|
status: None,
|
||||||
|
limit: 50,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum FraudType {
|
||||||
|
AccountTakeover,
|
||||||
|
SubscriptionFraud,
|
||||||
|
PaymentFraud,
|
||||||
|
UsageAnomaly,
|
||||||
|
SimSwap,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum FraudSeverity {
|
||||||
|
Low,
|
||||||
|
Medium,
|
||||||
|
High,
|
||||||
|
Critical,
|
||||||
|
}
|
||||||
+10
-4
@@ -14,7 +14,7 @@ use error::TelecomError;
|
|||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use types::*;
|
use types::*;
|
||||||
|
|
||||||
pub use api::{GraphQLAPI, PaymentAPI, RatingPlanAPI, SubscriberAPI, SystemAPI, UsageAPI};
|
pub use api::{AnalyticsAPI, CurrencyAPI, PaymentAPI, RatingPlanAPI, SecurityAPI, SubscriberAPI, SystemAPI, UsageAPI};
|
||||||
|
|
||||||
/// Telecom Platform SDK client
|
/// Telecom Platform SDK client
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -28,7 +28,9 @@ pub struct TelecomClient {
|
|||||||
pub payments: PaymentAPI,
|
pub payments: PaymentAPI,
|
||||||
pub rating_plans: RatingPlanAPI,
|
pub rating_plans: RatingPlanAPI,
|
||||||
pub system: SystemAPI,
|
pub system: SystemAPI,
|
||||||
pub graphql: GraphQLAPI,
|
pub analytics: AnalyticsAPI,
|
||||||
|
pub security: SecurityAPI,
|
||||||
|
pub currency: CurrencyAPI,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
@@ -73,7 +75,9 @@ impl TelecomClient {
|
|||||||
let payments = PaymentAPI::new(http_client.clone());
|
let payments = PaymentAPI::new(http_client.clone());
|
||||||
let rating_plans = RatingPlanAPI::new(http_client.clone());
|
let rating_plans = RatingPlanAPI::new(http_client.clone());
|
||||||
let system = SystemAPI::new(http_client.clone());
|
let system = SystemAPI::new(http_client.clone());
|
||||||
let graphql = GraphQLAPI::new(http_client.clone());
|
let analytics = AnalyticsAPI::new(http_client.clone());
|
||||||
|
let security = SecurityAPI::new(http_client.clone());
|
||||||
|
let currency = CurrencyAPI::new(http_client.clone());
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
auth_provider,
|
auth_provider,
|
||||||
@@ -83,7 +87,9 @@ impl TelecomClient {
|
|||||||
payments,
|
payments,
|
||||||
rating_plans,
|
rating_plans,
|
||||||
system,
|
system,
|
||||||
graphql,
|
analytics,
|
||||||
|
security,
|
||||||
|
currency,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,199 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Analytics API for churn prediction, market analysis, and pricing optimization
|
||||||
|
public class AnalyticsAPI {
|
||||||
|
private let client: HTTPClient
|
||||||
|
|
||||||
|
public init(client: HTTPClient) {
|
||||||
|
self.client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Churn Analysis
|
||||||
|
|
||||||
|
/// Predict churn risk for a profile
|
||||||
|
public func predictChurn(profileId: String) async throws -> ChurnPrediction {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/analytics/churn/predict",
|
||||||
|
body: ["profile_id": profileId],
|
||||||
|
responseType: ChurnPrediction.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get churn metrics
|
||||||
|
public func getChurnMetrics(period: String = "monthly") async throws -> ChurnMetrics {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/analytics/churn/metrics",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: ChurnMetrics.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get at-risk customers
|
||||||
|
public func getAtRiskCustomers(
|
||||||
|
riskLevel: ChurnRiskLevel,
|
||||||
|
limit: Int = 100
|
||||||
|
) async throws -> [ChurnPrediction] {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/analytics/churn/at-risk",
|
||||||
|
body: [
|
||||||
|
"risk_level": riskLevel.rawValue,
|
||||||
|
"limit": limit
|
||||||
|
],
|
||||||
|
responseType: [ChurnPrediction].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Market Analytics
|
||||||
|
|
||||||
|
/// Get market metrics
|
||||||
|
public func getMarketMetrics(period: String = "monthly") async throws -> MarketMetrics {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/analytics/market/metrics",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: MarketMetrics.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get competitor analysis
|
||||||
|
public func getCompetitors() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/analytics/market/competitors")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get market opportunities
|
||||||
|
public func getMarketOpportunities() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/analytics/market/opportunities")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Predictive Maintenance
|
||||||
|
|
||||||
|
/// Get maintenance metrics
|
||||||
|
public func getMaintenanceMetrics(period: String = "monthly") async throws -> MaintenanceMetrics {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/analytics/maintenance/metrics",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: MaintenanceMetrics.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get assets health
|
||||||
|
public func getAssetsHealth() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/analytics/maintenance/assets")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get maintenance alerts
|
||||||
|
public func getMaintenanceAlerts() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/analytics/maintenance/alerts")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Predict failure for an asset
|
||||||
|
public func predictFailure(assetId: String) async throws -> [String: Any] {
|
||||||
|
return try await client.post("/api/v1/analytics/maintenance/predict/\(assetId)", body: [:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Pricing Optimization
|
||||||
|
|
||||||
|
/// Get pricing metrics
|
||||||
|
public func getPricingMetrics(period: String = "monthly") async throws -> PricingMetrics {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/analytics/pricing/metrics",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: PricingMetrics.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Optimize pricing for rate plans
|
||||||
|
public func optimizePricing(
|
||||||
|
ratePlanIds: [String],
|
||||||
|
strategy: String = "revenue_maximization"
|
||||||
|
) async throws -> [PricingOptimizationResult] {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/analytics/pricing/optimize",
|
||||||
|
body: [
|
||||||
|
"rate_plan_ids": ratePlanIds,
|
||||||
|
"strategy": strategy
|
||||||
|
],
|
||||||
|
responseType: [PricingOptimizationResult].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get price elasticity data
|
||||||
|
public func getPriceElasticity() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/analytics/pricing/elasticity")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analytics Types
|
||||||
|
|
||||||
|
public struct ChurnPrediction: Codable {
|
||||||
|
public let profileId: String
|
||||||
|
public let riskLevel: String
|
||||||
|
public let riskScore: Double
|
||||||
|
public let predictedChurnDate: String?
|
||||||
|
public let reasons: [String]
|
||||||
|
public let recommendations: [String]
|
||||||
|
public let lastUpdated: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ChurnMetrics: Codable {
|
||||||
|
public let period: String
|
||||||
|
public let totalSubscribers: Int64
|
||||||
|
public let churnedSubscribers: Int64
|
||||||
|
public let churnRate: Double
|
||||||
|
public let monthlyChurnRate: Double
|
||||||
|
public let annualChurnRate: Double
|
||||||
|
public let averageTenureDays: Double
|
||||||
|
public let riskDistribution: [String: Int64]
|
||||||
|
public let generatedAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct MarketMetrics: Codable {
|
||||||
|
public let period: String
|
||||||
|
public let totalMarketSize: Int64
|
||||||
|
public let ourSubscribers: Int64
|
||||||
|
public let marketShare: Double
|
||||||
|
public let growthRate: Double
|
||||||
|
public let byCountry: [String: [String: Any]]
|
||||||
|
public let generatedAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct MaintenanceMetrics: Codable {
|
||||||
|
public let period: String
|
||||||
|
public let totalAssets: Int64
|
||||||
|
public let healthyAssets: Int64
|
||||||
|
public let assetsNeedingAttention: Int64
|
||||||
|
public let uptime: Double
|
||||||
|
public let meanTimeToFailure: Double
|
||||||
|
public let meanTimeToRepair: Double
|
||||||
|
public let generatedAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct PricingMetrics: Codable {
|
||||||
|
public let period: String
|
||||||
|
public let totalRevenue: Double
|
||||||
|
public let arpu: Double
|
||||||
|
public let priceElasticity: Double
|
||||||
|
public let competitiveIndex: Double
|
||||||
|
public let optimizationRoi: Double
|
||||||
|
public let generatedAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct PricingOptimizationResult: Codable {
|
||||||
|
public let ratePlanId: String
|
||||||
|
public let strategy: String
|
||||||
|
public let currentPrice: Double
|
||||||
|
public let optimalPrice: Double
|
||||||
|
public let priceChangePct: Double
|
||||||
|
public let expectedRevenue: Double
|
||||||
|
public let expectedDemand: Double
|
||||||
|
public let confidence: Double
|
||||||
|
public let reasoning: [String]
|
||||||
|
public let risks: [String]
|
||||||
|
public let recommendations: [String]
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum ChurnRiskLevel: String, CaseIterable {
|
||||||
|
case low = "low"
|
||||||
|
case medium = "medium"
|
||||||
|
case high = "high"
|
||||||
|
case critical = "critical"
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Currency and Billing API
|
||||||
|
public class CurrencyAPI {
|
||||||
|
private let client: HTTPClient
|
||||||
|
|
||||||
|
public init(client: HTTPClient) {
|
||||||
|
self.client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Currency Conversion
|
||||||
|
|
||||||
|
/// Convert currency
|
||||||
|
public func convert(from: String, to: String, amount: Double) async throws -> ConvertResponse {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/currency/convert",
|
||||||
|
body: [
|
||||||
|
"from": from,
|
||||||
|
"to": to,
|
||||||
|
"amount": amount
|
||||||
|
],
|
||||||
|
responseType: ConvertResponse.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get exchange rate between currencies
|
||||||
|
public func getExchangeRate(from: String, to: String) async throws -> ExchangeRate {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/exchange/\(from)/\(to)",
|
||||||
|
responseType: ExchangeRate.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get exchange rate history
|
||||||
|
public func getExchangeRateHistory(from: String, to: String, days: Int = 30) async throws -> [ExchangeRate] {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/exchange/\(from)/\(to)/history",
|
||||||
|
parameters: ["days": days],
|
||||||
|
responseType: [ExchangeRate].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get supported currencies
|
||||||
|
public func getSupportedCurrencies() async throws -> [Currency] {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/currencies",
|
||||||
|
responseType: [Currency].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Refresh exchange rates
|
||||||
|
public func refreshExchangeRates() async throws -> [String: Any] {
|
||||||
|
return try await client.post("/api/v1/currency/exchange/refresh", body: [:])
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Billing
|
||||||
|
|
||||||
|
/// Process billing transaction
|
||||||
|
public func processBilling(_ billingData: [String: Any]) async throws -> BillingTransaction {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/currency/billing",
|
||||||
|
body: billingData,
|
||||||
|
responseType: BillingTransaction.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing history for a profile
|
||||||
|
public func getBillingHistory(profileId: String, limit: Int = 50) async throws -> [BillingTransaction] {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/billing/history/\(profileId)",
|
||||||
|
parameters: ["limit": limit],
|
||||||
|
responseType: [BillingTransaction].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing summary for a profile
|
||||||
|
public func getBillingSummary(profileId: String, period: String = "monthly") async throws -> BillingSummary {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/billing/summary/\(profileId)",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: BillingSummary.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Process refund
|
||||||
|
public func processRefund(transactionId: String, reason: String) async throws -> BillingTransaction {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/currency/billing/refund/\(transactionId)",
|
||||||
|
body: ["reason": reason],
|
||||||
|
responseType: BillingTransaction.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get billing analytics
|
||||||
|
public func getBillingAnalytics(period: String = "monthly") async throws -> [String: Any] {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/currency/billing/analytics",
|
||||||
|
parameters: ["period": period]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Currency Types
|
||||||
|
|
||||||
|
public struct ConvertRequest: Codable {
|
||||||
|
public let from: String
|
||||||
|
public let to: String
|
||||||
|
public let amount: Double
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ConvertResponse: Codable {
|
||||||
|
public let from: String
|
||||||
|
public let to: String
|
||||||
|
public let amount: Double
|
||||||
|
public let converted: Double
|
||||||
|
public let rate: Double
|
||||||
|
public let timestamp: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct ExchangeRate: Codable {
|
||||||
|
public let from: String
|
||||||
|
public let to: String
|
||||||
|
public let rate: Double
|
||||||
|
public let timestamp: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct Currency: Codable {
|
||||||
|
public let code: String
|
||||||
|
public let name: String
|
||||||
|
public let symbol: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct BillingTransaction: Codable {
|
||||||
|
public let id: String
|
||||||
|
public let profileId: String
|
||||||
|
public let amount: Double
|
||||||
|
public let currency: String
|
||||||
|
public let type: String
|
||||||
|
public let status: String
|
||||||
|
public let description: String
|
||||||
|
public let createdAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct BillingSummary: Codable {
|
||||||
|
public let profileId: String
|
||||||
|
public let period: String
|
||||||
|
public let totalAmount: Double
|
||||||
|
public let currency: String
|
||||||
|
public let transactionCount: Int
|
||||||
|
public let breakdown: [String: Double]
|
||||||
|
}
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import Foundation
|
|
||||||
|
|
||||||
/// API for GraphQL queries
|
|
||||||
public class GraphQLAPI {
|
|
||||||
private let client: HTTPClient
|
|
||||||
|
|
||||||
public init(client: HTTPClient) {
|
|
||||||
self.client = client
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Execute a GraphQL query
|
|
||||||
public func execute(query: String, variables: [String: Any]? = nil) async throws -> [String: Any] {
|
|
||||||
let request = GraphQLRequest(query: query, variables: variables)
|
|
||||||
return try await client.post(path: "/graphql", body: request)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Security API for fraud detection and SIM swap protection
|
||||||
|
public class SecurityAPI {
|
||||||
|
private let client: HTTPClient
|
||||||
|
|
||||||
|
public init(client: HTTPClient) {
|
||||||
|
self.client = client
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Analyze a transaction for fraud
|
||||||
|
public func analyzeTransaction(_ transaction: [String: Any]) async throws -> FraudAlert? {
|
||||||
|
do {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/security/fraud/analyze",
|
||||||
|
body: transaction,
|
||||||
|
responseType: FraudAlert.self
|
||||||
|
)
|
||||||
|
} catch {
|
||||||
|
if case HTTPClient.APIError.notFound = error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
throw error
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get fraud alerts with filtering
|
||||||
|
public func getFraudAlerts(filter: FraudAlertFilter? = nil) async throws -> [FraudAlert] {
|
||||||
|
var body: [String: Any] = [:]
|
||||||
|
if let filter = filter {
|
||||||
|
if let type = filter.type { body["type"] = type }
|
||||||
|
if let severity = filter.severity { body["severity"] = severity }
|
||||||
|
if let status = filter.status { body["status"] = status }
|
||||||
|
body["limit"] = filter.limit
|
||||||
|
}
|
||||||
|
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/security/fraud/alerts",
|
||||||
|
body: body,
|
||||||
|
responseType: [FraudAlert].self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Update fraud alert status
|
||||||
|
public func updateAlertStatus(
|
||||||
|
alertId: String,
|
||||||
|
status: String,
|
||||||
|
actions: [String] = []
|
||||||
|
) async throws -> [String: Any] {
|
||||||
|
return try await client.put(
|
||||||
|
"/api/v1/security/fraud/alerts/\(alertId)",
|
||||||
|
body: [
|
||||||
|
"status": status,
|
||||||
|
"actions": actions
|
||||||
|
]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get fraud detection metrics
|
||||||
|
public func getFraudMetrics(period: String = "monthly") async throws -> FraudMetrics {
|
||||||
|
return try await client.get(
|
||||||
|
"/api/v1/security/fraud/metrics",
|
||||||
|
parameters: ["period": period],
|
||||||
|
responseType: FraudMetrics.self
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get detected fraud patterns
|
||||||
|
public func getFraudPatterns() async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/security/fraud/patterns")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Verify SIM swap request
|
||||||
|
public func verifySIMSwap(profileId: String, msisdn: String) async throws -> [String: Any] {
|
||||||
|
return try await client.post(
|
||||||
|
"/api/v1/security/simswap/verify",
|
||||||
|
body: [
|
||||||
|
"profile_id": profileId,
|
||||||
|
"msisdn": msisdn
|
||||||
|
]
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Get SIM swap history for a profile
|
||||||
|
public func getSIMSwapHistory(profileId: String) async throws -> [String: Any] {
|
||||||
|
return try await client.get("/api/v1/security/simswap/history/\(profileId)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct FraudAlert: Codable {
|
||||||
|
public let id: String
|
||||||
|
public let type: String
|
||||||
|
public let severity: String
|
||||||
|
public let profileId: String
|
||||||
|
public let description: String
|
||||||
|
public let riskScore: Double
|
||||||
|
public let evidence: [String]
|
||||||
|
public let ipAddress: String
|
||||||
|
public let timestamp: String
|
||||||
|
public let status: String
|
||||||
|
public let actionsTaken: [String]
|
||||||
|
public let metadata: [String: Any]
|
||||||
|
|
||||||
|
enum CodingKeys: String, CodingKey {
|
||||||
|
case id, type, severity, profileId, description, riskScore
|
||||||
|
case evidence, ipAddress, timestamp, status, actionsTaken, metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
public init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||||
|
id = try container.decode(String.self, forKey: .id)
|
||||||
|
type = try container.decode(String.self, forKey: .type)
|
||||||
|
severity = try container.decode(String.self, forKey: .severity)
|
||||||
|
profileId = try container.decode(String.self, forKey: .profileId)
|
||||||
|
description = try container.decode(String.self, forKey: .description)
|
||||||
|
riskScore = try container.decode(Double.self, forKey: .riskScore)
|
||||||
|
evidence = try container.decode([String].self, forKey: .evidence)
|
||||||
|
ipAddress = try container.decode(String.self, forKey: .ipAddress)
|
||||||
|
timestamp = try container.decode(String.self, forKey: .timestamp)
|
||||||
|
status = try container.decode(String.self, forKey: .status)
|
||||||
|
actionsTaken = try container.decode([String].self, forKey: .actionsTaken)
|
||||||
|
metadata = try container.decode([String: Any].self, forKey: .metadata)
|
||||||
|
}
|
||||||
|
|
||||||
|
public func encode(to encoder: Encoder) throws {
|
||||||
|
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||||
|
try container.encode(id, forKey: .id)
|
||||||
|
try container.encode(type, forKey: .type)
|
||||||
|
try container.encode(severity, forKey: .severity)
|
||||||
|
try container.encode(profileId, forKey: .profileId)
|
||||||
|
try container.encode(description, forKey: .description)
|
||||||
|
try container.encode(riskScore, forKey: .riskScore)
|
||||||
|
try container.encode(evidence, forKey: .evidence)
|
||||||
|
try container.encode(ipAddress, forKey: .ipAddress)
|
||||||
|
try container.encode(timestamp, forKey: .timestamp)
|
||||||
|
try container.encode(status, forKey: .status)
|
||||||
|
try container.encode(actionsTaken, forKey: .actionsTaken)
|
||||||
|
try container.encode(metadata, forKey: .metadata)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct FraudMetrics: Codable {
|
||||||
|
public let period: String
|
||||||
|
public let totalAlerts: Int64
|
||||||
|
public let resolvedAlerts: Int64
|
||||||
|
public let falsePositives: Int64
|
||||||
|
public let resolutionRate: Double
|
||||||
|
public let falsePositiveRate: Double
|
||||||
|
public let byType: [String: Int64]
|
||||||
|
public let bySeverity: [String: Int64]
|
||||||
|
public let generatedAt: String
|
||||||
|
}
|
||||||
|
|
||||||
|
public struct FraudAlertFilter {
|
||||||
|
public let type: String?
|
||||||
|
public let severity: String?
|
||||||
|
public let status: String?
|
||||||
|
public let limit: Int
|
||||||
|
|
||||||
|
public init(type: String? = nil, severity: String? = nil, status: String? = nil, limit: Int = 50) {
|
||||||
|
self.type = type
|
||||||
|
self.severity = severity
|
||||||
|
self.status = status
|
||||||
|
self.limit = limit
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum FraudType: String, CaseIterable {
|
||||||
|
case accountTakeover = "account_takeover"
|
||||||
|
case subscriptionFraud = "subscription_fraud"
|
||||||
|
case paymentFraud = "payment_fraud"
|
||||||
|
case usageAnomaly = "usage_anomaly"
|
||||||
|
case simSwap = "sim_swap"
|
||||||
|
}
|
||||||
|
|
||||||
|
public enum FraudSeverity: String, CaseIterable {
|
||||||
|
case low = "low"
|
||||||
|
case medium = "medium"
|
||||||
|
case high = "high"
|
||||||
|
case critical = "critical"
|
||||||
|
}
|
||||||
@@ -19,9 +19,9 @@ public class TelecomSDK {
|
|||||||
public let payments: PaymentAPI
|
public let payments: PaymentAPI
|
||||||
public let ratingPlans: RatingPlanAPI
|
public let ratingPlans: RatingPlanAPI
|
||||||
public let system: SystemAPI
|
public let system: SystemAPI
|
||||||
public let graphql: GraphQLAPI
|
public let analytics: AnalyticsAPI
|
||||||
|
public let security: SecurityAPI
|
||||||
// MARK: - Initialization
|
public let currency: CurrencyAPI
|
||||||
|
|
||||||
/// Initialize a new TelecomSDK instance
|
/// Initialize a new TelecomSDK instance
|
||||||
/// - Parameter config: Configuration for the SDK
|
/// - Parameter config: Configuration for the SDK
|
||||||
@@ -36,7 +36,9 @@ public class TelecomSDK {
|
|||||||
self.payments = PaymentAPI(client: httpClient)
|
self.payments = PaymentAPI(client: httpClient)
|
||||||
self.ratingPlans = RatingPlanAPI(client: httpClient)
|
self.ratingPlans = RatingPlanAPI(client: httpClient)
|
||||||
self.system = SystemAPI(client: httpClient)
|
self.system = SystemAPI(client: httpClient)
|
||||||
self.graphql = GraphQLAPI(client: httpClient)
|
self.analytics = AnalyticsAPI(client: httpClient)
|
||||||
|
self.security = SecurityAPI(client: httpClient)
|
||||||
|
self.currency = CurrencyAPI(client: httpClient)
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Authentication Methods
|
// MARK: - Authentication Methods
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { HTTPClient } from './api/http-client';
|
||||||
|
import {
|
||||||
|
ChurnPrediction,
|
||||||
|
ChurnMetrics,
|
||||||
|
ChurnRiskLevel,
|
||||||
|
MarketMetrics,
|
||||||
|
PredictiveMaintenanceMetrics,
|
||||||
|
PricingOptimizationResult,
|
||||||
|
PricingMetrics
|
||||||
|
} from './types';
|
||||||
|
|
||||||
|
export class AnalyticsAPI {
|
||||||
|
constructor(private client: HTTPClient) {}
|
||||||
|
|
||||||
|
async predictChurn(profileId: string): Promise<ChurnPrediction> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/analytics/churn/predict',
|
||||||
|
data: { profileId }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getChurnMetrics(period: string): Promise<ChurnMetrics> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/analytics/churn/metrics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getAtRiskCustomers(riskLevel: ChurnRiskLevel, limit: number): Promise<ChurnPrediction[]> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/analytics/churn/at-risk',
|
||||||
|
params: { riskLevel, limit: limit.toString() }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getMarketMetrics(period: string): Promise<MarketMetrics> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/analytics/market/metrics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPredictiveMaintenanceMetrics(period: string): Promise<PredictiveMaintenanceMetrics> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/analytics/maintenance/metrics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPricingMetrics(period: string): Promise<PricingMetrics> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/analytics/pricing/metrics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async optimizePrice(ratePlanId: string, strategy: string): Promise<PricingOptimizationResult> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/analytics/pricing/optimize',
|
||||||
|
data: { ratePlanId, strategy }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { HTTPClient } from './api/http-client';
|
||||||
|
|
||||||
|
export interface ConvertRequest {
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
amount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ConvertResponse {
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
amount: number;
|
||||||
|
converted: number;
|
||||||
|
rate: number;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ExchangeRate {
|
||||||
|
from: string;
|
||||||
|
to: string;
|
||||||
|
rate: number;
|
||||||
|
timestamp: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BillingTransaction {
|
||||||
|
id: string;
|
||||||
|
profileId: string;
|
||||||
|
amount: number;
|
||||||
|
currency: string;
|
||||||
|
type: string;
|
||||||
|
status: string;
|
||||||
|
description: string;
|
||||||
|
createdAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BillingSummary {
|
||||||
|
profileId: string;
|
||||||
|
period: string;
|
||||||
|
totalAmount: number;
|
||||||
|
currency: string;
|
||||||
|
transactionCount: number;
|
||||||
|
breakdown: Record<string, number>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CurrencyAPI {
|
||||||
|
constructor(private client: HTTPClient) {}
|
||||||
|
|
||||||
|
async convert(request: ConvertRequest): Promise<ConvertResponse> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/currency/convert',
|
||||||
|
data: request
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getExchangeRate(from: string, to: string): Promise<ExchangeRate> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: `/api/v1/currency/exchange/${from}/${to}`
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getExchangeRateHistory(from: string, to: string, days: number = 30): Promise<ExchangeRate[]> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: `/api/v1/currency/exchange/${from}/${to}/history`,
|
||||||
|
params: { days: days.toString() }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getSupportedCurrencies(): Promise<string[]> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/currency/currencies'
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshExchangeRates(): Promise<void> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/currency/exchange/refresh',
|
||||||
|
data: {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async processBilling(billingData: Record<string, any>): Promise<BillingTransaction> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/currency/billing',
|
||||||
|
data: billingData
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBillingHistory(profileId: string, limit: number = 50): Promise<BillingTransaction[]> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: `/api/v1/currency/billing/history/${profileId}`,
|
||||||
|
params: { limit: limit.toString() }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBillingSummary(profileId: string, period: string = 'monthly'): Promise<BillingSummary> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: `/api/v1/currency/billing/summary/${profileId}`,
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async processRefund(transactionId: string, reason: string): Promise<BillingTransaction> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: `/api/v1/currency/billing/refund/${transactionId}`,
|
||||||
|
data: { reason }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBillingAnalytics(period: string = 'monthly'): Promise<Record<string, any>> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/currency/billing/analytics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,9 @@ export { SDKConfig, TelecomSDKConfig } from './config';
|
|||||||
export { HttpClient } from './http-client';
|
export { HttpClient } from './http-client';
|
||||||
export { SubscribersService } from './subscribers';
|
export { SubscribersService } from './subscribers';
|
||||||
export { WebSocketClient } from './websocket';
|
export { WebSocketClient } from './websocket';
|
||||||
|
export { AnalyticsAPI } from './analytics';
|
||||||
|
export { SecurityAPI } from './security';
|
||||||
|
export { CurrencyAPI } from './currency';
|
||||||
|
|
||||||
// Export all types
|
// Export all types
|
||||||
export * from './types';
|
export * from './types';
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { HTTPClient } from './api/http-client';
|
||||||
|
import { FraudAlert, FraudAlertFilter, FraudMetrics } from './types';
|
||||||
|
|
||||||
|
export class SecurityAPI {
|
||||||
|
constructor(private client: HTTPClient) {}
|
||||||
|
|
||||||
|
async analyzeTransaction(transaction: Record<string, any>): Promise<FraudAlert> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/security/fraud/analyze',
|
||||||
|
data: transaction
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFraudAlerts(filter: FraudAlertFilter): Promise<FraudAlert[]> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'POST',
|
||||||
|
endpoint: '/api/v1/security/fraud/alerts',
|
||||||
|
data: filter
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateAlertStatus(alertId: string, status: string, actions: string[]): Promise<void> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'PUT',
|
||||||
|
endpoint: `/api/v1/security/fraud/alerts/${alertId}`,
|
||||||
|
data: { status, actions }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async getFraudMetrics(period: string): Promise<FraudMetrics> {
|
||||||
|
return this.client.request({
|
||||||
|
method: 'GET',
|
||||||
|
endpoint: '/api/v1/security/fraud/metrics',
|
||||||
|
params: { period }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,9 +5,11 @@ import {
|
|||||||
UsageAPI,
|
UsageAPI,
|
||||||
PaymentAPI,
|
PaymentAPI,
|
||||||
RatingPlanAPI,
|
RatingPlanAPI,
|
||||||
SystemAPI,
|
SystemAPI
|
||||||
GraphQLAPI
|
|
||||||
} from './api';
|
} from './api';
|
||||||
|
import { AnalyticsAPI } from './analytics';
|
||||||
|
import { SecurityAPI } from './security';
|
||||||
|
import { CurrencyAPI } from './currency';
|
||||||
import { WebSocketClient } from './websocket';
|
import { WebSocketClient } from './websocket';
|
||||||
import { Alert, RealTimeUsageUpdate, WebSocketMessage } from './types';
|
import { Alert, RealTimeUsageUpdate, WebSocketMessage } from './types';
|
||||||
|
|
||||||
@@ -23,7 +25,9 @@ export class TelecomSDK {
|
|||||||
public payments: PaymentAPI;
|
public payments: PaymentAPI;
|
||||||
public ratingPlans: RatingPlanAPI;
|
public ratingPlans: RatingPlanAPI;
|
||||||
public system: SystemAPI;
|
public system: SystemAPI;
|
||||||
public graphql: GraphQLAPI;
|
public analytics: AnalyticsAPI;
|
||||||
|
public security: SecurityAPI;
|
||||||
|
public currency: CurrencyAPI;
|
||||||
|
|
||||||
private constructor(config: {
|
private constructor(config: {
|
||||||
baseURL: string;
|
baseURL: string;
|
||||||
@@ -61,7 +65,9 @@ export class TelecomSDK {
|
|||||||
this.payments = new PaymentAPI(this.apiClient);
|
this.payments = new PaymentAPI(this.apiClient);
|
||||||
this.ratingPlans = new RatingPlanAPI(this.apiClient);
|
this.ratingPlans = new RatingPlanAPI(this.apiClient);
|
||||||
this.system = new SystemAPI(this.apiClient);
|
this.system = new SystemAPI(this.apiClient);
|
||||||
this.graphql = new GraphQLAPI(this.apiClient);
|
this.analytics = new AnalyticsAPI(this.apiClient);
|
||||||
|
this.security = new SecurityAPI(this.apiClient);
|
||||||
|
this.currency = new CurrencyAPI(this.apiClient);
|
||||||
}
|
}
|
||||||
|
|
||||||
static initialize(config: {
|
static initialize(config: {
|
||||||
|
|||||||
@@ -47,6 +47,219 @@ export interface CreateSubscriberRequest {
|
|||||||
euiccId?: string;
|
euiccId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Churn Analysis Types
|
||||||
|
export enum ChurnRiskLevel {
|
||||||
|
Low = 'low',
|
||||||
|
Medium = 'medium',
|
||||||
|
High = 'high',
|
||||||
|
Critical = 'critical'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChurnPrediction {
|
||||||
|
profileId: string;
|
||||||
|
riskLevel: ChurnRiskLevel;
|
||||||
|
riskScore: number;
|
||||||
|
predictedChurnDate?: string;
|
||||||
|
reasons: string[];
|
||||||
|
recommendations: string[];
|
||||||
|
lastUpdated: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ChurnMetrics {
|
||||||
|
period: string;
|
||||||
|
totalSubscribers: number;
|
||||||
|
churnedSubscribers: number;
|
||||||
|
churnRate: number;
|
||||||
|
monthlyChurnRate: number;
|
||||||
|
annualChurnRate: number;
|
||||||
|
averageTenureDays: number;
|
||||||
|
riskDistribution: Record<ChurnRiskLevel, number>;
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fraud Detection Types
|
||||||
|
export enum FraudType {
|
||||||
|
AccountTakeover = 'account_takeover',
|
||||||
|
SubscriptionFraud = 'subscription_fraud',
|
||||||
|
PaymentFraud = 'payment_fraud',
|
||||||
|
UsageAnomaly = 'usage_anomaly',
|
||||||
|
SIMSwap = 'sim_swap'
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum FraudSeverity {
|
||||||
|
Low = 'low',
|
||||||
|
Medium = 'medium',
|
||||||
|
High = 'high',
|
||||||
|
Critical = 'critical'
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FraudAlert {
|
||||||
|
id: string;
|
||||||
|
type: FraudType;
|
||||||
|
severity: FraudSeverity;
|
||||||
|
profileId: string;
|
||||||
|
description: string;
|
||||||
|
riskScore: number;
|
||||||
|
evidence: string[];
|
||||||
|
ipAddress: string;
|
||||||
|
timestamp: string;
|
||||||
|
status: string;
|
||||||
|
actionsTaken: string[];
|
||||||
|
metadata: Record<string, any>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FraudMetrics {
|
||||||
|
period: string;
|
||||||
|
totalAlerts: number;
|
||||||
|
resolvedAlerts: number;
|
||||||
|
falsePositives: number;
|
||||||
|
resolutionRatePct: number;
|
||||||
|
falsePositiveRatePct: number;
|
||||||
|
byType: Record<FraudType, number>;
|
||||||
|
bySeverity: Record<FraudSeverity, number>;
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FraudAlertFilter {
|
||||||
|
type?: FraudType;
|
||||||
|
severity?: FraudSeverity;
|
||||||
|
status?: string;
|
||||||
|
fromDate?: string;
|
||||||
|
toDate?: string;
|
||||||
|
limit?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Market Analytics Types
|
||||||
|
export interface MarketMetrics {
|
||||||
|
period: string;
|
||||||
|
totalMarketSize: number;
|
||||||
|
ourSubscribers: number;
|
||||||
|
marketSharePct: number;
|
||||||
|
growthRatePct: number;
|
||||||
|
byCountry: Record<string, CountryMetrics>;
|
||||||
|
byCarrier: Record<string, MarketCarrierMetrics>;
|
||||||
|
byDemographic: Record<string, DemoMetrics>;
|
||||||
|
competitorAnalysis: Record<string, CompetitorMetrics>;
|
||||||
|
marketOpportunities: MarketOpportunity[];
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CountryMetrics {
|
||||||
|
country: string;
|
||||||
|
marketSize: number;
|
||||||
|
ourSubscribers: number;
|
||||||
|
marketSharePct: number;
|
||||||
|
growthRatePct: number;
|
||||||
|
averageRevenue: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarketCarrierMetrics {
|
||||||
|
carrierId: string;
|
||||||
|
carrierName: string;
|
||||||
|
subscribers: number;
|
||||||
|
marketSharePct: number;
|
||||||
|
averageRevenue: number;
|
||||||
|
qualityScore: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DemoMetrics {
|
||||||
|
segment: string;
|
||||||
|
subscribers: number;
|
||||||
|
marketSharePct: number;
|
||||||
|
averageRevenue: number;
|
||||||
|
growthRatePct: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompetitorMetrics {
|
||||||
|
name: string;
|
||||||
|
marketSharePct: number;
|
||||||
|
subscribers: number;
|
||||||
|
averagePrice: number;
|
||||||
|
strengths: string[];
|
||||||
|
weaknesses: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MarketOpportunity {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
description: string;
|
||||||
|
potentialSize: number;
|
||||||
|
confidence: number;
|
||||||
|
requiredActions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Predictive Maintenance Types
|
||||||
|
export interface PredictiveMaintenanceMetrics {
|
||||||
|
period: string;
|
||||||
|
totalAssets: number;
|
||||||
|
healthyAssets: number;
|
||||||
|
atRiskAssets: number;
|
||||||
|
criticalAssets: number;
|
||||||
|
overallHealthScore: number;
|
||||||
|
byAssetType: Record<string, AssetTypeMetrics>;
|
||||||
|
predictedFailures: PredictedFailure[];
|
||||||
|
maintenanceSchedule: MaintenanceTask[];
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetTypeMetrics {
|
||||||
|
assetType: string;
|
||||||
|
total: number;
|
||||||
|
healthy: number;
|
||||||
|
atRisk: number;
|
||||||
|
critical: number;
|
||||||
|
healthScore: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PredictedFailure {
|
||||||
|
assetId: string;
|
||||||
|
assetType: string;
|
||||||
|
failureType: string;
|
||||||
|
predictedDate: string;
|
||||||
|
confidence: number;
|
||||||
|
recommendedActions: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MaintenanceTask {
|
||||||
|
id: string;
|
||||||
|
assetId: string;
|
||||||
|
taskType: string;
|
||||||
|
priority: string;
|
||||||
|
scheduledDate: string;
|
||||||
|
estimatedDurationMinutes: number;
|
||||||
|
description: string;
|
||||||
|
status: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pricing Optimization Types
|
||||||
|
export interface PricingOptimizationResult {
|
||||||
|
ratePlanId: string;
|
||||||
|
currentPrice: number;
|
||||||
|
optimalPrice: number;
|
||||||
|
strategy: string;
|
||||||
|
expectedRevenue: number;
|
||||||
|
expectedDemand: number;
|
||||||
|
priceChangePct: number;
|
||||||
|
reasoning: string[];
|
||||||
|
risks: string[];
|
||||||
|
recommendations: string[];
|
||||||
|
confidence: number;
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PricingMetrics {
|
||||||
|
period: string;
|
||||||
|
totalRatePlans: number;
|
||||||
|
optimizedRatePlans: number;
|
||||||
|
averagePriceChangePct: number;
|
||||||
|
expectedRevenueImpactPct: number;
|
||||||
|
churnRateReductionPct: number;
|
||||||
|
priceElasticity: number;
|
||||||
|
competitiveIndex: number;
|
||||||
|
optimizationRoiPct: number;
|
||||||
|
generatedAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface UpdateSubscriberRequest {
|
export interface UpdateSubscriberRequest {
|
||||||
firstName?: string;
|
firstName?: string;
|
||||||
lastName?: string;
|
lastName?: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user