All files / src/components/Merchants/MerchantPreview/hooks usePAHUploader.tsx

46.66% Statements 35/75
44.18% Branches 19/43
58.33% Functions 7/12
48.61% Lines 35/72

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                                                            65x                 87x 87x 87x 87x 87x   87x         87x 53x             87x 87x   87x 53x     53x           87x                                                                                                         87x         87x                 2x   2x 1x         1x     1x                                                     87x           1x 1x   1x     1x         1x           87x                         87x         1x                   1x                                     87x 53x               87x                              
import { useCallback, useEffect, useReducer, useState } from "react";
import { IFileWithMeta, IMeta, StatusValue } from "react-dropzone-uploader";
import { useQueryClient } from "react-query";
import {
  UploaderEvent,
  UploaderState,
  machine,
} from "../components/PrimaryAccountHolder/PAHUploaderMachine";
import { TFileAttachmentType } from "@components/UploadFile/hooks/useUploadFiles";
import { PAHMapper } from "../components/PrimaryAccountHolder/PAHMapper";
import {
  LocalOwnerFileType,
  TOwnerFile,
} from "../components/PrimaryAccountHolder/types";
import { deleteDocument } from "@hooks/common/documents/utils";
import { useUploadFiles } from "@hooks/upload-api/uploadHooks";
import { useIsValidFile } from "@hooks/upload-api/useIsValidFile";
import useHEICConversion from "@components/UploadFile/hooks/useHEICConversion";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
 
type Props = {
  docUrl: string;
  merchantId: number;
  type: TOwnerFile;
  fileId: number | undefined;
  documentType?: UploadDocumentTypes;
  setLocalDocs?: (data: LocalOwnerFileType) => void;
};
 
export const usePAHUploader = ({
  docUrl,
  merchantId,
  type,
  fileId,
  documentType,
  setLocalDocs,
}: Props) => {
  // Hooks
  const queryClient = useQueryClient();
  const { handleUpload } = useUploadFiles();
  const [fileUrl, setFileUrl] = useState<string>(docUrl);
  const [fileName, setFileName] = useState<string>("");
  const { convertAndUploadHEICFiles } = useHEICConversion();
 
  const [state, dispatch] = useReducer(
    machine,
    docUrl ? UploaderState.ON_UPLOADED : UploaderState.ON_INITIAL,
  );
 
  useEffect(() => {
    Iif (docUrl && docUrl !== fileUrl) {
      setFileUrl(docUrl);
      dispatch(UploaderEvent.UPLOAD);
      dispatch(UploaderEvent.SUCCESS);
    }
  }, [docUrl]);
 
  const { isDropzoneImageFileValid } = useIsValidFile();
  const [isLoadingNewUrl, setIsLoadingNewUrl] = useState(false);
 
  useEffect(() => {
    Iif (!docUrl && state === UploaderState.ON_UPLOADED) {
      dispatch(UploaderEvent.RESET);
    }
    Iif (docUrl && fileUrl !== docUrl && state === UploaderState.ON_UPLOADED) {
      setFileUrl(docUrl);
      setFileName("");
    }
  }, [docUrl]);
 
  const uploadFileNew = async ({
    allFiles,
    meta,
    customType,
  }: {
    allFiles: File[];
    meta: IMeta;
    customType?: TOwnerFile;
  }) => {
    if (meta.status !== "done") {
      return;
    }
    const files = allFiles.map((file) => ({ file: file }));
 
    const res = await handleUpload({
      list: [files[files.length - 1]], // this is done to not upload multiple files simulataneously as previously uploaded is still saved temporarily
      merchantId,
      resourceID: merchantId,
      attachmentType: PAHMapper[customType || type]
        .attachmentType as TFileAttachmentType,
      label: "",
      tag: `Account owner ${
        type === "primaryAccountHolderSelfie" ? "selfie" : "ID"
      }`,
    });
 
    if (res === "upload_failed") {
      setFileName("");
      dispatch(UploaderEvent.FAIL);
      return;
    }
    dispatch(UploaderEvent.SUCCESS);
    queryClient.invalidateQueries([
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES,
      merchantId,
    ]);
    queryClient.invalidateQueries([
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_PAH_FILES,
      merchantId,
    ]);
    // Uploading the PAH documents can advance the owner onboarding status
    // (pending -> ready_for_verification) on the backend once both the ID proof
    // and the selfie are uploaded. That endpoint returns 204 (no body), so refetch
    // the merchant detail to pull the fresh owner.statusName instead of showing the
    // stale "pending" until a manual refresh.
    queryClient.invalidateQueries([
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET,
      merchantId,
    ]);
 
    if (meta.previewUrl) setFileUrl(meta.previewUrl);
  };
 
  const isUploadable = [
    UploaderState.ON_INITIAL,
    UploaderState.ON_FAULTED,
  ].includes(state);
 
  const handleConversionAndUpload = async ({
    allFiles,
    status,
    customType,
  }: {
    allFiles: IFileWithMeta[];
    status: StatusValue;
    customType?: TOwnerFile;
  }) => {
    const selectedFile = allFiles[allFiles.length - 1];
 
    if (setLocalDocs) {
      setLocalDocs({
        fileName: selectedFile?.file?.name,
        fileURL: selectedFile?.file,
        type,
      });
      return;
    }
 
    convertAndUploadHEICFiles({
      files: [selectedFile.file],
      documentType,
      onComplete: async (files: File[]) => {
        const [file] = files;
        // Handle successful upload
        if (status === "done") {
          setFileName(file.name);
          dispatch(UploaderEvent.UPLOAD);
        }
        await uploadFileNew({
          meta: {
            ...selectedFile.meta,
            name: file.name,
            size: file.size,
            type: file.type,
            previewUrl: URL.createObjectURL(file),
            status,
          },
          allFiles: files,
          customType,
        });
      },
    });
  };
 
  // Upload logic
  const handleChangeStatus = useCallback(
    (
      fileWithMeta: IFileWithMeta,
      status: StatusValue,
      allFiles: IFileWithMeta[],
    ) => {
      const { remove } = fileWithMeta;
      const isNotValidFile = !isDropzoneImageFileValid(fileWithMeta, status);
 
      Iif (isNotValidFile) return;
 
      // Handle non-uploadable files
      Iif (!isUploadable) {
        remove && remove();
        return;
      }
 
      handleConversionAndUpload({ status, allFiles });
    },
    [PAHMapper[type].attachmentType, state, isUploadable],
  );
 
  // Reset
  const reset = async () => {
    setIsLoadingNewUrl(true);
    await queryClient.invalidateQueries([
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_FILES,
      merchantId,
    ]);
    await queryClient.invalidateQueries([
      MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET_PAH_FILES,
      merchantId,
    ]);
  };
 
  // Delete
  const _deleteDocument = (
    customType?: TOwnerFile,
    customFileId?: number,
    onEnd?: () => void,
  ) => {
    Iif (setLocalDocs) {
      setLocalDocs({
        fileName: "",
        fileURL: null,
        type,
        fileId: fileId,
      });
      return;
    }
 
    deleteDocument(
      merchantId,
      {
        fileName: PAHMapper[customType || type].deleteMessage,
        id: customFileId || fileId!,
      },
      () => {
        reset();
        onEnd?.();
      },
      { hideModal: !!customFileId },
    );
  };
 
  /**
   * Resets the uploader state after fetching a new docUrl during the reset action.
   * This prevents the user from selecting another file before the new URL is ready,
   * ensuring the component maintains its context during re-renders.
   */
  useEffect(() => {
    Iif (isLoadingNewUrl) {
      dispatch(UploaderEvent.RESET);
      setFileUrl(docUrl);
      setFileName("");
      setIsLoadingNewUrl(false);
    }
  }, [docUrl]);
 
  return {
    state,
    fileName,
    // We are using fileUrl to give instant background image to the upload zone
    // The main problem is that when docUrl change we are not changing the fileUrl to not give flicker/glitch effect
    // So this check removes the image if the image was deleted in other parts of the application (e.g. document section)
    // and the useEffect with docUrl dep resets the component to initial state if that's the case
    fileUrl: docUrl,
    handleChangeStatus,
    _deleteDocument,
    isUploadable,
    canDelete: !isLoadingNewUrl,
    handleConversionAndUpload,
  };
};