All files / src/components/Merchants/MerchantPreview/modals GiveConfigureBankAccountModal.tsx

80.95% Statements 34/42
85.18% Branches 23/27
57.14% Functions 8/14
80% Lines 32/40

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                                                        42x   6x 6x   6x   6x     6x           6x 6x 6x           6x   6x                   6x 6x   6x       6x 3x 1x       6x 1x       1x     1x     6x           6x   6x             6x         6x                                                                                                                     3x                                                         6x   6x                                                                                                     24x                     42x   4x                            
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as Yup from "yup";
import { Box, BoxProps, CircularProgress, Stack } from "@mui/material";
import { styled, useAppTheme } from "@theme/v2/Provider";
import { useListParentBankAccounts } from "../hooks/useListParentBankAccounts";
import { useUpdateBankAccountSettings } from "../hooks/useUpdateBankAccountSettings";
import { TMerchantBankAccountSettings } from "../data.types";
import { useEffect } from "react";
import { useEnterprisePermissions } from "@components/AcquirerEnterprises/CreateEnterprise/hooks/useEnterprisePermissions";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import GiveMerchantBankAccountItem from "../components/BankAccounts/GiveMerchantBankAccountItem";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveButton from "@shared/Button/GiveButton";
import GiveBankAccountItem from "@features/Merchants/MerchantSidePanel/GiveMerchantFile/bankAccounts/GiveBankAccountItem";
import GiveText from "@shared/Text/GiveText";
import HFGiveSwitch from "@shared/HFInputs/HFGiveSwitch/HFGiveSwitch";
type FormInputs = TMerchantBankAccountSettings;
import { FileAttachmentType } from "@hooks/upload-api/uploadHooks";
 
interface ModalProps {
  merchantId: number;
  parentAccID: number;
  data: TMerchantBankAccountSettings;
}
 
const GiveConfigureBankAccountModal = NiceModal.create(
  ({ parentAccID, merchantId, data }: ModalProps) => {
    const modal = useModal();
    const theme = useAppTheme();
    const { bank_account_linking, manage_bank_account, money_transfers } =
      useEnterprisePermissions();
    const { bankAccountList, firstApprovedBankAccount } =
      useListParentBankAccounts(parentAccID, {
        enabled: bank_account_linking,
      });
    const isEditAllowed = useAccessControl({
      resource: RESOURCE_BASE.MERCHANT,
      operation: OPERATIONS.UPDATE,
    });
 
    const { handleUpdateBankAccountSettings, isLoading } =
      useUpdateBankAccountSettings(merchantId, data);
    const open = modal.visible;
    const schema = Yup.object().shape({
      allowBankAccounts: Yup.boolean(),
      allowTransfers: Yup.boolean(),
      isLinkAccount: Yup.boolean(),
    });
 
    const defaultValues = data;
 
    const methods = useForm<FormInputs>({
      resolver: yupResolver(schema),
      defaultValues,
    });
 
    const {
      reset,
      watch,
      setValue,
      formState: { isDirty },
    } = methods;
    const values = watch();
 
    const handleCancel = () => {
      modal.hide();
    };
 
    useEffect(() => {
      if (open) {
        reset(data);
      }
    }, [open, parentAccID, merchantId]);
 
    const handleSwitchLink = (event: React.ChangeEvent<HTMLInputElement>) => {
      const linkedAccountID = event.target.checked
        ? data?.linkedAccountID || firstApprovedBankAccount?.id || null
        : null;
 
      setValue("linkedAccountID", linkedAccountID, {
        shouldDirty: true,
      });
      setValue("isLinkAccount", event.target.checked, { shouldDirty: true });
    };
 
    const handleCheckAccount = (id: number) => () => {
      setValue("linkedAccountID", id, {
        shouldDirty: true,
      });
    };
 
    const isChecked = (id: number) => values.linkedAccountID === id;
 
    const onSubmit: SubmitHandler<FormInputs> = (data) => {
      handleUpdateBankAccountSettings(data, () => {
        modal.hide();
        reset(data);
      });
    };
 
    const handleReset = () => {
      reset();
      modal.hide();
    };
 
    const inputList = [
      {
        input: (
          <Stack direction="row" alignItems="center" gap={1}>
            <HFGiveSwitch
              name="allowBankAccounts"
              size="small"
              label="Allow merchant to add bank accounts"
              disabled={!isEditAllowed || isLoading}
            />
          </Stack>
        ),
        hidden: !manage_bank_account,
      },
      {
        input: (
          <Stack direction="row" alignItems="center" gap={1}>
            <HFGiveSwitch
              name="allowTransfers"
              label="Allow merchant to make money transfers"
              size="small"
              disabled={!isEditAllowed || isLoading}
            />
          </Stack>
        ),
        hidden: !money_transfers,
      },
      {
        input: (
          <SettingsBankAccountContainer disabled={!parentAccID}>
            <Stack direction="row" alignItems="flex-start" gap={1}>
              <HFGiveSwitch
                name="isLinkAccount"
                size="small"
                inputProps={{
                  ["data-testid" as string]: "link-provider-switch",
                }}
                label={
                  <Stack gap="4px">
                    <GiveText variant="bodyS">
                      Link provider bank account
                    </GiveText>
                    <GiveText variant="bodyXS" color="secondary">
                      Add the Provider’s bank account to this merchant.
                    </GiveText>
                  </Stack>
                }
                onChange={handleSwitchLink}
                disabled={!isEditAllowed || isLoading}
              />
            </Stack>
          </SettingsBankAccountContainer>
        ),
        hidden: bankAccountList?.length === 0 || !bank_account_linking,
      },
      {
        input: (
          <Stack spacing={1}>
            {bankAccountList?.map((bankAccount) => (
              <GiveMerchantBankAccountItem
                key={bankAccount.id}
                handleCheckAccount={handleCheckAccount(bankAccount.id)}
                isChecked={isChecked(bankAccount.id)}
                {...bankAccount}
              >
                <GiveBankAccountItem
                  key={bankAccount.id}
                  account={bankAccount}
                  parentAccID={parentAccID}
                  merchantId={merchantId}
                  localDocuments={
                    bankAccount.uploadedBankFiles?.map((doc) => ({
                      ...doc,
                      tag: FileAttachmentType.BankAccountConfirm,
                      updatedAt: new Date().getTime() / 1000,
                    })) as any
                  }
                  withWrapper={false}
                />
              </GiveMerchantBankAccountItem>
            ))}
          </Stack>
        ),
        hidden: !values.isLinkAccount,
      },
    ];
 
    const cannotPickLinkedBA =
      values.isLinkAccount && !firstApprovedBankAccount;
 
    return (
      <GiveBaseModal
        title="Bank Accounts"
        height="fit-content"
        open={open}
        onClose={handleCancel}
        buttons={
          <>
            <GiveButton
              label="Cancel"
              size="large"
              onClick={handleReset}
              disabled={isLoading}
              variant="ghost"
            />
            <GiveButton
              label="Save"
              size="large"
              type="submit"
              form="manage-bank-accounts-form"
              disabled={
                !isDirty || isLoading || !isEditAllowed || cannotPickLinkedBA
              }
              endIcon={
                isLoading ? (
                  <CircularProgress
                    size={14}
                    style={{
                      color: theme?.palette.primitive?.neutral?.[0],
                    }}
                  />
                ) : undefined
              }
            />
          </>
        }
        sx={{
          "& .MuiPaper-root": {
            width: "640px !important",
            maxWidth: "640px !important",
          },
        }}
      >
        <FormProvider {...methods}>
          <Stack
            component="form"
            id="manage-bank-accounts-form"
            onSubmit={methods.handleSubmit(onSubmit)}
            gap="24px"
          >
            {inputList.map(({ input, hidden }, index) => (
              <Box key={index} sx={{ ...(hidden && { display: "none" }) }}>
                {input}
              </Box>
            ))}
          </Stack>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
const SettingsBankAccountContainer = styled(Box)<
  BoxProps & { disabled?: boolean }
>(({ disabled }) => ({
  display: "flex",
  alignItems: "center",
  flexDirection: "row",
  gap: "16px",
  borderRadius: "8px",
  "& p": {
    margin: 0,
  },
  ...(disabled && {
    opacity: 0.5,
  }),
}));
export default GiveConfigureBankAccountModal;