Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 | import { Injectable, Logger } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import { SaaSMonthlyMetric } from './schemas/analytics.schema'; import { Subscription, SubscriptionHistory, } from '../subscriptions/schemas/subscription.schema'; import { PlanPrice, SubscriptionPlanVersion, } from '../subscriptions/schemas/subscription-plan.schema'; import { Cron, CronExpression } from '@nestjs/schedule'; @Injectable() export class SaaSAnalyticsService { private readonly logger = new Logger(SaaSAnalyticsService.name); constructor( @InjectModel(SaaSMonthlyMetric.name) private readonly metricModel: Model<SaaSMonthlyMetric>, @InjectModel(Subscription.name) private readonly subscriptionModel: Model<Subscription>, @InjectModel(SubscriptionHistory.name) private readonly subscriptionHistoryModel: Model<SubscriptionHistory>, @InjectModel(PlanPrice.name) private readonly planPriceModel: Model<PlanPrice>, @InjectModel(SubscriptionPlanVersion.name) private readonly planVersionModel: Model<SubscriptionPlanVersion>, ) {} @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT) async generateDailyRollup() { const monthKey = new Date().toISOString().substring(0, 7); // e.g. 2026-07 this.logger.log(`Starting SaaS metric rollup for ${monthKey}`); const activeSubscriptions = await this.subscriptionModel .find({ status: 'active' }) .exec(); let totalMrr = 0; const planPrices = new Map<string, number>(); for (const sub of activeSubscriptions) { if (!planPrices.has(sub.planVersionId)) { const price = await this.planPriceModel .findOne({ planVersionId: sub.planVersionId, billingCycle: 'monthly', isActive: true, }) .exec(); if (!price) { const yearlyPrice = await this.planPriceModel .findOne({ planVersionId: sub.planVersionId, billingCycle: 'yearly', isActive: true, }) .exec(); if (yearlyPrice) { planPrices.set( sub.planVersionId, Math.floor(yearlyPrice.amount / 12), ); } else { planPrices.set(sub.planVersionId, 0); } } else { planPrices.set(sub.planVersionId, price.amount); } } totalMrr += planPrices.get(sub.planVersionId) || 0; } const arr = totalMrr * 12; const activeSubscribersCount = activeSubscriptions.length; const startOfMonth = new Date( new Date().getFullYear(), new Date().getMonth(), 1, ); const cancelledCount = await this.subscriptionModel .countDocuments({ status: 'cancelled', cancelledAt: { $gte: startOfMonth }, }) .exec(); const newSubsCount = await this.subscriptionModel .countDocuments({ createdAt: { $gte: startOfMonth }, }) .exec(); let churnRate = 0; const totalAtStart = activeSubscribersCount + cancelledCount - newSubsCount; if (totalAtStart > 0) { churnRate = (cancelledCount / totalAtStart) * 100; } await this.metricModel .findOneAndUpdate( { monthKey }, { $set: { mrr: totalMrr, arr, activeSubscribers: activeSubscribersCount, churnRate: parseFloat(churnRate.toFixed(2)), newSubscribers: newSubsCount, cancelledSubscribers: cancelledCount, }, }, { upsert: true, new: true }, ) .exec(); this.logger.log( `SaaS metric rollup completed for ${monthKey}: MRR=${totalMrr}, ARR=${arr}`, ); } async getMetrics(monthKey: string): Promise<any> { return this.metricModel.findOne({ monthKey }).lean().exec(); } async getHistoricalMetrics(limit: number = 12): Promise<any[]> { return this.metricModel .find() .sort({ monthKey: -1 }) .limit(limit) .lean() .exec(); } } |