All files / src/features/Settings/Team/Modals AddTeamMemberModal.tsx

81.03% Statements 47/58
64.28% Branches 27/42
69.23% Functions 9/13
82.45% Lines 47/57

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                                          1x   25x 25x 25x   25x   25x 25x 25x 25x     25x   25x       25x                                 25x   25x 25x   25x 16x 16x 16x 16x         25x 2x 2x   2x         2x         2x     2x 2x     25x     1x 1x 1x 1x 1x         25x       25x 1x     1x   1x       1x 1x                         25x         25x                                                               29x                                         17x 1x       1x                                                                                    
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import { Stack } from "@mui/material";
import { useForm, FormProvider, Controller } from "react-hook-form";
import GiveInputWithTags from "@shared/InputTags/GiveInputWithTags";
import GiveButton from "@shared/Button/GiveButton";
import { yupResolver } from "@hookform/resolvers/yup";
 
import { useInviteTeamMember } from "@components/Settings/ManageTeam/hooks/useInviteTeamMember";
import { isValidEmail } from "@validation/regex";
import ProcessorInput from "@features/Merchants/MerchantSidePanel/components/UnderwriterRiskAnalystAssignCard/ProcessorInput";
 
import { useState } from "react";
import {
  AddTeamMemberFormValues,
  AddTeamMemberSchema,
  IAddTeamMemberModal,
} from "../types";
import { useGetCurrentMerchantId } from "@hooks/common";
import { useGetMerchantById } from "@hooks/enterprise-api/account/useGetMerchants";
 
const AddTeamMemberModal = NiceModal.create(
  ({ roleName, roleValue }: IAddTeamMemberModal) => {
    const modal = useModal();
    const { handleInvite, isLoading } = useInviteTeamMember();
    const [inputValue, setInputValue] = useState("");
 
    const { data: merchantData } = useGetMerchantById();
 
    const { isSponsor } = useGetCurrentMerchantId();
    const isInviteeSponsor = roleValue === "sponsor";
    const isAdminInvitingSponsor = !isSponsor && isInviteeSponsor;
    const isSponsorInvitingSponsor = isSponsor && isInviteeSponsor;
 
    // Show processor input only when admin is inviting a sponsor
    const showProcessorInput = isAdminInvitingSponsor;
    // When sponsor invites sponsor, silently attach their own processorName
    const implicitProcessorId = isSponsorInvitingSponsor
      ? merchantData?.processorName
      : undefined;
 
    const methods = useForm<AddTeamMemberFormValues>({
      resolver: yupResolver(AddTeamMemberSchema(isAdminInvitingSponsor)),
      defaultValues: {
        emailList: [],
        processor: undefined,
      },
      mode: "onChange",
      reValidateMode: "onBlur",
    });
 
    const {
      control,
      setError,
      clearErrors,
      setValue,
      watch,
      formState: { isValid },
    } = methods;
 
    const emailList = watch("emailList");
    const processor = watch("processor");
 
    const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
      Eif (emailList.length === 0) {
        setInputValue(e.target.value);
        Eif (e.target.value.trim()) {
          clearErrors("emailList");
        }
      }
    };
 
    const tryAddEmail = () => {
      Iif (emailList.length > 0) return false;
      const trimmedValue = inputValue.trim();
 
      Iif (!trimmedValue) {
        setError("emailList", { message: "Please enter an email." });
        return false;
      }
 
      Iif (!isValidEmail(trimmedValue)) {
        setError("emailList", { message: "Please enter a valid email." });
        return false;
      }
 
      setValue("emailList", [trimmedValue], {
        shouldValidate: true,
      });
      setInputValue("");
      return true;
    };
 
    const handleKeyDown = (
      e: React.KeyboardEvent<HTMLInputElement | HTMLDivElement>,
    ) => {
      Eif (["Enter", " "].includes(e.key)) {
        e.preventDefault();
        const added = tryAddEmail();
        Eif (added) {
          (e.target as HTMLInputElement).blur();
        }
      }
    };
 
    const handleRemoveTeamMember = () => {
      setValue("emailList", []);
    };
 
    const handleInviteClick = () => {
      Eif (emailList.length > 0) {
        // processor from form (admin case) or implicit (sponsor case)
        const processorId =
          methods.getValues("processor") || implicitProcessorId;
 
        handleInvite(roleValue, processorId || undefined)(
          { emailList },
          {
            onSuccess: () => {
              modal.hide();
              setValue("emailList", []);
            },
            onError: (errorMessage: any) => {
              setError("emailList", {
                type: "manual",
                message: errorMessage || "Failed to invite team member",
              });
            },
          },
        );
      }
    };
 
    const handleCancel = () => {
      modal.hide();
      setValue("emailList", []);
    };
 
    return (
      <GiveBaseModal
        open={modal.visible}
        title={`Add ${roleName}`}
        width="600px"
        height="fit-content"
        onClose={modal.hide}
        buttons={
          <Stack direction="row" gap="12px">
            <GiveButton
              variant="ghost"
              size="large"
              label="Cancel"
              onClick={handleCancel}
            />
            <GiveButton
              size="large"
              variant="filled"
              label="Invite"
              color="primary"
              onClick={handleInviteClick}
              disabled={isLoading || !isValid}
            />
          </Stack>
        }
      >
        <FormProvider {...methods}>
          <Stack gap="20px">
            <Controller
              name="emailList"
              control={control}
              render={({ fieldState: { error } }) => (
                <GiveInputWithTags
                  value={emailList}
                  error={error}
                  chipProps={{
                    variant: "light",
                    size: "large",
                    color: error ? "error" : "blue",
                    sx: {
                      padding: "4px 8px",
                      margin: "0 !important",
                      height: "28px",
                    },
                  }}
                  inputProps={{
                    label: "",
                    placeholder: emailList.length > 0 ? "" : "Enter email",
                    value: emailList.length > 0 ? "" : inputValue,
                    onChange: handleInputChange,
                    onKeyDown: (
                      e: React.KeyboardEvent<HTMLInputElement | HTMLDivElement>,
                    ) => {
                      if (["Enter", " "].includes(e.key)) {
                        handleKeyDown(e);
                      }
                    },
                    onFocus: (e) => {
                      Iif (emailList.length > 0) {
                        e.target.blur();
                      }
                    },
                    onBlur: tryAddEmail,
                    sx: {
                      "& .MuiOutlinedInput-root": {
                        padding: "12px !important",
                        "& input": {
                          padding: "0 !important",
                        },
                      },
                    },
                    height: "52px",
                  }}
                  handleDelete={handleRemoveTeamMember}
                  inputValue={inputValue}
                />
              )}
            />
 
            {showProcessorInput && (
              <ProcessorInput
                name="processor"
                label={null}
                processorValue={processor}
                placeholder="Select a processor"
                onChange={(val) => {
                  setValue("processor", val, { shouldValidate: true });
                }}
                withoutConfirm
                controlled
              />
            )}
          </Stack>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
export default AddTeamMemberModal;