All files / modules/75-cd/pages/dashboard DeploymentsHealthCards.tsx

100% Statements 53/53
67.56% Branches 277/410
100% Functions 9/9
100% Lines 52/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 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              11x 11x 11x 11x 11x 11x   11x 11x 11x 11x 11x   11x 11x 11x   11x 11x                             11x 1x 1x   1x                   1x 1x 15x   1x 1x 1x 1x 1x 1x 1x                       5x           1x                                       1x 1x                 5x         1x 1x                 5x         1x       1x                                                     1x             2x                   1x   1x                                                                                             1x                                                   11x                     3x 1x                     2x                                                                                                                                 11x                                                                                                         11x                                 11x                                                  
/*
 * 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 } from 'react'
import { Container, Text, Icon, Layout } from '@wings-software/uicore'
import cx from 'classnames'
import { Color, FontVariation } from '@harness/design-system'
import HighchartsReact from 'highcharts-react-official'
import Highcharts from 'highcharts'
 
import { useParams } from 'react-router-dom'
import { Classes } from '@blueprintjs/core'
import merge from 'lodash-es/merge'
import moment from 'moment'
import { useStrings } from 'framework/strings'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { roundNumber, useErrorHandler } from '@pipeline/components/Dashboards/shared'
import { useGetDeploymentHealth, DeploymentDateAndCount } from 'services/cd-ng'
import { PieChart, PieChartProps } from '@cd/components/PieChart/PieChart'
 
import { numberFormatter } from '@cd/components/Services/common'
import styles from './CDDashboardPage.module.scss'
 
export interface HealthCardProps {
  title: string
  text: any
  rate?: number
  primaryChartOptions?: any
  secondaryChartOptions?: any
  layout: 'vertical' | 'horizontal'
  isLoading?: boolean
  pieChartProps?: any
  showPieChart?: boolean
  showLineChart?: boolean
}
 
export default function DeploymentsHealthCards(props: any) {
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const { range, title } = props
 
  const { data, loading, error } = useGetDeploymentHealth({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      startTime: range?.range[0]?.getTime() || 0,
      endTime: range?.range[1]?.getTime() || 0
    }
  })
 
  useErrorHandler(error)
  const { getString } = useStrings()
  const mapTime = (value: DeploymentDateAndCount) => (value?.time ? moment(value.time).format('YYYY-MM-DD') : '')
 
  const chartsData = useMemo(() => {
    Eif (data?.data?.healthDeploymentInfo) {
      const ret: any = {}
      Eif (data?.data?.healthDeploymentInfo?.total) {
        const { countList, production, nonProduction } = data?.data?.healthDeploymentInfo?.total
        Eif (countList?.length) {
          ret.totalChartOptions = merge({}, defaultChartOptions, primaryChartOptions, {
            chart: {
              height: 40
            },
            xAxis: {
              categories: countList?.map(mapTime)
            },
            series: [
              {
                name: 'Deployments',
                type: 'line',
                color: 'var(--ci-color-blue-500)',
                data: countList?.map(val => val?.deployments?.count)
              }
            ]
          })
        }
 
        ret.totalBarChartOptions = merge({}, defaultChartOptions, secondaryChartOptions, {
          xAxis: {
            categories: [`Non Prod (${nonProduction})`, `Prod (${production})`]
          },
          series: [
            {
              type: 'bar',
              name: 'Non Prod',
              color: 'var(--grey-600)',
              data: [nonProduction, 0]
            },
            {
              type: 'bar',
              name: 'Prod',
              color: 'var(--grey-600)',
              data: [0, production]
            }
          ]
        })
      }
      Eif (data?.data?.healthDeploymentInfo?.success?.countList?.length) {
        ret.successChartOptions = merge({}, defaultChartOptions, primaryChartOptions, {
          xAxis: {
            categories: data.data.healthDeploymentInfo.success.countList.map(mapTime)
          },
          series: [
            {
              name: 'Deployments',
              type: 'line',
              color: 'var(--ci-color-blue-500)',
              data: data.data.healthDeploymentInfo.success.countList.map(val => val?.deployments?.count)
            }
          ]
        })
      }
      Eif (data?.data?.healthDeploymentInfo?.failure?.countList?.length) {
        ret.failureChartOptions = merge({}, defaultChartOptions, primaryChartOptions, {
          xAxis: {
            categories: data.data.healthDeploymentInfo.failure.countList.map(mapTime)
          },
          series: [
            {
              name: 'Deployments',
              type: 'line',
              color: 'var(--ci-color-blue-500)',
              data: data.data.healthDeploymentInfo.failure.countList.map(val => val?.deployments?.count)
            }
          ]
        })
      }
      return ret
    }
  }, [data])
 
  const pieChartProps: PieChartProps = {
    items: [
      {
        label: getString('cd.serviceDashboard.nonProd'),
        value: data?.data?.healthDeploymentInfo?.total?.nonProduction || 0,
        formattedValue: numberFormatter(data?.data?.healthDeploymentInfo?.total?.nonProduction),
        color: 'var(--primary-2)'
      },
      {
        label: getString('cd.serviceDashboard.prod'),
        value: data?.data?.healthDeploymentInfo?.total?.production || 0,
        formattedValue: numberFormatter(data?.data?.healthDeploymentInfo?.total?.production),
        color: 'var(--primary-7)'
      }
    ],
    size: 36,
    customCls: styles.topDepPiechart,
    showInRevOrder: true,
 
    options: {
      tooltip: {
        enabled: false
      }
    }
  }
 
  const labelsHtml = (
    <Layout.Vertical
      flex={{ alignItems: 'flex-end' }}
      height="100%"
      padding={{ top: 'xsmall', bottom: 'xsmall', right: 'large' }}
    >
      <ul>
        {pieChartProps.items.map(({ label, formattedValue, value, color }) => (
          <li style={{ fontWeight: 500, fontSize: 15, color }} key={`${label}_${value}`}>
            <Text font={{ size: 'xsmall' }} color={Color.GREY_500} key={label}>{`${label} (${
              formattedValue ? formattedValue : value
            })`}</Text>
          </li>
        ))}
      </ul>
    </Layout.Vertical>
  )
 
  pieChartProps['labelsContent'] = labelsHtml
 
  return (
    <Container>
      <Text className={styles.healthCardTitle}>{title}</Text>
      <Container className={styles.healthCards}>
        <HealthCard
          title="Total Deployments"
          text={data?.data?.healthDeploymentInfo?.total?.count}
          isLoading={loading}
          layout="vertical"
          primaryChartOptions={chartsData?.totalChartOptions}
          secondaryChartOptions={chartsData?.totalBarChartOptions}
          showLineChart={data?.data?.healthDeploymentInfo?.total?.count ? true : false}
          showPieChart={
            data?.data?.healthDeploymentInfo?.total?.nonProduction !== 0 ||
            data?.data?.healthDeploymentInfo?.total?.production !== 0
          }
          pieChartProps={pieChartProps}
        />
        <HealthCard
          title="Successful Deployments"
          text={data?.data?.healthDeploymentInfo?.success?.count}
          rate={data?.data?.healthDeploymentInfo?.success?.rate}
          isLoading={loading}
          layout="horizontal"
          primaryChartOptions={chartsData?.successChartOptions}
        />
        <HealthCard
          title="Failed Deployments"
          text={data?.data?.healthDeploymentInfo?.failure?.count}
          rate={data?.data?.healthDeploymentInfo?.failure?.rate}
          isLoading={loading}
          layout="horizontal"
          primaryChartOptions={chartsData?.failureChartOptions}
        />
      </Container>
    </Container>
  )
}
 
function TotalDepHealthCard({
  title,
  text,
  layout,
  isLoading,
  pieChartProps = {},
  showPieChart = false
}: HealthCardProps) {
  return (
    <Container
      font={{ variation: FontVariation.SMALL_SEMI }}
      color={Color.GREY_600}
      className={cx(styles.healthCard, styles.totalDepCard)}
    >
      <Container style={layout === 'horizontal' ? { display: 'flex', justifyContent: 'space-between' } : {}}>
        <Text className={styles.cardHeader}>{title}</Text>
        <Container className={styles.textAndRate}>
          {isLoading ? (
            <Container height={30} width={100} className={Classes.SKELETON} />
          ) : (
            <Text className={styles.cardText}>{text}</Text>
          )}
        </Container>
      </Container>
      <div className={styles.separator}></div>
      {showPieChart && (
        <Container className={styles.chartWrap}>
          <PieChart size={65} {...pieChartProps} />
        </Container>
      )}
    </Container>
  )
}
 
export function HealthCard({
  title,
  text,
  rate,
  primaryChartOptions,
  secondaryChartOptions,
  layout,
  isLoading,
  pieChartProps = {},
  showPieChart = false
}: HealthCardProps) {
  if (showPieChart) {
    return (
      <TotalDepHealthCard
        title={title}
        text={text}
        layout={layout}
        pieChartProps={pieChartProps}
        showPieChart={showPieChart}
      />
    )
  }
 
  return (
    <Container font={{ variation: FontVariation.SMALL_SEMI }} color={Color.GREY_600} className={styles.healthCard}>
      <Text className={styles.cardHeader}>{title}</Text>
      <Container style={layout === 'horizontal' ? { display: 'flex', justifyContent: 'space-between' } : {}}>
        <Container className={styles.textAndRate}>
          {isLoading ? (
            <Container height={30} width={100} className={Classes.SKELETON} />
          ) : (
            <Text className={styles.cardText}>{text}</Text>
          )}
        </Container>
 
        {primaryChartOptions && !isLoading && rate ? (
          <Container className={styles.chartWrap}>
            <HighchartsReact highcharts={Highcharts} options={primaryChartOptions} />
            {typeof rate === 'number' && rate && !isLoading ? (
              <Container flex>
                <Text
                  margin={{ left: 'xsmall' }}
                  style={{
                    color: rate >= 0 ? 'var(--green-600)' : 'var(--ci-color-red-500)'
                  }}
                >
                  {Math.abs(roundNumber(rate)!)}%
                </Text>
                <Icon
                  size={14}
                  name={rate >= 0 ? 'caret-up' : 'caret-down'}
                  style={{
                    color: rate >= 0 ? 'var(--green-600)' : 'var(--ci-color-red-500)'
                  }}
                />
              </Container>
            ) : null}
          </Container>
        ) : null}
        {secondaryChartOptions && !isLoading && rate ? (
          <Container className={styles.chartWrap} margin={{ top: 'large' }}>
            <HighchartsReact highcharts={Highcharts} options={secondaryChartOptions} />
            {typeof rate === 'number' && rate && !isLoading ? (
              <Container flex>
                <Text
                  margin={{ left: 'xsmall' }}
                  style={{
                    color: rate >= 0 ? 'var(--green-600)' : 'var(--ci-color-red-500)'
                  }}
                >
                  {Math.abs(roundNumber(rate)!)}%
                </Text>
                <Icon
                  size={14}
                  name={rate >= 0 ? 'caret-up' : 'caret-down'}
                  style={{
                    color: rate >= 0 ? 'var(--green-600)' : 'var(--ci-color-red-500)'
                  }}
                />
              </Container>
            ) : null}
          </Container>
        ) : null}
      </Container>
    </Container>
  )
}
 
const defaultChartOptions: Highcharts.Options = {
  chart: {
    animation: false,
    backgroundColor: 'transparent',
    height: 25,
    spacing: [5, 0, 5, 0]
  },
  credits: undefined,
  title: {
    text: ''
  },
  legend: {
    enabled: false
  },
  plotOptions: {
    series: {
      marker: {
        states: {
          hover: {
            enabled: false
          }
        },
        enabled: false,
        radius: 1
      }
    }
  },
  tooltip: {
    enabled: false,
    outside: true
  },
  xAxis: {
    title: {
      text: ''
    },
    labels: {
      enabled: false
    },
    gridLineWidth: 0,
    lineWidth: 0,
    tickLength: 0
  },
  yAxis: {
    labels: { enabled: false },
    title: {
      text: ''
    },
    gridLineWidth: 0,
    lineWidth: 0,
    tickLength: 0
  }
}
 
const primaryChartOptions: Highcharts.Options = {
  tooltip: {
    enabled: true
  },
  plotOptions: {
    line: {
      lineWidth: 2,
      marker: {
        enabled: false
      }
    }
  },
  yAxis: {
    min: -1
  }
}
 
const secondaryChartOptions: Highcharts.Options = {
  chart: {
    height: 80
  },
  plotOptions: {
    bar: {
      stacking: 'normal',
      pointPadding: 0,
      borderWidth: 3,
      borderRadius: 4,
      pointWidth: 20
    }
  },
  xAxis: {
    labels: {
      enabled: true,
      style: {
        fontSize: '8',
        color: '#9293AB',
        whiteSpace: 'nowrap',
        fontFamily: 'Inter, sans-serif'
      }
    }
  }
}