All files / modules/75-ce/pages/perspective-details PerspectiveDetailsPage.tsx

86.67% Statements 104/120
70.54% Branches 91/129
56.25% Functions 9/16
86.67% Lines 104/120

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 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495              1x 1x 1x 1x 1x 1x 1x 1x 1x               1x                         1x 1x 1x 1x 1x 1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x   1x             1x 4x 4x 4x 4x   4x         4x   4x                 4x 2x                 4x 4x                                                                                     4x                                   1x 9x 8x 8x 8x 8x 8x   8x             8x   8x   8x 8x       8x   8x   8x             8x             8x   8x   8x   8x   8x 8x   8x 8x   8x 2x     8x 2x   2x     2x   2x             2x       8x 4x                           4x         8x                     8x 8x               8x               8x                       8x 8x 8x                     8x                     8x               8x 8x 8x 8x   8x   8x                           8x                           8x         8x 8x   8x                                                                                                                                                                                                                   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, { useState, useEffect, useRef, useMemo } from 'react'
import { useParams, useHistory } from 'react-router-dom'
import cronstrue from 'cronstrue'
import qs from 'qs'
import cx from 'classnames'
import { Button, Container, Text, PageHeader, PageBody, Icon, useToaster } from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import routes from '@common/RouteDefinitions'
import {
  PerspectiveAnomalyData,
  QLCEViewFilterWrapper,
  QLCEViewGroupBy,
  useGetPerspective,
  useGetReportSetting,
  useListPerspectiveAnomalies
} from 'services/ce/'
import {
  useFetchPerspectiveTimeSeriesQuery,
  QlceViewTimeGroupType,
  useFetchPerspectiveDetailsSummaryWithBudgetQuery,
  QlceViewFilterInput,
  QlceViewFilterOperator,
  QlceViewFieldInputInput,
  useFetchperspectiveGridQuery,
  ViewChartType,
  ViewType,
  QlceViewAggregateOperation,
  useFetchPerspectiveTotalCountQuery
} from 'services/ce/services'
import { useStrings } from 'framework/strings'
import PerspectiveGrid from '@ce/components/PerspectiveGrid/PerspectiveGrid'
import CloudCostInsightChart from '@ce/components/CloudCostInsightChart/CloudCostInsightChart'
import PerspectiveExplorerGroupBy from '@ce/components/PerspectiveExplorerGroupBy/PerspectiveExplorerGroupBy'
import PersepectiveExplorerFilters from '@ce/components/PersepectiveExplorerFilters/PerspectiveExplorerFilters'
import PerspectiveSummary from '@ce/components/PerspectiveSummary/PerspectiveSummary'
import {
  getViewFilterForId,
  getTimeFilters,
  getGroupByFilter,
  getTimeRangeFilter,
  getFilters,
  DEFAULT_GROUP_BY,
  highlightNode,
  resetNodeState,
  clusterInfoUtil,
  getQueryFiltersFromPerspectiveResponse
} from '@ce/utils/perspectiveUtils'
import { AGGREGATE_FUNCTION } from '@ce/components/PerspectiveGrid/Columns'
import { getGMTStartDateTime, getGMTEndDateTime, DEFAULT_TIME_RANGE } from '@ce/utils/momentUtils'
import { useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import { ModuleLicenseType } from '@common/constants/SubscriptionTypes'
import EmptyView from '@ce/images/empty-state.svg'
import { CCM_CHART_TYPES } from '@ce/constants'
import { DAYS_FOR_TICK_INTERVAL } from '@ce/components/CloudCostInsightChart/Chart'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { PAGE_NAMES } from '@ce/TrackingEventsConstants'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import { useDeepCompareEffect, useQueryParams, useUpdateQueryParams } from '@common/hooks'
import type { PerspectiveQueryParams, TimeRangeFilterType } from '@ce/types'
import { useQueryParamsState } from '@common/hooks/useQueryParamsState'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './PerspectiveDetailsPage.module.scss'
 
const PAGE_SIZE = 10
interface PerspectiveParams {
  perspectiveId: string
  perspectiveName: string
  accountId: string
}
 
const PerspectiveHeader: React.FC<{ title: string; viewType: string }> = ({ title, viewType }) => {
  const { perspectiveId, accountId } = useParams<{ perspectiveId: string; accountId: string }>()
  const history = useHistory()
  const { getString } = useStrings()
  const isDefaultPerspective = viewType === ViewType.Default
 
  const { data, loading } = useGetReportSetting({
    accountIdentifier: accountId,
    queryParams: { perspectiveId }
  })
 
  const reports = data?.data || []
 
  const goToEditPerspective: () => void = () => {
    history.push(
      routes.toCECreatePerspective({
        perspectiveId,
        accountId
      })
    )
  }
 
  const breadcrumbsLinks = useMemo(
    () => [
      {
        url: routes.toCEPerspectives({ accountId }),
        label: getString('ce.perspectives.sideNavText')
      }
    ],
    []
  )
 
  const getHeaderContent = () => {
    return (
      <Container
        className={css.headerContentSection}
        padding={{
          top: 'xlarge',
          left: 'xsmall'
        }}
      >
        {loading ? <Icon name="spinner" color={Color.BLUE_500} /> : null}
 
        {reports.length ? (
          <Container className={css.headerContent}>
            <Icon name="notification" size={14} color={Color.PRIMARY_7} />
            <Text
              margin={{
                left: 'xsmall'
              }}
              color={Color.GREY_500}
              font={{ variation: FontVariation.SMALL }}
            >
              {getString('ce.perspectives.perspectiveReportsTxt', {
                reportInfo: cronstrue.toString(reports[0].userCron || '')
              })}
            </Text>
            {reports.length > 1 ? (
              <Text
                margin={{
                  left: 'xsmall'
                }}
                color={Color.GREY_500}
                font={{ variation: FontVariation.SMALL }}
              >
                {getString('ce.perspectives.perspectiveReportsMoreTxt', {
                  count: reports.length - 1
                })}
              </Text>
            ) : null}
          </Container>
        ) : null}
      </Container>
    )
  }
 
  return (
    <PageHeader
      title={title}
      breadcrumbs={<NGBreadcrumbs links={breadcrumbsLinks} />}
      content={getHeaderContent()}
      toolbar={
        <Button
          disabled={isDefaultPerspective}
          text={getString('edit')}
          icon="edit"
          intent="primary"
          onClick={goToEditPerspective}
        />
      }
    />
  )
}
 
const PerspectiveDetailsPage: React.FC = () => {
  const history = useHistory()
  const { perspectiveId, accountId, perspectiveName } = useParams<PerspectiveParams>()
  const { getString } = useStrings()
  const isAnomaliesEnabled = useFeatureFlag(FeatureFlag.CCM_ANOMALY_DETECTION_NG)
  const { getRBACErrorMessage } = useRBACError()
  const { showError } = useToaster()
 
  const { updateQueryParams } = useUpdateQueryParams()
 
  const {
    timeRange: timeQueryParam,
    groupBy: gQueryParam,
    aggregation: aggQueryParam,
    chartType: chartTypeQueryParam
  } = useQueryParams<PerspectiveQueryParams>()
 
  const [timeRange, setTimeRange] = useQueryParamsState<TimeRangeFilterType>('timeRange', DEFAULT_TIME_RANGE)
 
  const [groupBy, setGroupBy] = useQueryParamsState<QlceViewFieldInputInput>('groupBy', DEFAULT_GROUP_BY)
  const [aggregation, setAggregation] = useQueryParamsState<QlceViewTimeGroupType>(
    'aggregation',
    QlceViewTimeGroupType.Day
  )
  const [filters, setFilters] = useQueryParamsState<QlceViewFilterInput[]>('filters', [])
 
  const { trackPage } = useTelemetry()
 
  const { data: perspectiveRes, loading } = useGetPerspective({
    queryParams: {
      perspectiveId: perspectiveId,
      accountIdentifier: accountId
    }
  })
 
  const { mutate: getAnomalies } = useListPerspectiveAnomalies({
    perspectiveId,
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const [anomaliesCountData, setAnomaliesCountData] = useState<PerspectiveAnomalyData[]>([])
 
  const chartRef = useRef<Highcharts.Chart>()
 
  const perspectiveData = perspectiveRes?.data
 
  const { isClusterOnly, hasClusterAsSource } = clusterInfoUtil(perspectiveData?.dataSources)
 
  const [gridPageOffset, setGridPageOffset] = useState(0) // This tells us the starting point of next data fetching(used in the api call)
  const [gridPageIndex, setPageIndex] = useState(0) // [Pagination] tells us the current page we are in the grid
 
  const [chartType, setChartType] = useQueryParamsState<CCM_CHART_TYPES>('chartType', CCM_CHART_TYPES.COLUMN)
  const [columnSequence, setColumnSequence] = useState<string[]>([])
 
  useEffect(() => {
    trackPage(PAGE_NAMES.PERSPECTIVE_DETAILS_PAGE, {})
  }, [])
 
  useEffect(() => {
    Eif (perspectiveData) {
      const cType =
        perspectiveData.viewVisualization?.chartType === ViewChartType.StackedTimeSeries
          ? CCM_CHART_TYPES.COLUMN
          : CCM_CHART_TYPES.AREA
      setChartType(cType)
 
      const queryParamsToUpdate = getQueryFiltersFromPerspectiveResponse(perspectiveData, {
        timeRange: timeQueryParam,
        groupBy: gQueryParam,
        aggregation: aggQueryParam,
        chartType: chartTypeQueryParam
      })
 
      updateQueryParams(queryParamsToUpdate, {}, true)
    }
  }, [perspectiveData])
 
  useDeepCompareEffect(() => {
    const fetchAnomaliesCount = async () => {
      try {
        const response = await getAnomalies({
          filters: [
            ...getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to)),
            ...getFilters(filters)
          ] as QLCEViewFilterWrapper[],
          groupBy: [getGroupByFilter(groupBy)] as QLCEViewGroupBy[]
        })
        setAnomaliesCountData(response?.data as PerspectiveAnomalyData[])
      } catch (error: any) {
        showError(getRBACErrorMessage(error))
      }
    }
    Iif (isAnomaliesEnabled) {
      fetchAnomaliesCount()
    }
  }, [isAnomaliesEnabled, timeRange.from, timeRange.to, filters, groupBy])
 
  const setFilterUsingChartClick: (value: string) => void = value => {
    setFilters([
      ...filters,
      {
        field: { ...groupBy },
        operator: QlceViewFilterOperator.In,
        values: [value]
      }
    ])
  }
 
  const queryFilters = useMemo(
    () => [
      getViewFilterForId(perspectiveId),
      ...getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to)),
      ...getFilters(filters)
    ],
    [perspectiveId, timeRange, filters]
  )
 
  const [chartResult] = useFetchPerspectiveTimeSeriesQuery({
    variables: {
      filters: queryFilters,
      limit: 12,
      groupBy: [getTimeRangeFilter(aggregation), getGroupByFilter(groupBy)]
    }
  })
 
  const [summaryResult] = useFetchPerspectiveDetailsSummaryWithBudgetQuery({
    variables: {
      isClusterQuery: false,
      aggregateFunction: [
        { operationType: QlceViewAggregateOperation.Sum, columnName: 'cost' },
        { operationType: QlceViewAggregateOperation.Max, columnName: 'startTime' },
        { operationType: QlceViewAggregateOperation.Min, columnName: 'startTime' }
      ],
      filters: queryFilters
    }
  })
 
  const getAggregationFunc = () => {
    Eif (!isClusterOnly) {
      return AGGREGATE_FUNCTION.DEFAULT
    }
 
    const af = AGGREGATE_FUNCTION[groupBy.fieldId]
    if (!af) {
      return AGGREGATE_FUNCTION.CLUSTER
    }
 
    return af
  }
 
  const [gridResults] = useFetchperspectiveGridQuery({
    variables: {
      aggregateFunction: getAggregationFunc(),
      filters: queryFilters,
      isClusterOnly: isClusterOnly,
      limit: PAGE_SIZE,
      offset: gridPageOffset,
      groupBy: [getGroupByFilter(groupBy)]
    }
  })
 
  const [perspectiveTotalCountResult] = useFetchPerspectiveTotalCountQuery({
    variables: {
      filters: queryFilters,
      groupBy: [getGroupByFilter(groupBy)],
      isClusterQuery: isClusterOnly
    }
  })
 
  const { data: chartData, fetching: chartFetching } = chartResult
  const { data: gridData, fetching: gridFetching } = gridResults
  const { data: summaryData, fetching: summaryFetching } = summaryResult
  const { data: { perspectiveTotalCount } = {} } = perspectiveTotalCountResult
 
  const persName = perspectiveData?.name || perspectiveName
 
  const goToWorkloadDetails = (clusterName: string, namespace: string, workloadName: string) => {
    history.push({
      pathname: routes.toCEPerspectiveWorkloadDetails({
        accountId,
        perspectiveId,
        perspectiveName: persName,
        clusterName,
        namespace,
        workloadName
      }),
      search: `?${qs.stringify({ timeRange: JSON.stringify(timeRange) })}`
    })
  }
 
  const goToNodeDetails = (clusterName: string, nodeId: string) => {
    history.push({
      pathname: routes.toCEPerspectiveNodeDetails({
        accountId,
        perspectiveId,
        perspectiveName: persName,
        clusterName,
        nodeId
      }),
      search: `?${qs.stringify({ timeRange: JSON.stringify(timeRange) })}`
    })
  }
 
  const isChartGridEmpty =
    chartData?.perspectiveTimeSeriesStats?.stats?.length === 0 &&
    gridData?.perspectiveGrid?.data?.length === 0 &&
    !chartFetching &&
    !gridFetching
 
  const { licenseInformation } = useLicenseStore()
  const isFreeEdition = licenseInformation['CE']?.edition === ModuleLicenseType.FREE
 
  return (
    <>
      <PerspectiveHeader title={persName} viewType={perspectiveData?.viewType || ViewType.Default} />
 
      <PageBody loading={loading}>
        <PersepectiveExplorerFilters
          featureEnabled={!isFreeEdition}
          setFilters={setFilters}
          filters={filters}
          setAggregation={setAggregation}
          aggregation={aggregation}
          setTimeRange={setTimeRange}
          timeRange={timeRange}
          showHourlyAggr={isClusterOnly}
        />
        <PerspectiveSummary
          data={summaryData?.perspectiveTrendStats as any}
          fetching={summaryFetching}
          forecastedCostData={summaryData?.perspectiveForecastCost as any}
          isDefaultPerspective={!!(perspectiveData?.viewType === ViewType.Default)}
          hasClusterAsSource={hasClusterAsSource}
        />
        <Container
          margin="xlarge"
          background="white"
          className={cx(css.chartGridContainer, { [css.emptyContainer]: isChartGridEmpty })}
        >
          <Container padding="small">
            <PerspectiveExplorerGroupBy
              chartType={chartType}
              setChartType={setChartType}
              groupBy={groupBy}
              setGroupBy={setGroupBy}
              timeFilter={getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to))}
            />
            {!isChartGridEmpty && (
              <CloudCostInsightChart
                showLegends={true}
                ref={chartRef as any}
                chartType={chartType}
                columnSequence={columnSequence}
                setFilterUsingChartClick={setFilterUsingChartClick}
                fetching={chartFetching}
                data={chartData?.perspectiveTimeSeriesStats as any}
                aggregation={aggregation}
                xAxisPointCount={chartData?.perspectiveTimeSeriesStats?.stats?.length || DAYS_FOR_TICK_INTERVAL + 1}
                anomaliesCountData={anomaliesCountData}
              />
            )}
          </Container>
 
          {isChartGridEmpty && (
            <Container className={css.emptyIllustrationContainer}>
              <img src={EmptyView} />
              <Text
                margin={{
                  top: 'large',
                  bottom: 'xsmall'
                }}
                font="small"
                style={{
                  fontWeight: 600
                }}
                color={Color.GREY_500}
              >
                {getString('ce.pageErrorMsg.noDataMsg')}
              </Text>
              <Text font="small">{getString('ce.pageErrorMsg.perspectiveNoData')}</Text>
            </Container>
          )}
 
          <PerspectiveGrid
            goToWorkloadDetails={goToWorkloadDetails}
            goToNodeDetails={goToNodeDetails}
            isClusterOnly={isClusterOnly}
            gridData={gridData?.perspectiveGrid?.data as any}
            gridFetching={gridFetching}
            columnSequence={columnSequence}
            highlightNode={
              /* istanbul ignore next */
              id => {
                highlightNode(chartRef, id)
              }
            }
            resetNodeState={
              /* istanbul ignore next */
              () => {
                resetNodeState(chartRef)
              }
            }
            setColumnSequence={colSeq => setColumnSequence(colSeq)}
            groupBy={groupBy}
            totalItemCount={perspectiveTotalCount || 0}
            gridPageIndex={gridPageIndex}
            pageSize={PAGE_SIZE}
            fetchData={(pageIndex, pageSize) => {
              setPageIndex(pageIndex)
              setGridPageOffset(pageIndex * pageSize)
            }}
          />
        </Container>
      </PageBody>
    </>
  )
}
 
export default PerspectiveDetailsPage