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

100% Statements 31/31
87.5% Branches 14/16
100% Functions 7/7
100% Lines 31/31

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                      96x                                                                       96x 385x 385x 385x         385x 385x   385x 97x 97x 16x 16x     97x                           46x 46x         2x 2x     385x 97x   385x   96x 482x 482x 482x       68x                                                                                         482x     96x 3457x 3457x 3457x   3457x                          
import { useQuery } from "@tanstack/react-query";
import { useEffect, useRef, useState } from "react";
import { useLocation } from "react-router";
import { opensearch } from "shared-types";
 
import { getOsData, useGetUser, useOsSearch } from "@/api";
import { useLzUrl } from "@/hooks";
 
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",
      // },
    ],
  },
};
/**
 *
@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 [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?: any) => {
    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: [
            ...query.filters,
            ...createSearchFilterable(query.search || ""),
            ...(DEFAULT_FILTERS[params.state.tab].filters || []),
          ],
        },
        {
          ...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
  return { data, isLoading, error, ...params, tabLoading };
};
export const useOsAggregate = () => {
  const { data: user } = useGetUser();
  const { state } = useOsUrl();
  const aggs = useQuery({
    refetchOnWindowFocus: false,
    queryKey: [state.tab],
    queryFn: (props) => {
      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[props.queryKey[0]].filters || [],
        pagination: { number: 0, size: 1 },
      });
    },
  });
  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,
  });
};