All files / libs/tenants/companies/currency-rates/core/src/lib currencies.service.ts

86.76% Statements 282/325
60% Branches 27/45
100% Functions 8/8
86.76% Lines 282/325

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 3261x 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 1x 1x 83x 83x 83x 83x 83x 83x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 5x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 5x 4x 4x 4x 48x 48x 48x 48x 48x 48x 48x 48x 48x     48x 48x 48x 48x 48x 48x 20x 20x 20x 20x 20x 20x 48x 48x 4x 4x 4x 8x 3x 3x 1x 1x 1x 1x 3x     3x 3x 3x 3x 3x 8x                 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 5x 5x     5x 5x 1x 1x 1x 1x 1x 1x 1x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x       1x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x         26x 26x 26x 26x           26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x         26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x     24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 3x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x         24x           24x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 1x  
import { HttpException, HttpStatus, Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios';
import { mapValues, pick, range, uniq } from 'lodash-es';
import { FindOptionsWhere, In, Not, Repository } from 'typeorm';
 
import { convertDateToTimestamp } from '@amalia/amalia-lang/formula/evaluate/shared';
import { Currency, globalConfiguration, type Company, type RatesType } from '@amalia/core/models';
import { dayjs } from '@amalia/ext/dayjs';
import { type CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import { toError } from '@amalia/ext/typescript';
import { PeriodFrequencyEnum } from '@amalia/payout-definition/periods/types';
import { CreateCurrencyRequest } from '@amalia/tenants/companies/currency-rates/types';
 
/**
 * Service currency.
 */
@Injectable()
export class CurrenciesService {
  private readonly logger = new Logger(CurrenciesService.name);
 
  private readonly configuration = globalConfiguration();
 
  public constructor(
    @InjectRepository(Currency)
    private readonly currencyRepository: Repository<Currency>,
  ) {}
 
  public static convertRatesToCompanyCurrency(companyCurrency: CurrencySymbolsEnum, currency: Currency): Currency {
    const companyRate = currency.rates[companyCurrency];
    return {
      ...currency,
      rates: mapValues(currency.rates, (rate) => rate / companyRate),
    };
  }
 
  /**
   * Find all currencies attached to a company
   * @param company company
   * @param year
   * @param date
   * @param excludeIds if you want to find all currencies in a year except some with given ids
   */
  public async findAll(
    company: Company,
    year: string | null = null,
    date: string | null = null,
    excludeIds?: string[],
  ): Promise<Currency[]> {
    // If year set, search for currencies using company frequency and if not exist create them
    let currencies: Currency[] = [];
    try {
      if (year) {
        if (company.statementFrequency === PeriodFrequencyEnum.quarter) {
          // Refresh currency for each quarter of the year (quarter index begins at 1)
          await Promise.all(
            range(1, 5).map(async (quarterIndex) => {
              // Get dates of the end of the quarter
              const quarterDate = dayjs(year, 'YYYY').quarter(quarterIndex).endOf('quarter').format('YYYY-MM-DD');
              const quarterDateUnix = dayjs(year, 'YYYY').quarter(quarterIndex).endOf('quarter').unix();
 
              const condition: FindOptionsWhere<Currency> = {
                date: quarterDateUnix,
              };
 
              if (excludeIds) {
                condition.id = Not(In(excludeIds));
              }
 
              let existingCurrency = await this.currencyRepository.findOne({
                where: condition,
              });
 
              if (!existingCurrency) {
                this.logger.warn(`Currency not found for quarter ${quarterIndex}, we must refresh.`);
                await this.refreshCurrency(company, quarterDate);
                existingCurrency = await this.currencyRepository.findOne({
                  where: condition,
                });
              }
 
              currencies.push(existingCurrency!);
            }),
          );
        } else if (company.statementFrequency === PeriodFrequencyEnum.month) {
          // Refresh currency for each month of the year (month index begins at 0)
          await Promise.all(
            range(0, 12).map(async (monthIndex) => {
              // get dates of the end of the month
              const monthDate = dayjs(year, 'YYYY').month(monthIndex).endOf('month').format('YYYY-MM-DD');
              const monthDateUnix = dayjs(year, 'YYYY').month(monthIndex).endOf('month').unix();
 
              const condition: FindOptionsWhere<Currency> = {
                date: monthDateUnix,
              };
 
              if (excludeIds) {
                condition.id = Not(In(excludeIds));
              }
 
              let existingCurrency = await this.currencyRepository.findOne({
                where: condition,
              });
 
              if (!existingCurrency) {
                this.logger.warn(`Currency not found for quarter ${monthIndex}, we must refresh.`);
                await this.refreshCurrency(company, monthDate);
                existingCurrency = await this.currencyRepository.findOne({
                  where: condition,
                });
              }
 
              currencies.push(existingCurrency!);
            }),
          );
        }
      } else {
        const condition: FindOptionsWhere<Currency> = {};
        if (date) {
          condition.date = dayjs(date, 'YYYY-MM-DD')
            .endOf(company.statementFrequency === PeriodFrequencyEnum.month ? 'month' : 'quarter')
            .unix();
        }
        if (excludeIds) {
          condition.id = Not(In(excludeIds));
        }
 
        currencies = await this.currencyRepository.find({
          where: condition,
        });
      }
    } catch (err) {
      const error = toError(err);
      this.logger.error({
        message: `Error on fetching currencies - ${error.message}`,
        error,
        company: pick(company, ['id', 'name']),
      });
      throw new HttpException('Error on fetching currencies', HttpStatus.INTERNAL_SERVER_ERROR);
    }
 
    return currencies
      .toSorted((c1, c2) => c1.date - c2.date)
      .map((c) => CurrenciesService.convertRatesToCompanyCurrency(company.currency, c));
  }
 
  /**
   * Find currency by id.
   * @id id of the currency
   * @throws {NotFoundException}
   */
  public async findOne(company: Company, id: string): Promise<Currency> {
    const currency = await this.currencyRepository.findOneBy({ id });
    if (!currency) {
      throw new NotFoundException();
    }
    return CurrenciesService.convertRatesToCompanyCurrency(company.currency, currency);
  }
 
  /**
   * Find currency by date
   * @param company company
   * @param date date
   */
  public async findCurrencyByDate(company: Company, date?: number): Promise<Currency> {
    const currency = await this.currencyRepository.findOneBy({
      date: dayjs
        .utc(date, 'X')
        .endOf(company.statementFrequency === PeriodFrequencyEnum.month ? 'month' : 'quarter')
        .unix(),
    });
 
    if (!currency) {
      throw new NotFoundException();
    }

    return CurrenciesService.convertRatesToCompanyCurrency(company.currency, currency);
  }
 
  /**
   * Create new currency.
   * @param company company of the new currency
   * @param currency currency to create
   * @throws {HttpException}
   */
  public async createOrUpdate(company: Company, currency: CreateCurrencyRequest): Promise<void> {
    // Use Company Frequency to ensure we are looking for end of month or end of Quarter date
    const date = convertDateToTimestamp(currency.date);
    const companyDate = dayjs(date, 'X')
      .endOf(company.statementFrequency === PeriodFrequencyEnum.month ? 'month' : 'quarter')
      .unix();
 
    let currencyAlreadyExist: Currency | null = null;
    try {
      currencyAlreadyExist = await this.findCurrencyByDate(company, companyDate);
    } catch {
      // do nothing here, we just wanted to check if we already have one currency
    }
 
    // Retrieve Rates from fixer.io
 
    //  compare companyDate to actual date (now)
    const url =
      companyDate > dayjs().unix()
        ? `${this.configuration.fixer.url}/api/latest?access_key=${this.configuration.fixer.accessKey}`
        : `${this.configuration.fixer.url}/api/${dayjs(companyDate, 'X').format('YYYY-MM-DD')}?access_key=${
            this.configuration.fixer.accessKey
          }`;
 
    const response = await axios.get<{ success?: boolean; rates: RatesType }>(url, { timeout: 10_000 }).catch(() => {
      throw new HttpException(
        'Axios in currency creation failed, please contact admin',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    });
 
    // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
    if (!response.data || response.data.success !== true) {
      throw new HttpException(
        'Fixer in currency creation failed, please contact admin',
        HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
 
    try {
      const currencyToUpsert = {
        date: companyDate,
        updatedAt: new Date(),
        id: currencyAlreadyExist?.id || undefined,
        rates: response.data.rates,
      };
 
      await this.currencyRepository.save(currencyToUpsert);
    } catch (err) {
      const error = toError(err);
      this.logger.error({ message: 'Error on create currency', error, company: pick(company, ['id', 'name']) });
      throw new HttpException('currency creation failed, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
 
  public async batchRefreshCurrencies() {
    const datesToRefresh: number[] = [
      // Add last month
      dayjs().add(-1, 'month').endOf('month').unix(),
      // Add last trimester
      dayjs().add(-3, 'month').endOf('quarter').unix(),
    ];
 
    // For current year AND next year, add all months
    range(0, 12).forEach((monthIndex) => {
      const currentYear = dayjs().format('YYYY');
      const nextYear = dayjs().add(1, 'year').format('YYYY');
 
      datesToRefresh.push(dayjs(currentYear, 'YYYY').month(monthIndex).endOf('month').unix());
      datesToRefresh.push(dayjs(nextYear, 'YYYY').month(monthIndex).endOf('month').unix());
    });
 
    const uniqueDatesToRefresh = uniq(datesToRefresh);
 
    // Call fixer APIs on all that
    // Doing a for: we want to do it one at a time
    for (const uniqueDateToRefresh of uniqueDatesToRefresh) {
      let currencyAlreadyExist: Currency | null = null;
 
      // Verify if currency already exists, passing a monthly company
      try {
        // One at a time
        currencyAlreadyExist = await this.findCurrencyByDate(
          { statementFrequency: PeriodFrequencyEnum.month } as Company,
          uniqueDateToRefresh,
        );
      } catch (err) {
        // Ignore not found exceptions
        if (!(err instanceof NotFoundException)) {
          throw err;
        }
      }
 
      const currencyToCreate: Currency = this.currencyRepository.create({
        id: currencyAlreadyExist?.id || undefined,
        date: uniqueDateToRefresh,
        rates: {} as RatesType,
        updatedAt: new Date(),
      });
 
      const url =
        uniqueDateToRefresh > dayjs().unix()
          ? `${this.configuration.fixer.url}/api/latest?access_key=${this.configuration.fixer.accessKey}`
          : `${this.configuration.fixer.url}/api/${dayjs(uniqueDateToRefresh, 'X').format('YYYY-MM-DD')}?access_key=${
              this.configuration.fixer.accessKey
            }`;
 
      // One at a time
 
      const response = await axios.get<{ success?: boolean; rates: RatesType }>(url, { timeout: 10_000 });
 
      if (response.data.success === true) {
        try {
          currencyToCreate.rates = response.data.rates;
          // One at a time
 
          await this.currencyRepository.save(currencyToCreate);
        } catch (err) {
          const error = toError(err);
          this.logger.error({ message: 'Error on batch create currency', error });
          throw new HttpException('currency creation failed, please contact admin', HttpStatus.INTERNAL_SERVER_ERROR);
        }
      } else {
        throw new HttpException(
          'Fixer in currency batch creation failed, please contact admin',
          HttpStatus.INTERNAL_SERVER_ERROR,
        );
      }
    }
  }
 
  /**
   * Refresh currency
   * @param company
   * @param dateToRefresh
   */
  public async refreshCurrency(company: Company, dateToRefresh: string): Promise<void> {
    await this.createOrUpdate(company, { date: dateToRefresh });
  }
}