All files / modules/70-pipeline/components/Dashboards/CIDashboardSummaryCards CIDashboardSummaryCards.tsx

92.68% Statements 38/41
79.26% Branches 149/188
100% Functions 3/3
92.68% Lines 38/41

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              5x 5x 5x 5x 5x 5x 5x 5x       5x   5x 5x 5x                         5x 4x 4x 4x 4x   4x                   4x 4x 4x   4x 2x 2x 2x 2x                                       4x                                                           5x                 16x   16x 16x 16x 14x 14x 14x 2x         16x                                                                         5x                                                                                                              
/*
 * 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, { useState, useEffect } from 'react'
import { Container, Text, Icon } from '@wings-software/uicore'
import { FontVariation, Color } from '@harness/design-system'
import { Classes } from '@blueprintjs/core'
import classnames from 'classnames'
import { useParams } from 'react-router-dom'
import HighchartsReact from 'highcharts-react-official'
import Highcharts from 'highcharts'
import type { GetDataError } from 'restful-react'
import type { TimeRangeSelectorProps } from '@common/components/TimeRangeSelector/TimeRangeSelector'
import type { Failure } from 'services/cd-ng'
import { useGetBuildHealth } from 'services/ci'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { roundNumber, formatDuration, useErrorHandler, useRefetchCall } from '../shared'
import styles from './CIDashboardSummaryCards.module.scss'
 
export interface SummaryCardProps {
  title: string | JSX.Element
  text?: any
  subContent?: React.ReactNode
  rate?: number
  rateDuration?: number
  isLoading?: boolean
  neutralColor?: boolean
  primaryChartOptions?: any
}
 
export default function CIDashboardSummaryCards(props: { timeRange?: TimeRangeSelectorProps }) {
  const { timeRange } = props
  const { getString } = useStrings()
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const [chartOptions, setChartOptions] = useState<any>(null)
 
  const { data, loading, error, refetch } = useGetBuildHealth({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      startTime: timeRange?.range[0]?.getTime() || 0,
      endTime: timeRange?.range[1]?.getTime() || 0
    }
  })
 
  useErrorHandler(error as GetDataError<Failure | Error> | null)
  const refetching = useRefetchCall(refetch, loading)
  const showLoader = loading && !refetching
 
  useEffect(() => {
    const success = data?.data?.builds?.success?.count
    const failed = data?.data?.builds?.failed?.count
    Eif (typeof success === 'number' && typeof failed === 'number') {
      setChartOptions({
        ...defaultChartOptions,
        series: [
          {
            name: 'Failed',
            type: 'bar',
            color: 'var(--ci-color-red-500)',
            data: [failed]
          },
          {
            name: 'Success',
            type: 'bar',
            color: 'var(--ci-color-green-500)',
            data: [success]
          }
        ]
      })
    }
  }, [data?.data?.builds])
 
  return (
    <Container>
      <Container className={styles.marginBottom4}>
        <Text font={{ variation: FontVariation.H5 }}>{getString('pipeline.dashboards.buildHealth')}</Text>
      </Container>
      <Container className={styles.summaryCards}>
        <SummaryCard
          title={getString('pipeline.dashboards.totalBuilds')}
          text={data?.data?.builds?.total?.count}
          subContent={chartOptions && <HighchartsReact highcharts={Highcharts} options={chartOptions} />}
          rate={data?.data?.builds?.total?.rate}
          isLoading={showLoader}
        />
        <SummaryCard
          title={getString('pipeline.dashboards.successfulBuilds')}
          text={data?.data?.builds?.success?.count}
          rate={data?.data?.builds?.success?.rate}
          isLoading={showLoader}
        />
        <SummaryCard
          title={getString('pipeline.dashboards.failedBuilds')}
          text={data?.data?.builds?.failed?.count}
          rate={data?.data?.builds?.failed?.rate}
          isLoading={showLoader}
        />
      </Container>
    </Container>
  )
}
 
export function SummaryCard({
  title,
  text,
  subContent,
  rate,
  rateDuration,
  isLoading,
  neutralColor
}: SummaryCardProps) {
  const isEmpty = typeof text === 'undefined'
  let rateFormatted
  let isIncrease = false
  let isDecrease = false
  if (typeof rate !== 'undefined') {
    isIncrease = rate >= 0
    isDecrease = rate < 0
    rateFormatted = `${Math.abs(roundNumber(rate!)!)}%`
  } else Iif (typeof rateDuration === 'number') {
    isIncrease = rateDuration >= 0
    isDecrease = rateDuration < 0
    rateFormatted = formatDuration(rateDuration)
  }
  return (
    <Container
      className={classnames(styles.card, {
        [styles.variantIncrease]: isIncrease && !neutralColor,
        [styles.variantDecrease]: isDecrease && !neutralColor
      })}
    >
      <Container className={styles.cardHeader}>{title}</Container>
      <Container className={styles.cardContent}>
        <Container className={styles.contentMain}>
          {isLoading && <Container height={30} width={100} className={Classes.SKELETON} />}
          {!isLoading &&
            (!isEmpty ? (
              <Text className={styles.contentMainText}>{text}</Text>
            ) : (
              <Container height={30} width={100} background={Color.GREY_200} />
            ))}
          {!isLoading && !isEmpty && <Container className={styles.subContent}>{subContent}</Container>}
        </Container>
        {!isEmpty && !isLoading && (
          <Container className={styles.diffContent}>
            {/* <HighchartsReact highcharts={Highcharts} options={primaryChartOptions} /> */}
            <Icon
              size={14}
              name={isIncrease ? 'caret-up' : 'caret-down'}
              style={{
                color: isIncrease ? 'var(--green-600)' : 'var(--ci-color-red-500)'
              }}
            />
            <Text>{rateFormatted}</Text>
          </Container>
        )}
      </Container>
    </Container>
  )
}
 
const defaultChartOptions: Highcharts.Options = {
  chart: {
    type: 'bar',
    backgroundColor: 'transparent',
    height: 15,
    width: 200,
    spacing: [5, 0, 5, 0]
  },
  credits: undefined,
  title: {
    text: ''
  },
  legend: {
    enabled: false
  },
  plotOptions: {
    bar: {
      stacking: 'normal',
      pointPadding: 0,
      borderWidth: 3,
      borderRadius: 4,
      pointWidth: 6
    },
    series: {
      stickyTracking: false,
      lineWidth: 1
    },
    line: {
      marker: {
        enabled: false
      }
    }
  },
  tooltip: {
    outside: true
  },
  xAxis: {
    labels: { enabled: false },
    title: {
      text: ''
    },
    gridLineWidth: 0,
    lineWidth: 0,
    tickLength: 0
  },
  yAxis: {
    labels: { enabled: false },
    title: {
      text: ''
    },
    gridLineWidth: 0,
    lineWidth: 0,
    tickLength: 0
  }
}