All files / src/features/MerchantPortal/Customer/Modals AddEditCustomerModalV2.tsx

0% Statements 0/19
0% Branches 0/28
0% Functions 0/3
0% Lines 0/19

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import NiceModal from "@ebay/nice-modal-react";
import { Grid, Stack } from "@mui/material";
import GiveButton from "@shared/Button/GiveButton";
import GiveBaseModal from "@shared/modals/GiveBaseModal";
import { FormProvider } from "react-hook-form";
import { useCreateEditCustomerV2 } from "features/MerchantPortal/Customer/hooks/useCreateEditCustomerV2";
import FadeUpWrapper from "@components/animation/FadeUpWrapper";
import GiveAvatar from "@shared/Avatar/GiveAvatar";
import GiveLink from "@shared/Link/GiveLink";
import { ArrowLineUpIcon } from "@phosphor-icons/react";
import {
  MAXIMUM_REQUIRED_AGE,
  MINIMUM_REQUIRED_AGE,
} from "@constants/constants";
import { subYears } from "date-fns";
import { HFGiveTelephone } from "@shared/HFInputs/HFGiveTelephone/HFGiveTelephone";
import HFGiveIntegerInput from "@shared/HFInputs/HFGiveInput/HFGiveIntegerInput";
import { HFGiveInput } from "@shared/HFInputs/HFGiveInput/HFGiveInput";
import GiveDivider from "@shared/GiveDivider/GiveDivider";
import GiveTooltip from "@shared/Tooltip/GiveTooltip";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, {
  OPERATIONS,
  UPLOAD_DENY_MESSAGE,
} from "@constants/permissions";
import GiveAlert from "@shared/GiveAlert/GiveAlert";
import { Info } from "@phosphor-icons/react";
import { useGetCustomerById } from "@services/api/customer";
import { Customer } from "@customTypes/customer.types";
import { ControlledDatePicker } from "@sections/PayBuilder/Forms/DateAndLocation/components/ControlledDatePicker";
import { cleanPhoneNumber } from "./utils";
import { useLocation } from "react-router-dom";
 
type TInput = {
  input: React.ReactNode;
  sm?: number;
  md?: number;
  lg?: number;
};
 
const WARNING_ALERT_MESSAGE =
  "The email address provided will be used as the customer's unique identifier in our system.";
 
type TAddEditCustomerModalV2Props = {
  id?: number;
  customerData?: Customer;
  onSuccess?: () => void;
  onCustomerCreated?: (id: number) => void;
};
 
const AddEditCustomerModalV2 = NiceModal.create(
  ({
    id,
    customerData,
    onSuccess,
    onCustomerCreated,
  }: TAddEditCustomerModalV2Props) => {
    const { data } = useGetCustomerById(id);
    const { open, onClose, TransitionProps } = useNiceModal();
 
    const isEditMode = !!id || !!customerData;
 
    const { methods, onSubmit, isDisabled, handleUploadPhoto } =
      useCreateEditCustomerV2({
        isEditMode,
        apiData: data,
        defaultData: customerData,
        onSuccess,
        onCustomerCreated,
      }); // Passing id when editing(From table row)
 
    const {
      reset,
      watch,
      formState: { isDirty, dirtyFields },
    } = methods;
    const values = watch();
 
    const hasEmail = values?.email?.length > 0;
 
    const isAddImageAllowed = useAccessControl({
      resource: RESOURCE_BASE.MEDIA_ITEM,
      operation: OPERATIONS.CREATE,
      withPortal: true,
    });
 
    const location = useLocation();
 
    const handleClose = () => {
      reset();
      onClose();
    };
 
    //this is to understand if fields are actually dirty
    //becuase we apply formating on phone, it becomes dirty even if we chnage back to original
    const isReallyDirty =
      dirtyFields.phone &&
      Object.values(dirtyFields).filter(Boolean)?.length === 1
        ? ![data?.phoneNumber, customerData?.phoneNumber].includes(
            cleanPhoneNumber(values.phone),
          )
        : isDirty;
 
    const shouldDisableSaveButton = isEditMode && !isReallyDirty;
 
    const inputList: TInput[] = [
      {
        input: (
          <HFGiveInput
            id="firstName"
            label="First Name (Optional)"
            name="firstName"
          />
        ),
      },
      {
        input: (
          <HFGiveInput
            id="lastName"
            label="Last Name (Optional)"
            name="lastName"
          />
        ),
      },
      {
        input: <HFGiveInput id="email" label="Email" name="email" />,
      },
      {
        input: (
          <ControlledDatePicker
            name="dateOfBirth"
            label="Date of Birth (Optional)"
            minDate={subYears(new Date(), MAXIMUM_REQUIRED_AGE)}
            maxDate={subYears(new Date(), MINIMUM_REQUIRED_AGE)}
            defaultPickerValue={subYears(new Date(), MINIMUM_REQUIRED_AGE)}
            disableFuture
            useUTCMoment
          />
        ),
      },
      {
        input: (
          <HFGiveTelephone
            name="phone"
            label="Customer Phone Number (Optional)"
          />
        ),
        sm: 12,
        md: 12,
        lg: 12,
      },
      {
        input: <GiveDivider sx={{ my: "8px" }} />,
        sm: 12,
        md: 12,
        lg: 12,
      },
      {
        input: (
          <HFGiveInput
            id="occupation"
            label="Occupation (Optional)"
            name="occupation"
          />
        ),
      },
      {
        input: (
          <HFGiveInput
            id="employer"
            label="Employer (Optional)"
            name="employer"
          />
        ),
      },
      {
        input: (
          <HFGiveInput
            id="line1"
            label="Street Address (Optional)"
            name="address.line1"
          />
        ),
        sm: 12,
        md: 12,
        lg: 12,
      },
      {
        input: (
          <HFGiveInput
            data-testid="city-input"
            id="city"
            label="City (Optional)"
            name="address.city"
          />
        ),
        sm: 12,
        md: 4,
        lg: 4,
      },
      {
        input: (
          <HFGiveInput
            data-testid="state-input"
            id="state"
            label="State (Optional)"
            name="address.state"
          />
        ),
        sm: 12,
        md: 4,
        lg: 4,
      },
      {
        input: (
          <HFGiveIntegerInput
            data-testid="zip-input"
            label="ZIP (Optional)"
            name="address.zip"
          />
        ),
        sm: 12,
        md: 4,
        lg: 4,
      },
      {
        input: (
          <HFGiveInput
            id="notes"
            name="notes"
            label="Notes (Optional)"
            placeholder=" " //if we use `hidePlaceholder` prop, the border color won't be correct
            multiline
            rows={6}
            fullWidth
            inputProps={{
              maxLength: "200",
            }}
            helperText={`${values.notes.length}/200`}
          />
        ),
        sm: 12,
        md: 12,
        lg: 12,
      },
    ];
 
    return (
      <GiveBaseModal
        open={open}
        title={`${isEditMode ? "Edit" : "Add"} Customer`}
        width="640px"
        onClose={handleClose}
        TransitionProps={TransitionProps}
        buttons={
          <>
            <GiveButton
              variant="ghost"
              size="large"
              label="Cancel"
              onClick={handleClose}
              sx={{
                width: "auto !important",
              }}
            />
 
            <GiveButton
              size="large"
              variant="filled"
              label={isEditMode ? "Save" : "Add Customer"}
              type="submit"
              form="add-customer-form"
              disabled={isDisabled || !hasEmail || shouldDisableSaveButton}
              sx={{
                border: "none",
                width: "auto !important",
              }}
            />
          </>
        }
      >
        <FormProvider {...methods}>
          <FadeUpWrapper delay={100}>
            <Stack
              component="form"
              id="add-customer-form"
              onSubmit={methods.handleSubmit(onSubmit)}
              gap={3}
            >
              <GiveAlert
                type="default"
                label={WARNING_ALERT_MESSAGE}
                Icon={<Info />}
                sx={{
                  alignItems: "flex-start",
                }}
              />
              <Stack direction="row" gap="16px" alignItems="center">
                <GiveAvatar
                  size="56px"
                  imageUrl={
                    values.avatarURL
                      ? typeof values.avatarURL === "string"
                        ? `${values.avatarURL}/thumb`
                        : URL.createObjectURL(values.avatarURL)
                      : ""
                  }
                  name={`${values.firstName} ${values.lastName}`}
                />
                <GiveTooltip
                  title={UPLOAD_DENY_MESSAGE}
                  color="default"
                  disableHoverListener={isAddImageAllowed}
                  sx={{
                    width: "auto",
                  }}
                >
                  <GiveLink
                    Icon={ArrowLineUpIcon}
                    color="secondary"
                    sx={{ alignItems: "center" }}
                    link={`${location.pathname}${location.search}`}
                    disabled={!isAddImageAllowed}
                    onClick={handleUploadPhoto}
                  >
                    Upload Photo
                  </GiveLink>
                </GiveTooltip>
              </Stack>
              <Grid container spacing={2.5}>
                {inputList.map(({ input, sm, md, lg }, index) => (
                  <Grid
                    key={index}
                    item
                    xs={12}
                    sm={sm || 6}
                    md={md || sm || 6}
                    lg={lg || md || sm || 6}
                  >
                    {input}
                  </Grid>
                ))}
              </Grid>
            </Stack>
          </FadeUpWrapper>
        </FormProvider>
      </GiveBaseModal>
    );
  },
);
 
export default AddEditCustomerModalV2;