All files / modules/75-ce/pages/workload-details WorkloadDetailsPage.tsx

94.23% Statements 49/52
57.89% Branches 44/76
66.67% Functions 4/6
94.23% Lines 49/52

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              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                   2x                     1x 1x 1x   1x 1x 1x           1x 1x                                                                             1x     1x     1x   1x             1x                                 1x             1x   1x               1x 1x 1x     1x         1x       1x                                                                                                                                                                                                                                                                           1x  
/*
 * Copyright 2021 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, { useMemo, useState } from 'react'
import { Container, Text, FlexExpander, Layout, HarnessDocTooltip } from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { Color } from '@harness/design-system'
import { noop } from 'lodash-es'
import cx from 'classnames'
import {
  useFetchWorkloadTimeSeriesQuery,
  useFetchWorkloadGridQuery,
  useFetchWorkloadSummaryQuery,
  QlceViewFilterOperator,
  ViewFieldIdentifier,
  QlceViewFilterWrapperInput,
  QlceViewTimeGroupType,
  ClusterData,
  K8sRecommendationFilterDtoInput
} from 'services/ce/services'
import { useStrings } from 'framework/strings'
import routes from '@common/RouteDefinitions'
import { getViewFilterForId, getTimeFilters, GROUP_BY_POD, getTimeRangeFilter } from '@ce/utils/perspectiveUtils'
import CloudCostInsightChart from '@ce/components/CloudCostInsightChart/CloudCostInsightChart'
import { CCM_CHART_TYPES } from '@ce/constants'
import PerspectiveTimeRangePicker from '@ce/components/PerspectiveTimeRangePicker/PerspectiveTimeRangePicker'
import { DAYS_FOR_TICK_INTERVAL } from '@ce/components/CloudCostInsightChart/Chart'
import {
  CE_DATE_FORMAT_INTERNAL,
  DATE_RANGE_SHORTCUTS,
  DEFAULT_TIME_RANGE,
  getGMTEndDateTime,
  getGMTStartDateTime
} from '@ce/utils/momentUtils'
import { CCM_PAGE_TYPE, TimeRangeFilterType } from '@ce/types'
import PerspectiveGrid from '@ce/components/PerspectiveGrid/PerspectiveGrid'
import { Page } from '@common/exports'
import WorkloadSummary from '@ce/components/WorkloadSummary/WorkloadSummary'
import EmptyView from '@ce/images/empty-state.svg'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { useQueryParamsState } from '@common/hooks/useQueryParamsState'
import { Aggregation, AggregationFunctionMapping } from './constants'
import css from './WorkloadDetailsPage.module.scss'
 
const WorkloadDetailsPage: () => JSX.Element = () => {
  const {
    clusterName,
    namespace,
    workloadName,
    perspectiveId,
    perspectiveName,
    recommendation,
    accountId,
    recommendationName
  } = useParams<{
    clusterName: string
    namespace: string
    workloadName: string
    perspectiveId: string
    perspectiveName: string
    recommendation: string
    accountId: string
    recommendationName: string
  }>()
 
  const { getString } = useStrings()
  const [timeRange, setTimeRange] = useQueryParamsState<TimeRangeFilterType>('timeRange', DEFAULT_TIME_RANGE)
  const [chartDataAggregation, setChartDataAggregation] = useState<Aggregation>(Aggregation.TimeWeighted)
 
  const isDateRangeInLast7Days = useMemo(() => {
    const last7DaysRange = DATE_RANGE_SHORTCUTS['LAST_7_DAYS']
    return (
      getGMTStartDateTime(timeRange.from) >= getGMTStartDateTime(last7DaysRange[0].format(CE_DATE_FORMAT_INTERNAL)) &&
      getGMTEndDateTime(timeRange.to) <= getGMTEndDateTime(last7DaysRange[1].format(CE_DATE_FORMAT_INTERNAL))
    )
  }, [timeRange])
 
  const filters = useMemo(() => {
    const commonFilters = [
      ...getTimeFilters(getGMTStartDateTime(timeRange.from), getGMTEndDateTime(timeRange.to)),
      {
        idFilter: {
          values: [clusterName],
          operator: QlceViewFilterOperator.In,
          field: {
            fieldId: 'clusterName',
            fieldName: 'Cluster Name',
            identifierName: ViewFieldIdentifier.Cluster,
            identifier: ViewFieldIdentifier.Cluster
          }
        }
      },
      {
        idFilter: {
          values: [namespace],
          operator: QlceViewFilterOperator.In,
          field: {
            fieldId: 'namespace',
            fieldName: 'Namespace',
            identifierName: ViewFieldIdentifier.Cluster,
            identifier: ViewFieldIdentifier.Cluster
          }
        }
      },
      {
        idFilter: {
          values: [workloadName],
          operator: QlceViewFilterOperator.In,
          field: {
            fieldId: 'workloadName',
            fieldName: 'Workload Name',
            identifierName: ViewFieldIdentifier.Cluster,
            identifier: ViewFieldIdentifier.Cluster
          }
        }
      }
    ] as QlceViewFilterWrapperInput[]
    Iif (perspectiveId) {
      return [getViewFilterForId(perspectiveId), ...commonFilters]
    }
    return commonFilters
  }, [timeRange.to, timeRange.from, perspectiveId, workloadName, clusterName, namespace])
 
  const isClusterQuery = !perspectiveId
 
  const [gridResult] = useFetchWorkloadGridQuery({
    variables: {
      filters: filters,
      isClusterQuery
    }
  })
 
  const [chartResult] = useFetchWorkloadTimeSeriesQuery({
    variables: {
      filters: filters,
      groupBy: [
        getTimeRangeFilter(isDateRangeInLast7Days ? QlceViewTimeGroupType.Hour : QlceViewTimeGroupType.Day),
        {
          entityGroupBy: { fieldId: 'workloadName', fieldName: 'Workload', identifier: ViewFieldIdentifier.Cluster }
        } as any,
        {
          entityGroupBy: { fieldId: 'clusterName', fieldName: 'Cluster Name', identifier: ViewFieldIdentifier.Cluster }
        } as any
      ],
      isClusterQuery,
      aggregateFunction: AggregationFunctionMapping[chartDataAggregation]
    }
  })
 
  const [summaryResult] = useFetchWorkloadSummaryQuery({
    variables: {
      isClusterQuery,
      filters: filters
    }
  })
 
  const recommendationsFilters = useMemo(
    () =>
      ({
        clusterNames: [clusterName],
        names: [workloadName],
        namespaces: [namespace]
      } as K8sRecommendationFilterDtoInput),
    [clusterName, workloadName, namespace]
  )
 
  const { data: gridData, fetching: gridFetching } = gridResult
  const { data: chartData, fetching: chartFetching } = chartResult
  const { data: summaryData, fetching: summaryFetching } = summaryResult
 
  const isChartGridEmpty =
    chartData?.perspectiveTimeSeriesStats?.cpuLimit?.length === 0 &&
    gridData?.perspectiveGrid?.data?.length === 0 &&
    !chartFetching &&
    !gridFetching
 
  const infoData = summaryData?.perspectiveGrid?.data?.length
    ? (summaryData.perspectiveGrid.data[0]?.clusterData as ClusterData)
    : ({} as ClusterData)
 
  return (
    <>
      <Page.Header
        title={workloadName}
        breadcrumbs={
          <NGBreadcrumbs
            links={
              recommendation
                ? [
                    {
                      url: routes.toCERecommendations({ accountId }),
                      label: getString('ce.recommendation.sideNavText')
                    },
                    {
                      url: routes.toCERecommendationDetails({ accountId, recommendation, recommendationName }),
                      label: workloadName
                    }
                  ]
                : [
                    {
                      url: routes.toCEPerspectives({ accountId }),
                      label: getString('ce.perspectives.sideNavText')
                    },
                    {
                      url: routes.toPerspectiveDetails({ accountId, perspectiveId, perspectiveName }),
                      label: perspectiveName
                    }
                  ]
            }
          />
        }
      />
      <Page.Body>
        <Container flex background="white" padding="small">
          <FlexExpander />
          <PerspectiveTimeRangePicker timeRange={timeRange} setTimeRange={setTimeRange} />
        </Container>
        <Container padding="large">
          <WorkloadSummary
            pageType={CCM_PAGE_TYPE.Workload}
            summaryData={summaryData?.perspectiveTrendStats as any}
            fetching={summaryFetching}
            infoData={infoData}
            showRecommendations={!recommendation}
            recommendationFilters={recommendationsFilters}
          />
        </Container>
        {!isChartGridEmpty && (
          <Container background="white">
            <Container padding="large">
              <Container
                margin={{
                  bottom: 'medium'
                }}
              >
                <Layout.Horizontal spacing="small">
                  <Text className={css.aggregationText} padding="xsmall" font="small">
                    {getString('ce.perspectives.workloadDetails.aggregation.text')}
                  </Text>
                  <div
                    className={cx(css.aggregationTags, {
                      [css.active]: chartDataAggregation === Aggregation.TimeWeighted
                    })}
                    onClick={() => {
                      setChartDataAggregation(Aggregation.TimeWeighted)
                    }}
                  >
                    <span data-tooltip-id="workloadRecommendationTimeWeighted">
                      {getString('ce.perspectives.workloadDetails.aggregation.timeWeighted')}
                    </span>
                    <HarnessDocTooltip tooltipId="workloadRecommendationTimeWeighted" useStandAlone={true} />
                  </div>
                  <div
                    className={cx(css.aggregationTags, {
                      [css.active]: chartDataAggregation === Aggregation.Absolute
                    })}
                    onClick={() => {
                      setChartDataAggregation(Aggregation.Absolute)
                    }}
                  >
                    <span data-tooltip-id="workloadRecommendationAbsolute">
                      {getString('ce.perspectives.workloadDetails.aggregation.absolute')}
                    </span>
                    <HarnessDocTooltip tooltipId="workloadRecommendationAbsolute" useStandAlone={true} />
                  </div>
                </Layout.Horizontal>
              </Container>
              <CloudCostInsightChart
                showLegends={false}
                pageType={CCM_PAGE_TYPE.Workload}
                chartType={CCM_CHART_TYPES.LINE}
                columnSequence={[]}
                fetching={chartFetching}
                data={chartData?.perspectiveTimeSeriesStats as any}
                aggregation={isDateRangeInLast7Days ? QlceViewTimeGroupType.Hour : QlceViewTimeGroupType.Day}
                xAxisPointCount={DAYS_FOR_TICK_INTERVAL + 1}
              />
            </Container>
            <Container>
              <PerspectiveGrid
                isClusterOnly={true}
                gridData={gridData?.perspectiveGrid?.data as any}
                gridFetching={gridFetching}
                columnSequence={[]}
                setColumnSequence={noop}
                groupBy={GROUP_BY_POD}
              />
            </Container>
          </Container>
        )}
        {isChartGridEmpty && (
          <Container className={css.emptyContainer} background="white">
            <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>
        )}
      </Page.Body>
    </>
  )
}
 
export default WorkloadDetailsPage