All files / src/platform/billing billing.service.ts

0% Statements 0/109
0% Branches 0/82
0% Functions 0/11
0% Lines 0/103

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 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import {
  Injectable,
  BadRequestException,
  NotFoundException,
  Logger,
} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import {
  PaymentIntent,
  PaymentTransaction,
  BillingInvoice,
  Coupon,
  CouponRedemption,
} from './schemas/billing.schema';
import { PaymentProvider } from './payment-provider.interface';
import {
  MockStripeProvider,
  MockRazorpayProvider,
  MockEasebuzzProvider,
} from './providers/mock-billing.providers';
import { StripeProvider } from './providers/stripe.provider';
import { RazorpayProvider } from './providers/razorpay.provider';
import { EasebuzzProvider } from './providers/easebuzz.provider';
import { Subscription } from '../subscriptions/schemas/subscription.schema';
import { AuditLogService } from '../audit/audit-log.service';
import { EventBusService } from '../events/event-bus.service';
 
@Injectable()
export class BillingService {
  private readonly logger = new Logger(BillingService.name);
  private readonly providers = new Map<string, PaymentProvider>();
 
  constructor(
    @InjectModel(PaymentIntent.name)
    private readonly intentModel: Model<PaymentIntent>,
    @InjectModel(PaymentTransaction.name)
    private readonly transactionModel: Model<PaymentTransaction>,
    @InjectModel(BillingInvoice.name)
    private readonly invoiceModel: Model<BillingInvoice>,
    @InjectModel(Coupon.name) private readonly couponModel: Model<Coupon>,
    @InjectModel(CouponRedemption.name)
    private readonly redemptionModel: Model<CouponRedemption>,
    @InjectModel(Subscription.name)
    private readonly subscriptionModel: Model<Subscription>,
    private readonly auditLog: AuditLogService,
    private readonly eventBus: EventBusService,
  ) {
    // Register providers based on environment variables
    if (process.env.STRIPE_SECRET_KEY) {
      this.registerProvider(
        new StripeProvider(
          process.env.STRIPE_SECRET_KEY,
          process.env.STRIPE_WEBHOOK_SECRET,
        ),
      );
    } else {
      this.registerProvider(new MockStripeProvider());
    }
 
    if (process.env.RAZORPAY_KEY_ID && process.env.RAZORPAY_KEY_SECRET) {
      this.registerProvider(
        new RazorpayProvider(
          process.env.RAZORPAY_KEY_ID,
          process.env.RAZORPAY_KEY_SECRET,
          process.env.RAZORPAY_WEBHOOK_SECRET,
        ),
      );
    } else {
      this.registerProvider(new MockRazorpayProvider());
    }
 
    if (process.env.EASEBUZZ_KEY && process.env.EASEBUZZ_SALT) {
      this.registerProvider(
        new EasebuzzProvider(
          process.env.EASEBUZZ_KEY,
          process.env.EASEBUZZ_SALT,
          (process.env.EASEBUZZ_ENV as 'test' | 'prod') || 'test',
        ),
      );
    } else {
      this.registerProvider(new MockEasebuzzProvider());
    }
  }
 
  registerProvider(provider: PaymentProvider) {
    this.providers.set(provider.name, provider);
    this.logger.log(`Registered billing provider: ${provider.name}`);
  }
 
  // ============================================================
  // INVOICE GENERATION
  // ============================================================
 
  async createInvoice(params: {
    tenantId: string;
    subtotal: number;
    tax: number;
    discount?: number;
    currency?: string;
  }): Promise<any> {
    const totalCount = await this.invoiceModel.countDocuments().exec();
    const invoiceNumber = `INV-${new Date().getFullYear()}-${(totalCount + 1).toString().padStart(5, '0')}`;
 
    const discount = params.discount || 0;
    const total = params.subtotal + params.tax - discount;
 
    const invoice = await this.invoiceModel.create({
      tenantId: params.tenantId,
      invoiceNumber,
      status: 'issued',
      subtotal: params.subtotal,
      tax: params.tax,
      discount,
      total,
      currency: params.currency || 'INR',
      issuedAt: new Date(),
    });
 
    await this.eventBus.publish(
      'platform.invoice.issued.v1',
      {
        invoiceId: (invoice as any)._id.toString(),
        tenantId: params.tenantId,
        total,
      },
      params.tenantId,
    );
 
    return { ...invoice.toObject(), id: (invoice as any)._id.toString() };
  }
 
  async getInvoices(tenantId: string): Promise<any[]> {
    return this.invoiceModel
      .find({ tenantId })
      .sort({ createdAt: -1 })
      .lean()
      .exec();
  }
 
  async getInvoice(id: string, tenantId: string): Promise<any> {
    const invoice = await this.invoiceModel
      .findOne({ _id: id, tenantId })
      .lean()
      .exec();
    if (!invoice) throw new NotFoundException('Invoice not found');
    return { ...invoice, id: (invoice as any)._id.toString() };
  }
 
  // ============================================================
  // CHECKOUT & TRANSACTIONS
  // ============================================================
 
  async createCheckout(params: {
    tenantId: string;
    invoiceId: string;
    providerName: string;
    callbackUrl: string;
  }): Promise<any> {
    const invoice = await this.invoiceModel
      .findOne({ _id: params.invoiceId, tenantId: params.tenantId })
      .exec();
    if (!invoice) throw new NotFoundException('Invoice not found');
    if (invoice.status === 'paid')
      throw new BadRequestException('Invoice is already paid');
 
    const provider = this.providers.get(params.providerName);
    if (!provider)
      throw new BadRequestException(
        `Payment provider not configured: ${params.providerName}`,
      );
 
    const checkout = await provider.createCheckoutLink({
      tenantId: params.tenantId,
      amount: invoice.total,
      currency: invoice.currency,
      invoiceId: params.invoiceId,
      callbackUrl: params.callbackUrl,
    });
 
    await this.intentModel.create({
      tenantId: params.tenantId,
      amount: invoice.total,
      currency: invoice.currency,
      providerName: params.providerName,
      providerIntentId: checkout.providerIntentId,
      status: 'PENDING',
    });
 
    return { checkoutUrl: checkout.checkoutUrl };
  }
 
  async processWebhook(
    providerName: string,
    payload: any,
    signature: string,
  ): Promise<any> {
    const provider = this.providers.get(providerName);
    if (!provider)
      throw new BadRequestException('Invalid provider webhook trigger');
 
    const verification = await provider.verifyWebhook(payload, signature);
    if (!verification.success) {
      throw new BadRequestException('Webhook signature validation failed');
    }
 
    // Idempotent transaction check
    const existingTx = await this.transactionModel
      .findOne({ transactionId: verification.transactionId })
      .exec();
    if (existingTx) {
      return { success: true, message: 'Webhook already processed' };
    }
 
    // Process payment success
    if (verification.status === 'SUCCESS') {
      const invoice = await this.invoiceModel
        .findOne({ _id: payload.invoiceId })
        .exec();
      if (invoice) {
        invoice.status = 'paid';
        invoice.paidAt = new Date();
        await invoice.save();
 
        // Create transaction record
        await this.transactionModel.create({
          tenantId: invoice.tenantId,
          invoiceId: (invoice as any)._id.toString(),
          amount: verification.amountPaid,
          currency: invoice.currency,
          provider: providerName,
          transactionId: verification.transactionId,
          status: 'SUCCESS',
        });
 
        // Update tenant subscription status to active
        await this.subscriptionModel
          .updateOne(
            { tenantId: invoice.tenantId },
            { $set: { status: 'active' } },
          )
          .exec();
 
        await this.eventBus.publish(
          'platform.payment.succeeded.v1',
          {
            tenantId: invoice.tenantId,
            invoiceId: (invoice as any)._id.toString(),
            amount: verification.amountPaid,
          },
          invoice.tenantId,
        );
 
        await this.eventBus.publish(
          'platform.invoice.paid.v1',
          {
            invoiceId: (invoice as any)._id.toString(),
            tenantId: invoice.tenantId,
          },
          invoice.tenantId,
        );
      }
    }
 
    return { success: true };
  }
 
  // ============================================================
  // COUPONS ENGINE
  // ============================================================
 
  async validateCoupon(code: string, tenantId: string): Promise<any> {
    const coupon = await this.couponModel
      .findOne({ code, isActive: true })
      .exec();
    if (!coupon)
      throw new BadRequestException('Invalid or inactive coupon code');
    if (coupon.expiresAt < new Date())
      throw new BadRequestException('Coupon code has expired');
    if (
      coupon.maxRedemptions > 0 &&
      coupon.currentRedemptionsCount >= coupon.maxRedemptions
    ) {
      throw new BadRequestException('Coupon code limit reached');
    }
 
    // Check if tenant already redeemed this coupon
    const redeemed = await this.redemptionModel
      .findOne({ couponId: (coupon as any)._id.toString(), tenantId })
      .lean()
      .exec();
    if (redeemed)
      throw new BadRequestException('Coupon already applied by this tenant');
 
    return coupon;
  }
 
  async applyCoupon(
    code: string,
    tenantId: string,
    invoiceId: string,
  ): Promise<any> {
    const coupon = await this.validateCoupon(code, tenantId);
    const invoice = await this.invoiceModel
      .findOne({ _id: invoiceId, tenantId })
      .exec();
    if (!invoice) throw new NotFoundException('Invoice not found');
 
    let discountApplied = 0;
    if (coupon.discountType === 'PERCENT') {
      discountApplied = Math.round((invoice.subtotal * coupon.value) / 100);
    } else {
      discountApplied = coupon.value;
    }
 
    // Enforce discount does not exceed total invoice subtotal
    if (discountApplied > invoice.subtotal) discountApplied = invoice.subtotal;
 
    // Apply discount transaction
    invoice.discount = discountApplied;
    invoice.total = invoice.subtotal + invoice.tax - discountApplied;
    await invoice.save();
 
    await this.redemptionModel.create({
      couponId: coupon._id.toString(),
      tenantId,
      discountApplied,
      invoiceId,
    });
 
    coupon.currentRedemptionsCount += 1;
    await coupon.save();
 
    await this.eventBus.publish(
      'platform.coupon.redeemed.v1',
      {
        couponId: coupon._id.toString(),
        tenantId,
        discountApplied,
      },
      tenantId,
    );
 
    return { success: true, discountApplied, total: invoice.total };
  }
 
  async createCoupon(params: {
    code: string;
    discountType: string;
    value: number;
    expiresAt: Date;
    maxRedemptions?: number;
  }): Promise<any> {
    return this.couponModel.create(params);
  }
 
  async listAllTransactionsCrossTenant(): Promise<any[]> {
    return this.invoiceModel.find().sort({ createdAt: -1 }).lean().exec();
  }
}