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

90.62% Statements 29/32
90.47% Branches 19/21
66.66% Functions 6/9
90% Lines 27/30

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                                                          1x   1x           1x   143x 143x   143x               143x       143x 143x       143x 7x 7x     3x 1x               2x               3x                   4x   4x     4x 4x 3x   1x         143x                                                                                                   3x     1x                                           3x               3x            
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 { List, ListItemButton, Stack } from "@mui/material";
import { IdentificationBadgeIcon, WarningIcon } from "@phosphor-icons/react";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveButton from "@shared/Button/GiveButton";
import GiveAlert from "@shared/GiveAlert/GiveAlert";
import GiveText from "@shared/Text/GiveText";
import { styled } from "@theme/v2/Provider";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import { showMessage } from "@components/common/Toast/ShowToast";
import { usePahReassignment } from "../hooks/usePahReassignment";
import useTeamMemberEmailOptions from "@features/Settings/Team/hooks/useTeamMemberEmailOptions";
import { filterMemberSuggestions } from "@features/Settings/Team/helpers/memberSuggestions";
 
type FormInputs = { email: string };
 
type Props = {
  merchantId: number;
  // Optional prefill for "Edit email" reuse (PAH006 SS-4 / T4.1).
  prefillEmail?: string;
  // GB-21471: opt-in (merchant Team tab) — suggest existing team members as the
  // PAH types. Off for the acquirer entry points.
  enableMemberSuggestions?: boolean;
};
 
const CHANGE_PAH_WARNING_TEXT =
  "Upon changing Primary Account Holder, the merchant is reassigned to a new recipient. The current Primary Account Holder will remain functional until the new Primary Account Holder accepts the ownership invitation.";
 
const schema = Yup.object({
  email: Yup.string()
    .email("Email not valid")
    .required("Enter account holder email"),
});
 
const ChangePAHModal = NiceModal.create(
  ({ merchantId, prefillEmail, enableMemberSuggestions }: Props) => {
    const modal = useModal();
    const { changePah, isLoading } = usePahReassignment(merchantId);
 
    const methods = useForm<FormInputs>({
      mode: "onChange",
      resolver: yupResolver(schema),
      defaultValues: { email: prefillEmail ?? "" },
    });
 
    // GB-21471: surface existing team members as suggestions while typing. The
    // helper hides the list once the value already equals a member's email.
    const { options } = useTeamMemberEmailOptions(
      merchantId,
      Boolean(enableMemberSuggestions),
    );
    const emailValue = methods.watch("email") ?? "";
    const suggestions = enableMemberSuggestions
      ? filterMemberSuggestions(options, emailValue)
      : [];
 
    const onSubmit: SubmitHandler<FormInputs> = async ({ email }) => {
      try {
        const result = await changePah({ email });
        // An existing member is reassigned immediately with no invite — the BE
        // returns `{ reassigned: true }`. A new user gets the invite view instead.
        if (result?.reassigned) {
          showMessage(
            "Success",
            "",
            true,
            `Primary account holder reassigned to ${email}`,
            5000,
          );
        } else {
          showMessage(
            "Invitation",
            "",
            true,
            `Invitation successfully sent to ${email}`,
            5000,
          );
        }
        modal.hide();
      } catch (error: any) {
        // PAH006 bug 1: this modal has a single email field, so every client-side
        // validation failure (same email, declined/deactivated PAH, invalid email,
        // reassignment in flight...) relates to the entered email. Surface them
        // inline under the input following the design system instead of as a
        // truncated snackbar. Field errors use the repo's
        // `{ input: [{ field, message }] }` shape; the rest come back as
        // `{ message }`. Only unexpected/server errors (5xx) or network failures
        // fall back to the toast.
        const status: number | undefined = error?.response?.status;
        const message =
          error?.response?.data?.input?.[0]?.message ??
          error?.response?.data?.message;
        const isClientError =
          typeof status === "number" && status >= 400 && status < 500;
        if (message && isClientError) {
          methods.setError("email", { message });
        } else {
          showMessage("Error", "", true, message ?? "Something went wrong");
        }
      }
    };
 
    return (
      <GiveBaseModal
        open={modal.visible}
        title="Change Primary Account Holder"
        headerLeftContent={<IdentificationBadgeIcon size={22} />}
        width="600px"
        onClose={() => modal.hide()}
        // hide() plays the exit transition; remove() on its completion unmounts
        // the modal so the next open remounts fresh with the latest prefillEmail.
        TransitionProps={{ onExited: () => modal.remove() }}
        buttons={
          <Stack gap="12px" flexDirection="row">
            <GiveButton
              onClick={() => modal.hide()}
              label="Cancel"
              variant="ghost"
              size="large"
            />
            <GiveButton
              label="Send Invitation"
              variant="filled"
              size="large"
              disabled={isLoading}
              type="submit"
              form="change-pah-form"
              sx={{ border: "none" }}
              data-testid="submit-change-pah-button"
            />
          </Stack>
        }
        closeIconProps={{ bgColor: "solidWhite" }}
      >
        <FormProvider {...methods}>
          <form id="change-pah-form" onSubmit={methods.handleSubmit(onSubmit)}>
            <GiveAlert
              type="warning2"
              Icon={<WarningIcon />}
              description={CHANGE_PAH_WARNING_TEXT}
              dataTestId="change-pah-warning"
              sx={{ mb: 2 }}
            />
            <HFGiveInput
              name="email"
              label="New PAH Email"
              fullWidth
              disabled={isLoading}
            />
            {suggestions.length > 0 && (
              <SuggestionsList data-testid="change-pah-suggestions">
                {suggestions.map((s) => (
                  <SuggestionRow
                    key={s.email}
                    onClick={() =>
                      methods.setValue("email", s.email, {
                        shouldValidate: true,
                      })
                    }
                  >
                    <GiveText variant="bodyS">{s.name}</GiveText>
                    <GiveText variant="bodyXS" color="secondary">
                      {s.email}
                    </GiveText>
                  </SuggestionRow>
                ))}
              </SuggestionsList>
            )}
          </form>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
export default ChangePAHModal;
 
const SuggestionsList = styled(List)(({ theme }) => ({
  marginTop: theme.spacing(1),
  border: `1px solid ${theme.palette.border?.primary}`,
  borderRadius: "12px",
  overflow: "hidden",
  padding: 0,
}));
 
const SuggestionRow = styled(ListItemButton)(() => ({
  display: "flex",
  flexDirection: "column",
  alignItems: "flex-start",
  gap: "2px",
}));