All files / modules/75-ce/pages/anomalies-overview AnomaliesOverviewPage.tsx

93.22% Statements 55/59
73.68% Branches 14/19
70% Functions 7/10
93.22% Lines 55/59

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              1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x             1x   1x   1x 4x               4x               4x     1x 4x                                 1x 3x 2x 2x 2x 2x 2x 2x 2x 2x   2x         2x   2x                         2x           2x             2x 2x                                               2x 2x 2x 2x                             2x           2x     2x 2x 2x 2x           2x 2x         2x                                                   2x                         2x                                                                                                   1x  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { Container, PageBody, PageHeader, Text } from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { useModalHook } from '@harness/use-modal'
import { Drawer, Position } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { CcmMetaData, QlceViewTimeFilterOperator, useFetchCcmMetaDataQuery } from 'services/ce/services'
import { AnomalyData, CCMStringFilter, useGetAnomalyWidgetsData, useListAnomalies } from 'services/ce'
import AnomaliesSummary from '@ce/components/AnomaliesSummary/AnomaliesSummary'
import AnomalyFilters from '@ce/components/AnomaliesFilter/AnomaliesFilter'
import AnomaliesListGridView from '@ce/components/AnomaliesListView/AnomaliesListView'
import AnomaliesSearch from '@ce/components/AnomaliesSearch/AnomaliesSearch'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import {
  CE_DATE_FORMAT_INTERNAL,
  DATE_RANGE_SHORTCUTS,
  getGMTEndDateTime,
  getGMTStartDateTime
} from '@ce/utils/momentUtils'
import type { orderType, sortType } from '@common/components/Table/react-table-config'
import { useQueryParamsState } from '@common/hooks/useQueryParamsState'
import type { TimeRangeFilterType } from '@ce/types'
import AnomaliesSettings from '@ce/components/AnomaliesSettings/AnomaliesSettings'
 
const getFilters = (filters: Record<string, Record<string, string>>, searchText: string) => {
  const updatedFilters = Object.values(filters).map(item => {
    return {
      field: item.field,
      operator: item.operator,
      values: [item.value]
    }
  })
 
  Iif (searchText) {
    updatedFilters.push({
      field: 'ALL',
      operator: 'LIKE',
      values: [searchText]
    })
  }
 
  return updatedFilters
}
 
const getTimeFilters = (from: number, to: number) => {
  return [
    {
      operator: QlceViewTimeFilterOperator.After,
      timestamp: from
    },
    {
      operator: QlceViewTimeFilterOperator.Before,
      timestamp: to
    }
  ]
}
 
interface SortByObjInterface {
  sort?: sortType
  order?: orderType
}
 
const AnomaliesOverviewPage: React.FC = () => {
  const { getString } = useStrings()
  const [searchText, setSearchText] = React.useState('')
  const { accountId } = useParams<AccountPathProps>()
  const [listData, setListData] = useState<AnomalyData[]>([])
  const [costData, setCostData] = useState([])
  const [perspectiveAnomaliesData, setPerspectiveANomaliesData] = useState([])
  const [cloudProvidersWiseData, setCloudProvidersWiseData] = useState([])
  const [statusWiseData, setStatusWiseData] = useState([])
  const [filters, setFilters] = useState({})
 
  const [timeRange, setTimeRange] = useQueryParamsState<TimeRangeFilterType>('timeRange', {
    to: DATE_RANGE_SHORTCUTS.LAST_30_DAYS[1].format(CE_DATE_FORMAT_INTERNAL),
    from: DATE_RANGE_SHORTCUTS.LAST_30_DAYS[0].format(CE_DATE_FORMAT_INTERNAL)
  })
 
  const [sortByObj, setSortByObj] = useState<SortByObjInterface>({})
 
  const drawerProps = {
    autoFocus: true,
    canEscapeKeyClose: true,
    canOutsideClickClose: true,
    enforceFocus: true,
    isOpen: true,
    hasBackdrop: true,
    position: Position.RIGHT,
    usePortal: true,
    size: '54%',
    isCloseButtonShown: true
  }
 
  const { mutate: getAnomaliesList, loading: isListFetching } = useListAnomalies({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: getAnomalySummary, loading: isSummaryDataFetching } = useGetAnomalyWidgetsData({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  // Fetch the default workload ID's for redirections
  const [ccmMetaResult] = useFetchCcmMetaDataQuery()
  const { data: ccmData, fetching: isFetchingCcmMetaData } = ccmMetaResult
 
  /* istanbul ignore next */
  const setAnomaliesFilters = (fieldName: string, operator: string, value: string) => {
    if (value) {
      setFilters(prevFilters => {
        return {
          ...prevFilters,
          [fieldName]: {
            field: fieldName,
            operator,
            value
          }
        }
      })
    } else {
      setFilters(prevFilters => {
        const updatedFilters = { ...prevFilters }
        delete updatedFilters[fieldName as keyof typeof updatedFilters]
        return updatedFilters
      })
    }
  }
 
  useEffect(() => {
    const getList = async () => {
      try {
        const response = await getAnomaliesList({
          filter: {
            stringFilters: getFilters(filters, searchText) as CCMStringFilter[],
            timeFilters: getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to))
          },
          groupBy: [],
          orderBy: [
            {
              field: sortByObj.sort || 'ACTUAL_COST',
              order: sortByObj.order === 'ASC' ? 'ASCENDING' : 'DESCENDING'
            }
          ],
          limit: 100,
          offset: 0
        })
        setListData(response?.data as AnomalyData[])
      } catch (error) {
        // console.log('AnomaliesOverviewPage: Error in fetching the anomalies list', error)
      }
    }
 
    getList()
  }, [filters, sortByObj, getAnomaliesList, searchText, timeRange.from, timeRange.to])
 
  useEffect(() => {
    const getSummary = async () => {
      try {
        const response = await getAnomalySummary({
          filter: {
            stringFilters: getFilters(filters, searchText) as CCMStringFilter[],
            timeFilters: getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to))
          }
        })
        const { data } = response
        parseSummaryData(data)
      } catch (error) {
        // console.log('AnomaliesOverviewPage: Error in fetching summary data', error)
      }
    }
    getSummary()
  }, [filters, getAnomalySummary, searchText, timeRange.from, timeRange.to])
 
  /* istanbul ignore next */
  const parseSummaryData = (summaryData: any) => {
    summaryData.forEach((item: any) => {
      switch (item.widgetDescription) {
        case 'TOP_N_ANOMALIES':
          setPerspectiveANomaliesData(item.widgetData)
          break
 
        case 'TOTAL_COST_IMPACT':
          setCostData(item.widgetData?.[0])
          break
 
        case 'ANOMALIES_BY_CLOUD_PROVIDERS':
          setCloudProvidersWiseData(item.widgetData)
          break
 
        case 'ANOMALIES_BY_STATUS':
          setStatusWiseData(item.widgetData)
          break
      }
    })
  }
 
  const [showModal, hideDrawer] = useModalHook(() => {
    return (
      <Drawer
        onClose={() => {
          hideDrawer()
        }}
        {...drawerProps}
      >
        <AnomaliesSettings hideDrawer={hideDrawer} />
      </Drawer>
    )
  }, [])
 
  return (
    <>
      <PageHeader
        title={
          <Text
            color="grey800"
            style={{ fontSize: 20, fontWeight: 'bold' }}
            tooltipProps={{ dataTooltipId: 'ccmAnomalies' }}
          >
            {getString('ce.anomalyDetection.sideNavText')}
          </Text>
        }
        breadcrumbs={<NGBreadcrumbs />}
      />
      <AnomalyFilters
        filters={filters}
        setFilters={setAnomaliesFilters}
        timeRange={timeRange}
        setTimeRange={setTimeRange}
      />
 
      <PageBody loading={isListFetching || isFetchingCcmMetaData || isSummaryDataFetching}>
        <Container
          padding={{
            right: 'xxxlarge',
            left: 'xxxlarge',
            bottom: 'medium',
            top: 'medium'
          }}
        >
          <AnomaliesSearch onChange={setSearchText} showModal={showModal} />
          <AnomaliesSummary
            costData={costData}
            perspectiveAnomaliesData={perspectiveAnomaliesData}
            cloudProvidersWiseData={cloudProvidersWiseData}
            statusWiseData={statusWiseData}
            allDefaultProviders={(ccmData?.ccmMetaData || {}) as CcmMetaData}
          />
          <AnomaliesListGridView
            timeRange={timeRange}
            listData={listData}
            sortByObj={sortByObj}
            setSortByObj={setSortByObj}
          />
        </Container>
      </PageBody>
    </>
  )
}
 
export default AnomaliesOverviewPage