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

97.44% Statements 76/78
80.19% Branches 170/212
88.89% Functions 16/18
97.1% Lines 67/69

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              4x 4x 4x 4x 4x 4x 4x 4x 4x   4x   4x   4x 4x   4x 4x                                       4x 1x 1x 1x   1x                   1x 1x   1x 1x 3x                   1x                         4x                   4x             4x 4x 4x 4x 4x 4x 4x 2x 2x 6x   2x 2x 2x 6x 6x 6x 6x 6x 6x   2x                                                                                                               4x 4x 6x 5x   8x 4x   10x 4x   12x 4x   4x                                                             4x 4x 4x 4x 60x 60x   4x                                         4x                                                                                                                                                      
/*
 * Copyright 2022 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, useMemo } from 'react'
import noop from 'lodash/noop'
import { Container, Text, Layout } from '@wings-software/uicore'
import HighchartsReact from 'highcharts-react-official'
import { FontVariation } from '@harness/design-system'
import Highcharts from 'highcharts'
import moment from 'moment'
import merge from 'lodash-es/merge'
import { Spinner } from '@blueprintjs/core'
 
import { useParams } from 'react-router-dom'
import type { GetDataError } from 'restful-react'
import { useGetBuildExecution } from 'services/ci'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { FailedStatus, useErrorHandler, useRefetchCall } from '@pipeline/components/Dashboards/shared'
import type { Failure } from 'services/cd-ng'
import NoBuilds from '../images/NoBuilds.svg'
import styles from './BuildExecutionsChart.module.scss'
 
export interface ExecutionsChartProps {
  titleText: React.ReactNode
  customTitleCls?: string
  data?: Array<{
    time?: number
    success?: number
    failed?: number
    aborted?: number
    expired?: number
  }>
  loading: boolean
  range: number[]
  onRangeChange(val: number[]): void
  yAxisTitle: string
  successColor?: string
  isCIPage?: boolean
}
 
export default function BuildExecutionsChart(props: any) {
  const { isCIPage, timeRange } = props
  const { getString } = useStrings()
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
 
  const { data, loading, error, refetch } = useGetBuildExecution({
    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 chartData = useMemo(() => {
    Eif (data?.data?.buildExecutionInfoList?.length) {
      return data.data.buildExecutionInfoList.map(val => ({
        time: val.time,
        success: val.builds?.success,
        failed: val.builds?.failed,
        aborted: val.builds?.aborted,
        expired: val.builds?.expired
      }))
    }
  }, [data])
 
  return (
    <ExecutionsChart
      titleText={getString('buildsText')}
      data={chartData}
      loading={loading && !refetching}
      range={timeRange}
      onRangeChange={noop}
      yAxisTitle="# of builds"
      isCIPage={isCIPage}
    />
  )
}
 
export function ExecutionsChart({
  titleText,
  data,
  loading,
  range,
  yAxisTitle,
  successColor,
  isCIPage,
  customTitleCls
}: ExecutionsChartProps) {
  const [chartOptions, setChartOptions] = useState<Highcharts.Options>(
    generateEmptyChartData(range[0], range[1], {
      yAxis: {
        title: { text: yAxisTitle }
      }
    })
  )
  const successful: number[] = []
  const failed: number[] = []
  const expired: number[] = []
  const aborted: number[] = []
  const empty: number[] = []
  const xCategories: string[] = []
  useEffect(() => {
    Eif (data?.length) {
      let totalMax = data.reduce((acc, curr) => {
        return Math.max((curr?.success || 0) + (curr?.failed || 0) + (curr?.aborted || 0) + (curr?.expired || 0), acc)
      }, 0)
      totalMax = Math.ceil(Math.max(totalMax * 1.2, 10))
      const highchartsTime = new Highcharts.Time({})
      data.forEach(val => {
        successful.push(val?.success || 0)
        failed.push(val?.failed || 0)
        aborted.push(val?.aborted || 0)
        expired.push(val?.expired || 0)
        empty.push(totalMax - ((val?.success || 0) + (val?.failed || 0) + (val?.aborted || 0) + (val?.expired || 0)))
        xCategories.push(highchartsTime.dateFormat('%e %B, %Y', val.time))
      })
      setChartOptions(
        merge({}, defaultChartOptions, {
          chart: {
            animation: false
          },
          yAxis: {
            endOnTick: false,
            title: {
              text: yAxisTitle
            }
          },
          xAxis: {
            categories: xCategories
          },
          series: [
            {
              type: 'column',
              name: 'empty',
              color: 'var(--ci-color-gray-100)',
              showInLegend: false,
              enableMouseTracking: false,
              data: empty
            },
            {
              type: 'column',
              name: 'Failed',
              color: 'var(--ci-color-red-500)',
              data: failed,
              legendIndex: 1
            },
            {
              type: 'column',
              name: 'Successful',
              color: successColor || 'var(--ci-color-green-500)',
              data: successful,
              legendIndex: 0
            },
            {
              type: 'column',
              name: FailedStatus.Aborted,
              color: 'var(--grey-500)',
              data: aborted,
              legendIndex: 2
            },
            {
              type: 'column',
              name: FailedStatus.Expired,
              color: 'var(--yellow-900)',
              data: expired,
              legendIndex: 3
            }
          ]
        })
      )
    }
  }, [data])
  const titleCls = customTitleCls ? styles.rangeSelectorHeader : ''
  const { getString } = useStrings()
  const failedData = chartOptions?.series?.find(item => item.name === 'Failed') as any
  const failedCount = failedData?.data?.every((item: any) => item === 0)
 
  const successData = chartOptions?.series?.find(item => item.name === 'Successful') as any
  const successCount = successData?.data?.every((item: any) => item === 0)
 
  const abortedData = chartOptions?.series?.find(item => item.name === FailedStatus.Aborted) as any
  const abortedCount = successData?.data?.every((item: any) => item === 0)
 
  const expiredData = chartOptions?.series?.find(item => item.name === FailedStatus.Expired) as any
  const expiredCount = successData?.data?.every((item: any) => item === 0)
 
  return (
    <Container className={styles.main}>
      <Layout.Horizontal className={styles.marginBottom4}>
        <Text margin={{ right: 'small' }} className={titleCls} font={{ variation: FontVariation.H5 }}>
          {titleText}
        </Text>
        {loading && <Spinner size={15} />}
      </Layout.Horizontal>
 
      {isCIPage ? (
        <Container className={styles.chartWrapper}>
          <HighchartsReact highcharts={Highcharts} options={chartOptions} />
        </Container>
      ) : (!failedData && !successData && !abortedData && !expiredData) ||
        (failedCount && successCount && abortedCount && expiredCount) ? (
        <Container className={styles.emptyView}>
          <Container className={styles.emptyViewCard}>
            <img src={NoBuilds} />
            <Text>{getString('pipeline.noBuildsLabel')}</Text>
          </Container>
        </Container>
      ) : (
        <Container className={styles.chartWrapper}>
          <HighchartsReact highcharts={Highcharts} options={chartOptions} />
        </Container>
      )}
    </Container>
  )
}
 
function generateEmptyChartData(start: number, end: number, config: Highcharts.Options): Highcharts.Options {
  let n = moment(end).diff(start, 'days')
  const empty: number[] = []
  const xCategories: string[] = []
  while (n-- > 0) {
    xCategories.push(moment().subtract(n, 'days').format('YYYY-MM-DD'))
    empty.push(10)
  }
  return merge({}, defaultChartOptions, config, {
    xAxis: {
      labels: { enabled: false },
      categories: xCategories
    },
    yAxis: {
      labels: { enabled: false }
    },
    series: [
      {
        type: 'column',
        name: 'nn',
        color: 'var(--ci-color-gray-100)',
        showInLegend: false,
        enableMouseTracking: false,
        data: empty
      }
    ]
  })
}
 
const defaultChartOptions: Highcharts.Options = {
  chart: {
    type: 'column',
    height: 215
  },
  title: {
    text: ''
  },
  credits: undefined,
  legend: {
    align: 'center',
    verticalAlign: 'bottom',
    symbolHeight: 9,
    symbolWidth: 9,
    symbolRadius: 2,
    squareSymbol: true,
    itemStyle: {
      fontWeight: '400',
      fontSize: '10',
      fontFamily: 'Inter, sans-serif'
    }
  },
  xAxis: {
    title: {
      text: 'Date',
      style: {
        fontSize: '8',
        color: '#9293AB'
      }
    },
    labels: {
      enabled: true,
      // autoRotation: false,
      formatter: lab => moment(lab.value).date() + '',
      style: {
        fontSize: '8',
        color: '#9293AB'
      }
    },
    tickWidth: 0,
    lineWidth: 0
  },
  yAxis: {
    labels: {
      enabled: true,
      style: {
        fontSize: '8',
        color: '#9293AB'
      }
    },
    title: {
      text: '',
      style: {
        fontSize: '8',
        color: '#9293AB'
      }
    },
    gridLineWidth: 0,
    lineWidth: 0
  },
  plotOptions: {
    column: {
      stacking: 'normal',
      pointPadding: 0,
      borderWidth: 3,
      borderRadius: 4,
      pointWidth: 6,
      events: {
        legendItemClick: function () {
          return false
        }
      }
    }
  }
}