All files / src/components/ProfileMenu/modals/hooks useNotificationTab.ts

89.88% Statements 80/89
73.46% Branches 36/49
95.23% Functions 20/21
95.18% Lines 79/83

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                                                  171x 171x   171x 171x   171x   171x               171x   41x 41x 14x           171x   65x                       171x 28x 28x       171x 96x 96x   96x 1990x   803x 803x         171x 20x 20x 20x     171x   20x 20x 20x   20x 60x 60x   60x 42x   42x 20x     42x                             20x           171x       6x 6x 6x   6x 6x   6x 6x 78x 6x         72x   72x   72x   72x 72x     72x                       6x           6x 6x     171x   11x 11x   11x             11x 11x 11x 11x             171x   171x 98x 60x   38x       171x                       9x 1990x 1990x   1990x 840x 1150x 1150x          
import { isEmpty, isEqual } from "lodash";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useQueryClient } from "react-query";
import { showMessage } from "@common/Toast";
import { checkPortals } from "@utils/routing";
import { stopEventPropagation } from "@utils/helpers";
import useGetAlerts from "./useGetAlerts";
import { QKEY_ALERTS_LIST } from "@constants/queryKeys";
import { TAlertMethods, TGroupedAlerts } from "../types";
import useAlertsTabs from "./useAlertsTabs";
import useAlertsLogs from "./useAlertsLogs";
import { filterGroupedAlertsByPermissions } from "../utils";
import {
  useAccessControl,
  composePermission,
} from "@features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
 
type TUseNotificationTabProps = {
  setIsDisabled: React.Dispatch<React.SetStateAction<boolean>>;
};
 
export default function useNotificationTab({
  setIsDisabled,
}: TUseNotificationTabProps) {
  const { currentPortal } = checkPortals();
  const queryClient = useQueryClient();
 
  const { activeTab, setActiveTab, tabs } = useAlertsTabs();
  const [data, setData] = useState<TGroupedAlerts | undefined>(undefined);
  const { resetLogs, updateLog, generatePayload, logsBulkUpdate } =
    useAlertsLogs();
 
  const isTransferFundsAllowed = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.ACQUIRER,
      RESOURCE_BASE.MOVE_FUNDS,
    ),
    operation: OPERATIONS.CREATE,
  });
 
  const { data: rawDefaultData, isLoading, alertsMutation } = useGetAlerts({
    onSuccess: (data: TGroupedAlerts) => {
      setData(filterGroupedAlertsByPermissions(data, { isTransferFundsAllowed }));
      if (!isEmpty(activeTab)) return;
      setActiveTab(currentPortal === "provider" ? "enterprise" : currentPortal);
    },
  });
 
  // Gate permission-restricted alerts out of the reference data too, so that
  // "select all" and the diff/payload never touch a hidden alert (GB-21568).
  const defaultData = useMemo(
    () =>
      filterGroupedAlertsByPermissions(rawDefaultData, {
        isTransferFundsAllowed,
      }),
    [rawDefaultData, isTransferFundsAllowed],
  );
 
  // Keep the editable copy re-filtered when the permission changes, not just at
  // load time. Permissions and alerts load independently (permissions briefly
  // default to allow while fetching), so a permission that resolves to `deny`
  // after the alerts loaded must still drop the gated alert from `data` - it
  // stays consistent with `defaultData`, keeps the alert un-toggleable, and
  // keeps `isDirty` honest.
  useEffect(() => {
    setData((prev) =>
      filterGroupedAlertsByPermissions(prev, { isTransferFundsAllowed }),
    );
  }, [isTransferFundsAllowed]);
 
  const customData = useMemo(() => {
    const hashedData = data && activeTab?.value ? data[activeTab.value] : {};
    const alerts = Object.values(hashedData);
 
    return {
      alerts: alerts.sort((a, b) => sorter(a.title, b.title)),
      totalAssigned: {
        emailCount: alerts.reduce((acc, a) => acc + +a.isAssigned.email, 0),
        pushCount: alerts.reduce((acc, a) => acc + +a.isAssigned.push, 0),
      },
    };
  }, [data, activeTab]);
 
  const addIdToLog = (id: string, method: TAlertMethods, newValue: boolean) => {
    Iif (!activeTab?.value || !defaultData) return;
    const originalValue = defaultData[activeTab.value][id].isAssigned[method];
    updateLog(id, method, newValue, originalValue);
  };
 
  const handleChange = useCallback(
    (id: string, method: TAlertMethods) => {
      setData((prevData) => {
        Iif (!prevData) return prevData;
        let groupedData = prevData;
 
        Object.keys(groupedData).forEach((key) => {
          const tabName = key as keyof typeof groupedData;
          const currentElement = groupedData[tabName][id];
 
          if (currentElement) {
            const assigned = !currentElement.isAssigned[method];
 
            if (tabName === activeTab?.value) {
              addIdToLog(id, method, assigned);
            }
 
            groupedData = {
              ...groupedData,
              [tabName]: {
                ...groupedData[tabName],
                [id]: {
                  ...currentElement,
                  isAssigned: {
                    ...currentElement.isAssigned,
                    [method]: assigned,
                  },
                },
              },
            };
          }
        });
        return groupedData;
      });
    },
    [defaultData, activeTab],
  );
 
  const handleCheckAll = (
    method: TAlertMethods,
    operation: "add" | "remove",
  ) => {
    Iif (!activeTab?.value) return;
    const idsToAttach: string[] = [];
    const idsToDetach: string[] = [];
 
    setData((prevData) => {
      Iif (!prevData) return prevData;
 
      const obj = prevData[activeTab.value];
      const groupedData = Object.entries(obj).reduce((acc, [key, value]) => {
        if (defaultData[activeTab.value][key].disabled[method]) {
          return {
            ...acc,
            [key]: value,
          };
        }
        const assigned = operation === "add" ? true : false;
        const originalValue =
          defaultData[activeTab.value][key].isAssigned[method];
 
        Iif (!assigned && originalValue) {
          idsToDetach.push(key);
        } else Eif (!originalValue && assigned) {
          idsToAttach.push(key);
        }
 
        return {
          ...acc,
          [key]: {
            ...value,
            isAssigned: {
              ...value.isAssigned,
              [method]: assigned,
            },
          },
        };
      }, {} as TGroupedAlerts);
 
      return {
        ...prevData,
        [activeTab.value]: groupedData,
      };
    });
 
    logsBulkUpdate(method, "subscribeList", idsToAttach);
    logsBulkUpdate(method, "unsubscribeList", idsToDetach);
  };
 
  const handleSubmit = useCallback(
    stopEventPropagation((e: any) => {
      Iif (!data || !defaultData) return;
      const payload = generatePayload();
 
      alertsMutation.mutate(payload, {
        onError: (error: any) => {
          if (error?.response?.data?.message) {
            showMessage("Error", error?.response?.data?.message, true);
          }
        },
        onSuccess: () => {
          queryClient.setQueriesData(QKEY_ALERTS_LIST, data);
          resetLogs();
          setIsDisabled(true);
          alertsMutation.reset();
        },
      });
    }),
    [data, defaultData],
  );
 
  const isDirty = !isEqual(data, defaultData);
 
  useEffect(() => {
    if (!isLoading && !alertsMutation.isLoading && data) {
      setIsDisabled(!isDirty);
    } else {
      setIsDisabled(true);
    }
  }, [isDirty, isLoading, alertsMutation.isLoading]);
 
  return {
    activeTab,
    setActiveTab,
    tabs,
    customData,
    isLoading,
    handleChange,
    handleCheckAll,
    handleSubmit,
  };
}
 
const sorter = (a: string, b: string) => {
  const titleA = a.toUpperCase();
  const titleB = b.toUpperCase();
 
  if (titleA < titleB) {
    return -1;
  } else if (titleA > titleB) {
    return 1;
  } else E{
    return 0;
  }
};