All files / libs/payout-calculation/payments/core/src/lib/paymentFinder finderQueryBuilder.ts

100% Statements 40/40
100% Branches 11/11
100% Functions 2/2
100% Lines 40/40

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 411x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 103x 73x 73x 30x 30x 103x 1x 1x 1x 29x 29x 29x 103x 103x 103x 103x 103x 1x  
import { isEmpty } from 'lodash-es';
import { type ObjectLiteral, type SelectQueryBuilder } from 'typeorm';
 
import { EMPTY_OPTION_VALUE } from '@amalia/core/types';
 
export class FinderQueryBuilder<T extends ObjectLiteral> {
  public constructor(public readonly queryBuilder: SelectQueryBuilder<T>) {}
 
  /**
   * Apply an In condition to queryBuilder to filter on values for a given field.
   *
   * If values contains 'None' (emptyOption key), we should also select for null values.
   *
   * Example for "paymentPeriod" field and queryBuilder alias "metric" with given values:
   * - ['None'] => AND "metric"."paymentPeriod" IS NULL
   * - ['None', 'period_id_1', 'period_id_2'] => AND ("metric"."paymentPeriod" IN ('period_id_1', 'period_id_2') OR "metric"."paymentPeriod" IS NULL)
   * - ['period_id_1', 'period_id_2'] => AND "metric"."paymentPeriod" IN ('period_id_1', 'period_id_2')
   *
   * @param field
   * @param fieldValues
   */
  public applyInCondition(field: keyof T, fieldValues?: string[]) {
    if (!fieldValues || isEmpty(fieldValues)) {
      return;
    }
 
    const selectNullValues = fieldValues.includes(EMPTY_OPTION_VALUE);
    if (fieldValues.length === 1 && selectNullValues) {
      this.queryBuilder.andWhere(`"${this.queryBuilder.alias}"."${String(field)}" IS NULL`);
      return;
    }
 
    const inCondition = `"${this.queryBuilder.alias}"."${String(field)}" IN (:...${String(field)})`;
    const condition = selectNullValues
      ? `(${inCondition} OR "${this.queryBuilder.alias}"."${String(field)}" IS NULL)`
      : inCondition;
 
    this.queryBuilder.andWhere(condition, { [field]: fieldValues.filter((value) => value !== EMPTY_OPTION_VALUE) });
  }
}