All files / src/shared/GiveExportModal/components ExportRadioComponent.tsx

87.75% Statements 43/49
87.5% Branches 42/48
100% Functions 8/8
89.36% Lines 42/47

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                                      103x 103x 103x 103x 103x 103x   103x                     8x         6x             6x 6x   6x 12x     6x 5x       8x 1x     103x 1x           1x 1x 1x                       103x     294x 294x   294x   294x           294x     7x                     7x 7x 7x               3x 3x             3x           1x               7x                       7x           7x 7x   294x                           6x                                                                    
import { Box, Stack } from "@mui/material";
import GiveRadio from "@shared/Radio/GiveRadio";
import GiveText from "@shared/Text/GiveText";
import React, { useRef, useState } from "react";
import { useFormContext } from "react-hook-form";
import { RadioInput } from "../giveExportTypes";
import { formatDescription, getDateRangeString } from "../utils";
import GiveTimezoneDatePicker, {
  FormValuesGiveDatePickerModal,
} from "@shared/GiveTimezoneDatePicker/GiveTimezoneDatePicker";
import { isEmpty } from "lodash";
import { PLATFORM_TIMEZONE } from "@utils/timezones";
import { endOfMonth, startOfMonth, subDays, subMonths } from "date-fns";
import moment from "moment";
 
import { buildReserveMonthlyFileName } from "../hooks/merchantTable/merchantTableReserveDate";
import { isReconciliationLikeReport } from "../hooks/merchantTable/merchantTableConfig";
 
function ExportRadioComponent({ field }: { field: RadioInput }) {
  const { setValue, watch } = useFormContext();
  const customRadioRef = useRef<any | null>(null);
  const columnsIncluded = watch("columnsIncluded") as string | undefined;
  const isReconciliationReport = isReconciliationLikeReport(columnsIncluded);
  const allTime = watch("allTime") as boolean | undefined;
  const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
 
  const setFiledValue = ({
    dateStringRep,
    endDate,
    startDate,
    timeZone = PLATFORM_TIMEZONE,
  }: {
    dateStringRep?: "All" | "7" | "month" | "custom" | string;
    startDate?: Date;
    endDate?: Date;
    timeZone?: string;
  }) => {
    if (
      field.changeInputValue &&
      field.changeInputName &&
      field?.stringKeyToUpdate
    ) {
      const dateRange = getDateRangeString({
        startDate,
        endDate,
        timeZone,
        dateStringRep,
      });
 
      const currentVal = watch(field.changeInputName);
      const choices = [currentVal, field.changeInputValue];
 
      const newString = choices
        .find((str) => str.includes(field?.stringKeyToUpdate))
        ?.replace(field?.stringKeyToUpdate, dateRange);
 
      if (newString) {
        setValue(field.changeInputName, newString);
      }
    }
 
    if (columnsIncluded === "reserve_monthly" && startDate && endDate) {
      setValue("fileName", buildReserveMonthlyFileName({ startDate, endDate }));
    }
  };
  const handleClose = (data?: FormValuesGiveDatePickerModal) => {
    setFiledValue({
      dateStringRep: "custom",
      startDate: data?.startDate,
      endDate: data?.endDate,
      timeZone: data?.timeZone,
    });
    setAnchorEl(null);
    Iif (isEmpty(data)) return;
    setValue(
      field.fieldName,
      {
        ...watch(field.fieldName),
        ...data,
      },
      {
        shouldValidate: true,
      },
    );
  };
 
  return (
    <Stack gap="16px">
      {field.options.map((option) => {
        const isCustom = option?.value === "custom";
        const checked = watch(field.fieldName)?.label === option.label;
 
        const { endDate, startDate } = watch(field.fieldName) || {};
        const description =
          isCustom && checked
            ? formatDescription({
                endDate,
                startDate,
              })
            : null;
        const handleChangeRadio = (
          event: React.ChangeEvent<HTMLInputElement>,
        ) => {
          Iif (option?.value === "all_time") {
            setValue("allTime", true);
            setValue(
              field.fieldName,
              { value: "all_time", label: "All Time" },
              { shouldValidate: true },
            );
            return;
          }
          // Use ET "today" so preset boundaries match the platform timezone,
          // not the browser's local calendar day.
          const today = moment.tz(PLATFORM_TIMEZONE).toDate();
          const presetRange = (() => {
            switch (option?.value) {
              case "current_month":
                return {
                  startDate: startOfMonth(today),
                  endDate: today,
                  timeZone: PLATFORM_TIMEZONE,
                };
              case "month": {
                const lastMonth = subMonths(today, 1);
                return {
                  startDate: startOfMonth(lastMonth),
                  endDate: endOfMonth(lastMonth),
                  timeZone: PLATFORM_TIMEZONE,
                };
              }
              case "7":
                return {
                  startDate: subDays(today, 6),
                  endDate: today,
                  timeZone: PLATFORM_TIMEZONE,
                };
              default:
                return {
                  startDate: today,
                  endDate: today,
                  timeZone: null,
                };
            }
          })();
 
          setValue(
            field.fieldName,
            {
              ...option,
              startDate: presetRange.startDate,
              endDate: presetRange.endDate,
              timeZone: presetRange.timeZone,
            },
            {
              shouldValidate: true,
            },
          );
          setFiledValue({
            dateStringRep: option?.value as string,
            startDate: presetRange.startDate,
            endDate: presetRange.endDate,
            timeZone: presetRange.timeZone || PLATFORM_TIMEZONE,
          });
          if (isReconciliationReport) setValue("allTime", false);
          isCustom && setAnchorEl(event.currentTarget);
        };
        return (
          <Stack
            alignItems="center"
            gap="12px"
            flexDirection="row"
            key={option.label}
            sx={{ pointerEvents: option.disabled ? "none" : "auto" }}
          >
            <GiveRadio
              data-testid={`give-export-radio-${option.label}`}
              ref={isCustom ? customRadioRef : null}
              onChange={handleChangeRadio}
              checked={checked}
              onClick={(e) => {
                Iif (isCustom && checked) {
                  setAnchorEl(e.currentTarget);
                }
              }}
              disabled={option.disabled}
            />
            <Box>
              <GiveText
                fontWeight={400}
                fontSize="14px"
                color={option.disabled ? "secondary" : "primary"}
              >
                {option.label}
              </GiveText>
              {(option?.description || description) && (
                <GiveText color="secondary" fontWeight={400} fontSize="12px">
                  {description || option?.description}
                </GiveText>
              )}
            </Box>
          </Stack>
        );
      })}
      <GiveTimezoneDatePicker
        anchorEl={anchorEl}
        handleClose={handleClose}
        width={370}
        hideTimezone
      />
    </Stack>
  );
}
 
export default ExportRadioComponent;