All files / src/features/Settlements/components DateSelectDropdownButton.tsx

1.88% Statements 1/53
0% Branches 0/36
0% Functions 0/10
1.96% Lines 1/51

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                                                1x                                                                                                                                                                                                                                                                                                                                                                                  
import { useState } from "react";
import { CaretDownIcon, CaretUpIcon } from "@phosphor-icons/react";
import DatePicker from "@common/DatePickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterDateFns } from "@mui/x-date-pickers/AdapterDateFns";
import { Picker } from "@shared/DatePicker/Picker";
import { ClickAwayListener, type PopperProps } from "@mui/material";
import { useCustomThemeV2 } from "@theme/hooks/useCustomThemeV2";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
  selectDateFilter,
  setSelectedDate,
} from "@redux/slices/merchantFilters";
import {
  CANARY_TZ,
  formatInCanaryMoment,
  formatInUTCMoment,
  useFormatDateInTimezone,
} from "@utils/date.helpers";
import { endOfDay } from "date-fns";
import { zonedTimeToUtc } from "date-fns-tz";
import moment, { Moment } from "moment";
import { StyledButton } from "../styles";
 
const DateSelectDropdownButton = ({
  disabled,
  useCanaryTime,
}: {
  disabled?: boolean;
  useCanaryTime?: boolean;
}) => {
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
  const [open, setOpen] = useState(false);
  const [tempValue, setTempValue] = useState<any>(null);
 
  const { isMobileView } = useCustomThemeV2();
  const dispatch = useAppDispatch();
  const { formatInTimezone, currentTimezone } = useFormatDateInTimezone();
  const queryKey = "settlement-date";
  const useTimezone = true;
  const selectedDate = useAppSelector((state) =>
    selectDateFilter(state, queryKey),
  );
  const usedTimezone =
    useTimezone && useCanaryTime ? CANARY_TZ : currentTimezone;
 
  const currentValue = (() => {
    if (!selectedDate) return "";
    if (!useTimezone) return new Date(selectedDate);
    const date = new Date(selectedDate);
    const inTimeZone =
      (useCanaryTime ? formatInCanaryMoment(date) : formatInTimezone(date)) ||
      "";
    return new Date(inTimeZone);
  })();
 
  const handleButtonClick = (e: React.MouseEvent<HTMLElement>) => {
    if (isMobileView) {
      setTempValue(currentValue);
      setOpen(true);
    } else {
      setAnchorEl(e.currentTarget);
    }
  };
 
  const handleAccept = (value: Moment | Date | string | null) => {
    if (!value) {
      setAnchorEl(null);
      setOpen(false);
      return;
    }
 
    // Convert value to Date object (handles Moment, Date, or formatted string like "MM/dd/yyyy")
    let originalDate: Date;
    if (moment.isMoment(value)) {
      originalDate = value.toDate();
    } else if (value instanceof Date) {
      originalDate = value;
    } else if (typeof value === "string") {
      // Handle formatted date string (e.g., "12/06/2025" from CustomActions when useUTCMoment is false)
      // Parse the string as a date in the local timezone
      const [month, day, year] = value.split("/");
      //string uses 1-based months (1–12) but Date expects 0-based (0–11), subtract 1:
      originalDate = new Date(
        parseInt(year),
        parseInt(month) - 1,
        parseInt(day),
      );
    } else {
      originalDate = new Date(value);
    }
 
    let isoDate: string;
    if (useTimezone && usedTimezone) {
      const startOfDayInTimezone = endOfDay(originalDate);
      isoDate = zonedTimeToUtc(
        startOfDayInTimezone,
        usedTimezone,
      ).toISOString();
    } else {
      isoDate = originalDate.toISOString();
    }
 
    dispatch(setSelectedDate({ queryKey, value: isoDate }));
    setAnchorEl(null);
    setOpen(false);
  };
  const label = formatInUTCMoment(selectedDate, "MMM DD, YYYY");
 
  return (
    <LocalizationProvider dateAdapter={AdapterDateFns}>
      {isMobileView ? (
        <Picker
          onOpen={() => setOpen(true)}
          onClose={() => setOpen(false)}
          handleClickAccept={handleAccept}
          label={undefined}
          minDate={null}
          maxDate={moment()}
          field={{ value: tempValue ?? currentValue, onChange: setTempValue }}
          defaultValue={null}
          disablePast={false}
          disableFuture={true}
          disabled={disabled}
          name="settlement-date"
          hidePlaceholder
          renderInput={(params: any) => (
            <StyledButton
              variant="filled"
              size="large"
              {...params}
              label={label}
              endIcon={
                open ? <CaretUpIcon size={16} /> : <CaretDownIcon size={16} />
              }
            />
          )}
        />
      ) : (
        <>
          <ClickAwayListener
            onClickAway={() => {
              setAnchorEl(null);
              setOpen(false);
            }}
          >
            <div>
              <DatePicker
                value={currentValue}
                onChange={handleAccept}
                minDate={null}
                maxDate={moment()}
                disableFuture
                popperPlacement="bottom-start"
                renderInput={() => (
                  <StyledButton
                    variant="filled"
                    label={label}
                    size="large"
                    onClick={handleButtonClick}
                    endIcon={
                      anchorEl ? (
                        <CaretUpIcon size={16} />
                      ) : (
                        <CaretDownIcon size={16} />
                      )
                    }
                  />
                )}
                popperProps={
                  {
                    anchorEl: anchorEl ? anchorEl : undefined,
                    open: Boolean(anchorEl),
                    placement: "bottom-start",
                  } as unknown as Omit<PopperProps, "open">
                }
                useUTCMoment
                paperStyle={{
                  "& .MuiPickersArrowSwitcher-root": {
                    "& .MuiIconButton-root": {
                      background: "none !important",
                      backgroundColor: "transparent !important",
                      boxShadow: "none",
                      border: "none !important",
                      "&:hover": {
                        background: "none !important",
                        backgroundColor: "transparent !important",
                      },
                    },
                    "& .Mui-disabled": {
                      background: "none !important",
                      backgroundColor: "transparent !important",
                      "&:hover": {
                        background: "none !important",
                        backgroundColor: "transparent !important",
                      },
                    },
                  },
                }}
              />
            </div>
          </ClickAwayListener>
        </>
      )}
    </LocalizationProvider>
  );
};
 
export default DateSelectDropdownButton;