All files / src/components/Disputes/RespondToDispute/hooks useRespondToDispute.tsx

83.33% Statements 80/96
58.76% Branches 57/97
74.19% Functions 23/31
85.55% Lines 77/90

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 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376                                                      1x           1x                   60x 60x 60x 60x         60x               60x 60x         60x 60x             60x         60x                     60x   60x 2x 2x     60x             2x 2x     2x               2x                                     2x 2x 2x               2x                       2x 2x 2x   2x 2x     2x                             2x   2x 2x           2x             2x             2x               2x   2x 2x 2x               2x     60x 1x 1x     1x               1x 1x   1x       1x       1x 1x 1x             1x                         60x 14x 7x   7x 7x                       7x               7x       60x   60x 208x     60x                   60x 60x       60x 1x 1x       60x 2x   2x         1x           60x                                                   1x                
import { useForm } from "react-hook-form";
import { RespondToDisputeFormType } from "../types";
import { useQueryClient } from "react-query";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { useUploadFiles } from "@hooks/upload-api/uploadHooks";
import { useGetCaseEvidence } from "@components/Disputes/RespondToDispute/hooks/useGetCaseEvidence";
import { useCallback, useEffect, useMemo } from "react";
import { showMessage } from "@common/Toast";
import { DISPUTES_QUERY_KEY } from "@components/Disputes/DisputesList/hooks/useDisputesTable";
import { yupResolver } from "@hookform/resolvers/yup";
import { object, string, mixed, boolean, array } from "yup";
import { useDisputeActions } from "./useDisputeActions";
import { useGetCaseActions } from "./useGetCaseActions";
import { isEmpty } from "lodash";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
 
type Props = {
  disputeId: string;
  lastCaseId: string;
  merchantId: number;
  isDraft?: boolean;
  isPassedDispute?: boolean;
  isPanelAction?: boolean;
  isWorldpay?: boolean;
  panelActionProps?: any;
};
 
const FORM_DEFAULT_VALUES = {
  caseAction: "",
  caseFiles: [],
  actionNote: "",
};
 
export const useRespondToDispute = ({
  disputeId,
  lastCaseId,
  merchantId,
  isDraft,
  isPassedDispute,
  isPanelAction,
  isWorldpay,
  panelActionProps,
}: Props) => {
  const queryClient = useQueryClient();
  const modal = useModal();
  const { handleUpload, isLoading: loadingFiles } = useUploadFiles();
  const { data, isLoading: isCaseEvidenceLoading } = useGetCaseEvidence({
    caseId: lastCaseId,
    disputeId,
  });
 
  const { files, lastEvidence } = data || {};
 
  const {
    removeDraftFilesMutation,
    respondToDisputeMutation,
    submitEvidenceMutation,
    postImages,
    patchImages,
  } = useDisputeActions({ disputeId, isDraft, lastCaseId });
  const { caseActions, isLoading: isActionLoading } = useGetCaseActions({
    disputeId,
    lastCaseId,
    isFilterApplied: !isPanelAction,
  });
  const hideInputsNotRequired = isEmpty(lastEvidence);
  const riskAcceptedRequired = hideInputsNotRequired
    ? false
    : new Date(lastEvidence?.responseDueAt * 1000) < new Date();
  // AC009.2: the MSP007 auto-generated evidence PDF is stored as case evidence
  // (file name "dispute_<case>_merchant_evidence.pdf"). For Worldpay disputes,
  // warn when it is absent so the user knows to upload evidence manually.
  const autoPdfMissing =
    Boolean(isWorldpay) &&
    !isCaseEvidenceLoading &&
    !(files || []).some((doc: any) =>
      /merchant_evidence/i.test(doc?.fileName || doc?.name || ""),
    );
  const methods = useForm<RespondToDisputeFormType>({
    resolver: yupResolver(schema),
    defaultValues: FORM_DEFAULT_VALUES,
    context: {
      isActionNoteVisible: true,
      isRefundDateVisible: true,
      isFeesConfirmationVisible: true,
      isRiskAcceptedVisible: true,
    },
    mode: "all",
  });
  const values = methods.watch();
 
  const handleClose = () => {
    modal.remove();
    methods.reset(FORM_DEFAULT_VALUES);
  };
 
  const handleSaveEvidence = async ({
    onSuccess,
    action,
  }: {
    onSuccess?: () => void;
    action?: string;
  }) => {
    const uploadedFiles = values.caseFiles
      ?.filter((caseFile) => !caseFile?.fileS3ObjectKey) // remove already existing ones
      ?.map((caseFile) => ({ file: caseFile.file }));
 
    let caseUploadedFiles = [] as {
      fileID: number | undefined;
      fileName: string;
      notes: string | undefined;
      id?: string;
      textTitle?: string;
    }[];
 
    Iif (uploadedFiles?.length > 0) {
      const filesRes = await handleUpload({
        list: uploadedFiles,
        merchantId: merchantId,
        resourceID: merchantId,
        attachmentType: "dispute_evidence",
        label: "",
      });
 
      caseUploadedFiles = values.caseFiles
        ?.filter((caseFile) => !caseFile?.fileS3ObjectKey) // remove already existing ones
        ?.map((caseFile, index) => ({
          ...caseFile,
          fileID: filesRes?.[index]?.id,
          fileName: caseFile?.file?.name || "",
          fileSize: caseFile?.file?.size,
          notes: caseFile.notes,
        }));
    }
    const caseExistingFiles = values.caseFiles
      ?.filter((caseFile) => caseFile?.fileS3ObjectKey) // if they have id, they exist already
      ?.map((caseFile) => ({
        ...caseFile,
        id: caseFile?.id,
        fileName: caseFile?.file?.name,
        notes: caseFile.notes,
        fileID: caseFile?.id,
      }));
 
    const data = {
      action: action || values.caseAction,
      notes: values?.actionNote || "",
      ...(isPassedDispute && {
        riskAccepted: Boolean(values?.riskAccepted),
      }),
      ...(values?.refundDate && {
        refundDate: Math.floor(new Date(values?.refundDate).getTime() / 1000),
      }),
      confirmFees: values?.feesConfirmation || false,
    };
 
    const currentFiles = values.caseFiles
      ?.filter((file) => file.id)
      .map((file) => file.id);
 
    const removedDocs = files
      ?.filter((doc) => !!doc?.fileURL && !currentFiles.includes(doc?.obj_id))
      ?.map((doc) => doc?.obj_id);
 
    Iif (removedDocs?.length > 0) {
      await removeDraftFilesMutation.mutateAsync(
        {
          texts: [],
          files: removedDocs,
        },
        {
          onSuccess: () => {
            queryClient.invalidateQueries(["dispute-preview", disputeId]);
            queryClient.invalidateQueries(["get-case-evidence", disputeId]);
          },
        },
      );
    }
 
    let res = null;
 
    try {
      const filesToPost = caseUploadedFiles?.map((item) => ({
        ...item,
        fileID: Number(item?.fileID || 0),
        title: item?.textTitle || "",
      }));
 
      const filesToPatch = caseExistingFiles?.map((item) => ({
        title: item?.textTitle || "",
        id: item?.fileID || "",
        fileName: item?.fileName,
        notes: item?.notes,
      }));
 
      !isEmpty(filesToPost) &&
        (await postImages.mutateAsync({
          data: {
            files: filesToPost,
          },
        }));
 
      !isEmpty(filesToPatch) &&
        (await patchImages.mutateAsync({
          caseId: lastCaseId,
          data: {
            files: filesToPatch,
          },
        }));
 
      res = await respondToDisputeMutation.mutateAsync(data);
 
      queryClient.invalidateQueries(["dispute-preview", disputeId]);
      queryClient.invalidateQueries(["get-case-evidence", disputeId]);
      if (onSuccess) onSuccess();
    } catch (err: any) {
      showMessage(
        "Error",
        err?.response?.data?.input?.[0].message || err?.response?.data?.message,
      );
    }
 
    return res?.id; // draft id;
  };
 
  const handleSubmitEvidence = async (action?: any) => {
    const selectedCaseAction = caseActions?.find(
      (x) => x?.name === (action || methods.watch("caseAction")),
    );
 
    const data = {
      ...(selectedCaseAction?.feesConfirmation && {
        confirmFees: Boolean(values.feesConfirmation),
      }),
      ...(isPassedDispute && {
        riskAccepted: Boolean(values.riskAccepted),
      }),
    };
    const caseId = await handleSaveEvidence({ action });
    Iif (!caseId) return;
 
    submitEvidenceMutation.mutate(
      { data, caseId: caseId ?? lastCaseId },
      {
        onSuccess: () => {
          queryClient.refetchQueries({
            queryKey: ["dispute-preview", disputeId],
            active: true,
          });
          queryClient.invalidateQueries(["get-case-evidence", disputeId]);
          queryClient.refetchQueries(DISPUTES_QUERY_KEY);
          Iif (isWorldpay) {
            // AC006.4: Worldpay transitions are driven by the daily sync worker.
            showMessage(
              "Success",
              "Worldpay response submitted. Updates will reflect after next sync.",
            );
          }
          handleClose();
        },
        onError: (err: any) => {
          showMessage(
            "Error",
            err?.response?.data?.input?.[0].message ||
              err?.response?.data?.message,
          );
        },
      },
    );
  };
 
  useEffect(() => {
    if (files || lastEvidence) {
      const filteredDocs = files?.filter((doc) => !!doc?.fileURL) || [];
 
      const documents = filteredDocs?.map((doc) => {
        return {
          file: {
            name: doc?.fileName || doc?.name,
            size: doc?.fileSize || 0,
            type: doc?.fileType || doc?.type,
          },
          fileURL: doc?.fileURL,
          notes: doc?.notes,
          id: doc?.obj_id,
          fileS3ObjectKey: doc?.fileS3ObjectKey,
        };
      });
      const payload = {
        actionNote: lastEvidence?.notes || "",
        caseAction:
          lastEvidence?.action === "pending" ? "" : lastEvidence?.action,
        feesConfirmation: lastEvidence?.confirmFees,
        riskAccepted: lastEvidence?.riskAccepted,
        caseFiles: documents as any[], // to replace any
      };
      methods.reset(payload);
    }
  }, [files, lastEvidence]);
 
  const checkHasError = useCallback(
    (action?: string) => {
      const selectedCaseAction = caseActions?.find(
        (x) => x?.name === (action || methods.watch("caseAction")),
      );
 
      return (
        (!selectedCaseAction && !values.caseAction) ||
        (selectedCaseAction?.notesRequired && !values.actionNote) ||
        (selectedCaseAction?.evidenceRequired && isEmpty(values.caseFiles)) ||
        (selectedCaseAction?.requiresDate && isEmpty(values.refundDate))
      );
    },
    [caseActions, methods, values],
  );
  //panelActionProps?.action is to handle when is not the Respond flow
  const hasError = useMemo(
    () => checkHasError(panelActionProps?.action),
    [checkHasError, panelActionProps?.action],
  );
 
  const handleSaveDraft = () => {
    handleSaveEvidence({
      onSuccess: () => handleClose(),
    });
  };
 
  const handleShowConfirmationPopup = (action?: string) => {
    Iif (action) handleSubmitEvidence(action);
    else {
      NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
        modalType: "submit",
        title: "Confirm Submission",
        description: `Are you sure you want to submit the evidence? Once submitted, you won’t be able to make further changes.`,
        actions: {
          handleSuccess: { onClick: () => handleSubmitEvidence() },
        },
      });
    }
  };
 
  return {
    modal,
    methods,
    values,
    handleSaveDraft,
    handleSubmitEvidence,
    handleClose,
    hideInputsNotRequired,
    isLoading:
      submitEvidenceMutation.isLoading ||
      respondToDisputeMutation.isLoading ||
      removeDraftFilesMutation.isLoading ||
      postImages.isLoading ||
      patchImages.isLoading ||
      loadingFiles ||
      isCaseEvidenceLoading,
    isInitialLoading: isCaseEvidenceLoading || isActionLoading,
    caseActions,
    handleShowConfirmationPopup,
    riskAcceptedRequired,
    autoPdfMissing,
    notes: lastEvidence?.notes,
    hasError,
  };
};
 
const schema = object().shape({
  caseAction: string(),
  actionNote: string(),
  refundDate: mixed(),
  feesConfirmation: boolean(),
  riskAccepted: boolean(),
  caseFiles: array(),
});