Backend · Data & Caching · Workflows & Automation· 7 min read
Wholesale margin and complex billing engines: real-time profit calculations
Building a high-precision wholesale telecom billing engine. Calculating multi-tier gross margins, fluctuating product tariffs, and real-time revenue analytics with MongoDB aggregation pipelines.
Billing EngineMongoDBCalculationsCRMZustand
In wholesale telecommunications, margins are paper-thin and multi-variable. A single broadband or SIP trunking deal may bundle wholesale wholesale carrier rates, line rental costs, dynamic usage tariffs, and tiered sales representative commissions. Designing the private telecom CRM required engineering a real-time margin calculation engine that accurately predicts gross profit, net margin, and amortization schedules before a contract is finalized.
The multi-variable margin formula
Floating point math in JavaScript (`0.1 + 0.2 === 0.30000000000000004`) causes devastating compounding rounding errors when computing thousands of line items. All currency amounts are stored and computed in integer minor units (pence/cents) or arbitrary-precision BigNumber representations before formatting for display.
export interface DealLineItem {
wholesaleCostPence: number;
salePricePence: number;
quantity: number;
rebatePercent: number; // Stored as basis points (e.g., 250 = 2.5%)
}
export function computeMarginBreakdown(items: DealLineItem[]) {
let totalCostPence = 0;
let totalRevenuePence = 0;
for (const item of items) {
const cost = item.wholesaleCostPence * item.quantity;
const rebate = Math.round((cost * item.rebatePercent) / 10000);
const effectiveCost = cost - rebate;
const revenue = item.salePricePence * item.quantity;
totalCostPence += effectiveCost;
totalRevenuePence += revenue;
}
const grossProfitPence = totalRevenuePence - totalCostPence;
const marginPercentage = totalRevenuePence > 0
? ((grossProfitPence / totalRevenuePence) * 100).toFixed(2)
: '0.00';
return {
totalCostPence,
totalRevenuePence,
grossProfitPence,
marginPercentage: parseFloat(marginPercentage),
};
}Real-time analytics using MongoDB aggregations
Executive dashboards require instant rollups of gross pipeline value, active monthly recurring revenue (MRR), and profit distributions across regional sales reps. Instead of pulling records into memory and looping in Node.js, we execute multi-stage MongoDB aggregation pipelines with `$facet` to compute financial summaries in a single indexed query.
export async function getRevenueAnalytics(tenantId: string, startDate: Date, endDate: Date) {
return DealModel.aggregate([
{
$match: {
tenantId,
createdAt: { $gte: startDate, $lte: endDate },
status: 'SIGNED',
},
},
{
$facet: {
totals: [
{
$group: {
_id: null,
totalRevenue: { $sum: '$financials.totalRevenuePence' },
totalGrossProfit: { $sum: '$financials.grossProfitPence' },
dealCount: { $sum: 1 },
},
},
],
byProductCategory: [
{ $unwind: '$items' },
{
$group: {
_id: '$items.category',
revenue: { $sum: '$items.lineTotalPence' },
profit: { $sum: '$items.lineProfitPence' },
},
},
],
},
},
]);
}