All files / src/components/Merchants/BulkInvite/modals GiveAddInviteModal.tsx

81.91% Statements 77/94
57.37% Branches 35/61
81.25% Functions 26/32
82.75% Lines 72/87

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 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418                                      2x                   2x 4x             2x 79x 79x 79x     79x 79x 79x   79x 31x 22x     22x     22x 3x   22x     79x                     79x   79x 79x   79x   79x 4x                   4x 4x 4x 4x     4x     79x 1x 1x     1x         79x                             79x 1x 1x 1x     79x 1x 1x 1x     79x 1x 1x 1x     79x   79x                                                                                                                       18x 18x 18x   18x 18x   18x             1x                                                                                                                       2x                 18x                                                                                                       1x 1x                 69x                   2x         2x   92x         18x                   2x   347x       69x                 2x 140x 69x                   18x             2x    
import { useRef, useState } from "react";
import { Box, Stack } from "@mui/material";
import { FormProvider, useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import NiceModal from "@ebay/nice-modal-react";
import { TrashIcon } from "@phosphor-icons/react";
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import GiveText from "@shared/Text/GiveText";
import GiveButton from "@shared/Button/GiveButton";
import GiveIconButton from "@shared/IconButton/GiveIconButton";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { styled } from "@theme/v2/Provider";
import { TInviteElement } from "../types";
import { isEmpty } from "lodash";
import { InviteFormFields } from "../components/InviteFormFields";
import { getInviteSchema } from "../utils/validation";
import { useBannerOffset } from "@hooks/common/useBannerOffset";
 
const defaultValues = {
  pahEmail: "",
  merchantName: "",
};
 
type FormValues = {
  pahEmail: string;
  merchantName: string;
};
 
const filterIfExists = (prev: TInviteElement[], newItem: TInviteElement) =>
  prev?.filter((item) => item.merchantName !== newItem.merchantName);
 
interface GiveAddInviteModalProps {
  listItems: TInviteElement[];
  onSubmit: (merchants: TInviteElement[]) => void;
}
 
const GiveAddInvite = ({ listItems, onSubmit }: GiveAddInviteModalProps) => {
  const { open, onClose } = useNiceModal();
  const { isMobileView } = useCustomThemeV2();
  const [merchantsNewList, setMerchantsNewList] = useState<TInviteElement[]>(
    [],
  );
  const [editingIndex, setEditingIndex] = useState<number | null>(null);
  const scrollRef = useRef<HTMLDivElement>(null);
  const formRef = useRef<HTMLDivElement>(null);
 
  const schema = getInviteSchema((value) => {
    if (!value) return true;
    const arr = [...merchantsNewList, ...listItems];
    // If editing, exclude the current item from uniqueness check
    const filteredArr =
      editingIndex !== null
        ? arr.filter((_, idx) => idx !== editingIndex)
        : arr;
    const doesNameExist = filteredArr?.some(
      (item) => item?.merchantName?.toLowerCase() === value?.toLowerCase(),
    );
    return !doesNameExist;
  });
 
  const methods = useForm<FormValues>({
    mode: "onChange",
    resolver: yupResolver(schema),
    defaultValues,
  });
 
  const {
    formState: { isValid, errors },
    handleSubmit,
    reset,
    watch,
  } = methods;
 
  const pahEmail = watch("pahEmail");
  const merchantName = watch("merchantName");
 
  const bannerOffset = useBannerOffset();
 
  const onHandleSubmit = (data: FormValues) => {
    Iif (editingIndex !== null) {
      // Update existing item
      setMerchantsNewList((prev) => {
        const updated = [...prev];
        updated[editingIndex] = { ...data, checked: true };
        return updated;
      });
      setEditingIndex(null);
    } else {
      // Add new item
      setMerchantsNewList((prev) => {
        const newItem = { ...data, checked: true };
        const updatedArray = [...filterIfExists(prev, newItem), newItem];
        return updatedArray;
      });
    }
    reset(defaultValues);
  };
 
  const handleRemoveMerchant = (index: number) => {
    setMerchantsNewList((prev) => prev.filter((_, idx) => idx !== index));
    Iif (editingIndex === index) {
      setEditingIndex(null);
      reset(defaultValues);
    } else Iif (editingIndex !== null && editingIndex > index) {
      setEditingIndex(editingIndex - 1);
    }
  };
 
  const handleSelectMerchant = (index: number) => {
    const merchant = merchantsNewList[index];
    setEditingIndex(index);
    reset({
      pahEmail: merchant.pahEmail,
      merchantName: merchant.merchantName,
    });
    setTimeout(() => {
      formRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      });
    }, 100);
  };
 
  const resetModalState = () => {
    reset(defaultValues);
    setMerchantsNewList([]);
    setEditingIndex(null);
  };
 
  const onFinalSubmit = () => {
    onSubmit(merchantsNewList);
    resetModalState();
    onClose();
  };
 
  const handleCancel = () => {
    reset(defaultValues);
    setMerchantsNewList([]);
    onClose();
  };
 
  const isAddDisabled = !pahEmail || !merchantName || !isValid;
 
  return (
    <GiveBaseModal
      open={open}
      onClose={handleCancel}
      title="Add Invitation"
      width={isMobileView ? "100%" : "720px"}
      sx={{
        "& .MuiPaper-root": {
          height: "auto",
          maxHeight: isMobileView
            ? `calc(100vh - ${bannerOffset + 48}px)`
            : "none",
        },
      }}
      showFooter
      buttons={
        <>
          <GiveButton
            variant="ghost"
            size="large"
            onClick={handleCancel}
            label="Cancel"
            sx={{
              width: "auto !important",
            }}
          />
          <GiveButton
            variant="filled"
            size="large"
            onClick={onFinalSubmit}
            disabled={isEmpty(merchantsNewList)}
            label="Save"
            sx={{
              width: "auto !important",
            }}
          />
        </>
      }
    >
      <Stack
        gap="16px"
        sx={{
          height: "100%",
          minHeight: 0,
          flex: 1,
          display: "flex",
          flexDirection: "column",
        }}
      >
        <GiveText variant="bodyS" color="secondary">
          Please enter the email address to send the invitation and provide the
          merchant's name.
        </GiveText>
 
        <InviteContainer>
          {/* Scrollable Merchant List */}
          {merchantsNewList.length > 0 && (
            <MerchantListWrapper ref={scrollRef}>
              {merchantsNewList.map((item, index) => {
                // Hide the row being edited
                Iif (editingIndex === index) return null;
                const visibleItems = merchantsNewList.filter(
                  (_, i) => i !== editingIndex,
                );
                const visibleIndex = visibleItems.findIndex(
                  (i) => i.merchantName === item.merchantName,
                );
                return (
                  <MerchantRow
                    key={`${item.merchantName}-${index}`}
                    item={item}
                    index={index}
                    isMobileView={isMobileView}
                    onSelect={() => handleSelectMerchant(index)}
                    onDelete={() => handleRemoveMerchant(index)}
                    isFirst={visibleIndex === 0}
                    isLast={visibleIndex === visibleItems.length - 1}
                  />
                );
              })}
            </MerchantListWrapper>
          )}
 
          {/* Input Form - Fixed at bottom */}
          <FormProvider {...methods}>
            <InputFormContainer
              ref={formRef}
              component="form"
              onSubmit={handleSubmit(onHandleSubmit)}
              isMobileView={isMobileView}
              hasItems={
                editingIndex !== null
                  ? merchantsNewList.length > 1
                  : merchantsNewList.length > 0
              }
            >
              <InviteFormFields
                isMobileView={isMobileView}
                errors={errors}
                values={{ pahEmail, merchantName }}
                setValue={methods.setValue}
              />
              <ButtonWrapper isMobileView={isMobileView}>
                <GiveButton
                  variant="filled"
                  color="light"
                  size="large"
                  type="submit"
                  disabled={isAddDisabled}
                  label="Add"
                  sx={{
                    width: isMobileView ? "100%" : "auto",
                    minWidth: "80px",
                  }}
                />
              </ButtonWrapper>
            </InputFormContainer>
          </FormProvider>
        </InviteContainer>
      </Stack>
    </GiveBaseModal>
  );
};
 
interface MerchantRowProps {
  item: TInviteElement;
  index: number;
  isMobileView: boolean;
  onSelect: () => void;
  onDelete: () => void;
  isFirst: boolean;
  isLast: boolean;
}
 
const MerchantRow = ({
  item,
  index,
  isMobileView,
  onSelect,
  onDelete,
  isFirst,
  isLast,
}: MerchantRowProps) => {
  return (
    <MerchantRowContainer
      onClick={onSelect}
      isMobileView={isMobileView}
      isFirst={isFirst}
      isLast={isLast}
    >
      <Stack
        direction={isMobileView ? "column" : "row"}
        alignItems={isMobileView ? "flex-start" : "center"}
        gap={isMobileView ? "4px" : "12px"}
        flex={1}
      >
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <GiveText
            variant="bodyS"
            color="primary"
            sx={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {item.pahEmail}
          </GiveText>
        </Box>
        <Box sx={{ flex: 1, minWidth: 0 }}>
          <GiveText
            variant="bodyS"
            color="secondary"
            sx={{
              overflow: "hidden",
              textOverflow: "ellipsis",
              whiteSpace: "nowrap",
            }}
          >
            {item.merchantName}
          </GiveText>
        </Box>
      </Stack>
      <Box
        sx={{
          display: "flex",
          justifyContent: "flex-end",
          minWidth: isMobileView ? "auto" : "80px",
        }}
      >
        <DeleteButton
          Icon={TrashIcon}
          variant="ghost"
          size="small"
          onClick={(e) => {
            e.stopPropagation();
            onDelete();
          }}
          data-testid={`delete-merchant-${index}`}
        />
      </Box>
    </MerchantRowContainer>
  );
};
 
const InviteContainer = styled(Box)(({ theme }) => ({
  border: `1px solid ${theme.palette.border?.primary}`,
  borderRadius: "12px",
  padding: "20px",
  display: "flex",
  flexDirection: "column",
  flex: 1,
  minHeight: 0,
}));
 
const MerchantListWrapper = styled(Box)({
  flex: 1,
  minHeight: 0,
});
 
const MerchantRowContainer = styled(Box, {
  shouldForwardProp: (prop) =>
    !["isMobileView", "isLast", "isFirst"].includes(prop as string),
})<{
  isMobileView: boolean;
  isFirst: boolean;
  isLast: boolean;
}>(({ theme, isMobileView, isFirst, isLast }) => ({
  display: "flex",
  alignItems: "center",
  justifyContent: "space-between",
  padding: isMobileView ? "20px 0" : "22px 0",
  paddingTop: isFirst ? 0 : isMobileView ? "20px" : "22px",
  borderBottom: isLast ? "none" : `1px solid ${theme.palette.border?.primary}`,
  cursor: "pointer",
}));
 
const InputFormContainer = styled(Box, {
  shouldForwardProp: (prop) =>
    !["isMobileView", "hasItems"].includes(prop as string),
})<{
  isMobileView: boolean;
  hasItems: boolean;
}>(({ theme, isMobileView, hasItems }) => ({
  display: "flex",
  flexDirection: isMobileView ? "column" : "row",
  gap: isMobileView ? "20px" : "12px",
  alignItems: isMobileView ? "stretch" : "flex-start",
  paddingTop: hasItems ? (isMobileView ? "20px" : "16px") : 0,
  borderTop: hasItems ? `1px solid ${theme.palette.border?.primary}` : "none",
}));
 
const ButtonWrapper = styled(Box, {
  shouldForwardProp: (prop) => prop !== "isMobileView",
})<{ isMobileView: boolean }>(({ isMobileView }) => ({
  display: "flex",
  alignItems: "flex-start",
  // Account for label height (23px line height + 8px margin + = 31px) to align button with input field
  paddingTop: isMobileView ? 0 : "31px",
  // Extra 4px on mobile to make gap before button 24px (20px gap + 4px margin)
  marginTop: isMobileView ? "4px" : 0,
  minWidth: isMobileView ? "100%" : "80px",
}));
 
const DeleteButton = styled(GiveIconButton)(({ theme }) => ({
  color: theme.palette.primitive?.error[50],
  "& svg": {
    color: theme.palette.primitive?.error[50],
  },
}));
 
const GiveAddInviteModal = NiceModal.create(GiveAddInvite);
export default GiveAddInviteModal;