All files / web/components/form/dropdown extendedFormDropdownOptions.ts

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

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                                                                                                                             
import { IApiSegment } from '@constants/api';
import { AppImage } from '@constants/image';
import { IDropdownOption } from '@contracts/dropdownOption';
import { ResultWithValue } from '@contracts/resultWithValue';
import { getStateService } from '@services/internal/stateService';
import { getNmsUdJsonFileService } from '@services/json/nmsudJsonFileService';

export const extendedFormDropdownOptions = async <T>(
  segment: keyof IApiSegment,
  mapper: (item: T) => IDropdownOption,
): Promise<ResultWithValue<Array<IDropdownOption>>> => {
  const result = await getNmsUdJsonFileService().getListOf<T>(segment);
  if (result.isSuccess === false) return { ...result, value: [] };

  const optsFromApi = result.value.map(mapper).sort((a, b) => a.title.localeCompare(b.title));
  const optsFromApiValues = optsFromApi.map((oa) => oa.value);
  const localOpts = getStateService()
    .getSubmissions(segment)
    .filter((sub) => optsFromApiValues.includes(sub.value) === false) // remove api items
    .sort((a, b) => a.title.localeCompare(b.title));

  let opts: Array<IDropdownOption> = [];
  if (localOpts.length > 0) {
    if (optsFromApi.length > 0) {
      opts.push({
        title: 'Your submissions:',
        disabled: true,
        value: '-',
      });
    }
    opts = [
      ...opts,
      ...localOpts.map((l) => ({
        ...l,
        title: `${l.title} (Pending approval)`,
        image: l.image ?? AppImage.fallbackImg,
      })),
      {
        title: '',
        disabled: true,
        value: '--',
      },
    ];
  }

  if (optsFromApi.length > 0) {
    if (localOpts.length > 0) {
      opts.push({
        title: 'Approved submissions:',
        disabled: true,
        value: '---',
      });
    }
    opts = [...opts, ...optsFromApi];
  }

  return {
    isSuccess: true,
    errorMessage: '',
    value: opts,
  };
};