All files / modules/75-ce/components/CloudCostInsightChart Chart.tsx

83.67% Statements 41/49
71.43% Branches 15/21
50% Functions 5/10
83.67% Lines 41/49

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              7x   7x 7x 7x 7x 7x   7x 7x 7x 7x 7x 7x 7x 7x   7x 7x 7x   7x 7x                                                       7x                     4x 4x   4x 4x 4x     4x 4x   4x       2x     4x                                   4x   4x                                                             4x                                                                                                                                           4x 4x                 4x     4x                                                                                                                                       7x                   4x     2x                                     7x  
/*
 * 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, { useEffect, useState } from 'react'
import type { OptionsStackingValue } from 'highcharts'
import moment from 'moment'
import { Icon } from '@wings-software/uicore'
import { useHistory, useParams } from 'react-router-dom'
import qs from 'qs'
import { QlceViewTimeGroupType } from 'services/ce/services'
import type { PerspectiveAnomalyData } from 'services/ce'
import formatCost from '@ce/utils/formatCost'
import routes from '@common/RouteDefinitions'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import { useStrings } from 'framework/strings'
import { CE_DATE_FORMAT_INTERNAL } from '@ce/utils/momentUtils'
import { generateGroupBy, getCloudProviderFromFields, getFiltersFromEnityMap } from '@ce/utils/anomaliesUtils'
import { useUpdateQueryParams } from '@common/hooks'
import type { ChartConfigType } from './chartUtils'
import CEChart from '../CEChart/CEChart'
import ChartLegend from './ChartLegend'
import css from './Chart.module.scss'
 
export const DAYS_FOR_TICK_INTERVAL = 10
export const ONE_MONTH = 24 * 3600 * 1000 * 30
 
/* istanbul ignore next */
function getxAxisFormat(aggregation: QlceViewTimeGroupType, value: number): string {
  switch (aggregation) {
    case QlceViewTimeGroupType.Month:
      return moment(value).utc().format('MMM')
 
    case QlceViewTimeGroupType.Hour:
      return moment(value).utc().format('MMM DD HH:00')
 
    default:
      return moment(value).utc().format('MMM DD')
  }
}
 
interface GetChartProps {
  chart: ChartConfigType[]
  idx: number
  onLoad: (chart: Highcharts.Chart) => void
  chartType: string
  aggregation: QlceViewTimeGroupType
  xAxisPointCount: number
  setFilterUsingChartClick?: (value: string) => void
  showLegends: boolean
  anomaliesCountData?: PerspectiveAnomalyData[]
}
 
const GetChart: React.FC<GetChartProps> = ({
  chart,
  idx,
  onLoad,
  chartType,
  aggregation,
  xAxisPointCount,
  setFilterUsingChartClick,
  showLegends,
  anomaliesCountData
}) => {
  const [chartObj, setChartObj] = useState<Highcharts.Chart | null>(null)
  const isAnomaliesEnabled = useFeatureFlag(FeatureFlag.CCM_ANOMALY_DETECTION_NG)
 
  const [forceCounter, setForceCounter] = useState(0)
  const history = useHistory()
  const { accountId } = useParams<{
    accountId: string
  }>()
  const { getString } = useStrings()
  const { updateQueryParams } = useUpdateQueryParams()
 
  useEffect(() => {
    // When the chart data changes the legend component is not getting updated due to no deps on data
    // This setForceCounter ensures that it is taken care of when chart data is changing.
    // This fixes the use case of sorting chart based column sequence of the grid.
    setForceCounter(forceCounter + 1)
  }, [chart])
 
  const xAxisOptions: Highcharts.XAxisOptions = {
    type: 'datetime',
    ordinal: true,
    min: null,
    tickInterval:
      aggregation === QlceViewTimeGroupType.Day && xAxisPointCount < DAYS_FOR_TICK_INTERVAL
        ? 24 * 3600 * 1000
        : undefined,
    // Add Tick Interval,
    labels: {
      formatter: function () {
        return getxAxisFormat(aggregation, Number(this.value))
      }
    },
    minPadding: 0.05,
    maxPadding: 0.05
  }
 
  const stacking: OptionsStackingValue = 'normal'
 
  const plotOptions = {
    series: {
      connectNulls: true,
      animation: {
        duration: 500
      },
      events: {
        click: function (event: any) {
          const name = event.point.series.userOptions.name as string
          setFilterUsingChartClick && setFilterUsingChartClick(name)
        }
      },
      stacking
    },
    area: {
      lineWidth: 1,
      marker: {
        enabled: false
      }
    },
    column: {
      borderColor: undefined
    },
    legend: {
      enabled: true,
      align: 'right',
      verticalAlign: 'middle',
      layout: 'vertical'
    }
  }
 
  Iif (aggregation === QlceViewTimeGroupType.Month) {
    xAxisOptions.tickInterval = ONE_MONTH
  }
 
  /* istanbul ignore next */
  const redirection = (event: any) => {
    if (event.target.id.includes('navAnomalies')) {
      const anchorElm = event.target.id
      const elmId = anchorElm.split('_')
      const time = moment(Number(elmId[1])).utc().format(CE_DATE_FORMAT_INTERNAL)
 
      history.push({
        pathname: routes.toCEAnomalyDetection({
          accountId: accountId
        }),
        search: `?${qs.stringify({
          timeRange: JSON.stringify({
            to: time,
            from: time
          })
        })}`
      })
    }
 
    if (event.target.id.includes('applyFilters')) {
      const anchorElm = event.target.id
      const elmId = anchorElm.split('_')
 
      const time = Number(elmId[1])
      const anomalyData = anomaliesCountData?.find(el => el.timestamp === time)
      const resourceData = anomalyData?.associatedResources as unknown as Array<Record<string, string>>
      if (resourceData?.length && resourceData[0]) {
        const cloudProvider = getCloudProviderFromFields(resourceData[0])
        updateQueryParams({
          groupBy: JSON.stringify(generateGroupBy(resourceData[0].field, cloudProvider)),
          filters: JSON.stringify(getFiltersFromEnityMap(resourceData, cloudProvider))
        })
      }
    }
  }
 
  /* istanbul ignore next */
  const labelsText = (item: Record<string, any>) => {
    return `
      <div class=${css.anomaliesWrapper}>
      <div class=${css.anomaliesWrapperTriangle}></div>
        <span class=${css.anomaliesText}>${item.anomalyCount}</span>
        <span class=${css.anomaliesTooltip}>
          <p class=${css.anomaliesCount}>${getString('ce.anomalyDetection.tooltip.countText', {
      count: item.anomalyCount
    })}
          </p>
          <div class=${css.costWrapper}>
            <span class=${css.anomaliesCost}>${item.actualCost && formatCost(item.actualCost)}</span>
            <span class=${item.differenceFromExpectedCost < 0 ? css.differenceCostNeg : css.differenceCostPos}>
              ${item.differenceFromExpectedCost < 0 ? '-' : '+'}
              ${item.differenceFromExpectedCost ? formatCost(item.differenceFromExpectedCost) : 0}
            </span>
          </div>
          <a id="navAnomalies_${item.timestamp}" class=${css.anomaliesNav}>${getString(
      'ce.anomalyDetection.tooltip.anomaliesRedirectionText'
    )}</a>
          <a id="applyFilters_${item.timestamp}" class=${css.anomaliesNav}>${getString(
      'ce.anomalyDetection.tooltip.filterText'
    )}</a>
        </span>
      <div>
    `
  }
 
  const anomaliesLabels = () => {
    const labels = anomaliesCountData?.map(item => {
      return {
        point: `${item.timestamp}`,
        useHTML: true,
        text: labelsText(item),
        y: -40
      }
    })
 
    return labels || []
  }
 
  return (
    <article key={idx} onClick={redirection}>
      <CEChart
        options={{
          series: chart as any,
          chart: {
            zoomType: 'x',
            height: 300,
            type: chartType,
            spacingTop: 40,
            events: {
              load() {
                setChartObj(this)
                onLoad(this)
              }
            }
          },
          plotOptions,
          yAxis: {
            endOnTick: true,
            min: 0,
            max: null,
            tickAmount: 3,
            title: {
              text: ''
            },
            labels: {
              formatter: function () {
                return `$${this.value}`
              }
            }
          },
          xAxis: xAxisOptions,
          annotations: [
            {
              labels: anomaliesLabels(),
              draggable: '',
              visible: isAnomaliesEnabled,
              labelOptions: {
                crop: false,
                useHTML: true,
                backgroundColor: 'transparent',
                borderWidth: 0
              }
            }
          ]
        }}
      />
      {chartObj && showLegends ? (
        <ChartLegend chartRefObj={chartObj as unknown as Highcharts.Chart} />
      ) : showLegends ? (
        <Icon name="spinner" />
      ) : null}
    </article>
  )
}
 
interface CCMChartProps {
  data: ChartConfigType[][]
  onLoad: (chart: Highcharts.Chart) => void
  chartType: string
  aggregation: QlceViewTimeGroupType
  xAxisPointCount: number
  setFilterUsingChartClick?: (value: string) => void
  showLegends: boolean
  anomaliesCountData?: PerspectiveAnomalyData[]
}
 
const Chart: React.FC<CCMChartProps> = ({
  data,
  onLoad,
  chartType,
  aggregation,
  xAxisPointCount,
  setFilterUsingChartClick,
  showLegends,
  anomaliesCountData
}) => {
  return (
    <>
      {data.map((chart, idx: number) => {
        return chart ? (
          <GetChart
            key={idx}
            chartType={chartType}
            aggregation={aggregation}
            xAxisPointCount={xAxisPointCount}
            chart={chart}
            idx={idx}
            setFilterUsingChartClick={setFilterUsingChartClick}
            onLoad={onLoad}
            showLegends={showLegends}
            anomaliesCountData={anomaliesCountData}
          />
        ) : /* istanbul ignore next */ null
      })}
    </>
  )
}
 
export default Chart