All files / src/shared/GiveTimezoneDatePicker GiveTimezoneDatePicker.tsx

79.24% Statements 42/53
62.79% Branches 27/43
78.94% Functions 15/19
79.16% Lines 38/48

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                                            25x                             117x 117x 117x 117x                 117x   117x 117x   117x 1x   117x 14x   4788x           117x   14x 4788x         117x                                       117x                             1x 1x                                                                                                                                     25x 30x 30x                 25x 14x     38x   38x             19x 19x             19x 11x       19x   19x   17x 17x   17x       17x             17x    
import { Stack } from "@mui/material";
import { ControlledDatePicker } from "@sections/PayBuilder/Forms/DateAndLocation/components/ControlledDatePicker";
import GiveButton from "@shared/Button/GiveButton";
import ContextualMenu from "@shared/ContextualMenu/ContextualMenu";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { useForm, FormProvider, useWatch } from "react-hook-form";
import * as yup from "yup";
import { yupResolver } from "@hookform/resolvers/yup";
import { VALIDATION_MESSAGES } from "@validation/messages";
import { endOfDay, startOfDay } from "date-fns";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { useMemo, useState } from "react";
import { getFullTimeZonesMomentAll } from "@utils/timezones";
import HFGiveSelect from "@shared/HFInputs/HFGiveSelect/HFGiveSelect";
import moment from "moment";
 
export type FormValuesGiveDatePickerModal = {
  timeZone: string;
  startDate: Date;
  endDate: Date;
};
 
const today = new Date();
 
type Props = {
  anchorEl: HTMLElement | null;
  handleClose: (data?: FormValuesGiveDatePickerModal) => void;
  width?: number;
  hideTimezone?: boolean;
};
 
function GiveTimezoneDatePicker({
  anchorEl,
  handleClose,
  width,
  hideTimezone,
}: Props) {
  const { isMobileView } = useCustomThemeV2();
  const [searchValue, setSearchValue] = useState("");
  const schema = useMemo(() => makeSchema(!!hideTimezone), [hideTimezone]);
  const methods = useForm<FormValuesGiveDatePickerModal>({
    resolver: yupResolver(schema),
    defaultValues: {
      timeZone: PLATFORM_TIMEZONE,
      startDate: startOfDay(new Date()),
      endDate: endOfDay(new Date()),
    },
  });
 
  const { handleSubmit, control, setValue } = methods;
 
  const startDate = useWatch({ control, name: "startDate" });
  const endDate = useWatch({ control, name: "endDate" });
 
  const onSubmit = (data: FormValuesGiveDatePickerModal) => {
    handleClose(data);
  };
  const timezoneOptions = useMemo(() => {
    const timezones = getFullTimeZonesMomentAll();
 
    return timezones?.map((item, key) => ({
      label: `GMT${item.gmt} ${item.timezone}`,
      id: key,
      value: item.timezone.toLowerCase(),
    }));
  }, []);
  const filteredOptions = useMemo(
    () =>
      timezoneOptions.filter((item) =>
        item?.label?.toLowerCase().includes(searchValue.toLowerCase()),
      ),
    [searchValue],
  );
 
  const contextualMenuProps = {
    searchBarProps: {
      handleChange: (val: string) => setSearchValue(val),
      value: searchValue,
    },
    onCloseEmptyState: () => setSearchValue(""),
    emptySection: "empty-search",
    height: "236px",
    anchorOrigin: {
      vertical: 45,
      horizontal: "left",
    },
    ...(!isMobileView
      ? {
          color: "tertiary",
          texture: "blurred",
          menuWidth: width || 470,
        }
      : {}),
  };
  return (
    <ContextualMenu
      handleClose={handleClose}
      anchorEl={anchorEl}
      color={isMobileView ? "primary" : "tertiary"}
      texture={isMobileView ? "solid" : "blurred"}
      options={[]}
      anchorOriginVertical="top"
      horizontalOrigin="left"
      transformOriginVertical="bottom"
      menuWidth={width || 314}
      customContent={
        <FormProvider {...methods}>
          <form
            onSubmit={(e) => {
              e.stopPropagation();
              handleSubmit(onSubmit)(e);
            }}
            style={{ width: "100%" }}
          >
            <Stack
              alignItems="center"
              gap="8px"
              width={isMobileView ? "100%" : "314px"}
              padding="20px 16px"
            >
              {!hideTimezone && (
                <HFGiveSelect
                  placeholder="Timezone"
                  useContextualMenu
                  fullWidth
                  defaultValue={timezoneOptions?.[0]?.value}
                  label="Timezone"
                  options={filteredOptions}
                  name="timeZone"
                  contextualMenuProps={contextualMenuProps as any}
                  onChange={(e) =>
                    setValue("timeZone", e.target.value.toString(), {
                      shouldValidate: true,
                    })
                  }
                />
              )}
              <ControlledDatePicker
                label="Start"
                name="startDate"
                isValidateForm
                placeholder="Start Date"
                maxDate={endDate || today}
                useUTCMoment
              />
              <ControlledDatePicker
                label="End"
                name="endDate"
                isValidateForm
                placeholder="End Date"
                minDate={startDate || undefined}
                maxDate={today}
                useUTCMoment
              />
              <GiveButton
                type="submit"
                fullWidth
                style={{
                  height: "42px",
                  borderRadius: "40px",
                  marginTop: "4px",
                }}
                size="medium"
                label="Apply"
                data-testid="apply-button"
              />
            </Stack>
          </form>
        </FormProvider>
      }
      isMultiSelect
    />
  );
}
 
export default GiveTimezoneDatePicker;
 
const isValideDate = (value: any, format = "MM/DD/YYYY") => {
  Eif (value instanceof Date && !isNaN(value.getTime())) {
    return value.getFullYear() > 1924;
  }
  if (typeof value === "string") {
    const momentDate = moment(value, format, true);
    return momentDate.isValid() && momentDate.year() > 1924;
  }
 
  return false;
};
const makeSchema = (hideTimezone: boolean) =>
  yup
    .object({
      timeZone: yup.string().when([], {
        is: () => !hideTimezone,
        then: (s) => s.required(VALIDATION_MESSAGES.REQUIRED),
        otherwise: (s) => s.optional(),
      }),
 
      startDate: yup
        .mixed()
        .required(VALIDATION_MESSAGES.REQUIRED)
        .test("is-valid-date", "Invalid date format", (value) => {
          Iif (!value) return false;
          return isValideDate(value);
        }),
 
      endDate: yup
        .mixed()
        .required(VALIDATION_MESSAGES.REQUIRED)
        .test("is-valid-date", "Invalid date format", (value) => {
          if (!value) return false;
          return isValideDate(value);
        }),
    })
    .test("date-order", "", (values, ctx) => {
      const { startDate, endDate } = values || {};
 
      if (!startDate || !endDate) return true;
 
      const start = new Date(startDate);
      const end = new Date(endDate);
 
      Iif (isNaN(start.getTime()) || isNaN(end.getTime())) {
        return true;
      }
 
      Iif (start > end) {
        return ctx.createError({
          path: "endDate",
          message: "End date cannot be before start date",
        });
      }
 
      return true;
    });