Billing Analytics
Billing Analytics provides comprehensive subscription performance analytics, revenue metrics, and administrative reporting capabilities for billing oversight and business intelligence within the DashClicks platform.
API Endpoints Overview
| Method | Endpoint | Description |
|---|---|---|
GET | /v1/admin/billing/analytics/overview | Get billing overview and key metrics |
GET | /v1/admin/billing/analytics/revenue | Get revenue analytics and trends |
GET | /v1/admin/billing/analytics/subscriptions | Get subscription lifecycle analytics |
Service Methods & Business Logic
Billing Overview Analytics
getBillingOverview(dateRange, filters) - Comprehensive billing overview and key performance indicators
- Provides high-level billing analytics and key performance indicators for administrative oversight
- Key Performance Indicators: Essential billing metrics including:
- Total active subscriptions and subscription growth rates
- Monthly recurring revenue (MRR) and annual recurring revenue (ARR)
- Subscription churn rates and retention metrics
- Average revenue per user (ARPU) and customer lifetime value (CLV)
- Subscription Status Distribution: Detailed breakdown of subscription health:
- Active subscription counts and percentage distribution
- Past-due subscription identification and recovery rates
- Cancellation patterns and period-end cancellation tracking
- Unpaid subscription monitoring and collection metrics
- Revenue Trend Analysis: Historical revenue pattern analysis:
- Month-over-month and year-over-year revenue growth
- Revenue trend identification and projection capabilities
- Seasonal pattern analysis and business cycle insights
- Product-specific revenue contribution analysis
- Performance Benchmarks: Comparative analysis and benchmarking:
- Industry standard comparisons and performance metrics
- Historical performance tracking and improvement indicators
- Goal tracking and target achievement monitoring
- MongoDB Collections: Aggregated subscription and revenue data
- Returns: Comprehensive billing overview with KPIs and trend analysis
Revenue Analytics
getRevenueAnalytics(period, segmentation) - Detailed revenue analysis and financial reporting
- Analyzes revenue patterns, growth metrics, and financial performance indicators
- Revenue Segmentation: Multi-dimensional revenue analysis including:
- Product-type revenue breakdown and contribution analysis
- Partner/agency revenue distribution and performance metrics
- Customer segment revenue analysis and growth patterns
- Geographic revenue distribution and market performance
- Growth Metrics: Comprehensive growth analysis and forecasting:
- Month-over-month (MoM) and year-over-year (YoY) growth rates
- Compound annual growth rate (CAGR) calculation and tracking
- Revenue growth trend analysis and pattern identification
- Growth acceleration and deceleration indicators
- Financial Health Indicators: Business financial health assessment:
- Revenue concentration and diversification metrics
- Customer acquisition cost (CAC) and revenue relationship
- Revenue predictability and recurring revenue stability
- Cash flow indicators and billing cycle analysis
- Forecasting and Projections: Revenue forecasting and business planning:
- Short-term and long-term revenue projections
- Scenario analysis for business planning and decision-making
- Seasonal adjustment and trend extrapolation
- Risk assessment and revenue protection strategies
- MongoDB Collections: Revenue tracking with temporal and segmentation data
- Returns: Detailed revenue analytics with growth metrics and projections
Subscription Lifecycle Analytics
getSubscriptionLifecycleAnalytics(cohortPeriod, metrics) - Subscription behavior and lifecycle analysis
- Analyzes subscription behavior patterns, lifecycle metrics, and customer retention indicators
- Cohort Analysis: Customer behavior analysis by subscription cohorts:
- Subscription cohort creation and tracking by signup period
- Retention rate analysis and churn pattern identification
- Customer lifetime value calculation by cohort segments
- Cohort-based revenue contribution and growth analysis
- Churn Analysis: Comprehensive churn analysis and prevention insights:
- Churn rate calculation by time period and customer segment
- Churn reason analysis and pattern identification
- Early churn indicators and risk factor analysis
- Churn prevention strategy effectiveness measurement
- Subscription Health Metrics: Subscription performance and health indicators:
- Subscription age distribution and maturity analysis
- Payment success rates and billing reliability metrics
- Upgrade and downgrade pattern analysis
- Cross-sell and upsell opportunity identification
- Customer Journey Analytics: Customer behavior and engagement analysis:
- Subscription lifecycle stage analysis and progression tracking
- Customer engagement patterns and usage correlation
- Customer success indicators and satisfaction metrics
- Renewal probability and retention likelihood scoring
- MongoDB Collections: Subscription lifecycle data with customer behavior tracking
- Returns: Subscription lifecycle analytics with cohort analysis and churn insights
Technical Implementation Details
Billing Overview Aggregation Pipeline
const getBillingOverviewPipeline = (dateRange, filters) => {
return [
{
$match: {
created: {
$gte: new Date(dateRange.start),
$lte: new Date(dateRange.end),
},
...(filters.status && { status: { $in: filters.status } }),
...(filters.productTypes && {
'plan.metadata.product_type': { $in: filters.productTypes },
}),
},
},
{
$group: {
_id: null,
totalSubscriptions: { $sum: 1 },
activeSubscriptions: {
$sum: {
$cond: [{ $in: ['$status', ['active', 'trialing']] }, 1, 0],
},
},
pastDueSubscriptions: {
$sum: {
$cond: [{ $eq: ['$status', 'past_due'] }, 1, 0],
},
},
canceledSubscriptions: {
$sum: {
$cond: [{ $eq: ['$status', 'canceled'] }, 1, 0],
},
},
totalRevenue: {
$sum: {
$cond: [{ $in: ['$status', ['active', 'trialing']] }, '$plan.amount', 0],
},
},
avgSubscriptionValue: { $avg: '$plan.amount' },
},
},
{
$project: {
_id: 0,
subscriptionMetrics: {
total: '$totalSubscriptions',
active: '$activeSubscriptions',
pastDue: '$pastDueSubscriptions',
canceled: '$canceledSubscriptions',
activeRate: {
$divide: ['$activeSubscriptions', '$totalSubscriptions'],
},
churnRate: {
$divide: ['$canceledSubscriptions', '$totalSubscriptions'],
},
},
revenueMetrics: {
total: '$totalRevenue',
mrr: {
$divide: [
{
$multiply: [
'$totalRevenue',
{
$switch: {
branches: [
{ case: { $eq: ['$plan.interval', 'year'] }, then: 1 / 12 },
{ case: { $eq: ['$plan.interval', 'month'] }, then: 1 },
{ case: { $eq: ['$plan.interval', 'day'] }, then: 30 },
],
default: 1,
},
},
],
},
100,
],
},
arpu: {
$divide: ['$avgSubscriptionValue', 100],
},
},
},
},
];
};
Revenue Growth Analysis
const calculateRevenueGrowth = async (currentPeriod, previousPeriod) => {
const [currentRevenue, previousRevenue] = await Promise.all([
StoreSubscription.aggregate([
{
$match: {
created: {
$gte: new Date(currentPeriod.start),
$lte: new Date(currentPeriod.end),
},
status: { $in: ['active', 'trialing'] },
},
},
{
$group: {
_id: null,
totalRevenue: { $sum: '$plan.amount' },
subscriptionCount: { $sum: 1 },
},
},
]),
StoreSubscription.aggregate([
{
$match: {
created: {
$gte: new Date(previousPeriod.start),
$lte: new Date(previousPeriod.end),
},
status: { $in: ['active', 'trialing'] },
},
},
{
$group: {
_id: null,
totalRevenue: { $sum: '$plan.amount' },
subscriptionCount: { $sum: 1 },
},
},
]),
]);
const current = currentRevenue[0] || { totalRevenue: 0, subscriptionCount: 0 };
const previous = previousRevenue[0] || { totalRevenue: 0, subscriptionCount: 0 };
const revenueGrowthRate =
previous.totalRevenue > 0
? ((current.totalRevenue - previous.totalRevenue) / previous.totalRevenue) * 100
: 0;
const subscriptionGrowthRate =
previous.subscriptionCount > 0
? ((current.subscriptionCount - previous.subscriptionCount) / previous.subscriptionCount) *
100
: 0;
return {
current: {
revenue: current.totalRevenue / 100, // Convert to dollars
subscriptions: current.subscriptionCount,
arpu:
current.subscriptionCount > 0 ? current.totalRevenue / current.subscriptionCount / 100 : 0,
},
previous: {
revenue: previous.totalRevenue / 100,
subscriptions: previous.subscriptionCount,
arpu:
previous.subscriptionCount > 0
? previous.totalRevenue / previous.subscriptionCount / 100
: 0,
},
growth: {
revenue: revenueGrowthRate,
subscriptions: subscriptionGrowthRate,
trend: revenueGrowthRate > 0 ? 'increasing' : revenueGrowthRate < 0 ? 'decreasing' : 'stable',
},
};
};
Subscription Cohort Analysis
const generateCohortAnalysis = async cohortPeriod => {
const cohortPipeline = [
{
$match: {
created: {
$gte: moment().subtract(cohortPeriod.months, 'months').startOf('month').toDate(),
$lte: moment().endOf('month').toDate(),
},
},
},
{
$group: {
_id: {
cohortMonth: {
$dateToString: {
format: '%Y-%m',
date: '$created',
},
},
currentStatus: '$status',
},
subscriptionCount: { $sum: 1 },
revenue: { $sum: '$plan.amount' },
},
},
{
$group: {
_id: '$_id.cohortMonth',
totalSubscriptions: { $sum: '$subscriptionCount' },
totalRevenue: { $sum: '$revenue' },
statusBreakdown: {
$push: {
status: '$_id.currentStatus',
count: '$subscriptionCount',
revenue: '$revenue',
},
},
},
},
{
$project: {
cohortMonth: '$_id',
totalSubscriptions: 1,
totalRevenue: { $divide: ['$totalRevenue', 100] },
retentionRate: {
$divide: [
{
$size: {
$filter: {
input: '$statusBreakdown',
cond: { $in: ['$$this.status', ['active', 'trialing']] },
},
},
},
'$totalSubscriptions',
],
},
churnRate: {
$divide: [
{
$size: {
$filter: {
input: '$statusBreakdown',
cond: { $eq: ['$$this.status', 'canceled'] },
},
},
},
'$totalSubscriptions',
],
},
statusBreakdown: 1,
},
},
{
$sort: { cohortMonth: 1 },
},
];
const cohortData = await StoreSubscription.aggregate(cohortPipeline);
return {
cohorts: cohortData,
summary: {
totalCohorts: cohortData.length,
avgRetentionRate:
cohortData.reduce((sum, cohort) => sum + cohort.retentionRate, 0) / cohortData.length,
avgChurnRate:
cohortData.reduce((sum, cohort) => sum + cohort.churnRate, 0) / cohortData.length,
period: cohortPeriod,
},
};
};
API Response Formats
Billing Overview Response
{
"success": true,
"message": "SUCCESS",
"data": {
"subscriptionMetrics": {
"total": 1250,
"active": 1125,
"pastDue": 45,
"canceled": 80,
"activeRate": 0.9,
"churnRate": 0.064
},
"revenueMetrics": {
"total": 2847500,
"mrr": 2847.5,
"arpu": 253.33
},
"trends": {
"subscriptionGrowth": 12.5,
"revenueGrowth": 18.3,
"churnTrend": "decreasing"
},
"dateRange": {
"start": "2024-10-01",
"end": "2024-10-31"
}
}
}
Revenue Analytics Response
{
"success": true,
"message": "SUCCESS",
"data": {
"current": {
"revenue": 28475.0,
"subscriptions": 1125,
"arpu": 253.33
},
"previous": {
"revenue": 24120.0,
"subscriptions": 1008,
"arpu": 239.29
},
"growth": {
"revenue": 18.03,
"subscriptions": 11.61,
"trend": "increasing"
},
"segmentation": {
"byProduct": [
{
"productType": "seo",
"revenue": 11390.0,
"subscriptions": 456,
"percentage": 40.0
},
{
"productType": "google_ads",
"revenue": 8542.5,
"subscriptions": 342,
"percentage": 30.0
}
],
"byPartner": [
{
"partnerName": "Top Agency",
"revenue": 5695.0,
"subscriptions": 228,
"percentage": 20.0
}
]
}
}
}
Subscription Lifecycle Response
{
"success": true,
"message": "SUCCESS",
"data": {
"cohorts": [
{
"cohortMonth": "2024-08",
"totalSubscriptions": 145,
"totalRevenue": 3625.0,
"retentionRate": 0.89,
"churnRate": 0.07,
"statusBreakdown": [
{
"status": "active",
"count": 129,
"revenue": 3225.0
},
{
"status": "canceled",
"count": 10,
"revenue": 250.0
}
]
}
],
"summary": {
"totalCohorts": 12,
"avgRetentionRate": 0.86,
"avgChurnRate": 0.08,
"period": {
"months": 12
}
}
}
}
Query Parameters
Analytics Parameters
start_date(string) - Start date for analytics period (ISO 8601)end_date(string) - End date for analytics period (ISO 8601)status(array) - Filter by subscription statusproduct_types(array) - Filter by product typesgranularity(string) - Data granularity: 'daily', 'weekly', 'monthly'
Revenue Parameters
period(string) - Analysis period: 'last_30_days', 'last_90_days', 'year_to_date'segmentation(array) - Segmentation dimensions: ['product', 'partner', 'geography']currency(string) - Currency for revenue display (default: 'USD')
Lifecycle Parameters
cohort_period(string) - Cohort analysis period: 'last_6_months', 'last_12_months'metrics(array) - Lifecycle metrics: ['retention', 'churn', 'ltv']segment(string) - Customer segment for analysis
Error Handling
Billing Analytics Error Scenarios
- 400 Bad Request: Invalid date range or analytics parameters
- 404 Not Found: No analytics data available for specified criteria
- 500 Internal Server Error: Analytics aggregation failures
No Data Response
{
"success": true,
"message": "No billing data available for the specified period",
"data": {
"subscriptionMetrics": null,
"revenueMetrics": null,
"dateRange": {
"start": "2024-10-01",
"end": "2024-10-31"
}
}
}
Usage Examples
Get Billing Overview
GET /v1/admin/billing/analytics/overview?start_date=2024-10-01&end_date=2024-10-31
Authorization: Bearer {admin_token}
Get Revenue Analytics with Segmentation
GET /v1/admin/billing/analytics/revenue?period=last_90_days&segmentation=product,partner
Authorization: Bearer {admin_token}
Get Subscription Lifecycle Analysis
GET /v1/admin/billing/analytics/subscriptions?cohort_period=last_12_months&metrics=retention,churn
Authorization: Bearer {admin_token}