All files / src/features/Minibuilders/EventsMinibuilder EventPayment.tsx

0% Statements 0/68
0% Branches 0/28
0% Functions 0/24
0% Lines 0/60

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         
import { useCallback, useEffect, useState } from "react";
import { Stack } from "@mui/material";
import { useFormContext } from "react-hook-form";
import { ModalSectionTitleProps } from "../atoms";
import {
  PaymentStepSection,
  AmountItem,
  AddAmountButton,
} from "../recurrence.atoms";
import {
  DndContext,
  closestCorners,
  MouseSensor,
  TouchSensor,
  useSensor,
  useSensors,
  DragStartEvent,
  DragEndEvent,
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { restrictToParentElement } from "@dnd-kit/modifiers";
import { PlusIcon } from "@assets/icons/RebrandedIcons";
import { palette } from "@palette";
import {
  DELETE_CONFIRMATION_MODAL,
  MINIBUILDER_CREATE_AMOUNT,
} from "modals/modal_names";
import NiceModal from "@ebay/nice-modal-react";
import { AmountType } from "./types";
import FadeUpWrapper from "@components/animation/FadeUpWrapper";
import {
  composePermission,
  useAccessControl,
} from "features/Permissions/AccessControl";
import RESOURCE_BASE, {
  CREATE_DENY_MESSAGE,
  OPERATIONS,
} from "@constants/permissions";
import { CustomToolTip } from "@common/BusinessOwners/CustomToolTip";
 
type FundraisersAboutProps = ModalSectionTitleProps & {
  isEdit?: boolean;
};
 
const EventPayment = ({
  title,
  titleSize = "large",
  isEdit = false,
}: FundraisersAboutProps) => {
  const { watch } = useFormContext();
  const values = watch();
 
  const amountsList = values.payment_set_up.amountsList;
 
  return (
    <Stack width="100%" direction="column" gap={isEdit ? 2 : 3}>
      <FadeUpWrapper delay={200}>
        <PaymentStepSection
          title="Payment amounts"
          description="Provide preset amounts for customers to pick."
        >
          <AmountList list={amountsList} />
        </PaymentStepSection>
      </FadeUpWrapper>
    </Stack>
  );
};
 
const AmountList = ({ list }: { list: AmountType[] }) => {
  const { setValue } = useFormContext();
 
  const [activeId, setActiveId] = useState<any>(null);
  const [lastActive, setLastActive] = useState<string>("");
 
  const sensors = useSensors(useSensor(MouseSensor), useSensor(TouchSensor));
  const handleDragStart = useCallback((event: DragStartEvent) => {
    setActiveId(event.active.id);
  }, []);
 
  useEffect(() => {
    const activeList = list.filter((v: any) => v.active);
 
    if (activeList.length === 1) {
      setLastActive(activeList[0].id);
    } else {
      setLastActive("");
    }
  }, [list]);
 
  const handleDragEnd = (event: DragEndEvent) => {
    const { active, over } = event;
 
    if (active.id !== over?.id) {
      const oldIndex = list.findIndex((x: any) => x.id === active.id);
      const newIndex = list.findIndex((x: any) => x.id === over?.id);
 
      const newList = arrayMove(list, oldIndex, newIndex);
 
      setValue("payment_set_up.amountsList", newList, { shouldDirty: true });
    }
    setActiveId(null);
  };
 
  const handleDragCancel = useCallback(() => {
    setActiveId(null);
  }, []);
 
  // changes the amount item status to active
  const handleShowAmountItem = (id: string) => {
    const newList = list.map((element: AmountType) =>
      element.id === id
        ? Object.assign({}, element, { active: !element.active })
        : element,
    );
    setValue("payment_set_up.amountsList", newList, { shouldDirty: true });
  };
 
  const onCloseModal = (item?: AmountType) => {
    if (!item) return;
 
    const amount = list.findIndex((element) => element.id === item.id);
    let newList = list;
    if (amount !== -1) {
      newList = list.map((element: AmountType) => {
        return element.id === item.id ? item : element;
      });
    } else {
      newList.push(item);
    }
    setValue("payment_set_up.amountsList", newList, { shouldDirty: true });
  };
 
  const handleRemoveAmountItem = (id: string) => {
    NiceModal.show(DELETE_CONFIRMATION_MODAL, {
      variant: "amount",
      deleteHandler: () => {
        const newList = list.filter((item) => item.id !== id);
        setValue("payment_set_up.amountsList", newList, { shouldDirty: true });
      },
    });
  };
 
  const hasUniqueTitle = (title: string, id?: string) => {
    const isNotUnique = list.some(
      (amount) => id !== amount.id && amount.title === title,
    );
    return !isNotUnique;
  };
 
  const createAmount = () => {
    NiceModal.show(MINIBUILDER_CREATE_AMOUNT, {
      onClose: onCloseModal,
      onDelete: handleRemoveAmountItem,
      variant: "ticket",
      hasUniqueTitle,
    });
  };
 
  const editAmount = (id: string, isLastActive?: boolean) => {
    const amount = list.find((element) => element.id === id);
 
    if (!amount) return;
    NiceModal.show(MINIBUILDER_CREATE_AMOUNT, {
      onClose: onCloseModal,
      item: amount,
      ...(!isLastActive && {
        onDelete: handleRemoveAmountItem,
      }),
      variant: "ticket",
      hasUniqueTitle,
    });
  };
 
  const isCreateAllowed = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.MERCHANT,
      RESOURCE_BASE.PRODUCT,
      RESOURCE_BASE.AMOUNT,
    ),
    operation: OPERATIONS.CREATE,
  });
 
  return (
    <div>
      <DndContext
        sensors={sensors}
        collisionDetection={closestCorners}
        onDragStart={handleDragStart}
        onDragEnd={handleDragEnd}
        onDragCancel={handleDragCancel}
        modifiers={[restrictToParentElement]}
      >
        <SortableContext items={list} strategy={verticalListSortingStrategy}>
          <Stack gap={1}>
            {list.map((item: AmountType) => {
              const { id, active } = item;
              const isDisabled = list.length === 1 || lastActive === id;
 
              return (
                <AmountItem
                  key={id}
                  amountItem={item}
                  showAmountItem={handleShowAmountItem}
                  isDisabled={isDisabled}
                  checked={list.length === 1 && !active ? true : active}
                  isDraggable={list.length > 1}
                  onClick={() => editAmount(id, isDisabled)}
                  showCount
                />
              );
            })}
            <CustomToolTip
              showToolTip={!isCreateAllowed}
              message={CREATE_DENY_MESSAGE}
            >
              <AddAmountButton
                onClick={createAmount}
                disabled={!isCreateAllowed}
                textColor={palette.black[100]}
              >
                Add Ticket{" "}
                <PlusIcon stroke={palette.black[100]} height={20} width={20} />
              </AddAmountButton>
            </CustomToolTip>
          </Stack>
        </SortableContext>
      </DndContext>
    </div>
  );
};
 
export default EventPayment;