All files / react-app/src/components/Opensearch/main useOpensearch.ts

98.24% Statements 56/57
87.09% Branches 27/31
100% Functions 16/16
98.21% Lines 55/56

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                        107x                                                         107x   107x           107x             107x 423x         107x     342x 423x 418x     6x 5x     107x   185x   107x                   103x                             107x 411x 411x 411x 411x         411x 411x   411x       103x 103x 16x 16x     103x                               50x 50x         2x 2x       411x 102x     411x 102x       102x 1x     102x 102x 100x       411x               107x 518x 518x 518x 518x       71x                                                                                                 518x     107x 3714x 3714x 3714x   3714x                          
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router";
import { opensearch, SEATOOL_STATUS } from "shared-types";
 
import { getOsData, useGetUser, useOsSearch } from "@/api";
import { useLzUrl } from "@/hooks";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
 
import { createSearchFilterable } from "../utils";
import { OsTab } from "./types";
 
export const DEFAULT_FILTERS: Record<OsTab, Partial<OsUrlState>> = {
  spas: {
    filters: [
      {
        field: "authority.keyword",
        type: "terms",
        value: ["Medicaid SPA", "CHIP SPA"],
        prefix: "must",
      },
    ],
  },
  waivers: {
    filters: [
      {
        field: "authority.keyword",
        type: "terms",
        value: ["1915(b)", "1915(c)"],
        prefix: "must",
      },
      // {
      //   field: "appkParentId",
      //   type: "exists",
      //   value: true,
      //   prefix: "must_not",
      // },
    ],
  },
};
 
export const OS_DASHBOARD_REFRESH_EVENT = "os-dashboard-refresh";
 
const DASHBOARD_DRAFT_STATUS_FIELDS = new Set<opensearch.main.Field>([
  "seatoolStatus.keyword",
  "stateStatus.keyword",
  "cmsStatus.keyword",
]);
 
export const EXCLUDE_DRAFT_STATUS_FILTER: opensearch.main.Filterable = {
  field: "seatoolStatus.keyword",
  type: "term",
  value: SEATOOL_STATUS.DRAFT,
  prefix: "must_not",
};
 
const isDraftStatusFilter = (filter: opensearch.main.Filterable) =>
  filter.type === "terms" &&
  DASHBOARD_DRAFT_STATUS_FIELDS.has(filter.field) &&
  Array.isArray(filter.value) &&
  filter.value.includes(SEATOOL_STATUS.DRAFT);
 
export const removeDraftStatusFilters = (
  filters: opensearch.main.Filterable[] = [],
): opensearch.main.Filterable[] =>
  filters.flatMap((filter) => {
    if (!isDraftStatusFilter(filter)) {
      return [filter];
    }
 
    const value = (filter.value as string[]).filter((status) => status !== SEATOOL_STATUS.DRAFT);
    return value.length ? [{ ...filter, value }] : [];
  });
 
export const getSaveInProgressDashboardFilters = (
  isSaveInProgressEnabled: boolean,
): opensearch.main.Filterable[] => (isSaveInProgressEnabled ? [] : [EXCLUDE_DRAFT_STATUS_FILTER]);
 
export const getDashboardSearchFilters = ({
  filters,
  search,
  tab,
  isSaveInProgressEnabled,
}: {
  filters: opensearch.main.Filterable[];
  search?: string;
  tab: OsTab;
  isSaveInProgressEnabled: boolean;
}): opensearch.main.Filterable[] => [
  ...(isSaveInProgressEnabled ? filters : removeDraftStatusFilters(filters)),
  ...createSearchFilterable(search || ""),
  ...(DEFAULT_FILTERS[tab].filters || []),
  ...getSaveInProgressDashboardFilters(isSaveInProgressEnabled),
];
 
/**
 *
@summary
use with main
Comments
- TODO: add index scope
- FIX: Initial render fires useEffect twice - 2 os requests
 */
export const useOsData = () => {
  const params = useOsUrl();
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const [data, setData] = useState<opensearch.main.Response["hits"]>();
  const { mutateAsync, isLoading, error } = useOsSearch<
    opensearch.main.Field,
    opensearch.main.Response
  >();
 
  const [tabLoading, setTabLoading] = useState(false);
  const previousTab = useRef(params.state.tab);
 
  const onRequest = async (
    query: opensearch.main.State,
    options?: Parameters<typeof mutateAsync>[1],
  ) => {
    try {
      if (params.state.tab !== previousTab.current) {
        setTabLoading(true);
        previousTab.current = params.state.tab;
      }
 
      await mutateAsync(
        {
          index: "main",
          pagination: query.pagination,
          sort: query.sort,
          filters: getDashboardSearchFilters({
            filters: query.filters,
            search: query.search,
            tab: params.state.tab,
            isSaveInProgressEnabled,
          }),
          includeDrafts: isSaveInProgressEnabled,
        },
        {
          ...options,
          onSuccess: (res) => {
            setData(res.hits);
            setTabLoading(false);
          },
        },
      );
    } catch (error) {
      console.error("Error occurred during search:", error);
      setTabLoading(false);
    }
  };
 
  useEffect(() => {
    onRequest(params.state);
  }, [params.queryString]); // eslint-disable-line react-hooks/exhaustive-deps
 
  useEffect(() => {
    Iif (typeof window === "undefined") {
      return;
    }
 
    const handleDashboardRefresh = () => {
      onRequest(params.state);
    };
 
    window.addEventListener(OS_DASHBOARD_REFRESH_EVENT, handleDashboardRefresh);
    return () => {
      window.removeEventListener(OS_DASHBOARD_REFRESH_EVENT, handleDashboardRefresh);
    };
  }, [params.queryString]); // eslint-disable-line react-hooks/exhaustive-deps
 
  return {
    data,
    isLoading,
    error,
    ...params,
    tabLoading,
  };
};
export const useOsAggregate = () => {
  const { data: user } = useGetUser();
  const { state } = useOsUrl();
  const isSaveInProgressEnabled = useFeatureFlag("SAVE_IN_PROGRESS");
  const aggs = useQuery({
    refetchOnWindowFocus: false,
    queryKey: [state.tab, isSaveInProgressEnabled],
    queryFn: () => {
      return getOsData({
        index: "main",
        aggs: [
          {
            field: "state.keyword",
            type: "terms",
            name: "state.keyword",
            size: 60,
          },
          {
            field: "authority.keyword",
            type: "terms",
            name: "authority.keyword",
            size: 10,
          },
          {
            field: "actionType.keyword",
            type: "terms",
            name: "actionType.keyword",
            size: 10,
          },
          {
            field:
              user?.isCms && user.user?.role !== "helpdesk"
                ? "cmsStatus.keyword"
                : "stateStatus.keyword",
            name:
              user?.isCms && user.user?.role !== "helpdesk"
                ? "cmsStatus.keyword"
                : "stateStatus.keyword",
            type: "terms",
            size: 20,
          },
          {
            field: "leadAnalystName.keyword",
            name: "leadAnalystName.keyword",
            type: "terms",
            size: 1000,
          },
        ],
        filters: [
          ...(DEFAULT_FILTERS[state.tab].filters || []),
          ...getSaveInProgressDashboardFilters(isSaveInProgressEnabled),
        ],
        pagination: { number: 0, size: 1 },
        includeDrafts: isSaveInProgressEnabled,
      });
    },
  });
  return aggs.data?.aggregations;
};
export type OsUrlState = opensearch.main.State & { tab: OsTab };
export const useOsUrl = () => {
  const location = useLocation();
  const queryParams = new URLSearchParams(location.search);
  const queryObject = Object.fromEntries(queryParams.entries());
 
  return useLzUrl<OsUrlState>({
    key: "os",
    initValue: {
      filters: [],
      search: "",
      tab: "spas",
      pagination: { number: 0, size: 100 },
      sort: { field: "makoChangedDate", order: "desc" },
      ...queryObject,
    },
    redirectTab: queryObject?.tab,
  });
};