All files / libs/payout-definition/periods/core/src/lib periods.service.ts

87.46% Statements 286/327
84.37% Branches 27/32
69.23% Functions 9/13
87.46% Lines 286/327

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 3281x 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 2x 2x 2x 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 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 4x 4x 6x 10x 2x 2x 4x 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 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 1x 1x 6x 6x 6x 6x 6x 7x 4x 4x 4x 4x 4x 4x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x       5x 5x               5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 19x 17x 17x 17x 17x 17x 19x 2x 2x 19x 19x 19x 19x 19x 1x  
import {
  HttpException,
  HttpStatus,
  Injectable,
  Logger,
  NotFoundException,
  UnprocessableEntityException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { flatten, pick, uniq } from 'lodash-es';
import { In, LessThanOrEqual, MoreThanOrEqual, Repository } from 'typeorm';
 
import { Period, type Company } from '@amalia/core/models';
import {
  findPeriodRelativeNumbersForRelativeKeyword,
  findRelativePeriodDate,
  formatPeriodName,
  getDateRangeBoundaries,
  isRelativePeriodKeyword,
} from '@amalia/payout-definition/periods/shared';
import { PeriodFrequencyEnum, type RelativePeriodKeyword } from '@amalia/payout-definition/periods/types';
 
/**
 * Service period.
 */
@Injectable()
export class PeriodsService {
  private readonly logger = new Logger(PeriodsService.name);
 
  public constructor(
    @InjectRepository(Period)
    private readonly periodRepository: Repository<Period>,
  ) {}
 
  public async list(company: Company): Promise<Period[]> {
    return this.periodRepository.findBy({ company: { id: company.id } });
  }
 
  public async getById(company: Company, id: string) {
    return this.periodRepository.findOneBy({ company: { id: company.id }, id });
  }
 
  /**
   * Return the period list from an id list
   *
   * @param company
   * @param ids
   * @returns
   */
  public async findMultiple(company: Company, ids: string[]): Promise<Period[]> {
    return this.periodRepository.findBy({
      company: { id: company.id },
      id: In(ids),
    });
  }
 
  /**
   * Find the current period, create it if it doesn't exist.
   *
   * @param company
   * @param currentDate
   * @param createIfNotExist
   * @param frequency
   */
  public async findPeriod(
    company: Company,
    currentDate: Date,
    createIfNotExist: boolean = false,
    frequency?: PeriodFrequencyEnum,
  ): Promise<Period> {
    const periodFrequency = frequency ?? company.statementFrequency;
 
    // You think that we just have to find a period like this: startDate < currentDate < endDate ?
    // WRONG!
    // Because of forPeriods, we cannot assume that there is not a period with a bigger range
    // that we're currently in. So we evaluate the startDate, endDate, and try to find a period like this.
    const { startDate, endDate } = getDateRangeBoundaries(periodFrequency, currentDate);
 
    const period = await this.periodRepository.findOne({
      where: {
        company: { id: company.id },
        startDate: startDate!,
        endDate: endDate!,
        frequency: periodFrequency,
      },
    });
 
    if (period) {
      return period;
    }
 
    if (!createIfNotExist) {
      throw new NotFoundException('Period not found');
    }
 
    return this.createPeriod(company, currentDate, periodFrequency);
  }
 
  /**
   * Find period by id.
   * @id id of the period
   * @throws {NotFoundException}
   */
  public async findOne(company: Company, id: string): Promise<Period> {
    const period = await this.periodRepository.findOneBy({
      company: { id: company.id },
      id,
    });
    if (!period) {
      throw new NotFoundException();
    }
    return period;
  }
 
  /**
   * Find Periods which include date range.
   * @param company
   * @param startDate
   * @param endDate
   */
  public async findPeriodsWhichIncludeDateRange(
    company: Company,
    startDate: number,
    endDate: number,
  ): Promise<Period[]> {
    return this.periodRepository.find({
      where: {
        company: { id: company.id },
        startDate: LessThanOrEqual(startDate),
        endDate: MoreThanOrEqual(endDate),
      },
      order: {
        startDate: 'ASC',
      },
    });
  }
 
  /**
   * Find next or previous period based on referenceDate.
   * @param company
   * @param period
   * @param frequencySelectMode - If PERIOD, will use frequency of reference period, else company.
   * @param diff the diff number, in periods
   * @param createIfNotExist
   */
  public async findNextPeriod(
    company: Company,
    period: Period,
    diff: number,
    {
      createIfNotExist,
      frequencySelectMode,
    }: {
      frequencySelectMode: 'COMPANY' | 'PERIOD';
      createIfNotExist: boolean;
    },
  ): Promise<Period> {
    const frequency = frequencySelectMode === 'PERIOD' ? period.frequency : company.statementFrequency;
 
    const newReferenceDate = findRelativePeriodDate(period, frequency, diff);
 
    // Now fetch the period for this date. We're using the same frequency as the current one.
    return this.findPeriod(company, newReferenceDate, createIfNotExist, frequency);
  }
 
  /**
   * Find periods for a period relative keyword
   * @param company
   * @param fromDate
   * @param keyword
   * @returns
   */
  public async findPeriodsForRelativeKeyword(company: Company, fromDate: Date, keyword: string): Promise<Period[]> {
    const { startDate, endDate } = findPeriodRelativeNumbersForRelativeKeyword(
      company.statementFrequency,
      fromDate,
      keyword,
    );
 
    return this.getPeriodsForDates(company, startDate!, endDate!, true);
  }
 
  /**
   * Interpret an input mixed of period ids and relative keywords.
   * If array contains both ids and keywords, it's the last keyword that is taken into account.
   * If no keyword is present, it will return the corresponding periodIds.
   *
   * @param company
   * @param periods
   * @param referenceDate
   * @returns
   */
  public async interpretPeriodParamsArray(
    company: Company,
    periods?: string[] | null,
    referenceDate?: Date,
  ): Promise<string[] | undefined> {
    if (!periods) {
      return undefined;
    }
 
    const keywordsInThisArray: RelativePeriodKeyword[] = periods.filter((p) =>
      isRelativePeriodKeyword(p),
    ) as RelativePeriodKeyword[];
 
    if (keywordsInThisArray.length) {
      const periods = await Promise.all(
        keywordsInThisArray.map((k) => this.findPeriodsForRelativeKeyword(company, referenceDate ?? new Date(), k)),
      );
 
      return uniq(flatten(periods).map((p) => p.id));
    }
    return uniq(periods);
  }
 
  /**
   * Given a company, creates a period that contains the date passed in parameters.
   *
   * @param company
   * @param date
   * @param frequency
   */
  public async createPeriod(company: Company, date: Date, frequency: PeriodFrequencyEnum): Promise<Period> {
    const name = formatPeriodName(frequency, date);
    const { startDate, endDate } = getDateRangeBoundaries(frequency, date);
 
    await this.isPeriodValid(company, name, startDate!, endDate!, frequency);
 
    const period: Partial<Period> = {
      company,
      name,
      startDate: startDate!,
      endDate: endDate!,
      frequency,
    };
 
    this.logger.log({ message: `Creating period ${name}`, company: pick(company, ['id', 'name']) });
 
    if (period.frequency === PeriodFrequencyEnum.month && company.statementFrequency !== PeriodFrequencyEnum.month) {
      throw new UnprocessableEntityException({
        message: `Creating a monthly period for a company with a ${company.statementFrequency} frequency`,
        company: pick(company, ['id', 'name']),
      });
    }
 
    return this.periodRepository.save(period);
  }
 
  /**
   * Check that there is no conflict with existing periods.
   * @param company company
   * @param name period name
   * @param startDate period start date
   * @param endDate period end date
   * @param frequency
   */
  public async isPeriodValid(
    company: Company,
    name: string,
    startDate: number,
    endDate: number,
    frequency: PeriodFrequencyEnum,
  ) {
    const [periodNameAlreadyExist, periodWithSameDatesAlreadyExist] = await Promise.all([
      this.periodRepository.findOneBy({
        company: { id: company.id },
        name,
        frequency,
      }),
      this.periodRepository.findOneBy({
        company: { id: company.id },
        startDate,
        endDate,
        frequency,
      }),
    ]);
 
    if (periodNameAlreadyExist) {
      this.logger.warn({ message: `Period with name ${name} already exists`, company: pick(company, ['id', 'name']) });
      throw new HttpException('Period with the same name already exist', HttpStatus.CONFLICT);
    }
 
    if (periodWithSameDatesAlreadyExist) {
      this.logger.warn({
        message: 'Period with same dates already exists',
        company: pick(company, ['id', 'name']),
        periodWithSameDatesAlreadyExist,
      });
      throw new HttpException('period with the same dates already exist', HttpStatus.CONFLICT);
    }
  }
 
  /**
   * Fetch periods between two dates.
   * @param company
   * @param startDate
   * @param endDate
   * @param isFetchAlsoPeriodsOver If true, will not fetch only periods between two dates,
   * but also periods that include these two dates
   */
  public async getPeriodsForDates(
    company: Company,
    startDate: number,
    endDate: number,
    isFetchAlsoPeriodsOver: boolean,
  ) {
    const queryBuilder = this.periodRepository.createQueryBuilder('period');
 
    queryBuilder.where('period.company = :companyId', {
      companyId: company.id,
    });
 
    if (isFetchAlsoPeriodsOver) {
      // Fetch also period that is over startDate and period that is over endDate
      queryBuilder.andWhere(
        '((period.startDate >= :startDate AND period.endDate <= :endDate) OR (period.startDate <= :startDate AND period.endDate >= :startDate) OR (period.startDate <= :endDate AND period.endDate >= :endDate))',
        { startDate, endDate },
      );
    } else {
      queryBuilder.andWhere('period.startDate >= :startDate AND period.endDate <= :endDate', { startDate, endDate });
    }
 
    queryBuilder.select(['period']);
 
    return queryBuilder.getMany();
  }
}