All files / libs/tenants/users/profile/components/src/lib/table/cells/currency use-company-currency-options.ts

0% Statements 0/45
0% Branches 0/1
0% Functions 0/1
0% Lines 0/45

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                                                                                           
import { useMemo } from 'react';

import { type CurrencySymbolsEnum } from '@amalia/ext/iso-4217';
import { toCurrencyOption, useCurrencyOptions, type CurrencyOption } from '@amalia/kernel/monetary/components';
import { useCurrentCompany } from '@amalia/tenants/companies/state';

export const useCompanyCurrencyOptions = ({
  currentValue,
  withValueLabel,
}: {
  currentValue?: CurrencySymbolsEnum;
  withValueLabel?: boolean;
} = {}): CurrencyOption[] => {
  const { data: company } = useCurrentCompany();

  const companySymbols = useMemo(
    () => Object.values(company.symbols).concat([company.currency]),
    [company.currency, company.symbols],
  );

  const companySymbolsOptions = useCurrencyOptions(companySymbols, withValueLabel);

  /**
   * If the current value is not in the company symbols, we prepend it to the list of options as disabled.
   * This is to avoid the user selecting a currency that isn't in the company symbols anymore.
   * But we still need to be able to display the current value.
   *
   * Memoized to avoid running .includes if the current value hasn't changed.
   */
  const isCurrentValueNotInCompanySymbols = useMemo(
    () => currentValue && !companySymbols.includes(currentValue),
    [companySymbols, currentValue],
  );

  const disabledCurrentValueOption = useMemo(
    () =>
      currentValue && isCurrentValueNotInCompanySymbols ? [toCurrencyOption(currentValue, { disabled: true })] : [],
    [isCurrentValueNotInCompanySymbols, currentValue],
  );

  return useMemo(
    () => disabledCurrentValueOption.concat(companySymbolsOptions),
    [disabledCurrentValueOption, companySymbolsOptions],
  );
};