All files / libs/payout-calculation/statements/core/src/modules/payments statementPayments.service.ts

93.57% Statements 262/280
71.42% Branches 15/21
100% Functions 8/8
93.57% Lines 262/280

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 2811x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x           3x 1x 1x 1x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 3x 1x 1x 1x 1x 1x 1x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
import { InjectRepository } from '@nestjs/typeorm';
import { DataSource, Repository, type SelectQueryBuilder } from 'typeorm';
 
import { Payment, type Statement } from '@amalia/core/models';
import { PaymentAmountsByCategory, PaymentCategory, PaymentType, type PaymentContract } from '@amalia/core/types';
import { assert } from '@amalia/ext/typescript';
import { formatPaymentResponse, PaymentsService } from '@amalia/payout-calculation/payments/core';
import { RuleType } from '@amalia/payout-definition/plans/types';
 
export class StatementPaymentsService {
  public constructor(
    private readonly connection: DataSource,
    @InjectRepository(Payment)
    private readonly paymentRepository: Repository<Payment>,
    private readonly paymentsService: PaymentsService,
  ) {}
 
  /**
   * Compute all three amounts for statement
   * @param companyId
   * @param statement
   * @returns
   */
  public async computeSumForStatement(companyId: string, statement: Statement): Promise<PaymentAmountsByCategory> {
    assert(statement.plan, 'Relation plan is missing on statement');
    assert(statement.period, 'Relation period is missing on statement');
    assert(statement.user, 'Relation user is missing on statement');
 
    const achievement = await this.connection
      .createQueryBuilder(Payment, 'achievement_payment')
      .select('SUM(achievement_payment.value)', 'sum')
      .leftJoin('plan', 'plan', 'plan."id" = achievement_payment."planId"')
      .where('achievement_payment.companyId = :companyId', { companyId })
      .andWhere('achievement_payment.statementId = :statementId', { statementId: statement.id })
      .andWhere('plan."isHidden" = :plan_is_hidden', {
        plan_is_hidden: statement.plan.isHidden,
      })
      .getRawOne<{ sum: number | null }>();
 
    const hold = await this.connection
      .createQueryBuilder(Payment, 'hold_payment')
      .select('SUM(hold_payment.value)', 'sum')
      .leftJoin('period', 'hold_period', 'hold_payment."periodId" = hold_period."id"')
      .leftJoin('period', 'hold_payment_period', 'hold_payment."paymentPeriodId" = hold_payment_period."id"')
      .leftJoin('plan', 'plan', 'plan."id" = hold_payment."planId"')
      .where('hold_payment."companyId" = :companyId', { companyId })
      // Has been earned in the past.
      .andWhere('hold_period."startDate" <= :startDate', { startDate: statement.period.startDate })
      .andWhere('hold_payment."userId" = :userId', { userId: statement.user.id })
      // Is not released, or is released in a future period.
      .andWhere('(hold_payment."paymentPeriodId" IS NULL OR hold_payment_period."startDate" > :endDate)', {
        endDate: statement.period.endDate,
      })
      .andWhere('plan."isHidden" = :plan_is_hidden', {
        plan_is_hidden: statement.plan.isHidden,
      })
      .getRawOne<{ sum: number | null }>();
 
    const paid = await this.connection
      .createQueryBuilder(Payment, 'paid_payment')
      .select('SUM(paid_payment.value)', 'sum')
      .leftJoin('period', 'paid_payment_period', 'paid_payment."paymentPeriodId" = paid_payment_period."id"')
      .leftJoin('plan', 'plan', 'plan."id" = paid_payment."planId"')
      .where('paid_payment."companyId" = :companyId', { companyId })
      .andWhere('paid_payment_period."startDate" >= :startDate', { startDate: statement.period.startDate })
      .andWhere('paid_payment_period."endDate" <= :endDate', { endDate: statement.period.endDate })
      .andWhere('paid_payment."userId" = :userId', { userId: statement.user.id })
      .andWhere('plan."isHidden" = :plan_is_hidden', {
        plan_is_hidden: statement.plan.isHidden,
      })
      .getRawOne<{ sum: number | null }>();
 
    const adjustments = await this.connection
      .createQueryBuilder(Payment, 'adjusment_payment')
      .select('SUM(adjusment_payment.value)', 'sum')
      .where('adjusment_payment."companyId" = :companyId', { companyId })
      .andWhere('adjusment_payment."statementId" = :statementId', { statementId: statement.id })
      .andWhere('adjusment_payment.type = :type', { type: PaymentType.ADJUSTMENT })
      .getRawOne<{ sum: number | null }>();
 
    return {
      achievement: achievement?.sum ?? null,
      hold: hold?.sum ?? null,
      paid: paid?.sum ?? null,
      adjustments: adjustments?.sum ?? null,
    };
  }
 
  public async findAllPaymentsForStatementAndCategory(
    companyId: string,
    statement: Statement,
    category: PaymentCategory = PaymentCategory.achievement,
  ): Promise<PaymentContract[]> {
    // If achivement, nothing to return
    if (category === 'achievement') {
      return [];
    }
 
    const queryBuilder = this.paymentRepository.createQueryBuilder('payment');
    // Join useful data
    queryBuilder.leftJoinAndSelect('payment.period', 'period');
    queryBuilder.leftJoinAndSelect('payment.paymentPeriod', 'paymentPeriod');
    queryBuilder.leftJoinAndSelect('payment.user', 'user');
    queryBuilder.leftJoinAndSelect('payment.adjustment', 'adjustment');
    queryBuilder.leftJoinAndSelect('adjustment.rowDefinition', 'rowDefinition');
 
    // Join data to gather
    queryBuilder.leftJoinAndSelect('payment.statement', 'statement');
    queryBuilder.leftJoinAndSelect('statement.period', 'statementPeriod');
    queryBuilder.leftJoinAndSelect('statement.plan', 'plan');
    queryBuilder.leftJoinAndSelect('payment.rule', 'rule');
    queryBuilder.leftJoinAndSelect('rule.commissionVariable', 'variable');
 
    // Custom object definition => permits to natch dealExternalId according to a definition
    queryBuilder.leftJoinAndSelect('rule.filter', 'filter');
    queryBuilder.leftJoinAndSelect('filter.object', 'object');
 
    queryBuilder.where('payment.company = :companyId', { companyId });
 
    // Filter payments for the requested type
    this.addConditionForPaymentCategory(queryBuilder, statement, category);
 
    queryBuilder.select([
      'payment',
      'user',
      'adjustment',
      'rowDefinition',
      'payment.period',
      'payment.paymentPeriod',
      'payment.statement',
      'statement.plan',
      'statement.period',
      'payment.rule',
      // periods
      'period',
      'paymentPeriod',
      'statementPeriod',
      // statement attributes
      'statement.id',
      // rule and plan
      'rule.name',
      'plan.name',
      'plan.isHidden',
      'rule.commissionVariable',
      // Variable name
      'variable.name',
      'variable.objectId',
      // Custom object definition id of the rule's filter
      'rule.filter',
      'filter.object',
      'object.id',
      'object.name',
    ]);
 
    assert(statement.plan, 'Relation plan missing on statement');
 
    // Payments visibility should be the same as current plan.
    queryBuilder.andWhere('plan.isHidden = :plan_is_hidden', { plan_is_hidden: statement.plan.isHidden });
 
    const payments = await queryBuilder.getMany();
    return this.paymentsService.formatPayments(companyId, payments);
  }
 
  /**
   * Compute all payments for a given statement
   *
   * @param companyId
   * @param statement
   * @returns
   */
  public async findAllForStatement(
    companyId: string,
    statement: Statement,
  ): Promise<Record<PaymentCategory, Partial<PaymentContract>[]>> {
    const paymentByCategoryArray = await Promise.all(
      Object.values(PaymentCategory).map((cat: PaymentCategory) =>
        this.findAllPaymentsForStatementAndCategory(companyId, statement, cat),
      ),
    );
 
    return Object.keys(PaymentCategory).reduce<Record<PaymentCategory, Partial<PaymentContract>[]>>(
      (acc, item, index) => ({
        ...acc,
        [item as PaymentCategory]: paymentByCategoryArray[index],
      }),
      {} as Record<PaymentCategory, Partial<PaymentContract>[]>,
    );
  }
 
  /**
   * Get all payments related to deals shown in the statement
   * @param companyId
   * @param statement
   */
  public async findStatementHoldAndReleasePayments(
    companyId: string,
    statement: Statement,
  ): Promise<PaymentContract[]> {
    // If statement has no HnR rules, return empty array
    if (!statement.results.definitions.plan.rules.some((r) => r.type === RuleType.HOLD_AND_RELEASE)) {
      return [];
    }

    // Return all payments that are linked to the statement and that are in hold and release mode.
    const payments = await this.paymentRepository.find({
      where: {
        company: { id: companyId },
        statementId: statement.id,
        type: PaymentType.LINE_HOLD,
      },
      relations: ['paymentPeriod'],
    });

    return payments.map((p) => formatPaymentResponse(p));
  }
 
  /**
   * Add condition to filter payments according to the requested category
   * /!\ payment.period and payment.paymentPeriod MUST be already loaded
   * @param queryBuilder
   * @param statement
   * @param category
   */
  private addConditionForPaymentCategory(
    queryBuilder: SelectQueryBuilder<Payment>,
    statement: Statement,
    category: PaymentCategory = PaymentCategory.achievement,
  ): void {
    assert(statement.period, 'Relation period missing on statement');
    assert(statement.user, 'Relation user missing on statement');
 
    // Filter according to requested amount category
    switch (category) {
      case PaymentCategory.achievement:
        // Payments that are generated from this statement
        queryBuilder.andWhere('payment.statementId = :statementId', {
          statementId: statement.id,
        });
        break;
      case PaymentCategory.adjustments:
        // Payments that are generated from this statement, but only linked to adjustments
        queryBuilder.andWhere('payment.statementId = :statementId', {
          statementId: statement.id,
        });
        queryBuilder.andWhere('payment.type = :adjustments', {
          adjustments: PaymentType.ADJUSTMENT,
        });
        break;
      case PaymentCategory.hold:
        this.addHoldCondition(queryBuilder, statement.period.startDate, statement.period.endDate);
        queryBuilder.andWhere('payment.userId = :userId', {
          userId: statement.user.id,
        });
        break;
      case PaymentCategory.paid:
        // Payments that are paid on this statement
        this.addPaidCondition(queryBuilder, statement.period.startDate, statement.period.endDate);
        queryBuilder.andWhere('payment.userId = :userId', {
          userId: statement.user.id,
        });
        break;
    }
  }
 
  private addPaidCondition(queryBuilder: SelectQueryBuilder<Payment>, periodStartDate: number, periodEndDate: number) {
    queryBuilder.andWhere(
      // Payments that are paid within the period.
      'paymentPeriod.startDate >= :periodStartDate AND paymentPeriod.endDate <= :periodEndDate',
      { periodStartDate, periodEndDate },
    );
  }
 
  private addHoldCondition(queryBuilder: SelectQueryBuilder<Payment>, periodStartDate: number, periodEndDate: number) {
    queryBuilder.andWhere(
      // Payments that were generated before, and that are not already paid or that are paid in future statements
      'period.startDate <= :periodStartDate AND (payment.paymentPeriodId IS NULL OR paymentPeriod.startDate > :periodEndDate)',
      { periodStartDate, periodEndDate },
    );
  }
}