All files / src/pages/ManageMoney/Modal useManageMoneyFilter.tsx

79.66% Statements 47/59
54.83% Branches 17/31
77.77% Functions 14/18
80.7% Lines 46/57

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 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349                                                            14x 13x 13x 18x   13x         13x 13x       13x   13x 1x             1x           1x     13x                                                         13x                                     13x               26x 26x     104x   104x     104x 104x                         1x                                 13x             13x     143x 143x 143x 11x     143x             1x       1x                   13x 13x                   1x                       13x               13x                 13x               13x             26x 26x 26x                                 13x   13x                     45x               1x                                                                                           1x                    
import useNiceModal from "@common/Modal/ModalFactory/hooks/useNiceModal";
import ChipsContainer from "@common/TableFilters/WrapperWithDateRange";
import Chip from "@common/TableFilters/Chip";
import { Stack, styled } from "@mui/material";
import { palette } from "@palette";
import { findByIdAndModify, getAmountArray } from "@utils/helpers";
import { isArray, isEmpty, isEqual } from "lodash";
import { useMemo } from "react";
import { useForm } from "react-hook-form";
import { FilterObjectTypes } from "@customTypes/utils.types";
import CustomVolumePopup from "@common/TableFilters/CustomVolumePopup";
import {
  getCustomProcessingLabel,
  getProcessingAmount,
} from "@common/TableFilters/utils";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import {
  resetFilterByKey,
  selectFiltersObject,
  setFilterByKey,
} from "@redux/slices/dynamicFilterSlice";
import { QKEY_MANAGE_MONEY_TRANSACTIONS_LIST } from "@constants/queryKeys";
import { DefaultValuesTypeManageMoney } from "@pages/ManageMoney/constants";
import {
  defaultValuesManageMoney,
  QUERYOBJECTKEYS_MANAGE_MONEY,
} from "../constants";
import { toUnixDateFormat } from "@utils/date.helpers";
 
export default function useManageMoneyFilter() {
  const { open, onClose, SlideProps } = useNiceModal();
  const dispatch = useAppDispatch();
  const filterObject = useAppSelector((state) =>
    selectFiltersObject(state, QKEY_MANAGE_MONEY_TRANSACTIONS_LIST),
  );
  const methods = useForm<DefaultValuesTypeManageMoney>({
    defaultValues: isEmpty(filterObject)
      ? defaultValuesManageMoney
      : filterObject,
  });
  const values = methods.watch();
  const isObjectsEqual = isEqual(
    values,
    isEmpty(filterObject) ? defaultValuesManageMoney : filterObject,
  );
  const canClearObj = isEqual(values, defaultValuesManageMoney);
 
  const onSubmit = (data: any) => {
    Iif (data.transactionDate.label === "Custom") {
      const { dateName, startDate, endDate } = data.transactionDate;
      const startDateUnix = toUnixDateFormat(startDate);
      const endDateUnix = toUnixDateFormat(endDate);
      data.transactionDate.val = `${dateName}:>=d${startDateUnix})%3B(${dateName}:<=d${endDateUnix}`;
    }
 
    dispatch(
      setFilterByKey({
        filterKey: QKEY_MANAGE_MONEY_TRANSACTIONS_LIST,
        params: data,
      }),
    );
    onClose();
  };
 
  const actions = {
    primaryAction: {
      label: "Apply filters",
      disabled: isObjectsEqual,
      sx: {
        fontSize: "18px",
        lineHeight: "18px",
        padding: "12px 24px",
      },
    },
    secondaryAction: {
      label: "Clear all filters",
      onClick: () => {
        methods.reset(defaultValuesManageMoney);
        dispatch(
          resetFilterByKey({
            filterKey: QKEY_MANAGE_MONEY_TRANSACTIONS_LIST,
          }),
        );
      },
      sx: {
        fontSize: "18px",
        lineHeight: "18px",
        padding: "12px 24px",
        color: palette.filled.red,
      },
      hidden: canClearObj,
    },
  };
  const handleSaveProcessingVolume = (param: {
    from: number | undefined;
    to: number | undefined;
    key: string;
    prefix?: string;
  }) => {
    const stringValue = getProcessingAmount({
      ...(typeof param.from === "number" && { amount: param.from * 100 }),
      ...(typeof param.to === "number" && { secondAmount: param.to * 100 }),
      modifier: "is between",
      prefix: param?.prefix,
    });
 
    const customLabel = getCustomProcessingLabel(param?.from, param?.to);
    methods.setValue(param?.key as any, {
      label: customLabel,
      value: stringValue,
    });
  };
  const renderFlowAmountChip = ({
    key,
  }: {
    key:
      | QUERYOBJECTKEYS_MANAGE_MONEY.inflow_amount
      | QUERYOBJECTKEYS_MANAGE_MONEY.outflow_amount;
  }) => {
    const prefix =
      key === QUERYOBJECTKEYS_MANAGE_MONEY.inflow_amount ? "inflow" : "outflow";
    return (
      <Wrapper>
        {getAmountArray(prefix)?.map((option) => {
          const selectedValue = values?.[key];
          const isCustom =
            (selectedValue?.label?.toLowerCase().includes("custom") &&
              option?.label === "Custom") ||
            false;
          const isSelected = selectedValue?.label === option?.label || isCustom;
          return (
            <Chip
              key={option.value}
              item={
                isCustom
                  ? {
                      label: selectedValue?.label || "Custom",
                      value: option.value,
                    }
                  : option
              }
              selected={isSelected}
              onSelect={() => {
                methods.setValue(key, isSelected ? {} : option);
              }}
              {...(option.value === "custom" && {
                PopupComponent: CustomVolumePopup,
                popupCallback: (e) =>
                  handleSaveProcessingVolume({
                    ...e,
                    key: key,
                    prefix,
                  }),
              })}
            />
          );
        })}
      </Wrapper>
    );
  };
  const renderChipsArray = ({
    arr,
    key,
  }: {
    arr: any[];
    key: QUERYOBJECTKEYS_MANAGE_MONEY;
  }) => {
    return (
      <Wrapper>
        {arr?.map((option) => {
          const selectedArray = values?.[key] || [];
          Iif (!isArray(selectedArray)) return;
          const isSelected = selectedArray?.find(
            (item: any) => item.value === option.value,
          );
 
          return (
            <Chip
              key={option.value}
              item={option}
              selected={!!isSelected}
              allowMultiSelect
              onSelect={() => {
                const newArray = findByIdAndModify(
                  selectedArray as FilterObjectTypes[],
                  option,
                );
                methods.setValue(key, newArray, {
                  shouldDirty: true,
                });
              }}
            />
          );
        })}
      </Wrapper>
    );
  };
  const filterSections = useMemo(() => {
    const transactionDate = {
      title: "Transaction Date",
      description:
        "See transactions created within a specific date range. Click on the transaction to see details.",
      children: (
        <Wrapper>
          <ChipsContainer
            dateName={QUERYOBJECTKEYS_MANAGE_MONEY.createdAt}
            selectedDate={values?.transactionDate}
            rangeSaveCallback={(val) =>
              methods.setValue(
                QUERYOBJECTKEYS_MANAGE_MONEY.transactionDate,
                val,
                {
                  shouldDirty: true,
                },
              )
            }
          />
        </Wrapper>
      ),
    };
    const tStatus = {
      title: "Transaction Status",
      description: "",
      children: renderChipsArray({
        arr: transactionStatusStaticArr,
        key: QUERYOBJECTKEYS_MANAGE_MONEY.transaction_status,
      }),
    };
    const inflowObj = {
      title: "Credit",
      description:
        "View transactions based on the amount of money received within specific range",
      children: renderFlowAmountChip({
        key: QUERYOBJECTKEYS_MANAGE_MONEY.inflow_amount,
      }),
    };
 
    const outflowOBJ = {
      title: "Debit",
      description:
        "View transactions based on the amount of money withdrawn within specific range",
      children: renderFlowAmountChip({
        key: QUERYOBJECTKEYS_MANAGE_MONEY.outflow_amount,
      }),
    };
    const paymentMethodObj = {
      title: "Payment Method",
      description: "",
      children: (
        <Wrapper>
          {paymentMethodsStaticArray?.map((option) => {
            const selectedValue =
              values?.[QUERYOBJECTKEYS_MANAGE_MONEY.payment_method];
            const selected = selectedValue?.value === option?.value;
            return (
              <Chip
                key={option.value}
                item={option}
                selected={selectedValue?.value === option?.value}
                onSelect={(val) => {
                  methods.setValue(
                    QUERYOBJECTKEYS_MANAGE_MONEY.payment_method,
                    selected ? {} : option,
                  );
                }}
              />
            );
          })}
        </Wrapper>
      ),
    };
    return [transactionDate, tStatus, inflowObj, outflowOBJ, paymentMethodObj];
  }, [values]);
  return {
    open,
    onClose,
 
    SlideProps,
    methods,
    onSubmit,
    actions,
    filterSections,
  };
}
const Wrapper = styled(Stack)(() => ({
  display: "flex",
  flexDirection: "row",
  spacing: "8px",
  flexWrap: "wrap",
  gap: "8px",
}));
 
const transactionStatusStaticArr = [
  {
    value: "Authorized",
    label: "Authorized ",
  },
  {
    value: "Chargeback",
    label: "Chargeback",
  },
  {
    value: "Chargeback Reversal",
    label: "Chargeback Reversal",
  },
  {
    value: "Requested",
    label: "Requested",
  },
  {
    value: "Pending",
    label: "Pending",
  },
  {
    value: "Refund Pending",
    label: "Refund Pending",
  },
  {
    value: "Refunded",
    label: "Refunded",
  },
  {
    value: "Sending",
    label: "Sending",
  },
  {
    value: "Sent",
    label: "Sent",
  },
  {
    value: "Settled",
    label: "Settled",
  },
  {
    value: "Voided",
    label: "Voided",
  },
];
const paymentMethodsStaticArray = [
  {
    value: "Credit",
    label: "Credit Card",
  },
  {
    value: "Debit",
    label: "Debit Card",
  },
];