All files / src/features/Merchants/MerchantSidePanel/Modals MerchantAgreementModal.tsx

97.72% Statements 43/44
73.17% Branches 30/41
100% Functions 9/9
100% Lines 41/41

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                                                              2x                           18x 18x 18x 18x 18x 18x             18x             18x 18x 18x                   18x 18x 18x   18x                   18x     18x                     18x       18x 1x             18x 1x 1x     18x   1x                   1x       1x 1x 1x       18x 2x   2x 1x   1x                     18x     18x                     18x 18x                                                                                                                                 2x                                                       14x                                       2x                  
import { Box, Stack } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import NiceModal from "@ebay/nice-modal-react";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import { IParsedData } from "../../../../components/Merchants/MerchantPreview/data.types";
import { MerchantAgreementDocument } from "./MerchantAgreementDocument";
import { usePublishedDocumentByType } from "@pages/AcquirerPortal/LegalDocuments/api/usePublishedDocumentByType";
import { useGetMerchantById } from "@hooks/enterprise-api/account/useGetMerchants";
import { useGetFeatureFlagValues } from "FeatureFlags/useGetFeatureFlagValues";
import { styled } from "@theme/v2/Provider";
import useHandleScroll from "../hooks/useHandleScroll";
import { TMerchantAgreementPayload } from "@components/Merchants/CreateMerchantPanel/hooks/TMerchantAgreementPayload";
import { useMutation, useQueryClient } from "react-query";
import { customInstance } from "@services/api";
import { isEmpty } from "lodash";
import { MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS } from "@features/Merchants/MerchantSidePanel/constants";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import GiveDivider from "@shared/GiveDivider/GiveDivider";
import GiveCheckbox from "@shared/GiveCheckbox/GiveCheckbox";
import GiveText from "@shared/Text/GiveText";
import { QKEY_GET_MERCHANT_BY_ID } from "@constants/queryKeys";
import { checkPortals } from "@utils/routing";
import {
  AGREEMENT_CHECKBOX_MERCHANT,
  AGREEMENT_CHECKBOX_PROVIDER,
} from "@components/Merchants/MerchantPreview/constants";
import { getTOSVersionDate } from "../helpers";
import { useMerchantDataPreview } from "@components/Merchants/MerchantPreview/hooks/useMerchantDataPreview";
 
//AGREEMENT used for review agreement update from drawer
const MerchantAgreementModal = NiceModal.create(
  ({
    data,
    merchantId,
    handleAgree,
    onSigningCompleted,
    isMerchant,
  }: {
    data?: IParsedData;
    merchantId: string | number;
    handleAgree?: () => void;
    onSigningCompleted?: () => void;
    isMerchant?: boolean;
  }) => {
    const { isEnterprisePortal } = checkPortals();
    const queryClient = useQueryClient();
    const { isMobileView } = useCustomThemeV2();
    const { open, onClose } = useNiceModal();
    isMerchant;
    const isEnterpriseOrEnterprisePortal = isEnterprisePortal && !isMerchant;
 
    // Opened from the "?agreement=true" email deep link, the modal receives only
    // { merchantId } and no `data`. Self-load the same merchant preview the
    // Settings agreement panel uses, so the version renders and "Agree" submits a
    // real acceptance (msaHadAgreed:true) instead of the blank default payload.
    const { data: fetchedData, isLoading: isLoadingFetchedData } =
      useMerchantDataPreview({
        id: Number(merchantId),
        isEnterprise: isEnterpriseOrEnterprisePortal,
        isAgreementOpen: true,
        enabled: !data && !!merchantId,
      });
 
    const agreementData = data ?? fetchedData;
    const isResolvingData = !data && isLoadingFetchedData;
    const hasAgreementData = !isEmpty(agreementData?.merchantAgreement);
 
    // The agreement the merchant is consenting to is the acquirer's PUBLISHED
    // legal document (its real content + version + published date), fetched
    // with the current account's OWN accID — an acquirer reads its own
    // documents; a merchant/provider reads its parent acquirer's published
    // documents (the backend resolves the hierarchy). Falls back to the legacy
    // hardcoded Terms of Service when nothing is published (or the Legal
    // Documents feature is off).
    const { isDocumentManagementEnabled, isFeatureFlagLoading } =
      useGetFeatureFlagValues();
    const { data: currentMerchant } = useGetMerchantById();
    const accountID = currentMerchant?.accID;
    const { data: publishedDoc, isResolving: isDocResolving } =
      usePublishedDocumentByType(
        accountID,
        isEnterpriseOrEnterprisePortal
          ? "provider_agreement"
          : "merchant_agreement",
        { enabled: isDocumentManagementEnabled },
      );
    // Still determining whether a published agreement exists (flags resolving or
    // the fetch in flight) — show a loader so the legacy Terms of Service does
    // not flash before the published agreement resolves.
    const isResolving = !!isFeatureFlagLoading || isDocResolving;
 
    const defaultHasAgreed =
      agreementData?.merchantAgreement?.tcVersion ===
        agreementData?.merchantAgreement?.msaLastAcceptedVersion &&
      !!agreementData?.merchantAgreement?.msaHadAgreed;
 
    const {
      scrollButton,
      handleScroll,
      containerRef,
      enabledAgreementCheckbox,
      viewRef,
      setEnabledAgreementCheckbox,
    } = useHandleScroll({
      defaultHasAgreed,
    });
 
    const getDefaultValuesFromData = (signData?: TMerchantAgreementPayload) => {
      return {
        msaHadAgreed: true,
        msaPCICompliant: true,
        signatureURL: signData?.signatureURL,
      };
    };
 
    const handleRebrandedSettingsAgreement = () => {
      handleAgree?.();
      onClose?.();
    };
 
    const updateMerchantInfoMutation = useMutation({
      mutationFn: () => {
        return customInstance({
          url: `/merchants/${merchantId}`,
          method: "PATCH",
          data: isEmpty(agreementData?.merchantAgreement)
            ? merchantAgreementDefaultValues
            : getDefaultValuesFromData(agreementData?.merchantAgreement),
        });
      },
 
      onSuccess: () => {
        queryClient.invalidateQueries([
          MERCHANT_SIDE_PANEL_PREVIEW_API_KEYS.GET,
          merchantId,
        ]);
        queryClient.invalidateQueries([QKEY_GET_MERCHANT_BY_ID, merchantId]);
        onSigningCompleted && onSigningCompleted();
        onClose();
      },
    });
 
    const handleSubmit = () => {
      Iif (!merchantId) return;
 
      if (handleAgree) {
        handleRebrandedSettingsAgreement();
      } else {
        updateMerchantInfoMutation.mutate();
      }
    };
 
    // Version + "Last updated" come straight from the acquirer's MSA settings
    // (merchant_msa_versions, merged into useGetMerchantById as
    // aquirerTcVersion / acquirerTcDate) — NOT from the opener's parsed
    // payload: that payload blanks tcVersion until the merchant has agreed
    // and, when the opener fetched without the acquirer call, falls back to
    // the hardcoded date constants.
    const settingsVersion =
      currentMerchant?.aquirerTcVersion ||
      agreementData?.merchantAgreement?.tcVersion ||
      "";
    const lastUpdated = currentMerchant?.acquirerTcDate
      ? getTOSVersionDate(
          currentMerchant.acquirerTcDate,
          isEnterpriseOrEnterprisePortal,
        )
      : agreementData?.merchantAgreement?.tcVersionUpdatedAt ??
        getTOSVersionDate(
          agreementData?.merchantAgreement?.msaLastUpdatedAt,
          isEnterpriseOrEnterprisePortal,
        );
 
    const portal = isEnterpriseOrEnterprisePortal ? "Provider" : "Merchant";
    return (
      <GiveBaseModal
        open={open}
        title={
          handleAgree
            ? `${portal} Application Agreement`
            : `${portal} Agreement Update`
        }
        width="720px"
        height={isMobileView ? "90%" : "57%"}
        onClose={onClose}
        hideScrollBar
        buttons={
          <Stack gap="12px" flexDirection="row">
            <GiveButton
              onClick={onClose}
              label="Cancel"
              variant="ghost"
              size="large"
            />
            <GiveButton
              label="Agree"
              variant="filled"
              size="large"
              sx={{ border: "none" }}
              disabled={
                !enabledAgreementCheckbox ||
                updateMerchantInfoMutation?.isLoading ||
                isResolvingData ||
                !hasAgreementData
              }
              onClick={handleSubmit}
            />
          </Stack>
        }
        closeIconProps={{
          bgColor: "solidWhite",
        }}
      >
        {scrollButton}
        <TOSWrapper
          onScroll={handleScroll}
          ref={containerRef}
          data-testid="agreement"
        >
          <MerchantAgreementDocument
            publishedDoc={publishedDoc}
            fallbackVersion={settingsVersion}
            fallbackLastUpdated={lastUpdated}
            isEnterprise={isEnterpriseOrEnterprisePortal}
            isResolving={isResolving}
          />
 
          <Box ref={viewRef} px="16px">
            <GiveDivider />
            <Stack
              mt="20px"
              gap="12px"
              flexDirection="row"
              alignItems="flex-start"
            >
              <Box>
                <GiveCheckbox
                  data-testid="agreement-confirmation-checkbox"
                  checked={enabledAgreementCheckbox}
                  onChange={() => setEnabledAgreementCheckbox((prev) => !prev)}
                />
              </Box>
              <Box>
                <GiveText fontWeight={400} color="primary" variant="bodyS">
                  Agreement Confirmation
                </GiveText>
                <GiveText
                  fontWeight={400}
                  mt="4px"
                  color="secondary"
                  variant="bodyXS"
                >
                  {isEnterpriseOrEnterprisePortal
                    ? AGREEMENT_CHECKBOX_PROVIDER
                    : AGREEMENT_CHECKBOX_MERCHANT}
                </GiveText>
              </Box>
            </Stack>
          </Box>
        </TOSWrapper>
      </GiveBaseModal>
    );
  },
);
 
export default MerchantAgreementModal;
 
const TOSWrapper = styled(Box)(({ theme }) => ({
  margin: "0 auto",
  width: "100%",
  height: "618px",
  borderRadius: "16px",
  border: "none",
  backgroundColor: "white",
  overflowY: "scroll",
  position: "relative",
  overflowX: "hidden",
  "*": {
    color: theme.palette.text.primary,
  },
  "& .MuiCardMedia-root": {
    backgroundColor: "white",
    height: "618px",
    overflowY: "scroll",
  },
}));
 
const merchantAgreementDefaultValues = {
  msaRefundPolicy: "30 Days of Purchase",
  msaPCICompliant: true,
  msaPreviousTermination: false,
  msaPreviousTerminationProcessorName: "",
  msaPreviousTerminationReason: "",
  msaPreviousTerminationAt: null,
  msaHadAgreed: false,
};