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

100% Statements 114/114
100% Branches 21/21
100% Functions 23/23
100% Lines 110/110

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
    3563x
    3x
    3x
    3x

    3x
    3x

    3x

    78x

    78x

    78x

    5x
    5x
    5x

    5x

    5x

    32x

    2x
    2x
    1x

    1x
    1x

    6x
    6x
    1x

    5x

    5x
    2x

    5x
    2x

    5x

    5x
    5x
    1x

    4x
    4x

    4x

    5x
    5x
    1x

    4x
    4x
    4x

    4x
    4x
    4x

    4x

    7x

    8x

    8x
    7x
    7x

    7x
    7x

    7x

    7x

    5x
    5x

    5x

    5x

    10x

    10x
    1x

    9x

    3x
    3x
    3x
    3x

    5x

    5x
    1x

    4x
    4x

    7x
    7x

    7x
    7x

    7x

    4x
    2x

    4x

    4x

    4x

    6x

    4x

    4x
    1x

    3x

    3x
    3x

    5x

    5x
    1x

    4x
    2x

    2x
    2x

    4x
    4x

    4x

    4x
    6x

    4x

    8x

    8x
    1x

    7x
    7x
    7x

    7x

    7x

     import { Injectable, NotFoundException, BadRequestException } from '@nestjs/common';
    import { InjectRepository } from '@nestjs/typeorm';
    import { Repository, LessThan } from 'typeorm';
    import {
      Subscription,
      SubscriptionStatus,
    } from '../entities/subscription.entity';
    import { Invoice, InvoiceStatus } from '../entities/invoice.entity';
    import { PaymentMethod } from '../entities/payment-method.entity';
    import { CreateSubscriptionDto } from '../dto/create-subscription.dto';
    import {
      UpdateSubscriptionDto,
      CancelSubscriptionDto,
    } from '../dto/update-subscription.dto';
    import { CreatePaymentMethodDto } from '../dto/create-payment-method.dto';

    @Injectable()
    export class BillingService {
      constructor(
        @InjectRepository(Subscription)
        private readonly subscriptionRepo: Repository<Subscription>,
        @InjectRepository(Invoice)
        private readonly invoiceRepo: Repository<Invoice>,
        @InjectRepository(PaymentMethod)
        private readonly paymentMethodRepo: Repository<PaymentMethod>,
      ) {}

      // ==================== Subscriptions ====================

      async createSubscription(dto: CreateSubscriptionDto): Promise<Subscription> {
        const now = new Date();
        const periodEnd = new Date(now);
        periodEnd.setMonth(periodEnd.getMonth() + 1);

        const subscription = this.subscriptionRepo.create({
          tenant_id: dto.tenant_id,
          plan_id: dto.plan_id,
          status: dto.trial_end ? SubscriptionStatus.TRIAL : SubscriptionStatus.ACTIVE,
          current_period_start: now,
          current_period_end: periodEnd,
          trial_end: dto.trial_end ? new Date(dto.trial_end) : null,
          payment_provider: dto.payment_provider,
        });

        return this.subscriptionRepo.save(subscription);
      }

      async getSubscription(tenantId: string): Promise<Subscription | null> {
        return this.subscriptionRepo.findOne({
          where: { tenant_id: tenantId },
          order: { created_at: 'DESC' },
        });
      }

      async updateSubscription(
        tenantId: string,
        dto: UpdateSubscriptionDto,
      ): Promise<Subscription> {
        const subscription = await this.getSubscription(tenantId);
        if (!subscription) {
          throw new NotFoundException('Subscription not found');
        }

        Object.assign(subscription, dto);
        return this.subscriptionRepo.save(subscription);
      }

      async cancelSubscription(
        tenantId: string,
        dto: CancelSubscriptionDto,
      ): Promise<Subscription> {
        const subscription = await this.getSubscription(tenantId);
        if (!subscription) {
          throw new NotFoundException('Subscription not found');
        }

        subscription.cancelled_at = new Date();

        if (dto.immediately) {
          subscription.status = SubscriptionStatus.CANCELLED;
        }

        if (dto.reason) {
          subscription.metadata = {
            ...subscription.metadata,
            cancellation_reason: dto.reason,
          };
        }

        return this.subscriptionRepo.save(subscription);
      }

      async changePlan(tenantId: string, newPlanId: string): Promise<Subscription> {
        const subscription = await this.getSubscription(tenantId);
        if (!subscription) {
          throw new NotFoundException('Subscription not found');
        }

        subscription.plan_id = newPlanId;
        subscription.metadata = {
          ...subscription.metadata,
          plan_changed_at: new Date().toISOString(),
        };

        return this.subscriptionRepo.save(subscription);
      }

      async renewSubscription(tenantId: string): Promise<Subscription> {
        const subscription = await this.getSubscription(tenantId);
        if (!subscription) {
          throw new NotFoundException('Subscription not found');
        }

        const now = new Date();
        const newPeriodEnd = new Date(subscription.current_period_end);
        newPeriodEnd.setMonth(newPeriodEnd.getMonth() + 1);

        subscription.current_period_start = subscription.current_period_end;
        subscription.current_period_end = newPeriodEnd;
        subscription.status = SubscriptionStatus.ACTIVE;

        return this.subscriptionRepo.save(subscription);
      }

      // ==================== Invoices ====================

      async createInvoice(
        tenantId: string,
        subscriptionId: string,
        lineItems: Array<{
          description: string;
          quantity: number;
          unit_price: number;
        }>,
      ): Promise<Invoice> {
        const invoiceNumber = await this.generateInvoiceNumber();

        const items = lineItems.map((item) => ({
          ...item,
          amount: item.quantity * item.unit_price,
        }));

        const subtotal = items.reduce((sum, item) => sum + item.amount, 0);
        const tax = subtotal * 0.16; // 16% IVA
        const total = subtotal + tax;

        const dueDate = new Date();
        dueDate.setDate(dueDate.getDate() + 15);

        const invoice = this.invoiceRepo.create({
          tenant_id: tenantId,
          subscription_id: subscriptionId,
          invoice_number: invoiceNumber,
          status: InvoiceStatus.OPEN,
          subtotal,
          tax,
          total,
          due_date: dueDate,
          line_items: items,
        });

        return this.invoiceRepo.save(invoice);
      }

      async getInvoices(
        tenantId: string,
        options?: { page?: number; limit?: number },
      ): Promise<{ data: Invoice[]; total: number; page: number; limit: number }> {
        const page = options?.page || 1;
        const limit = options?.limit || 10;

        const [data, total] = await this.invoiceRepo.findAndCount({
          where: { tenant_id: tenantId },
          order: { created_at: 'DESC' },
          skip: (page - 1) * limit,
          take: limit,
        });

        return { data, total, page, limit };
      }

      async getInvoice(invoiceId: string, tenantId: string): Promise<Invoice> {
        const invoice = await this.invoiceRepo.findOne({
          where: { id: invoiceId, tenant_id: tenantId },
        });

        if (!invoice) {
          throw new NotFoundException('Invoice not found');
        }

        return invoice;
      }

      async markInvoicePaid(invoiceId: string, tenantId: string): Promise<Invoice> {
        const invoice = await this.getInvoice(invoiceId, tenantId);
        invoice.status = InvoiceStatus.PAID;
        invoice.paid_at = new Date();
        return this.invoiceRepo.save(invoice);
      }

      async voidInvoice(invoiceId: string, tenantId: string): Promise<Invoice> {
        const invoice = await this.getInvoice(invoiceId, tenantId);

        if (invoice.status === InvoiceStatus.PAID) {
          throw new BadRequestException('Cannot void a paid invoice');
        }

        invoice.status = InvoiceStatus.VOID;
        return this.invoiceRepo.save(invoice);
      }

      private async generateInvoiceNumber(): Promise<string> {
        const year = new Date().getFullYear();
        const month = String(new Date().getMonth() + 1).padStart(2, '0');

        const count = await this.invoiceRepo.count();
        const sequence = String(count + 1).padStart(6, '0');

        return `INV-${year}${month}-${sequence}`;
      }

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

      async addPaymentMethod(
        tenantId: string,
        dto: CreatePaymentMethodDto,
      ): Promise<PaymentMethod> {
        // If this is set as default, unset other defaults
        if (dto.is_default) {
          await this.paymentMethodRepo.update(
            { tenant_id: tenantId, is_default: true },
            { is_default: false },
          );
        }

        const paymentMethod = this.paymentMethodRepo.create({
          tenant_id: tenantId,
          ...dto,
        });

        return this.paymentMethodRepo.save(paymentMethod);
      }

      async getPaymentMethods(tenantId: string): Promise<PaymentMethod[]> {
        return this.paymentMethodRepo.find({
          where: { tenant_id: tenantId, is_active: true },
          order: { is_default: 'DESC', created_at: 'DESC' },
        });
      }

      async getDefaultPaymentMethod(tenantId: string): Promise<PaymentMethod | null> {
        return this.paymentMethodRepo.findOne({
          where: { tenant_id: tenantId, is_default: true, is_active: true },
        });
      }

      async setDefaultPaymentMethod(
        paymentMethodId: string,
        tenantId: string,
      ): Promise<PaymentMethod> {
        const paymentMethod = await this.paymentMethodRepo.findOne({
          where: { id: paymentMethodId, tenant_id: tenantId },
        });

        if (!paymentMethod) {
          throw new NotFoundException('Payment method not found');
        }

        // Unset current default
        await this.paymentMethodRepo.update(
          { tenant_id: tenantId, is_default: true },
          { is_default: false },
        );

        paymentMethod.is_default = true;
        return this.paymentMethodRepo.save(paymentMethod);
      }

      async removePaymentMethod(
        paymentMethodId: string,
        tenantId: string,
      ): Promise<void> {
        const paymentMethod = await this.paymentMethodRepo.findOne({
          where: { id: paymentMethodId, tenant_id: tenantId },
        });

        if (!paymentMethod) {
          throw new NotFoundException('Payment method not found');
        }

        if (paymentMethod.is_default) {
          throw new BadRequestException('Cannot remove default payment method');
        }

        paymentMethod.is_active = false;
        await this.paymentMethodRepo.save(paymentMethod);
      }

      // ==================== Usage & Billing Summary ====================

      async getBillingSummary(tenantId: string): Promise<{
        subscription: Subscription | null;
        defaultPaymentMethod: PaymentMethod | null;
        pendingInvoices: number;
        totalDue: number;
      }> {
        const subscription = await this.getSubscription(tenantId);
        const defaultPaymentMethod = await this.getDefaultPaymentMethod(tenantId);

        const pendingInvoices = await this.invoiceRepo.find({
          where: { tenant_id: tenantId, status: InvoiceStatus.OPEN },
        });

        const totalDue = pendingInvoices.reduce(
          (sum, inv) => sum + Number(inv.total),
          0,
        );

        return {
          subscription,
          defaultPaymentMethod,
          pendingInvoices: pendingInvoices.length,
          totalDue,
        };
      }

      async checkSubscriptionStatus(tenantId: string): Promise<{
        isActive: boolean;
        daysRemaining: number;
        status: SubscriptionStatus;
      }> {
        const subscription = await this.getSubscription(tenantId);

        if (!subscription) {
          return { isActive: false, daysRemaining: 0, status: SubscriptionStatus.EXPIRED };
        }

        const now = new Date();
        const periodEnd = new Date(subscription.current_period_end);
        const daysRemaining = Math.ceil(
          (periodEnd.getTime() - now.getTime()) / (1000 * 60 * 60 * 24),
        );

        const isActive = [
          SubscriptionStatus.ACTIVE,
          SubscriptionStatus.TRIAL,
        ].includes(subscription.status);

        return {
          isActive,
          daysRemaining: Math.max(0, daysRemaining),
          status: subscription.status,
        };
      }
    }