# All files / modules/billing/services stripe.service.ts

97.02% Statements 196/202
84.74% Branches 50/59
96.66% Functions 29/30
97.47% Lines 193/198

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
    362
    363
    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    391
    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    423
    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    446
    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    466
    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    497
    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    558
    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    5771x

    1x
    1x
    1x
    1x
    1x
    1x
    1x
    1x

    1x

    67x

    67x

    67x

    67x

    67x

    68x
    68x
    1x
    1x

    67x

    67x

    43x
    1x

    2x

    2x

    2x
    2x

    5x

    5x
    5x
    3x

    2x
    1x

    1x

    7x

    7x

    7x

    3x

    3x

    3x
    1x

    3x

    3x
    3x

    3x

    3x
    3x

    1x
    1x

    3x

    3x
    1x

    2x

    2x

    2x

    2x

    3x

    3x

    3x
    1x

    2x

    2x

    2x
    2x

    2x

    2x

    2x
    1x

    1x

    1x
    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

    3x

    3x
    3x
    1x

    2x

    21x

    21x

    4x
    4x

    2x
    2x

    3x
    3x

    3x
    3x

    3x
    3x

    2x
    2x

    3x
    3x

    1x

    5x
    5x
    1x
    1x

    4x

    4x

    4x
    3x

    4x
    4x
    4x

    4x
    1x

    4x

    4x

    4x
    4x

    2x

    2x
    1x
    1x
    1x
    1x

    3x

    3x
    1x
    1x

    2x

    2x
    1x

    2x
    2x
    2x
    2x

    2x
    2x

    3x

    3x
    1x

    2x

    2x
    1x
    1x

    1x
    1x

    3x
    3x

    2x
    2x

    2x

    2x

    2x
    1x

    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    2x

    2x
    2x

    2x

    2x
    1x
    1x
    1x

    3x

    3x
    2x

    1x
    1x
    1x

    1x

    13x

    13x

    2x

    2x

    2x
    1x

    2x
    2x

    2x

    2x
    2x

    1x
    1x

    1x

    1x

     import {
      Injectable,
      BadRequestException,
      NotFoundException,
      Logger,
      OnModuleInit,
    } from '@nestjs/common';
    import { ConfigService } from '@nestjs/config';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository } from 'typeorm';
    import Stripe from 'stripe';
    import { Subscription, SubscriptionStatus } from '../entities/subscription.entity';
    import { Invoice, InvoiceStatus } from '../entities/invoice.entity';
    import { PaymentMethod } from '../entities/payment-method.entity';
    import {
      CreateStripeCustomerDto,
      CreateStripeSubscriptionDto,
      CreateCheckoutSessionDto,
      CreateBillingPortalSessionDto,
      StripeWebhookEventType,
    } from '../dto/stripe-webhook.dto';

    @Injectable()
    export class StripeService implements OnModuleInit {
      private stripe: Stripe;
      private readonly logger = new Logger(StripeService.name);

      constructor(
        private readonly configService: ConfigService,
        @InjectRepository(Subscription)
        private readonly subscriptionRepo: Repository<Subscription>,
        @InjectRepository(Invoice)
        private readonly invoiceRepo: Repository<Invoice>,
        @InjectRepository(PaymentMethod)
        private readonly paymentMethodRepo: Repository<PaymentMethod>,
      ) {}

      onModuleInit() {
        const apiKey = this.configService.get<string>('STRIPE_SECRET_KEY');
        if (!apiKey) {
          this.logger.warn('STRIPE_SECRET_KEY not configured - Stripe integration disabled');
          return;
        }

        this.stripe = new Stripe(apiKey, {
          apiVersion: '2025-02-24.acacia',
          typescript: true,
        });
        this.logger.log('Stripe client initialized');
      }

      private ensureStripeConfigured(): void {
        if (!this.stripe) {
          throw new BadRequestException('Stripe is not configured');
        }
      }

      // ==================== Customer Management ====================

      async createCustomer(dto: CreateStripeCustomerDto): Promise<Stripe.Customer> {
        this.ensureStripeConfigured();

        const customer = await this.stripe.customers.create({
          email: dto.email,
          name: dto.name,
          metadata: {
            tenant_id: dto.tenant_id,
            ...dto.metadata,
          },
        });

        this.logger.log(`Created Stripe customer ${customer.id} for tenant ${dto.tenant_id}`);
        return customer;
      }

      async getCustomer(customerId: string): Promise<Stripe.Customer | null> {
        this.ensureStripeConfigured();

        try {
          const customer = await this.stripe.customers.retrieve(customerId);
          return customer as Stripe.Customer;
        } catch (error) {
          if (error.code === 'resource_missing') {
            return null;
          }
          throw error;
        }
      }

      async findCustomerByTenantId(tenantId: string): Promise<Stripe.Customer | null> {
        this.ensureStripeConfigured();

        const customers = await this.stripe.customers.search({
          query: `metadata['tenant_id']:'${tenantId}'`,
        });

        return customers.data[0] || null;
      }

      async updateCustomer(
        customerId: string,
        data: Partial<{ email: string; name: string; metadata: Record<string, string> }>,
      ): Promise<Stripe.Customer> {
        this.ensureStripeConfigured();

        return this.stripe.customers.update(customerId, data);
      }

      // ==================== Subscription Management ====================

      async createSubscription(dto: CreateStripeSubscriptionDto): Promise<Stripe.Subscription> {
        this.ensureStripeConfigured();

        const subscriptionData: Stripe.SubscriptionCreateParams = {
          customer: dto.customer_id,
          items: [{ price: dto.price_id }],
          payment_behavior: 'default_incomplete',
          payment_settings: {
            save_default_payment_method: 'on_subscription',
          },
          expand: ['latest_invoice.payment_intent'],
          metadata: dto.metadata,
        };

        if (dto.trial_period_days) {
          subscriptionData.trial_period_days = dto.trial_period_days;
        }

        const subscription = await this.stripe.subscriptions.create(subscriptionData);

        this.logger.log(`Created Stripe subscription ${subscription.id}`);
        return subscription;
      }

      async getStripeSubscription(subscriptionId: string): Promise<Stripe.Subscription | null> {
        this.ensureStripeConfigured();

        try {
          return await this.stripe.subscriptions.retrieve(subscriptionId);
        } catch (error) {
          if (error.code === 'resource_missing') {
            return null;
          }
          throw error;
        }
      }

      async cancelStripeSubscription(
        subscriptionId: string,
        options?: { immediately?: boolean },
      ): Promise<Stripe.Subscription> {
        this.ensureStripeConfigured();

        if (options?.immediately) {
          return this.stripe.subscriptions.cancel(subscriptionId);
        }

        return this.stripe.subscriptions.update(subscriptionId, {
          cancel_at_period_end: true,
        });
      }

      async updateStripeSubscription(
        subscriptionId: string,
        priceId: string,
      ): Promise<Stripe.Subscription> {
        this.ensureStripeConfigured();

        const subscription = await this.stripe.subscriptions.retrieve(subscriptionId);

        return this.stripe.subscriptions.update(subscriptionId, {
          items: [
            {
              id: subscription.items.data[0].id,
              price: priceId,
            },
          ],
          proration_behavior: 'create_prorations',
        });
      }

      // ==================== Checkout & Portal ====================

      async createCheckoutSession(dto: CreateCheckoutSessionDto): Promise<Stripe.Checkout.Session> {
        this.ensureStripeConfigured();

        let customer = await this.findCustomerByTenantId(dto.tenant_id);

        if (!customer) {
          throw new NotFoundException('Stripe customer not found for tenant');
        }

        const sessionParams: Stripe.Checkout.SessionCreateParams = {
          customer: customer.id,
          mode: 'subscription',
          line_items: [
            {
              price: dto.price_id,
              quantity: 1,
            },
          ],
          success_url: dto.success_url,
          cancel_url: dto.cancel_url,
          subscription_data: {
            metadata: {
              tenant_id: dto.tenant_id,
            },
            ...(dto.trial_period_days && { trial_period_days: dto.trial_period_days }),
          },
        };

        const session = await this.stripe.checkout.sessions.create(sessionParams);

        this.logger.log(`Created checkout session ${session.id} for tenant ${dto.tenant_id}`);
        return session;
      }

      async createBillingPortalSession(dto: CreateBillingPortalSessionDto): Promise<Stripe.BillingPortal.Session> {
        this.ensureStripeConfigured();

        const customer = await this.findCustomerByTenantId(dto.tenant_id);

        if (!customer) {
          throw new NotFoundException('Stripe customer not found for tenant');
        }

        const session = await this.stripe.billingPortal.sessions.create({
          customer: customer.id,
          return_url: dto.return_url,
        });

        this.logger.log(`Created billing portal session for tenant ${dto.tenant_id}`);
        return session;
      }

      // ==================== Payment Methods ====================

      async attachPaymentMethod(
        paymentMethodId: string,
        customerId: string,
      ): Promise<Stripe.PaymentMethod> {
        this.ensureStripeConfigured();

        return this.stripe.paymentMethods.attach(paymentMethodId, {
          customer: customerId,
        });
      }

      async detachPaymentMethod(paymentMethodId: string): Promise<Stripe.PaymentMethod> {
        this.ensureStripeConfigured();

        return this.stripe.paymentMethods.detach(paymentMethodId);
      }

      async listPaymentMethods(customerId: string): Promise<Stripe.PaymentMethod[]> {
        this.ensureStripeConfigured();

        const paymentMethods = await this.stripe.paymentMethods.list({
          customer: customerId,
          type: 'card',
        });

        return paymentMethods.data;
      }

      async setDefaultPaymentMethod(
        customerId: string,
        paymentMethodId: string,
      ): Promise<Stripe.Customer> {
        this.ensureStripeConfigured();

        return this.stripe.customers.update(customerId, {
          invoice_settings: {
            default_payment_method: paymentMethodId,
          },
        });
      }

      // ==================== Webhook Handling ====================

      constructWebhookEvent(payload: Buffer, signature: string): Stripe.Event {
        this.ensureStripeConfigured();

        const webhookSecret = this.configService.get<string>('STRIPE_WEBHOOK_SECRET');
        if (!webhookSecret) {
          throw new BadRequestException('Webhook secret not configured');
        }

        return this.stripe.webhooks.constructEvent(payload, signature, webhookSecret);
      }

      async handleWebhookEvent(event: Stripe.Event): Promise<void> {
        this.logger.log(`Processing webhook event: ${event.type}`);

        switch (event.type) {
          case StripeWebhookEventType.SUBSCRIPTION_CREATED:
          case StripeWebhookEventType.SUBSCRIPTION_UPDATED:
            await this.syncSubscription(event.data.object as Stripe.Subscription);
            break;

          case StripeWebhookEventType.SUBSCRIPTION_DELETED:
            await this.handleSubscriptionDeleted(event.data.object as Stripe.Subscription);
            break;

          case StripeWebhookEventType.INVOICE_PAID:
            await this.handleInvoicePaid(event.data.object as Stripe.Invoice);
            break;

          case StripeWebhookEventType.INVOICE_PAYMENT_FAILED:
            await this.handleInvoicePaymentFailed(event.data.object as Stripe.Invoice);
            break;

          case StripeWebhookEventType.PAYMENT_METHOD_ATTACHED:
            await this.syncPaymentMethod(event.data.object as Stripe.PaymentMethod);
            break;

          case StripeWebhookEventType.PAYMENT_METHOD_DETACHED:
            await this.handlePaymentMethodDetached(event.data.object as Stripe.PaymentMethod);
            break;

          case StripeWebhookEventType.CHECKOUT_SESSION_COMPLETED:
            await this.handleCheckoutCompleted(event.data.object as Stripe.Checkout.Session);
            break;

          default:
            this.logger.log(`Unhandled event type: ${event.type}`);
        }
      }

      // ==================== Sync Methods ====================

      private async syncSubscription(stripeSubscription: Stripe.Subscription): Promise<void> {
        const tenantId = stripeSubscription.metadata?.tenant_id;
        if (!tenantId) {
          this.logger.warn(`Subscription ${stripeSubscription.id} has no tenant_id metadata`);
          return;
        }

        let subscription = await this.subscriptionRepo.findOne({
          where: { external_subscription_id: stripeSubscription.id },
        });

        const status = this.mapStripeStatus(stripeSubscription.status);

        if (!subscription) {
          subscription = this.subscriptionRepo.create({
            tenant_id: tenantId,
            plan_id: stripeSubscription.items.data[0]?.price?.product as string,
            external_subscription_id: stripeSubscription.id,
            payment_provider: 'stripe',
          });
        }

        subscription.status = status;
        subscription.current_period_start = new Date(stripeSubscription.current_period_start * 1000);
        subscription.current_period_end = new Date(stripeSubscription.current_period_end * 1000);

        if (stripeSubscription.trial_end) {
          subscription.trial_end = new Date(stripeSubscription.trial_end * 1000);
        }

        Iif (stripeSubscription.canceled_at) {
          subscription.cancelled_at = new Date(stripeSubscription.canceled_at * 1000);
        }

        subscription.metadata = {
          ...subscription.metadata,
          stripe_customer_id: stripeSubscription.customer as string,
          stripe_price_id: stripeSubscription.items.data[0]?.price?.id,
        };

        await this.subscriptionRepo.save(subscription);
        this.logger.log(`Synced subscription ${stripeSubscription.id} for tenant ${tenantId}`);
      }

      private async handleSubscriptionDeleted(stripeSubscription: Stripe.Subscription): Promise<void> {
        const subscription = await this.subscriptionRepo.findOne({
          where: { external_subscription_id: stripeSubscription.id },
        });

        if (subscription) {
          subscription.status = SubscriptionStatus.CANCELLED;
          subscription.cancelled_at = new Date();
          await this.subscriptionRepo.save(subscription);
          this.logger.log(`Cancelled subscription ${stripeSubscription.id}`);
        }
      }

      private async handleInvoicePaid(stripeInvoice: Stripe.Invoice): Promise<void> {
        const tenantId = stripeInvoice.subscription_details?.metadata?.tenant_id ||
                         stripeInvoice.metadata?.tenant_id;

        if (!tenantId) {
          this.logger.warn(`Invoice ${stripeInvoice.id} has no tenant_id`);
          return;
        }

        let invoice = await this.invoiceRepo.findOne({
          where: {
            tenant_id: tenantId,
            invoice_number: stripeInvoice.number || stripeInvoice.id,
          },
        });

        if (!invoice) {
          invoice = this.invoiceRepo.create({
            tenant_id: tenantId,
            subscription_id: stripeInvoice.subscription as string,
            invoice_number: stripeInvoice.number || stripeInvoice.id,
            subtotal: stripeInvoice.subtotal / 100,
            tax: stripeInvoice.tax ? stripeInvoice.tax / 100 : 0,
            total: stripeInvoice.total / 100,
            due_date: stripeInvoice.due_date
              ? new Date(stripeInvoice.due_date * 1000)
              : new Date(),
          });
        }

        invoice.status = InvoiceStatus.PAID;
        invoice.paid_at = new Date();
        invoice.external_invoice_id = stripeInvoice.id;
        invoice.pdf_url = stripeInvoice.invoice_pdf || stripeInvoice.hosted_invoice_url || null;

        await this.invoiceRepo.save(invoice);
        this.logger.log(`Recorded paid invoice ${stripeInvoice.id} for tenant ${tenantId}`);
      }

      private async handleInvoicePaymentFailed(stripeInvoice: Stripe.Invoice): Promise<void> {
        const tenantId = stripeInvoice.subscription_details?.metadata?.tenant_id;

        if (!tenantId) {
          return;
        }

        const subscription = await this.subscriptionRepo.findOne({
          where: { tenant_id: tenantId },
          order: { created_at: 'DESC' },
        });

        if (subscription) {
          subscription.status = SubscriptionStatus.PAST_DUE;
          subscription.metadata = {
            ...subscription.metadata,
            payment_failed_at: new Date().toISOString(),
            failed_invoice_id: stripeInvoice.id,
          };
          await this.subscriptionRepo.save(subscription);
          this.logger.log(`Marked subscription as past_due for tenant ${tenantId}`);
        }
      }

      private async syncPaymentMethod(stripePaymentMethod: Stripe.PaymentMethod): Promise<void> {
        const customerId = stripePaymentMethod.customer as string;
        if (!customerId) return;

        const customer = await this.getCustomer(customerId);
        const tenantId = customer?.metadata?.tenant_id;

        Iif (!tenantId) return;

        let paymentMethod = await this.paymentMethodRepo.findOne({
          where: { external_payment_method_id: stripePaymentMethod.id },
        });

        if (!paymentMethod) {
          paymentMethod = this.paymentMethodRepo.create({
            tenant_id: tenantId,
            external_payment_method_id: stripePaymentMethod.id,
          });
        }

        const card = stripePaymentMethod.card;
        if (card) {
          paymentMethod.type = 'card' as any;
          paymentMethod.card_brand = card.brand;
          paymentMethod.card_last_four = card.last4;
          paymentMethod.card_exp_month = card.exp_month;
          paymentMethod.card_exp_year = card.exp_year;
        }
        paymentMethod.payment_provider = 'stripe';

        paymentMethod.is_active = true;

        await this.paymentMethodRepo.save(paymentMethod);
        this.logger.log(`Synced payment method ${stripePaymentMethod.id} for tenant ${tenantId}`);
      }

      private async handlePaymentMethodDetached(stripePaymentMethod: Stripe.PaymentMethod): Promise<void> {
        const paymentMethod = await this.paymentMethodRepo.findOne({
          where: { external_payment_method_id: stripePaymentMethod.id },
        });

        if (paymentMethod) {
          paymentMethod.is_active = false;
          await this.paymentMethodRepo.save(paymentMethod);
          this.logger.log(`Deactivated payment method ${stripePaymentMethod.id}`);
        }
      }

      private async handleCheckoutCompleted(session: Stripe.Checkout.Session): Promise<void> {
        const tenantId = session.metadata?.tenant_id ||
                         (session as any).subscription_data?.metadata?.tenant_id;

        if (!tenantId || !session.subscription) {
          return;
        }

        const stripeSubscription = await this.getStripeSubscription(session.subscription as string);
        if (stripeSubscription) {
          await this.syncSubscription(stripeSubscription);
        }

        this.logger.log(`Processed checkout completion for tenant ${tenantId}`);
      }

      // ==================== Utility Methods ====================

      private mapStripeStatus(stripeStatus: Stripe.Subscription.Status): SubscriptionStatus {
        const statusMap: Record<Stripe.Subscription.Status, SubscriptionStatus> = {
          trialing: SubscriptionStatus.TRIAL,
          active: SubscriptionStatus.ACTIVE,
          past_due: SubscriptionStatus.PAST_DUE,
          canceled: SubscriptionStatus.CANCELLED,
          unpaid: SubscriptionStatus.PAST_DUE,
          incomplete: SubscriptionStatus.TRIAL,
          incomplete_expired: SubscriptionStatus.EXPIRED,
          paused: SubscriptionStatus.CANCELLED,
        };

        return statusMap[stripeStatus] || SubscriptionStatus.ACTIVE;
      }

      // ==================== Price & Product Management ====================

      async listPrices(productId?: string): Promise<Stripe.Price[]> {
        this.ensureStripeConfigured();

        const params: Stripe.PriceListParams = {
          active: true,
          expand: ['data.product'],
        };

        if (productId) {
          params.product = productId;
        }

        const prices = await this.stripe.prices.list(params);
        return prices.data;
      }

      async getPrice(priceId: string): Promise<Stripe.Price | null> {
        this.ensureStripeConfigured();

        try {
          return await this.stripe.prices.retrieve(priceId, {
            expand: ['product'],
          });
        } catch (error) {
          if (error.code === 'resource_missing') {
            return null;
          }
          throw error;
        }
      }

      // ==================== Setup Intent (for adding cards without charging) ====================

      async createSetupIntent(customerId: string): Promise<Stripe.SetupIntent> {
        this.ensureStripeConfigured();

        return this.stripe.setupIntents.create({
          customer: customerId,
          payment_method_types: ['card'],
        });
      }
    }