All files / modules/75-ci/pages/dashboard CIDashboardPage.tsx

95.12% Statements 39/41
71.97% Branches 95/132
71.43% Functions 5/7
95% Lines 38/40

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              1x 1x 1x 1x   1x 1x 1x     1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x   1x 1x     3x         3x                                         1x 1x 1x 1x 1x         1x                         1x                   1x 1x   1x 1x   1x                                         1x                                                       2x                                       1x                             1x  
/*
 * 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 } from 'react'
import { Container, PageHeader } from '@wings-software/uicore'
import { useParams, useHistory } from 'react-router-dom'
import { camelCase } from 'lodash-es'
import type { GetDataError } from 'restful-react'
import moment from 'moment'
import { Page } from '@common/exports'
import routes from '@common/RouteDefinitions'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import type { Failure } from 'services/cd-ng'
import { BuildActiveInfo, BuildFailureInfo, CIWebhookInfoDTO, useGetBuilds, useGetRepositoryBuild } from 'services/ci'
import { useStrings } from 'framework/strings'
import {
  startOfDay,
  TimeRangeSelector,
  TimeRangeSelectorProps
} from '@common/components/TimeRangeSelector/TimeRangeSelector'
import CIDashboardSummaryCards from '@pipeline/components/Dashboards/CIDashboardSummaryCards/CIDashboardSummaryCards'
import CardRailView from '@pipeline/components/Dashboards/CardRailView/CardRailView'
import BuildExecutionsChart from '@pipeline/components/Dashboards/BuildExecutionsChart/BuildExecutionsChart'
import RepositoryCard from '@pipeline/components/Dashboards/BuildCards/RepositoryCard'
import { ActiveStatus, FailedStatus, useErrorHandler, useRefetchCall } from '@pipeline/components/Dashboards/shared'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import ExecutionCard from '@pipeline/components/ExecutionCard/ExecutionCard'
import { CardVariant } from '@pipeline/utils/constants'
import type { ExecutionTriggerInfo, PipelineExecutionSummary } from 'services/pipeline-ng'
import { TitleWithToolTipId } from '@common/components/Title/TitleWithToolTipId'
import styles from './CIDashboardPage.module.scss'
 
function buildInfoToExecutionSummary(buildInfo: BuildActiveInfo | BuildFailureInfo): PipelineExecutionSummary {
  const ciExecutionInfoDTO: CIWebhookInfoDTO = {
    author: buildInfo.author,
    branch: { name: buildInfo.branch, commits: [{ message: buildInfo.commit, id: buildInfo.commitID }] }
  }
 
  return {
    startTs: buildInfo.startTs,
    endTs: typeof buildInfo.endTs === 'number' && buildInfo.endTs > 0 ? buildInfo.endTs : undefined,
    name: buildInfo.piplineName,
    status: (buildInfo.status
      ? buildInfo.status.charAt(0).toUpperCase() + camelCase(buildInfo.status).slice(1)
      : '') as any,
    planExecutionId: (buildInfo as any).planExecutionId, // TODO: fix once BE changes are merged
    pipelineIdentifier: buildInfo.pipelineIdentifier,
    moduleInfo: {
      ci: {
        ciExecutionInfoDTO,
        branch: buildInfo.branch as any
      }
    },
    executionTriggerInfo: {
      triggerType: buildInfo.triggerType as ExecutionTriggerInfo['triggerType']
    }
  }
}
 
export const CIDashboardPage: React.FC = () => {
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  const history = useHistory()
  const { getString } = useStrings()
  const [timeRange, setTimeRange] = useState<TimeRangeSelectorProps>({
    range: [startOfDay(moment().subtract(1, 'month').add(1, 'day')), startOfDay(moment())],
    label: getString('common.duration.month')
  })
 
  const { data, loading, error, refetch } = useGetBuilds({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier
    }
  })
 
  const {
    data: repositoriesData,
    loading: loadingRepositories,
    error: repoError,
    refetch: refetchRepos
  } = useGetRepositoryBuild({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      startTime: timeRange?.range[0]?.getTime() || 0,
      endTime: timeRange?.range[1]?.getTime() || 0
    }
  })
 
  const refetchingBuilds = useRefetchCall(refetch, loading)
  const refetchingRepos = useRefetchCall(refetchRepos, loadingRepositories)
 
  useErrorHandler(error as GetDataError<Failure | Error> | null, undefined, 'ci.get.build.error')
  useErrorHandler(repoError as GetDataError<Failure | Error> | null, undefined, 'ci.get.repo.error')
 
  return (
    <>
      <PageHeader
        title={<TitleWithToolTipId title={getString('overview')} toolTipId={'ciOverViewTitle'} />}
        breadcrumbs={<NGBreadcrumbs links={[]} />}
        toolbar={
          <>
            <TimeRangeSelector timeRange={timeRange?.range} setTimeRange={setTimeRange} minimal />
          </>
        }
      />
      <Page.Body
        className={styles.content}
        loading={loading && !refetchingBuilds && loadingRepositories && !refetchingRepos}
      >
        <Container className={styles.page} padding="large">
          <CIDashboardSummaryCards timeRange={timeRange} />
          <Container className={styles.executionsWrapper}>
            <BuildExecutionsChart isCIPage={true} timeRange={timeRange} />
          </Container>
          <CardRailView contentType="REPOSITORY" isCIPage={true} isLoading={loadingRepositories && !refetchingRepos}>
            {repositoriesData?.data?.repositoryInfo?.map((repo, index) => (
              <RepositoryCard
                key={index}
                title={repo.name!}
                message={repo?.lastRepository?.commit}
                lastBuildStatus={repo?.lastRepository?.status}
                startTime={repo?.lastRepository?.startTime}
                endTime={repo?.lastRepository?.endTime}
                username={(repo?.lastRepository as any)?.author?.name}
                avatarUrl={(repo?.lastRepository as any)?.author?.url}
                count={repo.buildCount!}
                successRate={repo.percentSuccess!}
                successRateDiff={repo.successRate!}
                countList={repo.countList}
              />
            ))}
          </CardRailView>
          <CardRailView
            contentType="FAILED_BUILD"
            isLoading={loading && !refetchingBuilds}
            onShowAll={() =>
              history.push(
                routes.toDeployments({ projectIdentifier, orgIdentifier, accountId, module: 'ci' }) +
                  `?filters=${JSON.stringify({ status: Object.keys(FailedStatus) })}`
              )
            }
          >
            {data?.data?.failed?.map((build, index) => (
              <ExecutionCard
                key={index}
                variant={CardVariant.Minimal}
                pipelineExecution={buildInfoToExecutionSummary(build)}
                staticCard={true}
                // staticCard={!build?.planExecutionId} // Enable when Backend supports re-routing
              />
            ))}
          </CardRailView>
          <CardRailView
            contentType="ACTIVE_BUILD"
            isLoading={loading && !refetchingBuilds}
            onShowAll={() =>
              history.push(
                routes.toDeployments({ projectIdentifier, orgIdentifier, accountId, module: 'ci' }) +
                  `?filters=${JSON.stringify({ status: Object.keys(ActiveStatus) })}`
              )
            }
          >
            {data?.data?.active?.map((build, index) => (
              <ExecutionCard
                key={index}
                variant={CardVariant.Minimal}
                pipelineExecution={buildInfoToExecutionSummary(build)}
                staticCard={true}
                // staticCard={!build?.planExecutionId} // Enable when Backend supports re-routing
              />
            ))}
          </CardRailView>
        </Container>
      </Page.Body>
    </>
  )
}
 
export default CIDashboardPage