All files / modules/85-cv/pages/monitored-service/CVMonitoredService CVMonitoredService.utils.tsx

97.4% Statements 75/77
83.84% Branches 83/99
100% Functions 11/11
97.01% Lines 65/67

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              16x 16x 16x 16x 16x 16x   16x   16x 16x   16x 16x 16x   16x 60x 60x       16x 63x 63x 63x   63x 69x 69x 69x     69x 69x 69x 8x 4x 4x 4x     61x       63x                   16x 62x                   16x 65x 4x     61x     16x 61x   61x     16x             73x 73x   73x                             16x 61x   61x       61x     16x 4x 3x 3x 3x   3x   3x 3x 1x   2x         1x     16x 2x   2x                       16x       35x                                  
/*
 * 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, { ReactElement } from 'react'
import { isNull, isNumber } from 'lodash-es'
import Highcharts, { PointOptionsObject } from 'highcharts'
import { Text, Layout, Tag, SelectOption } from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import HighchartsReact from 'highcharts-react-official'
import type { Renderer, CellProps } from 'react-table'
import { useStrings, UseStringsReturn } from 'framework/strings'
import type { ChangeSummaryDTO, CountServiceDTO, MonitoredServiceListItemDTO, RiskData } from 'services/cv'
import { getRiskColorValue, getRiskLabelStringId } from '@cv/utils/CommonUtils'
import ImageDeleteService from '@cv/assets/delete-service.svg'
import type { FilterCardItem } from '@cv/components/FilterCard/FilterCard.types'
import { RiskTagWithLabelProps, FilterTypes } from './CVMonitoredService.types'
import { HistoricalTrendChartOption, DefaultChangePercentage } from './CVMonitoredService.constants'
import css from './CVMonitoredService.module.scss'
 
export const getEnvironmentIdentifier = (environment?: SelectOption): string | undefined => {
  Eif (environment?.value !== 'All') {
    return environment?.value as string
  }
}
 
export const createTrendDataWithZone = (trendData: RiskData[]): Highcharts.SeriesLineOptions => {
  const highchartsLineData: PointOptionsObject[] = []
  let currentRiskColor: string | null = getRiskColorValue(trendData?.[0].riskStatus)
  const zones: Highcharts.SeriesZonesOptionsObject[] = [{ value: undefined, color: currentRiskColor }]
 
  trendData.forEach((dataPoint, index) => {
    const { riskStatus } = dataPoint || {}
    let { healthScore } = dataPoint || {}
    Iif (isNull(healthScore)) {
      healthScore = -2
    }
    const riskColor = getRiskColorValue(riskStatus)
    highchartsLineData.push({ x: index, y: healthScore })
    if (isNumber(healthScore) && riskStatus) {
      if (riskColor !== currentRiskColor) {
        zones[zones.length - 1].value = index
        zones.push({ value: undefined, color: riskColor })
        currentRiskColor = riskColor
      }
    } else {
      currentRiskColor = null
    }
  })
 
  return {
    data: highchartsLineData,
    zones,
    name: '',
    type: 'line',
    zoneAxis: 'x',
    clip: false
  }
}
 
export const getHistoricalTrendChartOption = (trendData: RiskData[]): Highcharts.Options => {
  return {
    ...HistoricalTrendChartOption,
    series: [
      {
        ...createTrendDataWithZone(trendData)
      }
    ]
  }
}
 
export const ServiceHealthTrend = ({ healthScores }: { healthScores?: RiskData[] }): JSX.Element => {
  if (!healthScores) {
    return <></>
  }
 
  return <HighchartsReact highcharts={Highcharts} options={getHistoricalTrendChartOption(healthScores)} />
}
 
export const RenderHealthTrend: Renderer<CellProps<MonitoredServiceListItemDTO>> = ({ row }) => {
  const healthScores = row.original.historicalTrend?.healthScores
 
  return <ServiceHealthTrend healthScores={healthScores} />
}
 
export const RiskTagWithLabel = ({
  riskData,
  labelVariation,
  color,
  label,
  isDarkBackground
}: RiskTagWithLabelProps): ReactElement => {
  const { getString } = useStrings()
  const { riskStatus, healthScore } = riskData ?? {}
 
  return (
    <Layout.Horizontal className={css.healthScoreCardContainer} spacing="small">
      <Tag
        className={css.healthScoreCard}
        style={{ backgroundColor: getRiskColorValue(riskStatus, true, !!isDarkBackground) }}
      >
        {healthScore || healthScore === 0 ? healthScore : '-'}
      </Tag>
      <Text color={color ?? Color.BLACK} font={{ variation: labelVariation ?? FontVariation.BODY }}>
        {label ?? getString(getRiskLabelStringId(riskStatus))}
      </Text>
    </Layout.Horizontal>
  )
}
 
export const RenderHealthScore: Renderer<CellProps<MonitoredServiceListItemDTO>> = ({ row }) => {
  const monitoredService = row.original
 
  Iif (!monitoredService.healthMonitoringEnabled) {
    return <></>
  }
 
  return <RiskTagWithLabel riskData={monitoredService.currentHealthScore} />
}
 
export const calculateChangePercentage = (changeSummary: ChangeSummaryDTO): { color: string; percentage: number } => {
  if (changeSummary?.categoryCountMap) {
    const { categoryCountMap } = changeSummary
    const { Infrastructure, Deployment, Alert } = categoryCountMap as any
    const totalCount = Infrastructure?.count + Deployment?.count + Alert?.count
    const totalCountInPrecedingWindow =
      Infrastructure?.countInPrecedingWindow + Deployment?.countInPrecedingWindow + Alert?.countInPrecedingWindow
    const percentageChange: number =
      ((totalCount - totalCountInPrecedingWindow) / (totalCount + totalCountInPrecedingWindow)) * 100
    if (isNaN(totalCount) || isNaN(totalCountInPrecedingWindow) || isNaN(percentageChange)) {
      return DefaultChangePercentage
    }
    return {
      color: percentageChange > 0 ? Color.SUCCESS : Color.ERROR,
      percentage: Math.abs(Math.floor(percentageChange))
    }
  }
  return DefaultChangePercentage
}
 
export const ServiceDeleteContext = ({ serviceName }: { serviceName?: string }): ReactElement => {
  const { getString } = useStrings()
 
  return (
    <Layout.Horizontal flex={{ justifyContent: 'space-between', alignItems: 'flex-start' }}>
      <Text color={Color.GREY_800}>
        {getString('cv.monitoredServices.deleteMonitoredServiceWarning', { name: serviceName })}
      </Text>
      <div>
        <img src={ImageDeleteService} width="204px" height="202px" />
      </div>
    </Layout.Horizontal>
  )
}
 
export const getMonitoredServiceFilterOptions = (
  getString: UseStringsReturn['getString'],
  serviceCountData: CountServiceDTO | null
): FilterCardItem[] => {
  return [
    {
      type: FilterTypes.ALL,
      title: getString('cv.allServices'),
      icon: 'services',
      iconSize: 18,
      count: serviceCountData?.allServicesCount
    },
    {
      type: FilterTypes.RISK,
      title: getString('cv.servicesAtRisk'),
      icon: 'offline-outline',
      iconSize: 18,
      count: serviceCountData?.servicesAtRiskCount
    }
  ]
}