All files / src/features/Minibuilders/MembershipsMinibuilder CreateMembershipsModal.tsx

7.93% Statements 5/63
0% Branches 0/22
0% Functions 0/16
8.19% Lines 5/61

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                                      2x                 2x                         2x                                                   2x           2x                                                                                                                                                                                                                                                                                                                        
import { useEffect, useRef, useState } from "react";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import ModalDrawer from "@common/Modal/ModalDrawer/ModalDrawer";
import FundraisersAbout from "../FundraisersAbout";
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
import { TFundraiserModalInputs } from "./types";
import { yupResolver } from "@hookform/resolvers/yup";
import {
  FundraiserModalSchema as schema,
  FundraiserModalDefaults as defaultValues,
} from "./utils";
import { Box } from "@mui/material";
import MembershipsPayment from "./MembershipsPayment";
import StyleSection from "../StyleSection";
import { useCreateProduct } from "../hooks";
import MembershipsConfiguration from "./MembershipsConfiguration";
import { useCalculatePercentage } from "@common/SignUp/useCalculatePercentage";
import { cloneDeep, isEqual } from "lodash";
 
const STEPS_OBJ = {
  ABOUT: "About",
  STYLE: "Style",
  PAYMENT_SETUP: "Payment set up",
  CONFIGURATION: "Configuration",
} as const;
 
type TStepsLabel = "About" | "Style" | "Payment set up" | "Configuration";
 
const getSchemaObject = (step: TStepsLabel) => {
  switch (step) {
    case "About":
      return "about";
    case "Style":
      return "style";
    case "Payment set up":
      return "payment_set_up";
    case "Configuration":
      return "configuration";
  }
};
 
const initialSteps = [
  {
    label: STEPS_OBJ.ABOUT,
    barValue: 0,
  },
  {
    label: STEPS_OBJ.STYLE,
    barValue: 0,
  },
  {
    label: STEPS_OBJ.PAYMENT_SETUP,
    barValue: 0,
  },
  {
    label: STEPS_OBJ.CONFIGURATION,
    barValue: 0,
  },
];
 
const initialStatus: {
  step: TStepsLabel;
  enabledSteps: TStepsLabel[];
  steps: {
    label: TStepsLabel;
    barValue: number;
  }[];
} = {
  step: STEPS_OBJ.ABOUT,
  enabledSteps: [],
  steps: initialSteps,
};
 
const CreateMembershipsModal = NiceModal.create(() => {
  const { submitProduct } = useCreateProduct("membership");
  const valuesRef = useRef<any>(null);
  const { calculatePercentageNested } = useCalculatePercentage({
    isEdit: false,
  });
 
  const [{ steps, step, enabledSteps }, setStatusBar] = useState(initialStatus);
 
  const modal = useModal();
 
  const methods = useForm<TFundraiserModalInputs>({
    mode: "onChange",
    resolver: yupResolver(schema),
    defaultValues,
  });
  const { reset, watch, trigger } = methods;
  const values = watch();
 
  useEffect(() => {
    if (step === STEPS_OBJ.STYLE || step === STEPS_OBJ.CONFIGURATION) {
      setStatusBar((prev) => {
        const array = prev.steps;
        const indexToUpdate = array.findIndex(
          (item) => item.label === prev.step,
        );
        array[indexToUpdate] = { ...array[indexToUpdate], barValue: 100 };
        enabledSteps.push(prev.step);
 
        return {
          ...prev,
          steps: array,
          enabledSteps,
        };
      });
    }
  }, [step]);
 
  useEffect(() => {
    if (isEqual(valuesRef.current, values)) return;
    valuesRef.current = cloneDeep(values);
    (async () => {
      const count =
        step === STEPS_OBJ.STYLE
          ? 100
          : await calculatePercentageNested(
              schema,
              values,
              getSchemaObject(step),
            );
 
      setStatusBar((prev) => {
        const array = prev.steps;
        const indexToUpdate = array.findIndex(
          (item) => item.label === prev.step,
        );
        array[indexToUpdate] = { ...array[indexToUpdate], barValue: count };
        const enabledSteps = prev?.enabledSteps;
        const addedIndex = enabledSteps.indexOf(prev.step);
        if (addedIndex !== -1 && count < 100) {
          enabledSteps.splice(addedIndex, 1);
        } else if (addedIndex === -1 && count >= 100) {
          enabledSteps.push(prev.step);
        }
 
        return {
          ...prev,
          steps: array,
          enabledSteps,
        };
      });
    })();
  }, [values, step]);
 
  const resetModal = () => {
    setStatusBar({
      ...initialStatus,
      steps: initialSteps.map((step) => ({ ...step, barValue: 0 })),
      enabledSteps: [],
    });
    reset();
    valuesRef.current = null;
  };
 
  const onClose = () => {
    modal.hide();
    resetModal();
  };
 
  const validateCurrentStep = () => {
    trigger("about.title");
  };
 
  const UISteps = {
    [STEPS_OBJ.ABOUT]: (
      <FundraisersAbout
        title="Tell us more about your Membership"
        placeHolderText="What’s the purpose of this membership?"
        fontSize="32px"
        mobileFontSize="24px"
      />
    ),
    [STEPS_OBJ.STYLE]: <StyleSection title="Make it unique" />,
    [STEPS_OBJ.PAYMENT_SETUP]: (
      <MembershipsPayment title="Set up Subscriptions" />
    ),
    [STEPS_OBJ.CONFIGURATION]: (
      <MembershipsConfiguration title="Configuration" />
    ),
  };
 
  const setCurrentStep = (activeStep: TStepsLabel) =>
    setStatusBar((prev) => ({
      ...prev,
      step: activeStep,
    }));
 
  const onSubmit: SubmitHandler<TFundraiserModalInputs> = async (data) => {
    submitProduct(data as any);
    onClose();
  };
 
  return (
    <ModalDrawer
      onModalClose={onClose}
      setCurrentStep={setCurrentStep}
      steps={steps}
      currentStep={step}
      HeaderProps={{
        title: "Create Membership",
      }}
      primaryAction={{
        onClick: validateCurrentStep,
        disabled: !enabledSteps.includes(step),
        label: "Next",
        type: step === "Configuration" ? "submit" : undefined,
        form: "create-membership",
        key: step,
      }}
    >
      <FormProvider {...methods}>
        <Box
          component="form"
          flexGrow={1}
          display="flex"
          id="create-membership"
          onSubmit={methods.handleSubmit(onSubmit)}
        >
          {UISteps[step]}
        </Box>
      </FormProvider>
    </ModalDrawer>
  );
});
 
export default CreateMembershipsModal;