All files / src/components/Disputes/GiveDisputePanel/modals GiveRespondToDisputeBody.tsx

71.87% Statements 69/96
63.21% Branches 55/87
65.21% Functions 15/23
72.52% Lines 66/91

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 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537                                                                              1x                     1x             1x 1x       1x 1x                                 1x                           54x     54x     54x   54x 54x 54x   54x 54x 54x   54x 1x 1x       1x     1x 1x       329x           54x 54x 215x           54x   54x     54x 1x   1x 1x   1x       1x     1x                             54x     2x           2x 2x                                 2x       2x                                       2x 2x                 2x 1x 1x 2x 2x 2x               1x   1x             1x     2x 2x     54x 16x                               1x                                 54x 216x     54x                 54x 54x                                                         1x                                                                                                                                                                                                                                                                                                                           54x   40x                                                         160x                  
import { Box, Stack } from "@mui/material";
import { WarningIcon, InfoIcon, UploadSimpleIcon } from "@phosphor-icons/react";
import { useFileUploadContext } from "@components/UploadFile/FileUploadContext";
import { FileMimeTypes, FileUploadStatus } from "@components/UploadFile/types";
import { useFormContext } from "react-hook-form";
import GiveAlert from "@shared/GiveAlert/GiveAlert";
import TaskCard from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/TaskCard";
import {
  AttachmentsContent,
  NotesContent,
} from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/Sections";
import HFGiveSwitch from "@shared/HFInputs/HFGiveSwitch/HFGiveSwitch";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import { CaseActionType } from "@components/Disputes/RespondToDispute/types";
import { convertPdfToImages } from "@components/Disputes/RespondToDispute/components/helpers";
import { dataURLtoFile } from "@utils/assets";
import {
  NOTE_MAX_LENGTH,
  RISK_TOGGLE_TOOLTIP_TEXT,
  RISK_TOGGLE_TOOLTIP_TEXT_WORLDPAY,
} from "@components/Disputes/DisputesList/constants";
import { useMemo, useRef, useState } from "react";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { ControlledDatePicker } from "@sections/PayBuilder/Forms/DateAndLocation/components/ControlledDatePicker";
import { GiveUploadItemProps } from "@shared/FileUpload/types";
import moment from "moment";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import { bytesToSize } from "@utils/index";
import NiceModal from "@ebay/nice-modal-react";
import { GIVE_CONFIRMATION_POP_UP } from "modals/modal_names";
import { AttachmentsUpload } from "@features/Merchants/MerchantSidePanel/UnderwritingTasks/components/Sections.atoms";
import { fiveMB } from "@hooks/upload-api/uploadHooks";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import GiveButton from "@shared/Button/GiveButton";
import { isEmpty, uniqueId } from "lodash";
import { showMessage } from "@common/Toast";
import { RespondModalLoadingSkeleton } from "./RespondModalSkeleton";
 
const AcceptJpgAndPdf = {
  "image/jpeg": [".jpg", ".jpeg"],
  "application/pdf": [".pdf"],
  "image/png": [".png"],
  "image/heic": [".heic"],
  "image/heif": [".heif"],
};
 
// Worldpay Documentation API supports jpg, gif, png, pdf and tiff (Worldpay
// eComm Chargeback API Reference V3.6, §4). Worldpay file-size caps (MSP009
// AC004.1, amended on record): 2 MB per file, 1 MB for American Express.
const WorldpayAcceptedFileTypes = {
  "image/jpeg": [".jpg", ".jpeg"],
  "image/gif": [".gif"],
  "image/png": [".png"],
  "application/pdf": [".pdf"],
  "image/tiff": [".tif", ".tiff"],
};
const WORLDPAY_MAX_FILE_SIZE = 2 * 1024 * 1024; // 2 MB
const WORLDPAY_MAX_FILE_SIZE_AMEX = 1 * 1024 * 1024; // 1 MB
// Worldpay per-case caps (Reference V3.6, §4 / MSP009 AC004.1): at most 10
// documents and 10 MB combined per case. The auto-attached MSP007 evidence PDF
// counts toward both (PO4), so the running totals include every file in the list.
const WORLDPAY_MAX_DOC_COUNT = 10;
const WORLDPAY_MAX_TOTAL_SIZE = 10 * 1024 * 1024; // 10 MB
 
type Props = {
  caseActions: CaseActionType[];
  isLoading: boolean;
  hideInputsNotRequired?: boolean;
  riskAcceptedRequired?: boolean;
  isPassedDispute?: boolean;
  isPanelAction?: boolean;
  action?: string;
  isAmex?: boolean;
  isWorldpay?: boolean;
  autoPdfMissing?: boolean;
  description?: string;
  notes?: string;
};
 
const GiveRespondToDisputeBody = ({
  caseActions,
  isLoading,
  riskAcceptedRequired,
  isPassedDispute,
  isPanelAction,
  action,
  isAmex,
  isWorldpay,
  autoPdfMissing,
  description,
  notes = "",
}: Props) => {
  // Worldpay enforces stricter, network-specific upload rules than RS2.
  const acceptedFileTypes = isWorldpay
    ? WorldpayAcceptedFileTypes
    : AcceptJpgAndPdf;
  const worldpayMaxFileSize = isAmex
    ? WORLDPAY_MAX_FILE_SIZE_AMEX
    : WORLDPAY_MAX_FILE_SIZE;
  const maxFileSize = isWorldpay ? worldpayMaxFileSize : fiveMB;
  const { getValues, setValue, watch, getFieldState, clearErrors, trigger } =
    useFormContext();
  const { setSnackbarFiles } = useFileUploadContext();
  const values = watch();
 
  const [isNotesFocused, setIsNotesFocused] = useState(false);
  const notesRef = useRef<any>();
  const initialNote = useRef<string>(notes);
 
  const handleDiscardNote = (e: React.MouseEvent) => {
    e.preventDefault(); // prevent focus jump
    setValue("actionNote", initialNote.current, {
      shouldDirty: true,
      shouldTouch: true,
    });
    setIsNotesFocused(false);
 
    // explicitly blur the textarea input and reset local state to false would be better
    Eif (notesRef?.current) {
      notesRef.current.blur();
    }
  };
 
  const caseActionOptions = caseActions?.map((action) => ({
    value: action?.name,
    label: action?.displayName,
    ...action,
  }));
 
  const selectedCaseAction = useMemo(() => {
    return caseActionOptions?.find(
      (x) => x?.value === (values.caseAction || action),
    );
  }, [caseActionOptions, values.caseAction, action]);
 
  const {
    globalName: { firstName, lastName },
  } = useAppSelector(selectUser);
 
  const filterOutFileById = (files: any[], idToRemove: number) => {
    return files.filter((file) => file.id !== idToRemove);
  };
  const handleDelete = (item: any) => {
    const currentFiles = getValues("caseFiles");
    const deleteFromPreview =
      typeof item === "number" || typeof item === "string"; //from preview we only get back the id
    const fileId = deleteFromPreview ? item : item.id;
 
    const applyFileDelete = (id: number) => {
      const filteredArr = filterOutFileById(currentFiles, id);
      setValue("caseFiles", filteredArr);
    };
    Iif (deleteFromPreview) {
      applyFileDelete(fileId);
    } else {
      NiceModal.show(GIVE_CONFIRMATION_POP_UP, {
        modalType: "delete",
        title: "Delete Document",
        description: `Are you sure you want to delete ${
          item.file.FileName ?? item.file.name
        } document?`,
        actions: {
          handleSuccess: {
            onClick: () => applyFileDelete(fileId),
          },
        },
      });
    }
  };
 
  const handleFileSelect = async (file: File | File[], status = "") => {
    // AttachmentsUpload/Content can hand back a single File or an array; fan
    // arrays out so each file goes through the same validation/upload path.
    Iif (Array.isArray(file)) {
      for (const f of file) {
        await handleFileSelect(f, status);
      }
      return;
    }
    const currentFiles = getValues().caseFiles;
    Iif (["error_file_size", "rejected_file_type"].includes(status)) {
      const { name, size } = file;
      setSnackbarFiles([
        {
          id: Math.random().toString(36).substring(7),
          name,
          size,
          status:
            status === "error_file_size"
              ? FileUploadStatus.FILE_TOO_LARGE
              : FileUploadStatus.FILE_NOT_SUPPORTED,
          uploadProgress: 0,
          canBeDeleted: true,
        },
      ]);
      return;
    }
    Iif (status === "preparing") return;
    // Worldpay enforces at most 10 documents and 10 MB combined per case
    // (the auto-attached MSP007 PDF counts toward both — PO4). Fail fast here
    // so the user gets a clear message before any upload is attempted.
    Iif (isWorldpay) {
      if ((currentFiles?.length || 0) >= WORLDPAY_MAX_DOC_COUNT) {
        showMessage(
          "Error",
          `You can attach at most ${WORLDPAY_MAX_DOC_COUNT} documents per dispute.`,
        );
        return;
      }
      const currentTotal = (currentFiles || []).reduce(
        (sum: number, f: any) => sum + (f?.file?.size || 0),
        0,
      );
      if (currentTotal + (file?.size || 0) > WORLDPAY_MAX_TOTAL_SIZE) {
        showMessage(
          "Error",
          "Attachments exceed the 10 MB total limit for this dispute.",
        );
        return;
      }
    }
    const defaultId = uniqueId();
    const commonFileProp = {
      fileID: defaultId,
      id: defaultId, //the file preview delete logic is based on id not fileID
      tag: "Acquirer Upload",
      attTypeName: "dispute_evidence",
      label: "Acquirer Upload",
      updatedAt: moment.now(),
    };
 
    if (file.type === FileMimeTypes.PDF && isAmex) {
      const imageDataUrls = await convertPdfToImages(file);
      const pdfAsImages = imageDataUrls.map((dataUrl, index) => {
        const name = `${file.name}-page${index + 1}.jpeg`;
        const newFile = dataURLtoFile(dataUrl, name);
        return {
          file: newFile,
          fileName: name,
          fileURL: dataUrl,
          fileType: "jpeg",
          ...commonFileProp,
        };
      });
      setValue("caseFiles", [...pdfAsImages, ...currentFiles]);
    } else {
      const formattedFile = {
        file,
        fileName: file.name,
        fileURL: URL.createObjectURL(file),
        fileType: file.type,
        ...commonFileProp,
      };
      setValue("caseFiles", [formattedFile, ...currentFiles]);
    }
 
    clearErrors("caseFiles");
    trigger();
  };
 
  const itemData: GiveUploadItemProps[] = useMemo(() => {
    return values?.caseFiles?.map((item: any, index: number) => ({
      merchantId: "",
      state: "uploaded",
      value: item.tag || "",
      byMessage: `by ${firstName} ${lastName}`,
      fileData: {
        id: item.fileID || item.id,
        fileName: item.fileName || item?.file?.name,
        fileID: index,
        fileType: item.fileType || item?.file?.type,
        attTypeName: "underwriting_match_report",
        fileURL: item.fileURL,
        tag: item.tag || "",
        label: item.label || "",
        notes: item?.notes || "",
      },
      onDelete: () => handleDelete(item),
      setNote: (value: string) => {
        const mappedFiles = values?.caseFiles?.map((file: any) => {
          if (file.fileID === item.fileID) {
            return {
              ...file,
              notes: value,
            };
          } else return file;
        });
        setValue("caseFiles", mappedFiles);
      },
      sizeMessage: bytesToSize(item.file?.size || 0)?.sizeString,
      useNotes: true,
    }));
  }, [values?.caseFiles]);
 
  const getFieldValue = (field: keyof CaseActionType) =>
    selectedCaseAction?.[field];
 
  //Notes and evidence should always appear according to BE
  const requiredFields = {
    caseAction: true, //it is always required to select one
    evidenceRequired: getFieldValue("evidenceRequired"),
    requiresDate: getFieldValue("requiresDate"),
    feesConfirmation: getFieldValue("feesConfirmation"),
    notesRequired: getFieldValue("notesRequired"),
    riskAccepted: riskAcceptedRequired,
  };
 
  const inputList = useMemo(() => {
    return [
      {
        input: (
          <Stack gap="16px">
            <HFGiveSelect
              name="caseAction"
              label="Case Action"
              placeholder="Select Type"
              options={caseActionOptions}
              hideError
            />
            {requiredFields.feesConfirmation && (
              <HFGiveSwitch
                name="feesConfirmation"
                value={Boolean(values.feesConfirmation)}
                size="small"
                label="Fees Confirmation"
              />
            )}
          </Stack>
        ),
        hidden: isPanelAction,
      },
      {
        input: (
          <Stack gap="16px">
            <TaskCard
              title="Action Note"
              onEdit={
                isNotesFocused ? undefined : () => notesRef?.current?.focus()
              }
              actions={
                isNotesFocused
                  ? [
                      {
                        element: (
                          <GiveButton
                            label="Discard"
                            variant="ghost"
                            onMouseDown={handleDiscardNote}
                            disabled={isEmpty(values.actionNote)}
                          />
                        ),
                      },
                      {
                        element: (
                          <GiveButton
                            data-testid="note-save-button"
                            label="Save"
                            variant="filled"
                            size="small"
                            onClick={() => setIsNotesFocused(false)}
                            disabled={isEmpty(values.actionNote)}
                          />
                        ),
                      },
                    ]
                  : undefined
              }
            >
              <NotesContent
                inputRef={notesRef}
                setIsNotesFocused={setIsNotesFocused}
                name="actionNote"
                placeholder="Enter your note..."
                maxLength={NOTE_MAX_LENGTH}
                minHeight={60}
                maxHeight={248}
              />
            </TaskCard>
            {/* The Accept Chargeback (panel action) modal must always offer the
                Fees Confirmation toggle, regardless of whether the matched case
                action carries the feesConfirmation flag (MSP009 QA bug #3). */}
            {isPanelAction && (
              <HFGiveSwitch
                name="feesConfirmation"
                value={Boolean(values.feesConfirmation)}
                size="small"
                label="Fees Confirmation"
              />
            )}
            {/* Accept Risk is normally deadline-driven, but the Accept Chargeback
                modal must always surface it (with its tooltip) so the user can
                acknowledge the risk before accepting (MSP009 QA bug #3). */}
            {(isPanelAction ||
              requiredFields.riskAccepted ||
              isPassedDispute) && (
              <Stack direction="row" gap="8px" alignItems="center">
                <HFGiveSwitch
                  name="riskAccepted"
                  value={Boolean(values.riskAccepted)}
                  size="small"
                  label="Accept Risk"
                />
                <GiveTooltip
                  fluidWidth
                  title={
                    isWorldpay
                      ? RISK_TOGGLE_TOOLTIP_TEXT_WORLDPAY
                      : RISK_TOGGLE_TOOLTIP_TEXT
                  }
                  placement="bottom-start"
                  color="default"
                >
                  <InfoIcon size={16} />
                </GiveTooltip>
              </Stack>
            )}
          </Stack>
        ),
      },
      {
        input: (
          <ControlledDatePicker
            name="refundDate"
            label="Refund Date"
            maxDate={new Date()}
            useUTCMoment
          />
        ),
        hidden: !requiredFields.requiresDate,
      },
      {
        input: (
          <TaskCard
            title="Attachments"
            actions={[
              {
                element: (
                  <AttachmentsUpload
                    data-testid="upload-button"
                    handleCustomUpload={handleFileSelect}
                    isEnterprise={false}
                    maxSizeInBytes={maxFileSize}
                    customElement={
                      <GiveIconButton
                        variant="ghost"
                        size="small"
                        Icon={UploadSimpleIcon}
                      />
                    }
                    sx={{
                      backgroundColor: "transparent",
                      padding: 0,
                      height: "auto",
                      width: "auto",
                    }}
                  />
                ),
              },
            ]}
          >
            <AttachmentsContent
              handleCustomUpload={handleFileSelect}
              uploadedItems={itemData}
              acceptedFileTypes={acceptedFileTypes}
              maxSizeInBytes={maxFileSize}
              uploadStackProps={{
                hideAllButtons: false,
                isHideDelete: false,
                hideDownload: true,
                hideEditButtons: true,
                showAddNote: true,
                showIconTooltip: true,
                handleLocalDelete: handleDelete,
              }}
            />
          </TaskCard>
        ),
        hidden: isPanelAction,
      },
    ];
  }, [
    requiredFields,
    values,
    getFieldState("feesConfirmation"),
    getFieldState("riskAccepted"),
    caseActionOptions,
    isPanelAction,
    isWorldpay,
    isNotesFocused,
    notesRef,
    setIsNotesFocused,
    isPassedDispute,
    handleFileSelect,
    itemData,
  ]);
  if (isLoading) return <RespondModalLoadingSkeleton />;
 
  return (
    <Stack gap="24px">
      <GiveAlert
        type="warning2"
        Icon={<WarningIcon size={24} />}
        label={
          isPanelAction
            ? description
            : "Check the dispute details and provide evidence or actions to contest the chargeback."
        }
        iconContainerSx={{
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
        }}
      />
      {isWorldpay && autoPdfMissing && (
        <GiveAlert
          type="warning2"
          Icon={<WarningIcon size={24} />}
          label="Auto Evidence PDF not available; please upload evidence manually."
          iconContainerSx={{
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
          }}
        />
      )}
      {inputList.map(({ input, hidden }, index) => (
        <Box key={index} sx={{ ...(hidden && { display: "none" }) }}>
          {input}
        </Box>
      ))}
    </Stack>
  );
};
 
export default GiveRespondToDisputeBody;