All files / src/sections/PayBuilder/Forms/About/Invoice InvoiceCustomerSection.tsx

53.48% Statements 23/43
41.17% Branches 14/34
35.71% Functions 5/14
56.41% Lines 22/39

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                                    2x 2x 2x   2x 2x 2x   2x   2x                 2x   2x 2x   2x                       2x 2x       2x 2x     2x 2x                   2x             2x             2x                                                                                                                                                   46x                                                    
import NiceModal from "@ebay/nice-modal-react";
import { Stack } from "@mui/material";
import {
  PencilSimpleIcon,
  PlusIcon,
  UserListIcon,
} from "@phosphor-icons/react";
import { usePayBuilderForm } from "@sections/PayBuilder/provider/PayBuilderFormProvider";
import { useGetInfiniteCustomers } from "@services/api/customer";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import GiveText from "@shared/Text/GiveText";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { MERCHANT_ADD_EDIT_CUSTOMER_V2 } from "modals/modal_names";
import { useEffect, useMemo, useRef, useState } from "react";
import GiveEmptyStateWrapper from "@shared/EmptyState/GiveEmptyStateWrapper";
import { useQueryClient } from "react-query";
 
function InvoiceCustomerSection() {
  const [page, setPage] = useState(1);
  const queryClient = useQueryClient();
  const [searchValue, setSearchValue] = useState("");
  const { customers, isLoading, fetchNextPage, hasNextPage, refetch } =
    useGetInfiniteCustomers({ searchQuery: searchValue });
  const { methods, customer } = usePayBuilderForm();
  const customerId = methods.watch("About.customerId");
 
  const childRef = useRef<any>(null);
 
  const setNextPage = async () => {
    if (hasNextPage && !isLoading) {
      const newPage = page + 1;
      const { isSuccess } = await fetchNextPage({
        pageParam: newPage,
      });
      if (isSuccess) setPage(newPage);
    }
  };
  const { isMobileView } = useCustomThemeV2();
 
  const options = useMemo(() => {
    Iif (!customers) return [];
 
    return customers.map((item: any) => {
      return {
        value: String(item.id),
        label: item.firstName
          ? `${item.firstName} ${item.lastName}`
          : item.email,
        description: item.email,
        hidden: false,
      };
    });
  }, [customers]);
 
  const selectedCustomer = useMemo(() => {
    Eif (!customerId) return null;
    return customers.find((item) => item.id == customerId);
  }, [customerId, customers]);
 
  useEffect(() => {
    selectedCustomer && methods.trigger("About.customerId");
  }, [selectedCustomer]);
 
  useEffect(() => {
    Iif (customer?.id) {
      methods.setValue("About.customerId", customer.id, {
        shouldValidate: true,
      });
 
      // Force dropdown to show correct result
      customer?.firstName && setSearchValue(customer.firstName);
    }
  }, []);
 
  const handleRefetch = () => {
    refetch();
    queryClient.invalidateQueries([
      "customer",
      selectedCustomer?.id?.toString(),
    ]);
  };
  const onCustomerCreated = (id: number) => {
    methods.setValue("About.customerId", id, { shouldValidate: true });
    if (childRef.current) {
      childRef.current.closeMenu();
    }
  };
 
  return (
    <Stack spacing={2}>
      <Stack direction="row" spacing={2}>
        <UserListIcon size={24} />
        <GiveText variant="bodyL" color="primary">
          Customer
        </GiveText>
      </Stack>
      <Stack direction="row" alignItems="center" spacing={1}>
        <HFGiveSelect
          name="About.customerId"
          placeholder="Find or create a customer"
          options={options}
          useContextualMenu
          value={String(selectedCustomer?.id ?? "")}
          withIconOffset={false}
          contextualMenuProps={
            {
              ...(!isMobileView
                ? {
                    height: "320px",
                    anchorOrigin: {
                      vertical: 55,
                      horizontal: "left",
                    },
                    transformOrigin: {
                      vertical: "top",
                      horizontal: "left",
                    },
                    color: "tertiary",
                    texture: "blurred",
                  }
                : { height: "240px" }),
              searchBarProps: {
                hideUI: !options.length && !searchValue.length,
                value: searchValue,
                handleChange: (val: string) => setSearchValue(val),
              },
 
              emptySection: "customers-list",
              optionsHeader: options.length ? (
                <CreateCustomer onCustomerCreated={onCustomerCreated} />
              ) : options.length || searchValue.length ? null : (
                <GiveEmptyStateWrapper
                  isEmpty
                  section={"customers-list"}
                  giveEmptyStateSx={{
                    paddingBottom: 2,
                  }}
                />
              ),
              onEndReached: setNextPage,
            } as any
          }
          ref={childRef}
        />
        {Boolean(selectedCustomer) && (
          <PencilSimpleIcon
            style={{ cursor: "pointer" }}
            onClick={() => {
              NiceModal.show(MERCHANT_ADD_EDIT_CUSTOMER_V2, {
                id: selectedCustomer.id,
                customerdata: selectedCustomer,
                onSuccess: handleRefetch,
              });
            }}
            size={20}
          />
        )}
      </Stack>
    </Stack>
  );
}
 
const CreateCustomer = ({
  onCustomerCreated,
}: {
  onCustomerCreated: (id: number) => void;
}) => {
  return (
    <Stack
      direction="row"
      alignItems="center"
      spacing={1}
      onClick={() => {
        NiceModal.show(MERCHANT_ADD_EDIT_CUSTOMER_V2, {
          onCustomerCreated,
        });
      }}
      sx={{ cursor: "pointer", padding: "8px 10px" }}
    >
      <PlusIcon size={20} />
      <GiveText variant="bodyS" color="primary">
        Create New Customer
      </GiveText>
    </Stack>
  );
};
 
export default InvoiceCustomerSection;