All files / src/features/Merchants/MerchantSidePanel/Modals/Signature SignAgreementModal.tsx

70.9% Statements 39/55
62.96% Branches 17/27
76.92% Functions 10/13
70.83% Lines 34/48

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                                                                          3x   27x 27x 27x     27x 27x 27x       27x                         27x   27x 4x 4x 4x 4x     27x 4x 4x   4x   4x   4x     27x                                                                                                                                   3x             1x 1x     1x 1x                                 1x                                                   1x                                               3x                             3x             9x               3x       3x           3x                                                    
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveText from "@shared/Text/GiveText";
import { useState } from "react";
import { Modals_types } from "./modal.types";
import DefaultMode from "./DefaultMode";
import UploadSignature from "./UploadSignature";
import Sign from "./Sign";
import Generate from "./Generate";
import AutoGenerated from "./AutoGenerated";
import { Box, Stack } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import { isEmpty } from "lodash";
import { styled, useAppTheme } from "@theme/v2/Provider";
import moment from "moment";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { useAppSelector } from "@redux/hooks";
import { selectUser } from "@redux/slices/auth/auth";
import { DownloadSimpleIcon, EyeIcon, TrashIcon } from "@phosphor-icons/react";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import useDocumentPreviewV2 from "@shared/FilePreview/hooks/useDocumentPreviewV2";
import NiceModal from "@ebay/nice-modal-react";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import { useCheckDocumentProcessing } from "@redux/slices/uploadProgressSlice";
import { UploadDocumentTypes } from "@redux/slices/uploadProgressSlice/types";
 
interface Props {
  uploadSignature?: (e: File) => void | Promise<void>;
  addSignature?: (e: File) => void | Promise<void>;
  /**
   * GB-21610 — set to the merchant's primary account holder's full name when the
   * person signing is NOT that PAH. The mode chooser is then skipped entirely and
   * the signature is generated from this name, so the image can never carry a
   * different name than the agreement attributes it to.
   */
  autoGenerateForPahName?: string;
}
//SIGN_AGREEMENT_MODAL_V2
const SignAgreementModal = NiceModal.create(
  ({ uploadSignature, addSignature, autoGenerateForPahName }: Props) => {
  const { open, onClose } = useNiceModal();
  const isAutoGenerate = Boolean(autoGenerateForPahName?.trim());
  const [modalOpened, setModalOpen] = useState<Modals_types>(
    isAutoGenerate ? "autoGenerate" : "default",
  );
  const [fileToUpload, setFileToUpload] = useState<File | null>(null);
  const { title, subtitle } = modalInfo[modalOpened];
  const isConvertingDocument = useCheckDocumentProcessing(
    UploadDocumentTypes.signature,
  );
 
  const Components = {
    default: <DefaultMode setModalOpen={setModalOpen} />,
    upload: <UploadSignature setFileToUpload={setFileToUpload} />,
    sign: <Sign setFileToUpload={setFileToUpload} />,
    generate: <Generate setFileToUpload={setFileToUpload} />,
    autoGenerate: (
      <AutoGenerated
        pahName={autoGenerateForPahName?.trim() ?? ""}
        setFileToUpload={setFileToUpload}
      />
    ),
  };
 
  const handleRemoveFile = () => setFileToUpload(null);
 
  const handleReset = () => {
    Iif (isConvertingDocument) return;
    setModalOpen(isAutoGenerate ? "autoGenerate" : "default");
    handleRemoveFile();
    onClose();
  };
 
  const handleUpload = () => {
    Iif (fileToUpload === null) return;
    const uploader = uploadSignature ?? addSignature;
    // If neither callback is provided, just close/reset without crashing the UI.
    Eif (typeof uploader === "function") {
      // Fire-and-forget: upstream callers often handle their own async state.
      void Promise.resolve(uploader(fileToUpload));
    }
    handleReset();
  };
 
  return (
    <GiveBaseModal
      open={open}
      title={title}
      onClose={handleReset}
      showFooter={modalOpened !== "default"}
      width="731px"
      height="auto"
      buttons={
        <ButtonContainer>
          {/* In auto-generate mode there is no chooser to go back to, so Back
              would strand the signer on an empty screen. */}
          {!isAutoGenerate && (
            <GiveButton
              onClick={() => {
                setFileToUpload(null);
                setModalOpen("default");
              }}
              disabled={isConvertingDocument}
              size="large"
              variant="ghost"
              label="Back"
            />
          )}
          <GiveButton
            disabled={fileToUpload === null || isConvertingDocument}
            size="large"
            variant="filled"
            label="Sign"
            onClick={handleUpload}
            sx={{
              border: "none",
            }}
          />
        </ButtonContainer>
      }
      sx={{
        "&.MuiModal-root": {
          zIndex: 2100,
        },
        ...(modalOpened === "default" && {
          "& .MuiDialogContent-root": {
            paddingBottom: "20px !important",
          },
        }),
      }}
    >
      <>
        <GiveText variant="bodyS" color="secondary">
          {subtitle}
        </GiveText>
        {Components[modalOpened]}
        {modalOpened === "upload" && !isEmpty(fileToUpload) && (
          <DocumentSection
            fileToUpload={fileToUpload}
            handleRemoveFile={handleRemoveFile}
          />
        )}
      </>
    </GiveBaseModal>
  );
  },
);
 
export default SignAgreementModal;
 
const DocumentSection = ({
  fileToUpload,
  handleRemoveFile,
}: {
  fileToUpload: File;
  handleRemoveFile: () => void;
}) => {
  const { globalName } = useAppSelector(selectUser);
  const { handlePreview } = useDocumentPreviewV2({
    handleLocalDelete: handleRemoveFile,
  });
  const { palette } = useAppTheme();
  const handleFileDownload = () => {
    if (fileToUpload) {
      const url = URL.createObjectURL(fileToUpload);
      const link = document.createElement("a");
      link.href = url;
      link.download = fileToUpload.name;
      document.body.appendChild(link);
      link.click();
      if (document.body.contains(link)) {
        document.body.removeChild(link);
      }
      URL.revokeObjectURL(url);
    } else {
      alert("No file uploaded to download!");
    }
  };
 
  const Icons = [
    {
      Icon: EyeIcon,
      onClick: () => {
        handlePreview({
          id: 0,
          fileName: fileToUpload.name,
          fileURL: URL.createObjectURL(fileToUpload),
          fileType: fileToUpload.type,
          tag: "",
          attTypeName: "",
        });
      },
      color: palette.icon?.["icon-primary"],
    },
    {
      Icon: DownloadSimpleIcon,
      onClick: handleFileDownload,
      color: palette.icon?.["icon-primary"],
    },
    {
      Icon: TrashIcon,
      onClick: handleRemoveFile,
      color: palette.primitive?.error[50],
    },
  ];
  return (
    <CardContainer
      flexDirection="row"
      justifyContent="space-between"
      alignItems="center"
    >
      <Box>
        <Stack mb="8px" gap="12px" flexDirection="row" alignItems="center">
          <GiveText fontWeight={400} color="primary" variant="bodyS">
            {fileToUpload?.name}
          </GiveText>
          <ChipText variant="bodyXS" color="secondary">
            Merchant Upload
          </ChipText>
        </Stack>
        <GiveText variant="bodyXS" color="primary">
          by {globalName?.firstName} {globalName.lastName}{" "}
          <GiveText variant="bodyXS" color="secondary" component="span">
            {moment().tz(PLATFORM_TIMEZONE).format("MMMM D YYYY, HH:mm")}
          </GiveText>{" "}
        </GiveText>
      </Box>
      <Stack gap="6px" alignItems="center" flexDirection="row">
        {Icons.map(({ Icon, onClick, color }, idx) => {
          return (
            <StyledButton
              onClick={onClick}
              size="medium"
              Icon={Icon}
              color={color}
              key={idx}
            />
          );
        })}
      </Stack>
    </CardContainer>
  );
};
 
const CardContainer = styled(Stack)(({ theme }) => ({
  padding: "12px",
  border: `1px solid ${theme.palette.border?.secondary}`,
  marginTop: "20px",
  borderRadius: "12px",
}));
 
const ButtonContainer = styled(Stack)(() => ({
  display: "flex",
  flexDirection: "row",
  alignItems: "center",
  gap: "12px",
  marginRight: "2px",
}));
 
const StyledButton = styled(GiveIconButton)(() => ({
  background: "transparent",
}));
 
const ChipText = styled(GiveText)(({ theme }) => ({
  padding: "6px 12px",
  backgroundColor: theme.palette.surface?.secondary,
  borderRadius: "4px",
}));
 
const modalInfo = {
  default: {
    title: "Sign Agreement",
    subtitle: "We need your signature to finalize the agreement.",
  },
  upload: {
    title: "Upload Signature",
    subtitle:
      "Submit your signature in either JPG or PNG format for seamless and secure document authentication.",
  },
  sign: {
    title: "Sign Agreement",
    subtitle:
      "Easily endorse agreements by simply using your mouse or trackpad to sign.",
  },
  generate: {
    title: "Generate",
    subtitle:
      "Craft your signature effortlessly using your name for a personalized and distinctive touch.",
  },
  autoGenerate: {
    title: "Sign Agreement",
    subtitle:
      "You are signing on behalf of the primary account holder, so the signature below is generated from their name on file.",
  },
};