subscription.service.ts362 lines, 11 KB
| 1 | import { User } from "../entities/user.entity"; |
| 2 | import { AppDataSource } from "../config/database"; |
| 3 | import Stripe from "stripe"; |
| 4 | import { SubscriptionPlan } from "../entities/subscription-plan.entity"; |
| 5 | import { UserSubscription } from "../entities/user-subscription.entity"; |
| 6 | import { AppError } from "../utils/errors"; |
| 7 | import { StatusCodes } from "http-status-codes/build/cjs"; |
| 8 | |
| 9 | export class SubscriptionService { |
| 10 | private static stripe: Stripe; |
| 11 | private static userRepository = AppDataSource.getRepository(User); |
| 12 | private static planRepository = AppDataSource.getRepository(SubscriptionPlan); |
| 13 | private static subscriptionRepository = |
| 14 | AppDataSource.getRepository(UserSubscription); |
| 15 | |
| 16 | public static async initialize() { |
| 17 | if (!process.env.STRIPE_SECRET_KEY) { |
| 18 | throw new Error("STRIPE_SECRET_KEY is not set"); |
| 19 | } |
| 20 | this.stripe = new Stripe(process.env.STRIPE_SECRET_KEY); |
| 21 | } |
| 22 | |
| 23 | public static async getPlans() { |
| 24 | return this.planRepository.find({ |
| 25 | where: { isActive: true }, |
| 26 | order: { price: "ASC" }, // sort by price |
| 27 | }); |
| 28 | } |
| 29 | |
| 30 | public static async getPlan(id: string) { |
| 31 | const plan = await this.planRepository.findOneBy({ id }); |
| 32 | if (!plan) { |
| 33 | throw new AppError(StatusCodes.NOT_FOUND, "Plan not found"); |
| 34 | } |
| 35 | return plan; |
| 36 | } |
| 37 | |
| 38 | public static async getUserSubscription(userId: string) { |
| 39 | const subscription = await this.subscriptionRepository.findOne({ |
| 40 | where: { user: { id: userId }, status: "active" }, |
| 41 | relations: ["plan"], |
| 42 | order: { createdAt: "DESC" }, |
| 43 | }); |
| 44 | return subscription; |
| 45 | } |
| 46 | |
| 47 | public static async createCheckoutSession(userId: string, planId: string) { |
| 48 | const user = await this.userRepository.findOneBy({ id: userId }); |
| 49 | if (!user) { |
| 50 | throw new AppError(StatusCodes.NOT_FOUND, "User not found"); |
| 51 | } |
| 52 | |
| 53 | const plan = await this.planRepository.findOneBy({ id: planId }); |
| 54 | if (!plan) { |
| 55 | throw new AppError(StatusCodes.NOT_FOUND, "Plan not found"); |
| 56 | } |
| 57 | |
| 58 | const activeSubscription = await this.getUserSubscription(userId); |
| 59 | if (activeSubscription) { |
| 60 | throw new AppError( |
| 61 | StatusCodes.BAD_REQUEST, |
| 62 | "You already have an active subscription" |
| 63 | ); |
| 64 | } |
| 65 | |
| 66 | if (!user.stripeCustomerId) { |
| 67 | const customer = await this.stripe.customers.create({ |
| 68 | email: user.email, |
| 69 | name: user.name || undefined, |
| 70 | metadata: { userId: user.id }, |
| 71 | }); |
| 72 | user.stripeCustomerId = customer.id; |
| 73 | await this.userRepository.save(user); |
| 74 | } |
| 75 | |
| 76 | const session = await this.stripe.checkout.sessions.create({ |
| 77 | customer: user.stripeCustomerId, |
| 78 | line_items: [ |
| 79 | { |
| 80 | price: plan.stripePriceId, |
| 81 | quantity: 1, |
| 82 | }, |
| 83 | ], |
| 84 | mode: "subscription", |
| 85 | success_url: `${process.env.FRONTEND_URL}/subscriptions/success?session_id={CHECKOUT_SESSION_ID}`, |
| 86 | cancel_url: `${process.env.FRONTEND_URL}/subscriptions/cancel`, |
| 87 | metadata: { |
| 88 | userId: user.id, |
| 89 | planId: plan.id, |
| 90 | }, |
| 91 | }); |
| 92 | |
| 93 | return { url: session.url }; |
| 94 | } |
| 95 | |
| 96 | public static async handleWebhook(event: Stripe.Event) { |
| 97 | switch (event.type) { |
| 98 | case "checkout.session.completed": |
| 99 | await this.handleCheckoutSessionCompleted( |
| 100 | event.data.object as Stripe.Checkout.Session |
| 101 | ); |
| 102 | break; |
| 103 | case "invoice.paid": |
| 104 | await this.handleInvoicePaid(event.data.object as Stripe.Invoice); |
| 105 | break; |
| 106 | case "customer.subscription.updated": |
| 107 | await this.handleSubscriptionUpdated( |
| 108 | event.data.object as Stripe.Subscription |
| 109 | ); |
| 110 | break; |
| 111 | case "customer.subscription.deleted": |
| 112 | await this.handleSubscriptionDeleted( |
| 113 | event.data.object as Stripe.Subscription |
| 114 | ); |
| 115 | break; |
| 116 | } |
| 117 | |
| 118 | return { received: true }; |
| 119 | } |
| 120 | |
| 121 | private static async handleCheckoutSessionCompleted( |
| 122 | session: Stripe.Checkout.Session |
| 123 | ) { |
| 124 | const { userId, planId } = session.metadata || {}; |
| 125 | const subscription = await this.stripe.subscriptions.retrieve( |
| 126 | session.subscription as string |
| 127 | ); |
| 128 | |
| 129 | if (userId && planId) { |
| 130 | await this.createUserSubscription(userId, planId, subscription); |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | private static async handleInvoicePaid(invoice: Stripe.Invoice) { |
| 135 | const subscriptionId = invoice.subscription as string; |
| 136 | const subscription = await this.stripe.subscriptions.retrieve( |
| 137 | subscriptionId |
| 138 | ); |
| 139 | const stripeCustomerId = subscription.customer as string; |
| 140 | |
| 141 | const user = await this.userRepository.findOneBy({ |
| 142 | stripeCustomerId, |
| 143 | }); |
| 144 | |
| 145 | if (user) { |
| 146 | // Update the subscription period |
| 147 | const userSubscription = await this.subscriptionRepository.findOne({ |
| 148 | where: { stripeSubscriptionId: subscriptionId }, |
| 149 | }); |
| 150 | |
| 151 | if (userSubscription) { |
| 152 | userSubscription.currentPeriodStart = new Date( |
| 153 | subscription.current_period_start * 1000 |
| 154 | ); |
| 155 | userSubscription.currentPeriodEnd = new Date( |
| 156 | subscription.current_period_end * 1000 |
| 157 | ); |
| 158 | userSubscription.status = "active"; |
| 159 | await this.subscriptionRepository.save(userSubscription); |
| 160 | } |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | private static async handleSubscriptionUpdated( |
| 165 | subscription: Stripe.Subscription |
| 166 | ) { |
| 167 | const stripeCustomerId = subscription.customer as string; |
| 168 | const user = await this.userRepository.findOneBy({ |
| 169 | stripeCustomerId, |
| 170 | }); |
| 171 | |
| 172 | if (user) { |
| 173 | const userSubscription = await this.subscriptionRepository.findOne({ |
| 174 | where: { stripeSubscriptionId: subscription.id }, |
| 175 | }); |
| 176 | |
| 177 | if (userSubscription) { |
| 178 | userSubscription.status = subscription.status as any; |
| 179 | userSubscription.currentPeriodStart = new Date( |
| 180 | subscription.current_period_start * 1000 |
| 181 | ); |
| 182 | userSubscription.currentPeriodEnd = new Date( |
| 183 | subscription.current_period_end * 1000 |
| 184 | ); |
| 185 | |
| 186 | if (subscription.cancel_at) { |
| 187 | userSubscription.cancelAt = new Date(subscription.cancel_at * 1000); |
| 188 | } |
| 189 | if (subscription.canceled_at) { |
| 190 | userSubscription.canceledAt = new Date( |
| 191 | subscription.canceled_at * 1000 |
| 192 | ); |
| 193 | } |
| 194 | |
| 195 | await this.subscriptionRepository.save(userSubscription); |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | private static async handleSubscriptionDeleted( |
| 201 | subscription: Stripe.Subscription |
| 202 | ) { |
| 203 | const userSubscription = await this.subscriptionRepository.findOne({ |
| 204 | where: { stripeSubscriptionId: subscription.id }, |
| 205 | }); |
| 206 | |
| 207 | if (userSubscription) { |
| 208 | userSubscription.status = "canceled"; |
| 209 | userSubscription.canceledAt = new Date(); |
| 210 | await this.subscriptionRepository.save(userSubscription); |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | private static async createUserSubscription( |
| 215 | userId: string, |
| 216 | planId: string, |
| 217 | stripeSubscription: Stripe.Subscription |
| 218 | ) { |
| 219 | const user = await this.userRepository.findOneBy({ id: userId }); |
| 220 | const plan = await this.planRepository.findOneBy({ id: planId }); |
| 221 | |
| 222 | if (!user || !plan) { |
| 223 | return; |
| 224 | } |
| 225 | |
| 226 | const subscription = new UserSubscription(); |
| 227 | subscription.user = user; |
| 228 | subscription.plan = plan; |
| 229 | subscription.status = stripeSubscription.status as any; |
| 230 | subscription.stripeSubscriptionId = stripeSubscription.id; |
| 231 | subscription.currentPeriodStart = new Date( |
| 232 | stripeSubscription.current_period_start * 1000 |
| 233 | ); |
| 234 | subscription.currentPeriodEnd = new Date( |
| 235 | stripeSubscription.current_period_end * 1000 |
| 236 | ); |
| 237 | |
| 238 | await this.subscriptionRepository.save(subscription); |
| 239 | } |
| 240 | |
| 241 | public static async checkSubscriptionLimits( |
| 242 | userId: string, |
| 243 | videoDurationInSeconds: number |
| 244 | ) { |
| 245 | const userSubscription = await this.getUserSubscription(userId); |
| 246 | |
| 247 | // Free tier (no subscription) |
| 248 | const FREE_TIER_VIDEO_LIMIT = 3; |
| 249 | const FREE_TIER_MINUTES_LIMIT = 30; |
| 250 | |
| 251 | if (!userSubscription) { |
| 252 | // Check user's usage in the free tier |
| 253 | const totalVideos = await this.countUserVideos(userId); |
| 254 | const totalMinutes = await this.countUserMinutes(userId); |
| 255 | |
| 256 | const minutesNeeded = Math.ceil(videoDurationInSeconds / 60); |
| 257 | |
| 258 | if (totalVideos >= FREE_TIER_VIDEO_LIMIT) { |
| 259 | throw new AppError( |
| 260 | StatusCodes.PAYMENT_REQUIRED, |
| 261 | `Free tier limit reached: ${FREE_TIER_VIDEO_LIMIT} videos. Please upgrade your subscription.` |
| 262 | ); |
| 263 | } |
| 264 | |
| 265 | if (totalMinutes + minutesNeeded > FREE_TIER_MINUTES_LIMIT) { |
| 266 | throw new AppError( |
| 267 | StatusCodes.PAYMENT_REQUIRED, |
| 268 | `Free tier limit reached: ${FREE_TIER_MINUTES_LIMIT} minutes. Please upgrade your subscription.` |
| 269 | ); |
| 270 | } |
| 271 | |
| 272 | return true; |
| 273 | } |
| 274 | |
| 275 | // Paid subscription |
| 276 | const plan = userSubscription.plan; |
| 277 | const minutesNeeded = Math.ceil(videoDurationInSeconds / 60); |
| 278 | |
| 279 | // If unlimited |
| 280 | if (plan.videoLimit === -1 || plan.minutesLimit === -1) { |
| 281 | return true; |
| 282 | } |
| 283 | |
| 284 | // Check video limit |
| 285 | if (plan.videoLimit > 0 && userSubscription.videosUsed >= plan.videoLimit) { |
| 286 | throw new AppError( |
| 287 | StatusCodes.PAYMENT_REQUIRED, |
| 288 | `Your subscription limit of ${plan.videoLimit} videos has been reached. Please upgrade your plan.` |
| 289 | ); |
| 290 | } |
| 291 | |
| 292 | // Check minutes limit |
| 293 | if ( |
| 294 | plan.minutesLimit > 0 && |
| 295 | userSubscription.minutesUsed + minutesNeeded > plan.minutesLimit |
| 296 | ) { |
| 297 | throw new AppError( |
| 298 | StatusCodes.PAYMENT_REQUIRED, |
| 299 | `Your subscription limit of ${plan.minutesLimit} minutes will be exceeded. Please upgrade your plan.` |
| 300 | ); |
| 301 | } |
| 302 | |
| 303 | return true; |
| 304 | } |
| 305 | |
| 306 | public static async cancelSubscription(userId: string) { |
| 307 | const subscription = await this.getUserSubscription(userId); |
| 308 | |
| 309 | if (!subscription) { |
| 310 | throw new AppError(StatusCodes.NOT_FOUND, "No active subscription found"); |
| 311 | } |
| 312 | |
| 313 | // Cancel at period end in Stripe |
| 314 | await this.stripe.subscriptions.update(subscription.stripeSubscriptionId!, { |
| 315 | cancel_at_period_end: true, |
| 316 | }); |
| 317 | |
| 318 | return { |
| 319 | message: "Subscription will be canceled at the end of the billing period", |
| 320 | }; |
| 321 | } |
| 322 | |
| 323 | public static async incrementUsage( |
| 324 | userId: string, |
| 325 | videoDurationInSeconds: number |
| 326 | ) { |
| 327 | const userSubscription = await this.getUserSubscription(userId); |
| 328 | const minutesUsed = Math.ceil(videoDurationInSeconds / 60); |
| 329 | |
| 330 | if (userSubscription) { |
| 331 | userSubscription.videosUsed += 1; |
| 332 | userSubscription.minutesUsed += minutesUsed; |
| 333 | await this.subscriptionRepository.save(userSubscription); |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | private static async countUserVideos(userId: string): Promise<number> { |
| 338 | const user = await this.userRepository.findOne({ |
| 339 | where: { id: userId }, |
| 340 | relations: ["videos"], |
| 341 | }); |
| 342 | |
| 343 | return user?.videos?.length || 0; |
| 344 | } |
| 345 | |
| 346 | private static async countUserMinutes(userId: string): Promise<number> { |
| 347 | const user = await this.userRepository.findOne({ |
| 348 | where: { id: userId }, |
| 349 | relations: ["videos"], |
| 350 | }); |
| 351 | |
| 352 | if (!user?.videos?.length) { |
| 353 | return 0; |
| 354 | } |
| 355 | |
| 356 | const totalSeconds = user.videos.reduce((total, video) => { |
| 357 | return total + (video.duration || 0); |
| 358 | }, 0); |
| 359 | |
| 360 | return Math.ceil(totalSeconds / 60); |
| 361 | } |
| 362 | } |