All files / src/features/Permissions/ModalV2/hooks usePermissionsPanel.ts

80.21% Statements 73/91
52.94% Branches 18/34
83.33% Functions 25/30
87.65% Lines 71/81

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                                          4x 241x 241x 241x     241x                                       241x           241x   241x         241x 17x 17x 17x           241x 14x 14x 14x     241x 3x 6x     241x   2x   2x       2x 2x 2x     241x   82x               241x                 241x                                     241x 1x 1x   1x 1x       241x 1x 1x 1x   1x 1x 1x   1x   1x 1x           241x 2x 2x     2x       241x 7x 7x 7x                 7x                 7x 7x 7x                         241x 7x 7x     241x                                     241x 38x 8x   38x     241x                                               2x 2x         4x 2x 2x 2x        
import { TListWrapperSection } from "@containers/types";
import usePanelState from "./usePanelState";
import usePermissionData from "./usePermissionData";
import { useEffect, useMemo, useState } from "react";
import { generateDynamicTabs } from "../utils/permissionPanel.utils";
import { DELETE_CONFIRMATION_MODAL } from "modals/modal_names";
import NiceModal, { useModal } from "@ebay/nice-modal-react";
import { useQueryClient } from "react-query";
import { useAddPermissionModalCache } from "./useAddPermissionsModal";
import { TPermissionsData } from "../types";
import { QKEY_LIST_TEAM_MEMBER_PERMISSIONS } from "@constants/queryKeys";
import { useDebouncedCallback } from "use-debounce";
import {
  composePermission,
  useAccessControl,
} from "features/Permissions/AccessControl";
import RESOURCE_BASE, {
  CREATE_DENY_MESSAGE,
  OPERATIONS,
} from "@constants/permissions";
 
const usePermissionsPanel = (memberId: number) => {
  const queryClient = useQueryClient();
  const modal = useModal();
  const { updateCache, queryKey } = useAddPermissionModalCache();
 
  const { open, sectionsRef, closeModal, setOpen, toggleLatest, showLatest } =
    usePanelState();
 
  const {
    totalItems,
    setSearchQuery,
    dataIsLoading,
    dataIsFetching,
    permissionsData,
    latestAddedData,
    isMutated,
    handleSetFilter,
    onDelete,
    clearChanges,
    onSaveSidePanel,
    setPermissionStatus,
    updateLatestAdded,
    updateAllHashedData,
    hashedData,
    updateAllLogs,
    removeItemFromLogs,
  } = usePermissionData(memberId, {
    withPagination: false,
    assignedOnly: true,
    enabled: modal.visible,
  });
 
  const [searchString, setSearchString] = useState<string>("");
 
  const setAPISearchQuery = useDebouncedCallback(
    (value) => setSearchQuery(value),
    200,
  );
 
  const handleSearch = (value: string) => {
    setSearchString(value);
    if (value === "") {
      setSearchQuery("");
    } else E{
      setAPISearchQuery(value);
    }
  };
 
  const toggleModal = () =>
    setOpen((prev) => {
      if (!prev) handleSearch("");
      return !prev;
    });
 
  const invalidateAllQueries = () =>
    [queryKey, QKEY_LIST_TEAM_MEMBER_PERMISSIONS].forEach((q) =>
      queryClient.invalidateQueries(q),
    );
 
  const handleDiscard = async () => {
    // on discard we delete the custom permissions that were added
    Object.values(latestAddedData.data).forEach(
      (permission: TPermissionsData[string]) => {
        Iif (permission?.custom) onDelete(permission.id);
      },
    );
 
    closeModal();
    clearChanges();
    invalidateAllQueries();
  };
 
  const tabs = useMemo(
    () =>
      generateDynamicTabs(
        showLatest,
        permissionsData.groups,
        latestAddedData.groups,
      ),
    [showLatest, latestAddedData.groups, permissionsData.groups],
  );
 
  const isAddAllowed = useAccessControl({
    resource: composePermission(
      RESOURCE_BASE.MEMBER,
      RESOURCE_BASE.ACCESS_POLICIES,
    ),
    operation: OPERATIONS.UPDATE,
    withPortal: true,
  });
 
  const listWrapperProps = {
    section: "permissions" as TListWrapperSection,
    isEmpty:
      totalItems === 0 && !searchString && !dataIsLoading && !dataIsFetching,
    action: {
      label: "Add Permissions",
      onClick: toggleModal,
      disabled: !isAddAllowed,
      tooltipProps: {
        show: !isAddAllowed,
        message: CREATE_DENY_MESSAGE,
      },
    },
    sx: {
      overflowY: "hidden",
      overflowX: "hidden",
    },
  };
 
  const deleteHandler = (permissionKey: string) => {
    const permissionId = permissionsData.data?.[permissionKey]?.id;
    Iif (!permissionId) return;
 
    onDelete(permissionId, "Changes saved").then(() => {
      invalidateAllQueries();
    });
  };
 
  const latestAddedDeleteHandler = (key: string) => {
    updateLatestAdded((old) => {
      Iif (!old) return {};
      return deleteEntry(old, key);
    });
    updateAllHashedData((old) => {
      Iif (!old) return {};
      Iif (!old[key]) return old;
 
      return deleteEntry(old, key);
    });
    removeItemFromLogs(key);
    updateCache(key, {
      ...latestAddedData.data[key],
      isAttached: false,
    });
  };
 
  const deletePermission = (permissionKey: string, permissionName: string) => {
    const onSubmit = showLatest ? latestAddedDeleteHandler : deleteHandler;
    NiceModal.show(DELETE_CONFIRMATION_MODAL, {
      variant: "permissions",
      itemName: permissionName,
      deleteHandler: () => onSubmit(permissionKey),
    });
  };
 
  const syncListWithNewAdded = (newAdded: TPermissionsData) => {
    Object.entries(newAdded).forEach(([key, values]) => {
      updateCache(key, values);
      updateLatestAdded((old) => ({
        ...old,
        [key]: {
          ...values,
          isDeny: false,
          isAttached: values.isAttached,
          isGlobal: false,
        },
      }));
      Iif (values.isDeny) {
        updateAllLogs((old) => ({
          ...old,
          [key]: {
            ...values,
            isDeny: false,
          },
        }));
      }
      updateAllHashedData((old) => {
        Eif (!old || !old[key] || values.isAttached) {
          return {
            ...old,
            [key]: {
              ...values,
              isDeny: false,
            },
          };
        }
        return deleteEntry(old, key);
      });
    });
  };
 
  const handleAddPermission = (newAdded: TPermissionsData) => {
    syncListWithNewAdded(newAdded);
    toggleModal();
  };
 
  const onAddCustomPermission = (permissionIds: string[], cb?: () => void) => {
    permissionIds.forEach((id) => {
      updateLatestAdded((old) => {
        if (!old || !hashedData || !hashedData[id]) return old;
 
        return {
          ...old,
          [id]: {
            ...hashedData[id],
            custom: true,
            isDeny: false,
          },
        };
      });
    });
    toggleModal();
    if (cb) cb();
  };
 
  useEffect(() => {
    const hasLatestAdded = Object.values(latestAddedData.data).some(
      (val) => val.isAttached,
    );
    toggleLatest(hasLatestAdded);
  }, [latestAddedData.data]);
 
  return {
    dataIsLoading,
    dataIsFetching,
    totalItems,
    searchQuery: searchString,
    listMutated: isMutated,
    permissionsData,
    latestAddedData,
    listWrapperProps,
    sectionsRef,
    showLatest,
    open,
    toggleModal,
    tabs,
    handleSetFilter,
    handleSearch,
    handleDiscard,
    deletePermission,
    onDelete: deletePermission,
    handleClose: closeModal,
    handleAddPermission,
    onAddCustomPermission,
    setPermissionStatus,
    onSave: () => {
      onSaveSidePanel();
      toggleLatest(false);
    },
  };
};
 
const deleteEntry = (data: TPermissionsData, key: string) => {
  const newData = data;
  delete newData[key];
  return newData;
};
 
export default usePermissionsPanel;