All files / src/features/Merchants/MerchantSidePanel/Modals/MatchReport/components ReportEvidenceUpload.tsx

70.96% Statements 22/31
64.28% Branches 9/14
45.45% Functions 5/11
72.41% Lines 21/29

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                                                    4x 21x 21x 21x 21x         21x   21x 1x   1x 1x 1x 1x   1x                       1x     21x             21x                     21x 7x                                         21x 19x                                                                                       2x                                                        
import { Stack } from "@mui/system";
import GiveText from "@shared/Text/GiveText";
import GiveUploadArea from "@shared/FileUpload/GiveUploadArea";
import { AcceptAllowedGeneralDocumentsTypes } from "@hooks/upload-api/uploadHooks";
import { useMemo } from "react";
import { useFormContext, useWatch } from "react-hook-form";
import { ReportFormFields } from "../types";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import GiveUploadStack from "@shared/FileUpload/GiveUploadStack";
import moment from "moment";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import { GiveUploadItemProps } from "@shared/FileUpload/types";
import {
  FILE_MAX_SIZE,
  FILES_UPLOAD_GENERAL_LABEL,
} from "@constants/constants";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { AttachmentsUpload } from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/Sections.atoms";
import TaskCard from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/TaskCard";
import { AttachmentsContent } from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/Sections";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import { UploadSimpleIcon } from "@phosphor-icons/react";
 
const ReportEvidenceUpload = ({ merchantID }: { merchantID: number }) => {
  const { isMastercardMatchEnabled } = useGetFeatureFlagValues();
  const { setValue, getValues } = useFormContext<ReportFormFields>();
  const { isMobileView } = useCustomThemeV2();
  const evidenceList: ReportFormFields["files"] = useWatch({
    name: "files",
  });
  const {
    globalName: { firstName, lastName },
  } = useAppSelector(selectUser);
 
  const handleSaveFile = (file: File | File[]) => {
    const fileArray = Array.isArray(file) ? file : [file];
 
    const newFiles = fileArray.map((f) => {
      const id = Math.random().toString(36).substring(2, 9);
      const lastDotIndex = f.name.lastIndexOf(".") + 1;
      const fileType = f.name.substring(lastDotIndex);
 
      return {
        file: f,
        id,
        updatedAt: moment.now(),
        fileName: f.name,
        fileURL: URL.createObjectURL(f),
        fileType,
        tag: "MATCH Evidence",
        label: "MATCH Evidence",
      };
    });
 
    setValue("files", [...getValues("files"), ...newFiles]);
  };
 
  const handleDeleteItem = (fileIndex: number) => {
    setValue(
      "files",
      getValues("files").filter((_, index) => index !== fileIndex),
    );
  };
 
  const handleUpdateTag = (index: number, value: string) => {
    const itemToUpdate = evidenceList[index];
    const filteredArray = evidenceList.filter((_item, i) => i !== index);
 
    const updatedArray = [
      ...filteredArray,
      { ...itemToUpdate, tag: value, label: value },
    ];
    setValue("files", updatedArray);
  };
 
  const itemData: GiveUploadItemProps[] = useMemo(() => {
    return evidenceList.map((item, index) => ({
      merchantId: merchantID,
      state: "uploaded",
      value: item.tag || "",
      setValue: (val) => handleUpdateTag(index, val),
      byMessage: `by ${firstName} ${lastName}`,
      dateMessage: moment(item.updatedAt).tz(PLATFORM_TIMEZONE).format("MMM DD YYYY, HH:mm"),
      fileData: {
        fileName: item.fileName,
        id: index,
        fileType: item.file.type,
        attTypeName: "underwriting_match_report",
        fileURL: item.fileURL,
        tag: item.tag || "",
        label: item.label || "",
      },
      onDelete: () => handleDeleteItem(index),
      tagType: "editable",
    }));
  }, [evidenceList]);
 
  if (isMastercardMatchEnabled)
    return (
      <TaskCard
        title="Evidence"
        sx={{ padding: 0 }}
        actions={
          itemData?.length > 0
            ? [
                {
                  element: (
                    <AttachmentsUpload
                      merchantID={merchantID}
                      isEnterprise={false}
                      customElement={
                        <GiveIconButton
                          variant="ghost"
                          size="small"
                          Icon={UploadSimpleIcon}
                        />
                      }
                      handleCustomUpload={handleSaveFile}
                      attachmentType="underwriting_match_report"
                      sx={{
                        backgroundColor: "transparent",
                        padding: 0,
                        height: "auto",
                        width: "auto",
                      }}
                    />
                  ),
                },
              ]
            : undefined
        }
      >
        <AttachmentsContent
          merchantID={merchantID}
          uploadedItems={itemData}
          isEnterprise={false}
          attachmentType="underwriting_match_report"
          handleCustomUpload={handleSaveFile}
        />
      </TaskCard>
    );
 
  return (
    <Stack gap={1} data-testid="match-upload-evidence">
      <GiveText variant="bodyS">Evidence</GiveText>
      <GiveUploadArea
        isMobile={isMobileView}
        disabled={false}
        uploadFunction={handleSaveFile}
        message={FILES_UPLOAD_GENERAL_LABEL}
        accept={AcceptAllowedGeneralDocumentsTypes}
        maxFiles={5}
        multiple
        maxSizeInBytes={FILE_MAX_SIZE}
        documentType={UploadDocumentTypes.merchantMatchReport}
      />
      {evidenceList.length > 0 && (
        <GiveUploadStack
          items={itemData}
          customStyles={{
            marginTop: "12px",
          }}
          handleLocalDelete={handleDeleteItem}
        />
      )}
    </Stack>
  );
};
 
export default ReportEvidenceUpload;